From 1467041ab6d8e44ea86efc7bba53b05213731dc2 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:02:48 -0500 Subject: [PATCH 01/37] teams: a hand-off says what happened to it; pause is the team's record; proposal crews join on standby A manager told the person work was under way that never began. The measured case: a member the person had paused was handed two directives, team_send answered both with "starts a turn on it now", the member's turn was started and cut in the same second, and nothing told the manager. - Pause is kept on the team's own record (teams.Member.Paused), not in the app's file. A paused member is not opened or woken; a directive waits on the log and starts its turn when the person resumes it. A pause from an earlier build is carried over once. - team_send's answer to a directive says, per member, whether it started, is already in a turn, did not start and why, or has shown no sign of starting, after a wait of at most four seconds on the traffic. - A member turn the person stops ends "stopped by the person" and wakes its manager, which is told the work it handed out is not done. - team_status and the manager's digest show a member's role, "paused by the person", "on standby", and a directive it has not started on. - A crew made from a proposal joins on standby: each helper has its role and starts nothing until the manager's first directive, which hands it the role line marked as a standing role. - The app process answers the engine's open-a-member door by waiting for its own crew watcher, so one directive no longer logs "could not wake" and then "woke". Co-Authored-By: Claude Fable 5.2 --- cmd/codeaf/appcrewlayer.go | 62 ++++- cmd/codeaf/appcrewmembers.go | 59 ++++- cmd/codeaf/appcrews.go | 13 +- cmd/codeaf/appproposalaccept_test.go | 122 ++++++++++ .../manual/chat/running-from-the-terminal.md | 9 +- internal/manual/chat/team-manager.md | 60 ++++- .../manual/chat/team-questions-and-caps.md | 3 +- internal/session/hermetic_test.go | 7 + internal/session/team.go | 23 +- internal/session/team_pause.go | 97 ++++++++ internal/session/team_pause_test.go | 213 ++++++++++++++++++ internal/session/team_pending.go | 8 +- internal/session/team_sendoutcome.go | 183 +++++++++++++++ internal/session/team_wake.go | 14 ++ internal/session/team_wakewatch.go | 40 +++- internal/session/team_wakewatch_test.go | 16 +- internal/session/teamevent.go | 27 ++- internal/session/tools_team.go | 27 ++- internal/teams/digest.go | 63 +++++- internal/teams/digest_test.go | 74 ++++++ internal/teams/member_json.go | 2 +- internal/teams/teams.go | 51 +++++ 22 files changed, 1118 insertions(+), 55 deletions(-) create mode 100644 internal/session/team_pause.go create mode 100644 internal/session/team_pause_test.go create mode 100644 internal/session/team_sendoutcome.go diff --git a/cmd/codeaf/appcrewlayer.go b/cmd/codeaf/appcrewlayer.go index c816cdb419..57b7af8f5e 100644 --- a/cmd/codeaf/appcrewlayer.go +++ b/cmd/codeaf/appcrewlayer.go @@ -21,12 +21,14 @@ import ( "os" "path/filepath" "strconv" + "strings" "sync" "time" "github.com/Agent-Field/codeaf/internal/appwire" "github.com/Agent-Field/codeaf/internal/filelock" "github.com/Agent-Field/codeaf/internal/fsreplace" + teamstore "github.com/Agent-Field/codeaf/internal/teams" ) // appCrewLayerName is the layer's file, beside the app's state file. @@ -64,6 +66,12 @@ type appPendingStart struct { ReportsTo string `json:"reports_to,omitempty"` Role string `json:"role,omitempty"` Model string `json:"model,omitempty"` + // RoleName is the role's name as the proposal gave it, kept on the team's + // own record of the member (teamstore's Member.Role). + RoleName string `json:"role_name,omitempty"` + // Standby says the member joins without starting on its start line + // (teamstore's Member.Standby). + Standby bool `json:"standby,omitempty"` } // appCrewLayerFile is the whole layer. @@ -213,15 +221,59 @@ func (b *appBackend) crewLayer() *appCrewLayer { return b.layer } -// crewPaused says the person paused this agent in some open crew. +// crewPaused says the person paused this agent in some open crew +// (teamstore's Member.Paused). func (b *appBackend) crewPaused(agent string) bool { - paused := false + f, err := teamstore.LoadTeamsOf(b.crewProfile(), agent, false) + if err != nil { + return false + } + for _, t := range f.Teams { + if t.Closed() { + continue + } + if m, ok := b.crewMemberOf(t, agent); ok && m.Paused && m.Key != t.Manager { + return true + } + } + return false +} + +// movePausesToStore carries a pause an earlier build kept in this layer into +// the team's own record, once, so a member paused before the update stays +// paused where the engine reads it. A pause that cannot be carried (its crew +// or member is gone) is dropped with the rest of that record. +func (b *appBackend) movePausesToStore() { + var paused []string _ = b.crewLayer().read(func(f *appCrewLayerFile) { for key, m := range f.Members { - if m != nil && m.Paused && filepath.Base(key) == agent { - paused = true + if m != nil && m.Paused { + paused = append(paused, key) + } + } + }) + if len(paused) == 0 { + return + } + for _, key := range paused { + crew, agent, ok := strings.Cut(key, "/") + if !ok { + continue + } + t, _, err := b.crewTeam(crew) + if err != nil { + continue + } + if m, found := b.crewMemberOf(t, agent); found { + _ = b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, true) }) + } + } + _ = b.crewLayer().write(func(f *appCrewLayerFile) error { + for _, key := range paused { + if m := f.Members[key]; m != nil { + m.Paused = false } } + return nil }) - return paused } diff --git a/cmd/codeaf/appcrewmembers.go b/cmd/codeaf/appcrewmembers.go index bc7fa531dc..2f775f26d0 100644 --- a/cmd/codeaf/appcrewmembers.go +++ b/cmd/codeaf/appcrewmembers.go @@ -57,11 +57,23 @@ func (b *appBackend) Member(verb string, ask appwire.MemberAsk) (appwire.CrewMem case "stop": err = b.memberStop(t, m, agent, ask.Reason) case "pause": - if err = b.memberStop(t, m, agent, "paused"); err == nil { - err = b.layerMember(crew, agent, func(x *appMemberExtra) { x.Paused = true }) + // THE PAUSE IS THE TEAM'S RECORD (teamstore's Member.Paused), written + // before the running turn is stopped: the member's own session reads + // it and starts nothing on the crew's traffic until the person + // resumes it, the manager's view of its crew says "paused", and a + // directive sent meanwhile waits on the log. + if err = b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, true) }); err == nil { + err = b.memberStop(t, m, agent, "paused") } case "resume": - err = b.layerMember(crew, agent, func(x *appMemberExtra) { x.Paused = false }) + if err = b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, false) }); err == nil && m.Paused { + // The resume is said on the crew's log beside the pause. What + // waited there starts the member's turn on its session's next look. + err = appEngineErrorOrNil(teamstore.AppendTraffic(b.crewProfile(), t.ID, teamstore.Entry{ + Kind: teamstore.KindEvent, From: teamstore.FromYou, To: m.Handle, ToKey: m.Key, Member: m.Key, + State: teamstore.StateIdle, Text: appResumedText, + })) + } case "remove": if m.Key == t.Manager { return appwire.CrewMember{}, appwire.Errorf(appwire.CodeBadParams, "the manager is not removed; make another member manager first") @@ -91,6 +103,18 @@ func (b *appBackend) Member(verb string, ask appwire.MemberAsk) (appwire.CrewMem return b.memberNow(crew, agent) } +// appResumedText is the crew log's word for the person lifting a pause, beside +// the "paused" a pause writes. +const appResumedText = "resumed" + +// appEngineErrorOrNil is [appEngineError] that leaves no error alone. +func appEngineErrorOrNil(err error) error { + if err == nil { + return nil + } + return appEngineError(err) +} + // memberNow is a member as its crew shows it now. func (b *appBackend) memberNow(crew, agent string) (appwire.CrewMember, error) { view, err := b.CrewGet(crew) @@ -322,6 +346,17 @@ func (b *appBackend) memberRole(crew, agent, role, instructions, model string) e if err != nil { return appEngineError(err) } + // THE ROLE'S NAME IS THE TEAM'S RECORD TOO (teamstore's Member.Role), which + // is where the member's own session and its manager read it: the member is + // told its role in its team note, and the manager sees it beside the handle + // when it chooses whom to hand work to. + if t, _, err := b.crewTeam(crew); err == nil { + if m, ok := b.crewMemberOf(t, agent); ok && m.Role != given.Name { + if err := b.crewEdit(func(f *teamstore.File) error { return f.SetRole(crew, m.Key, given.Name) }); err != nil { + return err + } + } + } return b.tellRole(agent, crew, given) } @@ -461,8 +496,10 @@ var appProposalAsk = fmt.Sprintf("Propose a crew for the work in this conversati `{"t":"shape","size":3,"teams":1,"why":"why this shape"}`+" (size counts helpers).\n"+ `{"t":"name","name":"the crew's name","goal":"one line"}`+"\n"+ `{"t":"team","id":"stream-id","name":"team name","lead":"lead-handle"}`+" (only for an org with 2+ teams).\n"+ - `{"t":"member","handle":"role-word","role":"short role name","brief":"whole assignment","team":"stream-id","reports_to":"manager"}`+"\n"+ + `{"t":"member","handle":"role-word","role":"short role name","brief":"what this helper is responsible for","team":"stream-id","reports_to":"manager"}`+"\n"+ "Write members top-down, breadth first. reports_to is manager or an earlier team lead's handle; omit team for a single crew. "+ + "Write each brief as the helper's standing responsibility, not as a task under way: an accepted crew joins on standby, nobody starts on the brief, "+ + "and you hand out the first work with team_send when the person asks for it. "+ "Do not start anyone yet; the person decides.", teamstore.HandleMin, teamstore.HandleWordMax, teamstore.HandleWordMax) // appNoProposal is the quiet line a conversation carries when what came back @@ -905,9 +942,11 @@ func (b *appBackend) createFromProposal(ask appwire.CrewCreate) (appwire.Crew, e } err = b.crewLayer().write(func(f *appCrewLayerFile) error { for _, h := range p.Helpers { - if h.Role == "" && h.Model == "" && h.ReportsTo == "" { - continue - } + // EVERY HELPER OF AN ACCEPTED PROPOSAL IS MADE ON STANDBY: it joins + // with its role and starts nothing. The proposal was written for a + // crew to exist, and starting each helper on its line of the + // proposal began work the person had not asked for; the manager + // hands out the first work when they do. role := "" if h.Role != "" { var found *appwire.Role @@ -928,7 +967,7 @@ func (b *appBackend) createFromProposal(ask appwire.CrewCreate) (appwire.Crew, e if f.Pending == nil { f.Pending = map[string]appPendingStart{} } - f.Pending[appPendingKey(id, h.Handle)] = appPendingStart{Role: role, Model: h.Model, ReportsTo: h.ReportsTo} + f.Pending[appPendingKey(id, h.Handle)] = appPendingStart{Role: role, RoleName: h.Role, Model: h.Model, ReportsTo: h.ReportsTo, Standby: true} } return nil }) @@ -970,7 +1009,9 @@ func (b *appBackend) createFromProposal(ask appwire.CrewCreate) (appwire.Crew, e if seated != "" { if err := b.crewLayer().write(func(f *appCrewLayerFile) error { pending := f.Pending[appPendingKey(id, helper.Handle)] - f.member(id, seated).Role = pending.Role + if pending.Role != "" { + f.member(id, seated).Role = pending.Role + } b.roleCopyLocked(f, pending.Role) delete(f.Pending, appPendingKey(id, helper.Handle)) return nil diff --git a/cmd/codeaf/appcrews.go b/cmd/codeaf/appcrews.go index cf912ee1ae..1598b0c554 100644 --- a/cmd/codeaf/appcrews.go +++ b/cmd/codeaf/appcrews.go @@ -177,6 +177,7 @@ func (b *appBackend) crews() *appCrewRun { }) if start { b.subscribeCrewTraffic(run) + b.movePausesToStore() b.crewTick(run, true) b.reopenProposals(run) guard.Go("app/crews", func() { b.crewLoop(run) }) @@ -695,8 +696,9 @@ func (b *appBackend) memberView(read appCrewRead, t teamstore.Team, m teamstore. if usd, set := b.agentBudget(agent, b.now()); set { view.CapUSD = &usd } + view.Paused = m.Paused if extra := read.layer.Members[appMemberKey(t.ID, agent)]; extra != nil { - view.Role, view.Paused, view.Was = extra.Role, extra.Paused, extra.Was + view.Role, view.Was = extra.Role, extra.Was if role := read.layer.Roles[extra.Role]; role != nil { view.Role = role.ID } @@ -1020,6 +1022,9 @@ func (b *appBackend) crewStart(t teamstore.Team, manager teamstore.Member, e tea // member's joining). The terminal's start writes none either. member.Handle, member.JoinedAt, member.Started = handle, time.Time{}, true member.ReportsTo = pending.ReportsTo + // What the start was made with: the role's name, and whether the member + // waits for a directive rather than beginning on this line. + member.Role, member.Standby = pending.RoleName, pending.Standby // THE MEMBERSHIP KEEPS THE ID OF THE LINE THAT MADE IT, so its brief is // that line by identity and survives a rename or a handle reused later. // Only a manager's start of this crew is recorded; the terminal's start @@ -1037,9 +1042,11 @@ func (b *appBackend) crewStart(t teamstore.Team, manager teamstore.Member, e tea b.crewNote(manager, "@"+handle+" opened but did not join "+t.Name+": "+err.Error()) return err } - if pending.Role != "" || pending.ReportsTo != "" { + if pending != (appPendingStart{}) { return b.crewLayer().write(func(f *appCrewLayerFile) error { - f.member(t.ID, agent.ID).Role = pending.Role + if pending.Role != "" { + f.member(t.ID, agent.ID).Role = pending.Role + } delete(f.Pending, appPendingKey(t.ID, handle)) b.roleCopyLocked(f, pending.Role) return nil diff --git a/cmd/codeaf/appproposalaccept_test.go b/cmd/codeaf/appproposalaccept_test.go index 5fcbcd52ad..868cd1c3e8 100644 --- a/cmd/codeaf/appproposalaccept_test.go +++ b/cmd/codeaf/appproposalaccept_test.go @@ -50,6 +50,7 @@ func testAppCrewProposalSeatsSixHelpers(t *testing.T, title, firstHandle, layout for _, handle := range []string{firstHandle, "arch", "scribe", "tabul", "fact", "polish"} { helpers = append(helpers, appwire.ProposalHelper{Handle: handle, Brief: "Own the " + handle + " assignment", ReportsTo: "manager"}) } + helpers[1].Role = "Architect" crew, err := backend.CrewCreate(appwire.CrewCreate{From: "proposal", Proposal: proposal, Edits: &appwire.Proposal{Helpers: helpers}}) if err != nil { t.Fatal(err) @@ -83,6 +84,22 @@ func testAppCrewProposalSeatsSixHelpers(t *testing.T, title, firstHandle, layout t.Fatal(err) } team, _ := file.Team(crew.ID) + // EVERY HELPER JOINS ON STANDBY, with the role the proposal named kept on + // the team's own record: nobody begins work on the proposal's lines. + for _, member := range team.Members { + if member.Key == team.Manager { + if member.Standby { + t.Fatal("the manager was put on standby") + } + continue + } + if !member.Standby { + t.Fatalf("helper @%s was not made on standby", member.Handle) + } + if want := map[string]string{"arch": "Architect"}[member.Handle]; member.Role != want { + t.Fatalf("helper @%s has role %q, want %q", member.Handle, member.Role, want) + } + } entries, err := teamstore.ReadTraffic(backend.profileDir, crew.ID, "", 100) if err != nil { t.Fatal(err) @@ -329,3 +346,108 @@ func TestAppCrewProposalLaterCannotReopenAnsweredAsk(t *testing.T) { t.Fatalf("answered proposal resurrected in Later: count=%d, error=%v", len(items), err) } } + +// A PAUSE IS THE TEAM'S OWN RECORD: the engine reads it where it would wake the +// member, and the crew's log says both the pause and the resume. +func TestAppMemberPauseIsKeptInTheTeamStore(t *testing.T) { + helperRoot := t.TempDir() + var minted atomic.Int64 + conv := &proposingConversation{fakeConversation: &fakeConversation{}, answer: helpersProposal} + backend, rec, manager := proposingBackend(t, conv) + if err := backend.CrewPropose(manager.ID); err != nil { + t.Fatal(err) + } + at := rec.waitFor(t, 5*time.Second, appAskEvent(appwire.EventAskOpened)) + rec.mu.Lock() + proposal := rec.data[at].(appwire.AskOpened).Ask.Proposal.ID + rec.mu.Unlock() + backend.mint = func(string) (string, error) { + return filepath.Join(helperRoot, fmt.Sprint(minted.Add(1)), "transcript.jsonl"), nil + } + backend.open = func(ask appOpenAsk) (*appConn, error) { + return &appConn{Conv: &fakeConversation{}, Workspace: ask.Workspace, Transcript: ask.Transcript, Release: func() {}}, nil + } + helpers := []appwire.ProposalHelper{{Handle: "scout", Brief: "Own the scouting", ReportsTo: "manager"}} + crew, err := backend.CrewCreate(appwire.CrewCreate{From: "proposal", Proposal: proposal, Edits: &appwire.Proposal{Helpers: helpers}}) + if err != nil { + t.Fatal(err) + } + var scout appwire.CrewMember + for _, member := range crew.Members { + if member.Handle == "scout" { + scout = member + } + } + stored := func() teamstore.Member { + t.Helper() + file, err := teamstore.Load(backend.profileDir) + if err != nil { + t.Fatal(err) + } + team, _ := file.Team(crew.ID) + member, ok := team.ByHandle("scout") + if !ok { + t.Fatal("scout is not in the crew") + } + return member + } + texts := func(kind, from string) []string { + t.Helper() + entries, err := teamstore.ReadTraffic(backend.profileDir, crew.ID, "", 100) + if err != nil { + t.Fatal(err) + } + var out []string + for _, entry := range entries { + if entry.Kind == kind && entry.From == from { + out = append(out, entry.Text) + } + } + return out + } + + paused, err := backend.Member("pause", appwire.MemberAsk{Crew: crew.ID, Agent: scout.Agent}) + if err != nil || !paused.Paused || !stored().Paused { + t.Fatalf("pause answered %+v, %v; the store has paused=%v", paused, err, stored().Paused) + } + if got := texts(teamstore.KindStop, teamstore.FromYou); len(got) != 1 || got[0] != "paused" { + t.Fatalf("the crew's log says %v about the pause", got) + } + if !backend.crewPaused(scout.Agent) { + t.Fatal("the app does not read the pause it wrote") + } + resumed, err := backend.Member("resume", appwire.MemberAsk{Crew: crew.ID, Agent: scout.Agent}) + if err != nil || resumed.Paused || stored().Paused { + t.Fatalf("resume answered %+v, %v; the store has paused=%v", resumed, err, stored().Paused) + } + if got := texts(teamstore.KindEvent, teamstore.FromYou); len(got) != 1 || got[0] != appResumedText { + t.Fatalf("the crew's log says %v about the resume", got) + } + // A second resume changes nothing and says nothing. + if _, err := backend.Member("resume", appwire.MemberAsk{Crew: crew.ID, Agent: scout.Agent}); err != nil { + t.Fatal(err) + } + if got := texts(teamstore.KindEvent, teamstore.FromYou); len(got) != 1 { + t.Fatalf("a resume of a member that was not paused was logged: %v", got) + } + if _, err := backend.Member("pause", appwire.MemberAsk{Crew: crew.ID, Agent: manager.ID}); err == nil || !strings.Contains(err.Error(), "is not paused") { + t.Fatalf("pausing the manager answered %v", err) + } + + // A pause an earlier build kept in the app's own file is carried over once. + if err := backend.crewLayer().write(func(f *appCrewLayerFile) error { + f.member(crew.ID, scout.Agent).Paused = true + return nil + }); err != nil { + t.Fatal(err) + } + backend.movePausesToStore() + if !stored().Paused { + t.Fatal("the earlier build's pause was not carried into the team store") + } + _ = backend.crewLayer().read(func(f *appCrewLayerFile) { + if f.member(crew.ID, scout.Agent).Paused { + t.Error("the carried pause is still in the app's file") + } + }) +} diff --git a/internal/manual/chat/running-from-the-terminal.md b/internal/manual/chat/running-from-the-terminal.md index 1921c9ee2b..7de0e3abdd 100644 --- a/internal/manual/chat/running-from-the-terminal.md +++ b/internal/manual/chat/running-from-the-terminal.md @@ -519,9 +519,10 @@ Closing a crew does not stop its conversations. A few things exist only in the app and the terminal never shows them: a crew's goal and end date, linked jobs, issues and pull requests, roles (instructions -and a model sent to a member as a message), a member's own budget, pausing a -member (its own turns are stopped until you resume it), and an agent's -proposal to bring in helpers. +and a model sent to a member as a message), a member's own budget, the Pause +and Resume controls for a member, and an agent's proposal to bring in helpers. +A pause itself is the team's record: the terminal's manager is told a paused +member did not start, and `team_status` shows it paused. ## Idle desktop chats, recovery checks and crew traffic @@ -2182,6 +2183,8 @@ generation asks for reasoning to be off, or the lowest level the provider suppor Your chat's reasoning setting stays the same. The default is the smallest useful crew, usually one to three helpers. Separate teams are proposed only for separate streams of work that each need multiple people. +Each helper's brief describes what it is responsible for, and an accepted crew +joins on standby with nobody started. The final **Bring in helpers** ask still offers **Make the crew**, **Edit**, and **Keep it one agent**. If the stream stops after at least one helper, the ask diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 417f3412b5..5b62b44880 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -333,8 +333,8 @@ A deliberate message jump opens the activity and tool-call groups that contain t A member of a team that has a manager tells the manager, through the traffic, three things it would never write in a message: -- `finished` when a turn ends, `stopped` when somebody stopped it, and `failed: ` with the - error's first line when a turn ends on one; +- `finished` when a turn ends, `stopped` when its manager stopped it, `stopped by the person` + when you did, and `failed: ` with the error's first line when a turn ends on one; - when it starts waiting on you: the permission line for a permission prompt (`needs your ok to run bash`), or `asks: ` and the question for anything else; - `no longer waiting` when the last of those questions comes down. @@ -376,9 +376,9 @@ on one waits for you. | Verb | What it does | Asks you first | |---|---|---| -| `team_status` | every member's handle, title and state (running, asking, idle, failed), the question waiting, the files touched, and recent traffic | no | +| `team_status` | every member's handle, role, title and state (running, asking, idle, failed, paused by the person, on standby), a directive it has not started on, the question waiting, the files touched, and recent traffic | no | | `team_read` | the end of one member's conversation, bounded; the member is not told | no | -| `team_send` | a message to one member, to several (one message, every handle in `to`), or to everyone, as a note (information, which waits) or a directive (an instruction, which starts an idle member) | no | +| `team_send` | a message to one member, to several (one message, every handle in `to`), or to everyone, as a note (information, which waits) or a directive (an instruction, which starts an idle member). The answer to a directive says for each member whether it started, is already in a turn, or did not start and why | no | | `team_stop` | ends one member's current turn, the way your own Stop does, whether a window has it open or codeaf opened it in the background: nothing is deleted, and its background tasks and jobs keep running | no | | `team_add` | list saved conversations (optional query), then add an existing conversation by its returned id or transcript path; context and existing reporting authority remain | under the approval posture | | `team_remove` | release one membership by its handle; preserve the session, work and other teams. Removing the reporting membership leaves it independent. Replace the manager before removing it | under the approval posture | @@ -556,10 +556,12 @@ A message reaches a conversation at the start of its next step. When the convers working, that is straight away. When it is idle, it depends on the kind of message: - A **directive** starts an idle member's turn. The member is handed the directive, marked - `◆ directive from manager`, never as if you had typed it. + `◆ directive from manager`, never as if you had typed it. A member you paused does not + start (see **Pausing a crew member**). - A **note** wakes nobody. An idle member reads it when it next runs, for whatever reason. - A member's **reply to the manager** (`team_post` to the manager), and a member finishing - without a reply, failing or starting to wait on you, start an idle manager's turn. A reply + without a reply, failing, starting to wait on you, or having its turn stopped by you, start + an idle manager's turn. A reply and the end of the same turn are one wake, even if the ending arrives after the manager already ran. Replies arriving within a few seconds are gathered into one turn. @@ -568,6 +570,11 @@ that opens it later joins the running conversation. A manager that moved to anot whose window has since closed, is woken the same way: in the desktop app it is brought back to the app and run there. +The manager is told what became of each directive in `team_send`'s answer, which waits up to +four seconds to see it: `@web started a turn on it`, `@web is in a turn and reads it at the +next step`, `@web did NOT start:` with the reason, or `@web has shown no sign of starting +yet`. A manager reports work as under way only where the answer says a member started. + ## could not wake ◆ — a wake that cannot be delivered is kept, not dropped When a wake cannot be delivered (the conversation is held by a window that is closing, or @@ -591,6 +598,47 @@ by its team with nothing from you stops being woken and asks you instead, as a w the traffic. It is woken again after you next say something to it. The ten wakes count ten replies when each member turn replies and then finishes. +## Pausing a crew member — pause, resume, why a directive did not start, held + +You can pause a member of a crew in the desktop app: **Pause** in the member's menu, and +**Resume** to lift it. A pause stops the member's current turn and is kept on the team's own +record, so the member's session, its manager and every window read the same answer. The +manager itself cannot be paused; stop its turn instead. + +While a member is paused, team traffic starts no turn for it: + +- A directive waits on the crew's log, unread. The traffic says + `held @web: the person paused it; it starts on this when they resume it`, once, at the send. +- `team_send` tells the manager `@web did NOT start` with the same reason, and that only you + can resume it. The manager cannot lift a pause. +- `team_status` shows the member as `paused by the person; a directive waits until they + resume it`, with `has not started on #22` when a directive is waiting. +- codeaf does not open the member's conversation for traffic it would only hold. + +**Resume** writes `resumed` to the crew's log, and the directive that waited starts the +member's turn within a second or two. Nothing is lost and nothing is delivered twice. + +Your own words are not held: typing into a paused member's conversation starts its turn, and +that turn reads what was waiting. A pause made by an earlier version of the app is carried +onto the team's record the first time the updated app opens. + +## A new crew's members wait on standby — why nobody started after Make the crew + +A crew made from a proposal (**Bring in helpers**, then **Make the crew**) joins on standby. +Each helper is created with its handle and role, and nobody begins work: the proposal +describes who the crew is, and accepting it is not a request to start. + +- The traffic says `opened @web on standby; it starts on its manager's first directive`. +- `team_status` shows `on standby; no work handed out yet` until the member first runs. +- The line the member was made with is handed to it at its first turn marked + `◆ your standing role from manager`, together with the directive that started that turn. +- A member's role name is told to it in its team note (`Your role in this team: …`) and shown + to the manager beside the handle. + +The first work starts when you ask the manager for it and it sends a directive. A member the +manager starts itself with `team_start`, or one you add with a brief from the crew's page, +still starts on its brief at once. + ## How do I turn team message wakes off? A team's auto-wake can be turned off. `team messages wake` in `/settings` under **Teams** is diff --git a/internal/manual/chat/team-questions-and-caps.md b/internal/manual/chat/team-questions-and-caps.md index dfe0e3143c..88550214f1 100644 --- a/internal/manual/chat/team-questions-and-caps.md +++ b/internal/manual/chat/team-questions-and-caps.md @@ -149,4 +149,5 @@ Waiting. Inbox Done records that answer once. The chat keeps one crew formation fact, including when a create request is retried. "Edit" leaves the proposal open in Inbox Waiting, including immediately after the answer returns. A proposal card reaches the app after its Inbox item is available. "Keep it one agent" -closes it with its own receipt. +closes it with its own receipt. The helpers of a crew made this way join on +standby: none starts until the manager sends it a directive. diff --git a/internal/session/hermetic_test.go b/internal/session/hermetic_test.go index fa76b520e3..29d7f35ff0 100644 --- a/internal/session/hermetic_test.go +++ b/internal/session/hermetic_test.go @@ -40,6 +40,7 @@ import ( "path/filepath" "sort" "testing" + "time" "github.com/Agent-Field/codeaf/internal/cell/celltest" "github.com/Agent-Field/codeaf/internal/cellstore" @@ -65,6 +66,12 @@ func runTests(m *testing.M) int { // test binary a throwaway root of its own (internal/home/undertest.go), and // a guard watching that would be watching the very directory it exists to // keep the files out of. + // A DIRECTIVE'S ANSWER WAITS TO SEE ITS MEMBERS START (team_sendoutcome.go), + // four seconds as shipped. Most tests that send one have no member that + // could start and assert nothing about the outcome, so the package waits a + // quarter of a second; the tests that do read the outcome take their own + // wait ([fastTeamWake]). + teamSendSettle, teamSendLook = 250*time.Millisecond, 5*time.Millisecond real := home.InheritedDir() before := journalTrees(real) // AND THE CHECKOUT THIS BINARY IS RUNNING IN, for the same reason and at the diff --git a/internal/session/team.go b/internal/session/team.go index e8f5ab06a7..49ebee1ee8 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -152,6 +152,15 @@ type teamRole struct { derived bool joinedAt time.Time startID string + // paused says the person paused this membership ([teams.Member.Paused]): + // team traffic starts no turn here until they resume it (team_pause.go). + paused bool + // standby says this membership was made without work to start on + // ([teams.Member.Standby]): its start line is its role's description and + // starts no turn. + standby bool + // roleName is what this member is in the team for ([teams.Member.Role]). + roleName string } // fileStamp is what a stat says about a file, and the whole of how this file @@ -441,6 +450,9 @@ func rolesFor(file *teams.File, keys []string, d teams.Defaults) []teamRole { derived: member.HandleDerived(), joinedAt: member.JoinedAt, startID: member.StartID, + paused: member.Paused && team.Manager != member.Key, + standby: member.Standby, + roleName: strings.TrimSpace(member.Role), } role.dissolvable = role.manager && file.Dissolvable(team.ID) if hasHome { @@ -1696,7 +1708,7 @@ func teamManagerDelivery(role teamRole) string { if !role.wakes { return "This team's auto-wake is off: what you send, and your members' replies, wait for each conversation's next turn, so an idle member does not start on a directive until it next runs." } - return "A directive (team_send kind directive) starts an idle member's turn; a note waits for its next turn. Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle, so do not wait or poll for them." + return "A directive (team_send kind directive) starts an idle member's turn; a note waits for its next turn. team_send's answer says whether each member started: one the person paused does not start until they resume it, and work is under way only where the answer says so. Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle, so do not wait or poll for them." } // teamRoster names the manager's members by handle, with the start of each @@ -1719,7 +1731,11 @@ func teamRoster(role teamRole, file *teams.File) string { if member.Handle != "" { who = "@" + member.Handle } - if word := strings.TrimSpace(member.Word); word != "" { + // The role is what the manager chooses a member by, so it comes before + // the title, which is only the start of whatever the member was first told. + if roleName := strings.TrimSpace(member.Role); roleName != "" { + who += ", " + cutRunesTeam(roleName, teamRosterWord) + } else if word := strings.TrimSpace(member.Word); word != "" { who += " (" + cutRunesTeam(word, teamRosterWord) + ")" } if member.Independent { @@ -1767,6 +1783,9 @@ func teamMemberRole(role teamRole) string { said := fmt.Sprintf("You are %s in the team %q, which has a manager. "+ "Lines from the manager arrive marked \"◆ from manager\" and from teammates \"from @handle\"; none of them is the person, whose own words outrank the manager's. "+ "Report progress, findings and blockers with team_post, to the manager, a teammate or the room. A conflict you cannot settle with another member or team goes up with team_raise.", you, role.name) + if role.roleName != "" { + said += fmt.Sprintf(" Your role in this team: %s.", cutRunesTeam(role.roleName, teamRosterWord)) + } if role.questionsUp { said += " Your clarifying questions (ask) go to your manager first, and its answer comes back marked \"◆ answered\"; permission prompts still go to the person." } diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go new file mode 100644 index 0000000000..7e7faabe24 --- /dev/null +++ b/internal/session/team_pause.go @@ -0,0 +1,97 @@ +package session + +// ── A PAUSED MEMBER IS HELD BEFORE ITS TURN STARTS ────────────────────────── +// +// The person can pause a member of a team ([teams.Member.Paused]). Until this +// file the pause lived in one interface's own file and the engine knew nothing +// of it: a directive opened the member, started its turn and logged "woke", +// and the interface then stopped the turn it found running. The manager was +// told the member had started, the directive was consumed, and resuming the +// member replayed nothing. The measured case was a manager that handed the +// same work to a paused member twice and reported it under way both times. +// +// SO THE PAUSE IS READ WHERE THE WAKE IS DECIDED. Team traffic starts no turn +// for a paused membership: the watch remembers that something asked for one, +// leaves the lines undelivered, and starts the turn on the first look that +// finds the pause lifted. A conversation that is not open is not opened for +// traffic it would only hold ([TeamOpenPending]), and the writer's rouse +// leaves it closed ([Agent.teamRouse]). +// +// THE SENDER SAYS SO, ONCE, AT THE SEND. `team_send` reads the same record and +// answers that the member is paused, and writes the one traffic line that says +// the directive is held ([teamHeldPausedText]). The paused member writes +// nothing, so the log carries one account whether or not anything has it open. +// +// THE PERSON'S OWN WORDS ARE NOT HELD, as with the daily cap (team_cap.go): a +// person typing into a paused member's conversation starts its turn, and that +// turn reads what was waiting. + +import "github.com/Agent-Field/codeaf/internal/teams" + +// teamPausedWhy is why a paused member did not start, in the words the manager +// and the traffic are both given. +const teamPausedWhy = "the person paused it; it starts on this when they resume it" + +// teamHeldPausedText is the traffic line for a directive a paused member was +// sent: "held @mac-dev: the person paused it; …". +func teamHeldPausedText(handle string) string { return "held @" + handle + ": " + teamPausedWhy } + +// teamPauseHoldLocked reports whether role is paused, and remembers that its +// traffic asked for a turn when asked is true. The caller holds a.team.mu. +func (a *Agent) teamPauseHoldLocked(role teamRole, asked bool) bool { + if !role.paused || role.manager { + return false + } + if asked { + w := &a.team.watch + if w.pausedHeld == nil { + w.pausedHeld = map[string]bool{} + } + w.pausedHeld[role.id] = true + } + return true +} + +// teamPauseReleasedLocked reports whether role owes a turn that was held while +// it was paused, and forgets the hold. The caller holds a.team.mu. +func (a *Agent) teamPauseReleasedLocked(role teamRole) bool { + w := &a.team.watch + if role.paused || !w.pausedHeld[role.id] { + return false + } + delete(w.pausedHeld, role.id) + return true +} + +// teamOwnStartWakes reports whether entry is the start line that owes this +// member its first turn: its own start, unless the membership was made on +// standby, whose start line is a role to read and not work to begin. +func (a *Agent) teamOwnStartWakes(role teamRole, entry teams.Entry) bool { + return !role.standby && a.teamOwnStart(role, entry) +} + +// teamStandbyText is the traffic line a member opened on standby writes, once: +// "opened @mac-dev on standby; …". +func teamStandbyText(handle string) string { + return "opened @" + handle + " on standby; it starts on its manager's first directive" +} + +// teamStandbySay writes that line unless the team's recent traffic already +// carries it: a conversation with nothing in it yet is fresh every time it is +// opened, and the line is said once. +func (a *Agent) teamStandbySay(profile string, role teamRole) { + text := teamStandbyText(role.handle) + tail, err := teams.ReadTraffic(profile, role.id, "", teamFirstLook) + if err != nil { + return + } + for _, entry := range tail { + if entry.Kind == teams.KindEvent && entry.Member == role.key && entry.Text == text { + return + } + } + a.teamSay(profile, role.id, teams.Entry{ + Kind: teams.KindEvent, From: teams.FromSystem, To: role.handle, Member: role.key, + State: teams.StateIdle, Text: text, + }) +} diff --git a/internal/session/team_pause_test.go b/internal/session/team_pause_test.go new file mode 100644 index 0000000000..aa3c098da2 --- /dev/null +++ b/internal/session/team_pause_test.go @@ -0,0 +1,213 @@ +package session + +import ( + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/teams" +) + +func setPaused(t *testing.T, fixture teamFixture, transcript string, paused bool) { + t.Helper() + err := teams.Update(fixture.profile, func(file *teams.File) error { + return file.SetPaused(fixture.teamID, convKeyOf(t, transcript), paused) + }) + if err != nil { + t.Fatal(err) + } +} + +// A DIRECTIVE TO A MEMBER THE PERSON PAUSED STARTS NOTHING, the manager is told +// so in the answer, the traffic says it once, and the directive is still there +// when the pause is lifted: the member starts on it then. +func TestTeamDirectiveToAPausedMemberWaitsForResume(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) + webCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.web, webCalls, nil) + + begun := time.Now() + said := sendDirective(t, manager, "web") + if !strings.Contains(said, "@web did NOT start: "+teamPausedWhy) || !strings.Contains(said, teamNotUnderWayRule) { + t.Fatalf("the send does not say the member is paused: %s", said) + } + if strings.Contains(said, "started a turn") { + t.Fatalf("the send reports a start for a paused member: %s", said) + } + if took := time.Since(begun); took > teamSendSettle/2 { + t.Fatalf("a paused member is known from the teams file, yet the send waited %s", took) + } + quietFor() + if got := webCalls.requests(); got != 0 { + t.Fatalf("the paused member made %d model calls", got) + } + if woke := trafficEvents(t, fixture, "woke @web"); len(woke) != 0 { + t.Fatalf("the traffic says a paused member woke: %+v", woke) + } + held := trafficEvents(t, fixture, teamHeldPausedText("web")) + if len(held) != 1 || held[0].From != teams.FromSystem || held[0].Answers == "" { + t.Fatalf("the hold was said %d times, want once, answering the directive: %+v", len(held), held) + } + // THE MEASURED CASE SENT A SECOND DIRECTIVE to the same paused member a few + // minutes later and was told it had started again. It is told the same + // thing as the first time, and the member still makes no call. + if again := sendDirective(t, manager, "web"); !strings.Contains(again, "@web did NOT start: "+teamPausedWhy) { + t.Fatalf("the second send does not say the member is paused: %s", again) + } + quietFor() + if got := webCalls.requests(); got != 0 { + t.Fatalf("the paused member made %d model calls after the second directive", got) + } + if held := trafficEvents(t, fixture, teamHeldPausedText("web")); len(held) != 2 { + t.Fatalf("two held directives were said %d times", len(held)) + } + // And the manager's own view of its team says why nothing is moving. + status, failed := callTool(t, manager.teamStatusTool, `{}`) + if failed || !strings.Contains(status, teams.DigestPaused) || !strings.Contains(status, "has not started on #") { + t.Fatalf("team_status does not show the pause and the waiting directive:\n%s", status) + } + + setPaused(t, fixture, fixture.web, false) + waitRequests(t, webCalls, 1) + asked := userTextIn(webCalls.request(0)) + if strings.Count(asked, "Fix the header.") != 2 || !strings.Contains(asked, teamWakeMemberLead) { + t.Fatalf("the resumed member was not handed both directives that waited, once each:\n%s", asked) + } + if woke := trafficEvents(t, fixture, "woke @web"); len(woke) != 1 { + t.Fatalf("the resumed member's wake was logged %d times", len(woke)) + } +} + +// A paused member that is not open is not a reason to open it. +func TestTeamOpenPendingLeavesAPausedMemberClosed(t *testing.T) { + fixture := newWakingTeamFixture(t) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header."}) + pending := func() bool { + file, err := teams.Load(fixture.profile) + if err != nil { + t.Fatal(err) + } + return TeamOpenPending(fixture.profile, fixture.web, file, teams.Defaults{Wake: true}, time.Now().Add(-time.Minute)) + } + if !pending() { + t.Fatal("a directive to an idle member is not pending") + } + setPaused(t, fixture, fixture.web, true) + if pending() { + t.Fatal("a paused member's directive asks for its conversation to be opened") + } + setPaused(t, fixture, fixture.web, false) + if !pending() { + t.Fatal("the directive is no longer pending after the resume") + } +} + +// THE MANAGER IS NOT PAUSED: the person talks to it directly. +func TestTeamManagerIsNotPaused(t *testing.T) { + fixture := newWakingTeamFixture(t) + err := teams.Update(fixture.profile, func(file *teams.File) error { + return file.SetPaused(fixture.teamID, convKeyOf(t, fixture.manager), true) + }) + if err == nil || !strings.Contains(err.Error(), "is not paused") { + t.Fatalf("pausing the manager answered %v", err) + } +} + +// A MEMBER MADE ON STANDBY STARTS NOTHING ON ITS START LINE, and its first +// directive hands it the role and the work together. +func TestTeamStandbyMemberStartsOnItsFirstDirective(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + start, err := teams.AppendTrafficID(fixture.profile, fixture.teamID, teams.Entry{ + Kind: teams.KindStart, From: teams.FromManager, To: "web", Text: "Owns the web frontend and its tests.", At: time.Now(), + }) + if err != nil { + t.Fatal(err) + } + err = teams.Update(fixture.profile, func(file *teams.File) error { + team := &file.Teams[0] + for i := range team.Members { + if team.Members[i].Handle == "web" { + team.Members[i].Standby, team.Members[i].Role = true, "Frontend developer" + team.Members[i].Started, team.Members[i].StartEntry, team.Members[i].StartID = true, start, start + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) + webCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.web, webCalls, nil) + quietFor() + if got := webCalls.requests(); got != 0 { + t.Fatalf("the standby member began %d turns on its start line", got) + } + if said := trafficEvents(t, fixture, teamStandbyText("web")); len(said) != 1 { + t.Fatalf("standby was said %d times in the traffic, want once", len(said)) + } + + if said := sendDirective(t, manager, "web"); !strings.Contains(said, "@web started a turn on it.") { + t.Fatalf("the first directive did not start the standby member: %s", said) + } + waitRequests(t, webCalls, 1) + asked := userTextIn(webCalls.request(0)) + for _, want := range []string{teamStandbyBriefWord, "Owns the web frontend and its tests.", "Fix the header.", "Your role in this team: Frontend developer."} { + if !strings.Contains(asked, want) { + t.Fatalf("the standby member's first turn lacks %q:\n%s", want, asked) + } + } + if strings.Contains(asked, teamBriefWord+" #") { + t.Fatalf("a standby start was handed over as a brief to begin:\n%s", asked) + } +} + +// THE PERSON'S STOP OF A MEMBER'S TURN REACHES ITS MANAGER, which handed that +// work out and is told nothing else about its ending. +func TestTeamPersonStopWakesTheManager(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.manager, managerCalls, nil) + streaming := make(chan struct{}) + web := teamAgent(t, fixture, fixture.web, &scriptedCompleter{steps: []step{thinkingStep(streaming)}}, nil) + events := mustSubmit(t, web, "work on the header") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start") + } + web.Interrupt() + collect(t, events) + waitRequests(t, managerCalls, 1) + asked := userTextIn(managerCalls.request(0)) + if !strings.Contains(asked, "@web's turn was "+teams.StoppedByPerson+" before it finished") { + t.Fatalf("the manager was not told the person stopped its member:\n%s", asked) + } + if stopped := trafficEvents(t, fixture, teams.StoppedByPerson); len(stopped) != 1 || stopped[0].State != teams.StateIdle { + t.Fatalf("the stop was logged as %+v", stopped) + } +} + +// AND ITS OWN STOP DOES NOT: the manager performed it and knows. +func TestTeamEventWakesManager(t *testing.T) { + for _, c := range []struct { + state, text string + want bool + }{ + {teams.StateFinished, "finished", true}, + {teams.StateFailed, "failed: x", true}, + {teams.StateAsking, "asks: x", true}, + {teams.StateIdle, teams.StoppedByPerson, true}, + {teams.StateIdle, "stopped", false}, + {teams.StateRunning, "woke @web", false}, + } { + if got := teamEventWakesManager(c.state, c.text); got != c.want { + t.Errorf("%s %q wakes the manager: %v, want %v", c.state, c.text, got, c.want) + } + } +} diff --git a/internal/session/team_pending.go b/internal/session/team_pending.go index 96287dceea..54e2d435a9 100644 --- a/internal/session/team_pending.go +++ b/internal/session/team_pending.go @@ -19,6 +19,10 @@ func TeamOpenPending(profile, transcript string, file *teams.File, defaults team if role.handle == "" && !role.manager { continue } + // A paused membership holds its traffic unopened (team_pause.go). + if role.paused && !role.manager { + continue + } cursor, ok := probe.team.cursors[role.id] if !ok { cursor = probe.firstTeamCursor(profile, role) @@ -49,7 +53,9 @@ func pendingTeamEntry(profile string, role teamRole, entry teams.Entry) bool { return false } if !role.manager && entry.Kind == teams.KindStart && entry.To == role.handle { - return true + // A standby start is a role to read at the first turn, not work that + // needs the conversation open. + return !role.standby } return teamWakes(role, entry) || teamPacketWakes(profile, role, entry) || teamLine(role, entry) != "" } diff --git a/internal/session/team_sendoutcome.go b/internal/session/team_sendoutcome.go new file mode 100644 index 0000000000..94be2aed05 --- /dev/null +++ b/internal/session/team_sendoutcome.go @@ -0,0 +1,183 @@ +package session + +// ── A DIRECTIVE'S ANSWER SAYS WHAT HAPPENED TO IT ─────────────────────────── +// +// `team_send` used to answer every directive with one sentence written before +// anything was known: "a member that is idle starts a turn on it now". A +// manager is a model, and a model reports what its tools tell it. The measured +// case told the person "I've started the setup" about a member that never +// began, twice, and then found an empty folder. +// +// SO THE ANSWER WAITS FOR THE EVIDENCE, BRIEFLY. A wake writes a line to the +// team's traffic that answers the directive by its id (team_wakewatch.go), a +// refused wake writes why, and a paused member is known from the teams file +// before anything is asked. The send looks at the traffic for a few seconds +// and says, per member, one of: started, in a turn already, did not start and +// why, or no sign of a start yet. The last is said as plainly as the rest: a +// manager told "no sign yet" checks before it reports. +// +// A REFUSAL IS NOT BELIEVED UNTIL THE WAIT IS OVER. Two processes may try to +// open one member, and the one that cannot may say so a moment before the one +// that can says it did; a start that arrives inside the wait is the answer. + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Agent-Field/codeaf/internal/teams" +) + +// teamSendSettle is how long a directive's answer waits to see its members +// start. A member some process holds starts within a second ([teamWatchEvery]); +// one that has to be opened first took half a second where it was measured. +// Four seconds covers both with room, and is short enough that a manager does +// not read the wait as a stall. teamSendLook is how often the traffic is read +// while waiting. Both are vars so a test does not sleep. +var ( + teamSendSettle = 4 * time.Second + teamSendLook = 200 * time.Millisecond +) + +// The traffic lines a wake writes, as the send reads them back. They are the +// prefixes of the texts team_wakewatch.go and team_pause.go write. +const ( + teamWokePrefix = "woke @" + teamCouldNotPrefix = "could not wake " + teamHeldPrefix = "held " + teamNotUnderWayRule = "Do not tell the person this work is under way." +) + +// teamSendOutcome is the sentences that follow "Sent a directive to …": what +// became of it for each member it was sent to on this computer. ready are the +// members a wake was asked for and paused the ones the person paused. +func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams.Team, id string, ready, paused []teams.Member) string { + var started, busy, unseen []string + refused := map[string]string{} + var refusedOrder []string + waiting := map[string]teams.Member{} + now := time.Now() + for _, member := range ready { + if member.Handle == "" { + continue + } + if state, _, ok := a.team.journals.stateOf(member.File, now); ok && + (state.State == teams.StateRunning || state.State == teams.StateAsking) { + busy = append(busy, "@"+member.Handle) + continue + } + waiting[member.Key] = member + } + deadline := now.Add(teamSendSettle) + for len(waiting) > 0 { + entries, err := teams.ReadTraffic(profile, team.ID, id, teamPageLimit) + if err == nil { + for _, entry := range entries { + member, ok := waiting[entry.Member] + if !ok || entry.Kind != teams.KindEvent { + continue + } + text := strings.TrimSpace(entry.Text) + switch { + case entry.State == teams.StateRunning && strings.HasPrefix(text, teamWokePrefix): + started = append(started, "@"+member.Handle) + delete(waiting, entry.Member) + delete(refused, member.Handle) + case entry.From == teams.FromSystem && (strings.HasPrefix(text, teamCouldNotPrefix) || strings.HasPrefix(text, teamHeldPrefix)): + if _, said := refused[member.Handle]; !said { + refusedOrder = append(refusedOrder, member.Handle) + } + _, why, _ := strings.Cut(text, ": ") + refused[member.Handle] = strings.TrimSpace(why) + } + } + } + if len(waiting) == 0 || !time.Now().Before(deadline) { + break + } + select { + case <-ctx.Done(): + deadline = time.Time{} + case <-time.After(teamSendLook): + } + } + for _, member := range ready { + if _, still := waiting[member.Key]; still { + if _, said := refused[member.Handle]; !said { + unseen = append(unseen, "@"+member.Handle) + } + } + } + var said []string + if len(started) > 0 { + said = append(said, strings.Join(started, ", ")+" started a turn on it.") + } + if len(busy) > 0 { + said = append(said, strings.Join(busy, ", ")+" "+isAre(len(busy))+" in a turn and "+readsRead(len(busy))+" it at the next step.") + } + if len(started)+len(busy) > 0 { + said = append(said, "Replies and endings wake you when they arrive, so there is no need to wait or poll.") + } + for _, member := range paused { + said = append(said, fmt.Sprintf("@%s did NOT start: %s. Tell the person it is paused; only they can resume it.", member.Handle, teamPausedWhy)) + } + for _, handle := range refusedOrder { + why, still := refused[handle] + if !still { + continue + } + if why == "" { + why = "its wake was refused" + } + said = append(said, fmt.Sprintf("@%s did NOT start: %s.", handle, strings.TrimSuffix(why, "."))) + } + if len(unseen) > 0 { + said = append(said, strings.Join(unseen, ", ")+" "+hasHave(len(unseen))+" shown no sign of starting yet; team_status says whether "+itThey(len(unseen))+" did.") + } + if len(paused)+len(refused)+len(unseen) > 0 { + said = append(said, teamNotUnderWayRule) + } + return strings.Join(said, " ") +} + +// splitPaused divides a directive's local targets into the members the person +// paused and the rest. The manager is never paused. +func splitPaused(team teams.Team, targets []teams.Member) (ready, paused []teams.Member) { + for _, member := range targets { + if member.Paused && member.Key != team.Manager { + paused = append(paused, member) + continue + } + ready = append(ready, member) + } + return ready, paused +} + +func isAre(n int) string { + if n == 1 { + return "is" + } + return "are" +} + +func readsRead(n int) string { + if n == 1 { + return "reads" + } + return "read" +} + +func hasHave(n int) string { + if n == 1 { + return "has" + } + return "have" +} + +func itThey(n int) string { + if n == 1 { + return "it" + } + return "they" +} diff --git a/internal/session/team_wake.go b/internal/session/team_wake.go index 37ba6495a6..cb813ddde6 100644 --- a/internal/session/team_wake.go +++ b/internal/session/team_wake.go @@ -110,6 +110,20 @@ func (a *Agent) awaitTeamStart(profile string, base int) { } var waking []teamRole for _, role := range started { + if role.standby { + // ON STANDBY NOTHING STARTS. The start line is this member's + // role, read at its first turn, and the manager's first + // directive is what begins that turn (team_pause.go). + a.teamStandbySay(profile, role) + continue + } + if role.paused { + // The watch holds it and starts the turn on resume. + a.team.mu.Lock() + a.teamPauseHoldLocked(role, true) + a.team.mu.Unlock() + continue + } if role.wakes { waking = append(waking, role) continue diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 13cb8d9179..753cbe4a5e 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -148,6 +148,10 @@ type teamWatch struct { held bool // capSaid is the last cap hold the Traffic was told of. capSaid string + // pausedHeld is the teams whose traffic asked for this member's turn while + // the person had it paused (team_pause.go). The lines stay undelivered on + // the log, and the turn they asked for starts when the pause is lifted. + pausedHeld map[string]bool } // personTurns counts turns the person started, for the loop breaker. It is @@ -219,11 +223,17 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { } // Membership can arrive after the fresh-session watch expires. // Its own start still owes this member its first turn. - if a.teamOwnStart(role, entry) || teamWakes(role, entry) || teamPacketWakes(profile, role, entry) { + if a.teamOwnStartWakes(role, entry) || teamWakes(role, entry) || teamPacketWakes(profile, role, entry) { waking = append(waking, entry) } } - if len(waking) == 0 { + // A PAUSED MEMBER IS NOT WOKEN, and what would have woken it is not + // consumed: the hold is remembered, and the turn starts on the tick + // that finds the pause lifted (team_pause.go). + if a.teamPauseHoldLocked(role, len(waking) > 0) { + continue + } + if len(waking) == 0 && !a.teamPauseReleasedLocked(role) { continue } if role.manager { @@ -417,6 +427,20 @@ func (a *Agent) teamWatchReadLocked(profile string, role teamRole) []teams.Entry return entries } +// teamEventWakesManager reports whether a member's event starts its manager's +// turn: finishing, failing, asking, and a turn the person stopped. The last is +// the one ending that is not the manager's own doing and carries no report, so +// without the wake a manager waited on work that was never going to arrive. +func teamEventWakesManager(state, text string) bool { + switch state { + case teams.StateFinished, teams.StateFailed, teams.StateAsking: + return true + case teams.StateIdle: + return text == teams.StoppedByPerson + } + return false +} + // teamWakes reports whether an entry starts this conversation's turn when it // is idle: a directive from the manager to its handle or to everyone, for a // member; a member's post to the manager, or a member's finished, failed or @@ -443,10 +467,12 @@ func teamWakes(role teamRole, entry teams.Entry) bool { case teams.KindNote: return entry.To == teams.ToManager && strings.TrimSpace(entry.Text) != "" case teams.KindEvent: - switch entry.State { - case teams.StateFinished, teams.StateFailed, teams.StateAsking: - return true + // The global manager is not woken by a stop the person made in a + // conversation they were talking to directly. + if role.root && entry.State == teams.StateIdle { + return false } + return teamEventWakesManager(entry.State, entry.Text) } return false } @@ -742,6 +768,10 @@ func teamEventLines(entries []teams.Entry) []string { lines = append(lines, who+" "+text) case teams.StateAsking: lines = append(lines, who+" is waiting on the person: "+strings.TrimPrefix(text, "asks: ")) + case teams.StateIdle: + if text == teams.StoppedByPerson { + lines = append(lines, who+"'s turn was "+teams.StoppedByPerson+" before it finished; it reported nothing, so what you handed it is not done") + } } } return lines diff --git a/internal/session/team_wakewatch_test.go b/internal/session/team_wakewatch_test.go index 5e60efcbe6..907bfd6dab 100644 --- a/internal/session/team_wakewatch_test.go +++ b/internal/session/team_wakewatch_test.go @@ -27,11 +27,17 @@ func fastTeamWake(t *testing.T) { every, settle, retry, longest := teamWatchEvery, teamWakeSettle, teamRouseRetry, teamRouseRetryMax teamWatchEvery, teamWakeSettle, teamRouseRetry, teamRouseRetryMax = 20*time.Millisecond, 300*time.Millisecond, 50*time.Millisecond, 200*time.Millisecond teamWatchClockMu.Unlock() + // A send waits to see its members start; with the watch this fast a second + // and a half is many looks, and a test of a member that never starts does + // not sit out the shipped four seconds. + sendSettle, sendLook := teamSendSettle, teamSendLook + teamSendSettle, teamSendLook = 1500*time.Millisecond, 5*time.Millisecond t.Cleanup(func() { forgetRouses() teamWatchClockMu.Lock() teamWatchEvery, teamWakeSettle, teamRouseRetry, teamRouseRetryMax = every, settle, retry, longest teamWatchClockMu.Unlock() + teamSendSettle, teamSendLook = sendSettle, sendLook }) } @@ -644,9 +650,11 @@ func TestTeamWakeADirectiveOpensAMemberNobodyHolds(t *testing.T) { manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) parser := oneAnswer(1) teamAgent(t, fixture, fixture.parser, parser, nil) + // The door here records the open and starts nothing, so the send has no + // start to report and says so, without claiming the work is under way. said := sendDirective(t, manager, "web") - if !strings.Contains(said, "starts a turn on it now") || !strings.Contains(said, "wake you") { - t.Errorf("the send does not say what happens next: %s", said) + if !strings.Contains(said, "@web has shown no sign of starting yet") || !strings.Contains(said, teamNotUnderWayRule) { + t.Errorf("the send claims more than it saw: %s", said) } deadline := time.Now().Add(5 * time.Second) for len(recorder.seen()) == 0 && time.Now().Before(deadline) { @@ -656,7 +664,9 @@ func TestTeamWakeADirectiveOpensAMemberNobodyHolds(t *testing.T) { if len(opened) != 1 || !strings.HasPrefix(opened[0], fixture.web+"|") { t.Fatalf("opened %v, want the web member's transcript once", opened) } - sendDirective(t, manager, "parser") + if said := sendDirective(t, manager, "parser"); !strings.Contains(said, "@parser started a turn on it.") || !strings.Contains(said, "wake you") { + t.Errorf("the send does not report the start it saw: %s", said) + } waitRequests(t, parser, 1) if got := recorder.seen(); len(got) != 1 { t.Fatalf("a member that is open was opened again: %v", got) diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index 15388939a7..12ca581556 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -154,8 +154,7 @@ func (a *Agent) writeTeamEvent(event teamEvent) { if err != nil || !role.wakes { continue } - switch event.state { - case teams.StateFinished, teams.StateFailed, teams.StateAsking: + if teamEventWakesManager(event.state, event.text) && !(role.root && event.state == teams.StateIdle) { // These wake the manager, so a manager nobody has open is opened // (team_wakewatch.go). a.rouseManager(profile, role, event.origin.provenance(role.key)) @@ -207,8 +206,16 @@ func (a *Agent) teamTurnEnded(ctx context.Context, hub *eventHub) { a.teamEventOwed(origin, teams.StateFailed, "failed: "+firstLineTeam(err.Error())) return } - if ctx.Err() != nil { - a.teamEventOwed(origin, teams.StateIdle, "stopped") + if door, stopped := stopCause(ctx); stopped { + // THE PERSON'S STOP IS SAID AS THE PERSON'S. The manager performed its + // own stop and knows of it; a turn the person ended is work the manager + // handed out ending without a report, which nothing else tells it + // ([teams.StoppedByPerson] wakes it, team_wakewatch.go). + text := "stopped" + if door == StopByPerson { + text = teams.StoppedByPerson + } + a.teamEventOwed(origin, teams.StateIdle, text) return } a.teamEventOwed(origin, teams.StateFinished, "finished") @@ -385,13 +392,23 @@ func teamBriefLine(role teamRole, entry teams.Entry) string { if text == "" { return "" } - return teamBriefWord + teamNumber(entry) + ": " + indentAfterFirst(cutRunesTeam(text, teamBriefText)) + word := teamBriefWord + if role.standby { + word = teamStandbyBriefWord + } + return word + teamNumber(entry) + ": " + indentAfterFirst(cutRunesTeam(text, teamBriefText)) } // teamBriefWord opens the brief's line, beside "◆ from manager" and // "◆ directive from manager". const teamBriefWord = "◆ brief from manager" +// teamStandbyBriefWord opens the start line of a member made on standby +// ([teams.Member.Standby]). The same text that is an assignment to a started +// member is a description of the role to this one, and a member told it under +// "brief" began the work nobody had asked for yet, so the line says which it is. +const teamStandbyBriefWord = "◆ your standing role from manager (what you are here for, not work to begin; work arrives as a directive)" + // teamBriefChangedLine is a member's brief replaced in place (teams' brief.go), // told to that member only: "◆ brief changed by the person #12: …". It is the // whole new brief, which stands in place of the one it was started with. diff --git a/internal/session/tools_team.go b/internal/session/tools_team.go index e4aad9632e..6ef42f6de4 100644 --- a/internal/session/tools_team.go +++ b/internal/session/tools_team.go @@ -91,7 +91,7 @@ var teamReadSchema = `{"type":"object","properties":{"handle":{"type":"string"," teamArgSchema + `},"required":["handle"],"additionalProperties":false}` const teamSendDescription = "Send a message to one member, to several (one message with every handle in to), or to everyone in the team. It arrives at the start of the member's next step, marked as from the manager, never as the person. " + - "kind note is information and waits for the member's next turn; kind directive is an instruction the member should follow unless the person said otherwise in its own conversation, and it starts an idle member's turn. " + + "kind note is information and waits for the member's next turn; kind directive is an instruction the member should follow unless the person said otherwise in its own conversation, and it starts an idle member's turn. The answer to a directive says, for each member, whether it started, is already in a turn, or did not start and why (the person paused it, the team is at its cap, it could not be opened); report work as under way only for a member the answer says started. " + "A member busy in a long tool call reads it when that returns; use team_stop to end its turn first." const teamSendSchema = `{"type":"object","properties":{"to":{"type":"string","description":"A member's handle, several separated by spaces, or everyone."},` + @@ -503,18 +503,27 @@ func (a *Agent) teamSendTool(ctx context.Context, args json.RawMessage) (said st } if kind == teams.KindDirective { // A DIRECTIVE WAKES, and a member nobody has open is opened so it can - // (team_wakewatch.go). The answer says what will happen and no more: - // whether the wake ran is the Traffic's to say, where the person reads it. - a.teamRouse(a.config.teamProfile(), team, role.wakes, local, id, prov) + // (team_wakewatch.go); a member the person paused is left as it is and + // the directive is held for it (team_pause.go). The answer then says + // what became of the directive for each member (team_sendoutcome.go). + profile := a.config.teamProfile() + ready, paused := splitPaused(team, local) + for _, member := range paused { + a.teamSay(profile, team.ID, teams.Entry{ + Kind: teams.KindEvent, From: teams.FromSystem, To: member.Handle, Member: member.Key, + State: teams.StateIdle, Text: teamHeldPausedText(member.Handle), Answers: id, Provenance: prov, + }) + } + a.teamRouse(profile, team, role.wakes, ready, id, prov) + sent := fmt.Sprintf("Sent a directive to %s.", who) if len(shared) > 0 { - return fmt.Sprintf("Sent a directive to %d member(s) of %q who report to you: %s. Not sent to %s: they report to another team's manager; send them a note.", - len(entry.Recipients()), team.Name, who, strings.Join(shared, ", ")), false, nil + sent = fmt.Sprintf("Sent a directive to %d member(s) of %q who report to you: %s. Not sent to %s: they report to another team's manager; send them a note.", + len(entry.Recipients()), team.Name, who, strings.Join(shared, ", ")) } if !role.wakes { - return fmt.Sprintf("Sent a directive to %s. This team's auto-wake is off, so a member that is idle reads it when its conversation next runs; a busy one at its next step.", who), false, nil + return sent + " This team's auto-wake is off, so a member that is idle reads it when its conversation next runs; a busy one at its next step.", false, nil } - return fmt.Sprintf("Sent a directive to %s. A member that is idle starts a turn on it now, and a busy one reads it at its next step. "+ - "Their replies and their finishing wake you when they arrive, so there is no need to wait or poll; the traffic shows each wake.", who), false, nil + return sent + " " + a.teamSendOutcome(ctx, profile, team, id, ready, paused), false, nil } return fmt.Sprintf("Sent a note to %s. It arrives at the start of their next step; a note wakes nobody, so a member that is idle reads it when its conversation next runs.", who), false, nil } diff --git a/internal/teams/digest.go b/internal/teams/digest.go index 51b6ec0939..f37a862037 100644 --- a/internal/teams/digest.go +++ b/internal/teams/digest.go @@ -13,6 +13,11 @@ import ( // Traffic. It is plain text cut to a character budget, and it is built only // from what the caller hands in, so the same inputs always give the same text. +// StoppedByPerson is the text of a member's turn-ending event when the person, +// and not its manager, stopped the turn. The manager is woken on it: work it +// handed out ended without a report, and only this line says so. +const StoppedByPerson = "stopped by the person" + // Member states a caller reports in [MemberState]. const ( StateRunning = "running" @@ -47,6 +52,7 @@ const ( digestFiles = 5 // the most files named per member digestQuestion = 160 // characters of a waiting question digestText = 200 // characters of one Traffic line's text + digestRole = 60 // characters of a member's role name ) // Digest is the text block for team's manager. states is keyed by conversation @@ -62,7 +68,7 @@ func Digest(team Team, states map[string]MemberState, recent []Entry, budget int } fmt.Fprintf(&head, "Team %q: %d members, %s.\n", team.Name, len(team.Members), manager) for _, m := range team.Members { - head.WriteString(memberLine(m, states[m.Key], m.Key == team.Manager)) + head.WriteString(memberLine(m, states[m.Key], m.Key == team.Manager, lastWord(m, recent))) head.WriteByte('\n') } text := head.String() @@ -106,12 +112,53 @@ func address(m Member) string { return "[" + m.Key + "]" } -func memberLine(m Member, s MemberState, manager bool) string { +// Words the digest says about a member beyond its state. They are the +// manager's only account of why handed-out work is not moving, so each names +// who caused it and what ends it. +const ( + // DigestPaused is a member the person paused ([Member.Paused]). + DigestPaused = "paused by the person; a directive waits until they resume it" + // DigestStandby is a member made without work that has not run yet + // ([Member.Standby]). + DigestStandby = "on standby; no work handed out yet" +) + +// lastWord is what the recent traffic says about how a member's last handed-out +// work went, "" when it says nothing worth a manager's attention: a directive +// the member has not started on, or a turn the person stopped. It reads only +// the lines the digest was given, newest first, and stops at the member's own +// newest line. +func lastWord(m Member, recent []Entry) string { + if m.Handle == "" { + return "" + } + for i := len(recent) - 1; i >= 0; i-- { + e := recent[i] + switch { + case e.From == m.Handle: + if e.Kind == KindEvent && e.State == StateIdle && e.Text == StoppedByPerson { + return "its last turn was " + StoppedByPerson + } + return "" + case e.Kind == KindEvent && e.From == FromManager && e.Member == m.Key && e.State == StateRunning: + // The wake line: the member started on what it was sent. + return "" + case e.Kind == KindDirective && e.From == FromManager && e.Addressed(m.Handle): + return "has not started on " + ThreadNumber(e.ID) + } + } + return "" +} + +func memberLine(m Member, s MemberState, manager bool, last string) string { var b strings.Builder b.WriteString("- " + address(m)) if manager { b.WriteString(" (manager)") } + if role := oneLine(m.Role); role != "" && !manager { + b.WriteString(", " + cutRunes(role, digestRole)) + } if title := oneLine(m.Word); title != "" { fmt.Fprintf(&b, " %q", title) } @@ -122,7 +169,19 @@ func memberLine(m Member, s MemberState, manager bool) string { if s.ReportsTo != "" && state == StateRunning { state = "busy for " + s.ReportsTo } + switch { + case manager: + case m.Paused && (state == StateIdle || state == "unknown"): + state = DigestPaused + case m.Paused: + state += ", " + DigestPaused + case m.Standby && s.SinceActive == 0 && (state == StateIdle || state == "unknown"): + state = DigestStandby + } b.WriteString(": " + state) + if last != "" && !manager { + b.WriteString(", " + last) + } if m.Independent { b.WriteString(", independent; notes only") } else if s.ReportsTo != "" { diff --git a/internal/teams/digest_test.go b/internal/teams/digest_test.go index 37b3e884c7..18780a5f13 100644 --- a/internal/teams/digest_test.go +++ b/internal/teams/digest_test.go @@ -1,6 +1,7 @@ package teams import ( + "encoding/json" "fmt" "strings" "testing" @@ -82,3 +83,76 @@ func TestDigestBudget(t *testing.T) { t.Fatalf("a members-only budget gave:\n%s", exact) } } + +// THE DIGEST SAYS WHY HANDED-OUT WORK IS NOT MOVING: a member the person paused, +// a directive nobody started on, a turn the person stopped, and a member that +// has not been given work yet. A manager told only "idle" hands the same work +// to the same member again. +func TestDigestSaysPausedStandbyAndUnstartedWork(t *testing.T) { + team := Team{Name: "harbor", Manager: "m", Members: []Member{ + {Key: "m", Handle: "boss", Word: "Harbor manager"}, + {Key: "a", Handle: "dev", Word: "Scaffold the app", Role: "macOS developer", Paused: true}, + {Key: "b", Handle: "review", Role: "Reviewer", Standby: true}, + {Key: "c", Handle: "design", Word: "Design the tiles"}, + {Key: "d", Handle: "docs", Word: "Write the guide"}, + }} + at := time.Date(2026, 11, 23, 22, 2, 0, 0, time.UTC) + recent := []Entry{ + {ID: "000000000021", At: at, Kind: KindDirective, From: FromManager, To: "docs", Text: "Write it."}, + {ID: "000000000022", At: at, Kind: KindDirective, From: FromManager, To: "dev", Text: "Build it."}, + {ID: "000000000023", At: at, Kind: KindEvent, From: FromSystem, To: "dev", Member: "a", State: StateIdle, Text: "held @dev: the person paused it", Answers: "000000000022"}, + {ID: "000000000024", At: at, Kind: KindEvent, From: FromManager, To: "docs", Member: "d", State: StateRunning, Text: "woke @docs", Answers: "000000000021"}, + {ID: "000000000025", At: at, Kind: KindEvent, From: "design", To: ToManager, Member: "c", State: StateIdle, Text: StoppedByPerson}, + } + states := map[string]MemberState{ + "m": {State: StateRunning}, + "a": {State: StateIdle, SinceActive: time.Hour}, + "b": {State: StateIdle}, + "c": {State: StateIdle, SinceActive: time.Minute}, + "d": {State: StateRunning, SinceActive: time.Minute}, + } + got := Digest(team, states, recent, 0) + for _, want := range []string{ + `- @boss (manager) "Harbor manager": running`, + `- @dev, macOS developer "Scaffold the app": ` + DigestPaused + `, has not started on #22, active 1h ago`, + `- @review, Reviewer: ` + DigestStandby, + `- @design "Design the tiles": idle, its last turn was ` + StoppedByPerson + `, active within the hour`, + `- @docs "Write the guide": running, active within the hour`, + } { + if !strings.Contains(got, want+"\n") { + t.Errorf("the digest lacks the line\n%s\nin\n%s", want, got) + } + } + // A member that ran is no longer on standby, whatever its record says. + states["b"] = MemberState{State: StateIdle, SinceActive: time.Minute} + if got := Digest(team, states, nil, 0); strings.Contains(got, DigestStandby) { + t.Errorf("a member that has run still reads as on standby:\n%s", got) + } +} + +func TestSetPausedAndSetRole(t *testing.T) { + file := &File{Teams: []Team{{ID: "t", Name: "harbor", Manager: "m", Members: []Member{{Key: "m", Handle: "boss"}, {Key: "a", Handle: "dev"}}}}} + if err := file.SetPaused("t", "a", true); err != nil || !file.Teams[0].Members[1].Paused { + t.Fatalf("pause: %v, %+v", err, file.Teams[0].Members[1]) + } + if err := file.SetPaused("t", "a", false); err != nil || file.Teams[0].Members[1].Paused { + t.Fatalf("resume: %v, %+v", err, file.Teams[0].Members[1]) + } + if err := file.SetPaused("t", "m", true); err == nil { + t.Fatal("the manager was paused") + } + if err := file.SetPaused("t", "x", true); err == nil { + t.Fatal("a stranger was paused") + } + if err := file.SetRole("t", "a", " macOS\n developer "); err != nil || file.Teams[0].Members[1].Role != "macOS developer" { + t.Fatalf("role: %v, %q", err, file.Teams[0].Members[1].Role) + } + raw, err := json.Marshal(Member{Key: "a", Paused: true, Role: "Reviewer", Standby: true}) + if err != nil { + t.Fatal(err) + } + var back Member + if err := json.Unmarshal(raw, &back); err != nil || !back.Paused || !back.Standby || back.Role != "Reviewer" || len(back.extra) != 0 { + t.Fatalf("a member did not survive its own JSON: %+v, %v (%s)", back, err, raw) + } +} diff --git a/internal/teams/member_json.go b/internal/teams/member_json.go index 90d442a15d..ebddc362d3 100644 --- a/internal/teams/member_json.go +++ b/internal/teams/member_json.go @@ -18,7 +18,7 @@ type wireMember struct { var knownMemberFields = map[string]bool{ "sync_id": true, "key": true, "file": true, "where": true, "word": true, "handle": true, "home": true, "independent": true, "joined_at": true, "start_id": true, "start_origin": true, "started": true, "handle_by": true, "start_entry": true, "briefs": true, - "factory_stage": true, "factory_brief": true, + "factory_stage": true, "factory_brief": true, "paused": true, "role": true, "standby": true, } func (m *Member) UnmarshalJSON(raw []byte) error { diff --git a/internal/teams/teams.go b/internal/teams/teams.go index 65e80921df..c6c51eb1ad 100644 --- a/internal/teams/teams.go +++ b/internal/teams/teams.go @@ -75,6 +75,22 @@ type Member struct { // Empty on every membership written before they were kept. FactoryStage bool `json:"factory_stage,omitempty"` FactoryBrief string `json:"factory_brief,omitempty"` + // Paused says the person paused this member in this team ([File.SetPaused]). + // Team traffic starts no turn for a paused member: a directive waits on the + // log, undelivered, and starts the member's turn when the person resumes it. + // It lives here, and not in an interface's own file, so the session that + // would wake the member, the manager's view of its team and every interface + // read one answer. + Paused bool `json:"paused,omitempty"` + // Role is the short name of what this member is in the team for, "macOS + // developer", as the person or the proposal gave it. It is told to the + // member in its role note and shown to the manager beside the handle. Empty + // on a membership nobody gave one. + Role string `json:"role,omitempty"` + // Standby says this membership was made without work to start on: its start + // line is a standing description of the role, read at the member's first + // turn, and that line starts no turn. The first directive does. + Standby bool `json:"standby,omitempty"` // Unknown membership fields survive whole-file updates from this build. extra map[string]json.RawMessage } @@ -627,6 +643,41 @@ func (f *File) SetHandle(id, key, h string) error { return nil } +// SetPaused pauses or resumes the member with key in team id ([Member.Paused]). +// The manager is not paused: the person talks to it directly. +func (f *File) SetPaused(id, key string, paused bool) error { + i, err := f.at(id) + if err != nil { + return err + } + t := &f.Teams[i] + j := t.member(key) + if j < 0 { + return fmt.Errorf("%s is not in team %s", key, t.Name) + } + if paused && t.Manager == key { + return fmt.Errorf("the manager of %s is not paused; stop its turn instead", t.Name) + } + t.Members[j].Paused = paused + return nil +} + +// SetRole names what the member with key in team id is there for +// ([Member.Role]); "" clears it. +func (f *File) SetRole(id, key, role string) error { + i, err := f.at(id) + if err != nil { + return err + } + t := &f.Teams[i] + j := t.member(key) + if j < 0 { + return fmt.Errorf("%s is not in team %s", key, t.Name) + } + t.Members[j].Role = oneLine(role) + return nil +} + // ── REPAIRS ───────────────────────────────────────────────────────────────── // tidy puts a list in order, in place, and reports whether it changed From e4aa7464f3c6ae19988bd3f05d6739287f4d817f Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:09:11 -0500 Subject: [PATCH 02/37] docs: change entry for the crew hand-off outcome (#2897) Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2897-crew-handoff-outcome.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 docs/changes/unreleased/2897-crew-handoff-outcome.md diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md new file mode 100644 index 0000000000..26109e50a0 --- /dev/null +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -0,0 +1,22 @@ +--- +kind: changed +title: A crew manager is told what became of each hand-off, and a paused member holds its work +pr: 2897 +surface: [engine, app, chat] +invalidates: + - "team_send answered every directive with \"A member that is idle starts a turn on it now, and a busy one reads it at its next step\" whatever happened. It now waits up to four seconds on the team's traffic and says for each member one of: \"@web started a turn on it.\", \"@web is in a turn and reads it at the next step.\", \"@web did NOT start: .\", or \"@web has shown no sign of starting yet; team_status says whether it did.\" Where a member did not start, the answer also tells the manager not to tell the person the work is under way." + - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A paused member is not opened, roused or woken; the directive stays undelivered and starts the member's turn when the person resumes it. The app carries an earlier build's pause onto the team's record once." + - "A directive to a paused member wrote \"woke @x\" then \"stopped\" to the traffic. It now writes one line from system, \"held @x: the person paused it; it starts on this when they resume it\", answering the directive, and Resume writes an event from you with the text \"resumed\"." + - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A turn the person stops now ends \"stopped by the person\" (teams.StoppedByPerson); it wakes the manager and is delivered as \"@x's turn was stopped by the person before it finished; it reported nothing, so what you handed it is not done\". A stop by the manager's team_stop still ends \"stopped\" and still wakes nobody. The global manager is not woken by either." + - "team_status and the manager's digest gave a member's state as running, asking, idle or failed only. A member's line may now read \"paused by the person; a directive waits until they resume it\" or \"on standby; no work handed out yet\", carries the member's role after its handle (\"- @dev, macOS developer\"), and may add \"has not started on #22\" or \"its last turn was stopped by the person\"." + - "Accepting a crew proposal (crews.create from proposal) started every helper at once on its brief. Each helper now joins on standby (teams.Member.Standby): its start line starts no turn, the traffic says \"opened @x on standby; it starts on its manager's first directive\", and the first directive hands it that line marked \"◆ your standing role from manager (what you are here for, not work to begin; work arrives as a directive)\" in place of \"◆ brief from manager\". team_start and members.start still start a member on its brief at once." + - "A proposal's role name was kept only as an app-layer role with no instructions, so it reached neither the member nor the manager. It is now also the team's record (teams.Member.Role, File.SetRole): the member's team note says \"Your role in this team: .\", and the manager's roster shows the role in place of the title. members.role writes it too." + - "The crew proposal prompt asked for each helper's brief as the \"whole assignment\". It now asks for \"what this helper is responsible for\", and says an accepted crew joins on standby." + - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\"." +--- + +A manager model reports what its tools tell it. In the measured run a member the +person had paused was handed two directives, the tool said both had started, and +the manager told the person so twice before finding an empty folder. Creating +that crew had also started every helper on its line of the proposal, one of which +began work nobody had asked for. From 12df45be1e55bfe75f40d6bc81b153db385936fc Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:42:58 -0500 Subject: [PATCH 03/37] teams: review round 1 repairs - A stopped turn is said as the person's only when the person's door ended a turn that team traffic started and no manager's stop is on the log for it. The app, the terminal and a remote window all perform a manager's team_stop through the person's door, which made the manager's own stop wake it as the person's; a turn the person opened and stopped tells the manager nothing. - Standby and a held directive outlive a restart: a standby member starts reading just before its start line however old that is, and a hold writes the member's cursor down when there was none. - The pause is read afresh before a member's wake hands anything over, so a directive sent in the second after the Pause is held. - A pause holds the conversation in every team it is a member of, and the app no longer stops a turn the person's own words opened on a paused member. - Standby is cleared when the start line is handed over, so team_status shows "on standby" until then (it never showed before: a journal's age is never zero). "has not started on #N" is said only of a member that is not in a turn. - The delivery card reads the standing role line; the roster shows a role in parentheses; the traffic line prefixes are one set of constants. - With auto-wake off no hold is promised for a paused member. - The app's pause carry-over clears a flag only once it is carried or its crew or member is gone; standby applies only to a start the person's proposal made; a renamed role is renamed on the team record; a manager, and a manager's seat in All teams, carry no pause or standby. Co-Authored-By: Claude Fable 5.2 --- cmd/codeaf/appcrewlayer.go | 28 ++- cmd/codeaf/appcrewmembers.go | 14 +- cmd/codeaf/appcrews.go | 5 +- cmd/codeaf/appwakes.go | 17 +- .../unreleased/2897-crew-handoff-outcome.md | 13 +- internal/manual/chat/team-manager.md | 48 ++-- internal/session/hermetic_test.go | 2 + internal/session/team.go | 27 ++- internal/session/team_pause.go | 138 ++++++++++- internal/session/team_pause_test.go | 214 +++++++++++++++++- internal/session/team_sendoutcome.go | 60 +++-- internal/session/team_wakewatch.go | 22 +- internal/session/team_wakewatch_test.go | 12 +- internal/session/teamevent.go | 6 +- internal/session/teamshape.go | 2 + internal/session/tools_team.go | 31 ++- internal/teams/digest.go | 33 ++- internal/teams/digest_test.go | 20 +- internal/teams/root.go | 2 + internal/teams/teams.go | 48 +++- 20 files changed, 621 insertions(+), 121 deletions(-) diff --git a/cmd/codeaf/appcrewlayer.go b/cmd/codeaf/appcrewlayer.go index 57b7af8f5e..3c5b6b2b46 100644 --- a/cmd/codeaf/appcrewlayer.go +++ b/cmd/codeaf/appcrewlayer.go @@ -240,9 +240,11 @@ func (b *appBackend) crewPaused(agent string) bool { } // movePausesToStore carries a pause an earlier build kept in this layer into -// the team's own record, once, so a member paused before the update stays -// paused where the engine reads it. A pause that cannot be carried (its crew -// or member is gone) is dropped with the rest of that record. +// the team's own record, so a member paused before the update stays paused +// where the engine reads it. A flag is cleared here only once it is on the +// team's record, or its crew or member is gone; one that could not be carried +// (the store could not be read or written) stays, and the next launch tries +// again. func (b *appBackend) movePausesToStore() { var paused []string _ = b.crewLayer().read(func(f *appCrewLayerFile) { @@ -255,21 +257,35 @@ func (b *appBackend) movePausesToStore() { if len(paused) == 0 { return } + var settled []string for _, key := range paused { crew, agent, ok := strings.Cut(key, "/") if !ok { + settled = append(settled, key) continue } t, _, err := b.crewTeam(crew) if err != nil { + var wire *appwire.Error + if errors.As(err, &wire) && wire.Code == appwire.CodeNotFound { + settled = append(settled, key) + } + continue + } + m, found := b.crewMemberOf(t, agent) + if !found || m.Key == t.Manager { + settled = append(settled, key) continue } - if m, found := b.crewMemberOf(t, agent); found { - _ = b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, true) }) + if err := b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, true) }); err == nil { + settled = append(settled, key) } } + if len(settled) == 0 { + return + } _ = b.crewLayer().write(func(f *appCrewLayerFile) error { - for _, key := range paused { + for _, key := range settled { if m := f.Members[key]; m != nil { m.Paused = false } diff --git a/cmd/codeaf/appcrewmembers.go b/cmd/codeaf/appcrewmembers.go index 2f775f26d0..82ba9c6004 100644 --- a/cmd/codeaf/appcrewmembers.go +++ b/cmd/codeaf/appcrewmembers.go @@ -264,6 +264,9 @@ func (b *appBackend) memberMove(t teamstore.Team, m teamstore.Member, agent, to err := b.crewEdit(func(f *teamstore.File) error { moved := m moved.Home, moved.Started = false, false + // Its start line stays on the crew it leaves, so it is not waiting on + // one here. A pause goes with it: the person paused the member. + moved.Standby = false if err := f.AddMember(to, moved); err != nil { return err } @@ -278,7 +281,7 @@ func (b *appBackend) memberMove(t teamstore.Team, m teamstore.Member, agent, to err = b.crewLayer().write(func(f *appCrewLayerFile) error { old := f.member(t.ID, agent) next := f.member(to, agent) - next.Role, next.Paused = old.Role, old.Paused + next.Role = old.Role next.Was = &appwire.MemberWas{Crew: t.ID, Role: old.Role, At: b.now()} delete(f.Members, appMemberKey(t.ID, agent)) return nil @@ -458,6 +461,15 @@ func (b *appBackend) RoleUpdate(id string, name, instructions, model *string) (a return appwire.Role{}, appEngineError(err) } for _, c := range copies { + // A renamed role is renamed on each member's team record too, where + // the member's session and its manager read it. + if name != nil { + if t, _, err := b.crewTeam(c.Crew); err == nil { + if m, ok := b.crewMemberOf(t, c.Agent); ok && m.Role != role.Name { + _ = b.crewEdit(func(f *teamstore.File) error { return f.SetRole(c.Crew, m.Key, role.Name) }) + } + } + } send := role if !told { send.Instructions = "" diff --git a/cmd/codeaf/appcrews.go b/cmd/codeaf/appcrews.go index 1598b0c554..2d33e609fa 100644 --- a/cmd/codeaf/appcrews.go +++ b/cmd/codeaf/appcrews.go @@ -1024,7 +1024,10 @@ func (b *appBackend) crewStart(t teamstore.Team, manager teamstore.Member, e tea member.ReportsTo = pending.ReportsTo // What the start was made with: the role's name, and whether the member // waits for a directive rather than beginning on this line. - member.Role, member.Standby = pending.RoleName, pending.Standby + // Standby is what accepting a proposal asks for, and only that: a pending + // start left behind by a proposal that failed half-way must not put a + // member the manager starts later under the same handle on standby. + member.Role, member.Standby = pending.RoleName, pending.Standby && createdBy == appwire.CreatedByPerson // THE MEMBERSHIP KEEPS THE ID OF THE LINE THAT MADE IT, so its brief is // that line by identity and survives a rename or a handle reused later. // Only a manager's start of this crew is recorded; the terminal's start diff --git a/cmd/codeaf/appwakes.go b/cmd/codeaf/appwakes.go index 7dd7d1e6c6..c93ab536cc 100644 --- a/cmd/codeaf/appwakes.go +++ b/cmd/codeaf/appwakes.go @@ -20,9 +20,10 @@ import ( // message gets back, and the terminal draws it as any other turn. The app does the same: a woken turn is a turn on // the wire, with no message of the person's in front of it. // -// A MEMBER THE PERSON PAUSED does not take one. The crew's app layer keeps the -// pause (appcrewlayer.go), and a turn woken while it holds is stopped at once; -// what woke it is still waiting on the crew's log for its next turn. +// A MEMBER THE PERSON PAUSED does not take one. The pause is the team's record +// (teamstore's Member.Paused) and the member's session holds team traffic +// before a turn starts; a turn woken some other way while it holds is stopped +// here at once. A turn the person's own words opened is not. // appWakeDoor is a conversation held in this process that hands over the // turns it starts itself. @@ -159,9 +160,13 @@ func (b *appBackend) wokenTurn(a *appAgent, live *appLive, elsewhere appTurnElse live.msgBase, live.noteBase = msgs, notes }) } - if b.crewPaused(id) { - // The person paused this member: the turn ends before it does anything, - // and the line that woke it stays on the crew's log. + if elsewhere.said == "" && b.crewPaused(id) { + // The person paused this member, and nothing they said opened this + // turn. The engine holds team traffic for a paused member before a + // turn starts (internal/session's team_pause.go), so what reaches here + // is another wake: a background process ending, a task landing. It ends + // before it does anything. A turn the person's own words opened, from + // any window, is theirs and runs. live.conn.Conv.Interrupt() } live.box.Event(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 26109e50a0..4f12d36fbe 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -4,14 +4,15 @@ title: A crew manager is told what became of each hand-off, and a paused member pr: 2897 surface: [engine, app, chat] invalidates: - - "team_send answered every directive with \"A member that is idle starts a turn on it now, and a busy one reads it at its next step\" whatever happened. It now waits up to four seconds on the team's traffic and says for each member one of: \"@web started a turn on it.\", \"@web is in a turn and reads it at the next step.\", \"@web did NOT start: .\", or \"@web has shown no sign of starting yet; team_status says whether it did.\" Where a member did not start, the answer also tells the manager not to tell the person the work is under way." - - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A paused member is not opened, roused or woken; the directive stays undelivered and starts the member's turn when the person resumes it. The app carries an earlier build's pause onto the team's record once." + - "team_send answered every directive with \"A member that is idle starts a turn on it now, and a busy one reads it at its next step\" whatever happened. It now waits up to four seconds on the team's traffic and says for each member one of: \"@web started a turn on it.\", \"@web is in a turn and reads it at the next step.\", \"@web did NOT start: .\", \"@web is waiting on the person and reads it once they answer.\", or \"@web has shown no sign of starting yet; team_status says whether it did.\" Where a member did not start, the answer also tells the manager not to tell the person the work is under way." + - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A member paused in any of its teams is not opened or woken by any team's traffic (File.PausedAnywhere); the directive stays undelivered and starts the member's turn when the person resumes it, including after a restart. The app carries an earlier build's pause onto the team's record once." - "A directive to a paused member wrote \"woke @x\" then \"stopped\" to the traffic. It now writes one line from system, \"held @x: the person paused it; it starts on this when they resume it\", answering the directive, and Resume writes an event from you with the text \"resumed\"." - - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A turn the person stops now ends \"stopped by the person\" (teams.StoppedByPerson); it wakes the manager and is delivered as \"@x's turn was stopped by the person before it finished; it reported nothing, so what you handed it is not done\". A stop by the manager's team_stop still ends \"stopped\" and still wakes nobody. The global manager is not woken by either." - - "team_status and the manager's digest gave a member's state as running, asking, idle or failed only. A member's line may now read \"paused by the person; a directive waits until they resume it\" or \"on standby; no work handed out yet\", carries the member's role after its handle (\"- @dev, macOS developer\"), and may add \"has not started on #22\" or \"its last turn was stopped by the person\"." - - "Accepting a crew proposal (crews.create from proposal) started every helper at once on its brief. Each helper now joins on standby (teams.Member.Standby): its start line starts no turn, the traffic says \"opened @x on standby; it starts on its manager's first directive\", and the first directive hands it that line marked \"◆ your standing role from manager (what you are here for, not work to begin; work arrives as a directive)\" in place of \"◆ brief from manager\". team_start and members.start still start a member on its brief at once." - - "A proposal's role name was kept only as an app-layer role with no instructions, so it reached neither the member nor the manager. It is now also the team's record (teams.Member.Role, File.SetRole): the member's team note says \"Your role in this team: .\", and the manager's roster shows the role in place of the title. members.role writes it too." + - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A turn that team traffic started and the person then stops now ends \"stopped by the person\" (teams.StoppedByPerson); it wakes the manager and is delivered as \"@x's turn on what you handed it was stopped by the person before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask.\" A turn the person opened with their own message and then stopped, and a stop by the manager's team_stop (whichever interface performs it), still end \"stopped\" and still wake nobody. The global manager is not woken by either." + - "team_status and the manager's digest gave a member's state as running, asking, idle or failed only. A member's line may now read \"paused by the person; it starts nothing until they resume it\" or \"on standby; no work handed out yet\", carries the member's role after its handle (\"- @dev, macOS developer\"), and may add \"has not started on #22\" (only for a member that is not in a turn) or \"its last turn was stopped by the person\"." + - "Accepting a crew proposal (crews.create from proposal) started every helper at once on its brief. Each helper now joins on standby (teams.Member.Standby, cleared by the member's session once its start line is handed to it): its start line starts no turn, however much later the first directive comes, the traffic says \"opened @x on standby; it starts on its manager's first directive\", and the first directive hands it that line marked \"◆ your standing role from manager (what you are here for, not work to begin; work arrives as a directive)\" in place of \"◆ brief from manager\". team_start and members.start still start a member on its brief at once." + - "A proposal's role name was kept only as an app-layer role with no instructions, so it reached neither the member nor the manager. It is now also the team's record (teams.Member.Role, File.SetRole): the member's team note says \"Your role in this team: .\", and the manager's roster shows the role in place of the title (\"@dev (macOS developer)\"). members.role and a role's rename write it too." - "The crew proposal prompt asked for each helper's brief as the \"whole assignment\". It now asks for \"what this helper is responsible for\", and says an accepted crew joins on standby." + - "The desktop app stopped every turn it had not started itself on a paused member, including one the person opened by typing to that member from another window. It now leaves a turn the person's own words opened alone, and still stops any other wake (a background process ending, a task landing)." - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\"." --- diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 5b62b44880..3fdce12fca 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -333,8 +333,9 @@ A deliberate message jump opens the activity and tool-call groups that contain t A member of a team that has a manager tells the manager, through the traffic, three things it would never write in a message: -- `finished` when a turn ends, `stopped` when its manager stopped it, `stopped by the person` - when you did, and `failed: ` with the error's first line when a turn ends on one; +- `finished` when a turn ends, `stopped` when its manager or codeaf itself ended it or you + stopped a turn you had started yourself, `stopped by the person` when you stopped a turn the + team's traffic had started, and `failed: ` with the error's first line when a turn ends on one; - when it starts waiting on you: the permission line for a permission prompt (`needs your ok to run bash`), or `asks: ` and the question for anything else; - `no longer waiting` when the last of those questions comes down. @@ -560,8 +561,8 @@ working, that is straight away. When it is idle, it depends on the kind of messa start (see **Pausing a crew member**). - A **note** wakes nobody. An idle member reads it when it next runs, for whatever reason. - A member's **reply to the manager** (`team_post` to the manager), and a member finishing - without a reply, failing, starting to wait on you, or having its turn stopped by you, start - an idle manager's turn. A reply + without a reply, failing, starting to wait on you, or having a turn the team started stopped + by you, start an idle manager's turn. A reply and the end of the same turn are one wake, even if the ending arrives after the manager already ran. Replies arriving within a few seconds are gathered into one turn. @@ -572,8 +573,13 @@ the app and run there. The manager is told what became of each directive in `team_send`'s answer, which waits up to four seconds to see it: `@web started a turn on it`, `@web is in a turn and reads it at the -next step`, `@web did NOT start:` with the reason, or `@web has shown no sign of starting -yet`. A manager reports work as under way only where the answer says a member started. +next step`, `@web is waiting on the person and reads it once they answer`, `@web did NOT +start:` with the reason, or `@web has shown no sign of starting yet`. A manager reports work +as under way only where the answer says a member started. + +When you stop a member's turn that the team's traffic had started, its manager is woken and +told the work is not done, that you chose to stop it, and not to hand it out again unless you +ask. Stopping a turn you started by typing to the member tells the manager nothing. ## could not wake ◆ — a wake that cannot be delivered is kept, not dropped @@ -600,27 +606,29 @@ The ten wakes count ten replies when each member turn replies and then finishes. ## Pausing a crew member — pause, resume, why a directive did not start, held -You can pause a member of a crew in the desktop app: **Pause** in the member's menu, and -**Resume** to lift it. A pause stops the member's current turn and is kept on the team's own -record, so the member's session, its manager and every window read the same answer. The -manager itself cannot be paused; stop its turn instead. +You can pause a member of a crew in the desktop app: **Pause** on its row in the Members tab +or in the member's menu, and **Resume** to lift it. A pause stops the member's current turn +and is kept on the team's own record, so the member's session, its manager and every window +read the same answer. The manager itself cannot be paused; stop its turn instead. -While a member is paused, team traffic starts no turn for it: +While a member is paused, team traffic starts no turn for it, in any crew it belongs to: - A directive waits on the crew's log, unread. The traffic says - `held @web: the person paused it; it starts on this when they resume it`, once, at the send. + `held @web: the person paused it; it starts on this when they resume it`, once per directive. - `team_send` tells the manager `@web did NOT start` with the same reason, and that only you can resume it. The manager cannot lift a pause. -- `team_status` shows the member as `paused by the person; a directive waits until they +- `team_status` shows the member as `paused by the person; it starts nothing until they resume it`, with `has not started on #22` when a directive is waiting. - codeaf does not open the member's conversation for traffic it would only hold. -**Resume** writes `resumed` to the crew's log, and the directive that waited starts the -member's turn within a second or two. Nothing is lost and nothing is delivered twice. +**Resume** writes `resumed` to the crew's log, and a directive that waited starts the member's +turn within a second or two, including after codeaf was closed in between. With the team's +auto-wake off, a resumed member reads it at its next turn like any other message. Your own words are not held: typing into a paused member's conversation starts its turn, and -that turn reads what was waiting. A pause made by an earlier version of the app is carried -onto the team's record the first time the updated app opens. +that turn reads what was waiting. Anything else that would wake it, such as one of its +background processes ending, is stopped at once in the desktop app. A pause made by an earlier +version of the app is carried onto the team's record the first time the updated app opens. ## A new crew's members wait on standby — why nobody started after Make the crew @@ -629,11 +637,13 @@ Each helper is created with its handle and role, and nobody begins work: the pro describes who the crew is, and accepting it is not a request to start. - The traffic says `opened @web on standby; it starts on its manager's first directive`. -- `team_status` shows `on standby; no work handed out yet` until the member first runs. +- `team_status` shows `on standby; no work handed out yet` until the member's first turn. - The line the member was made with is handed to it at its first turn marked `◆ your standing role from manager`, together with the directive that started that turn. - A member's role name is told to it in its team note (`Your role in this team: …`) and shown - to the manager beside the handle. + to the manager beside the handle, `@web (Frontend developer)`. +- Standby lasts across restarts: however much later the first directive comes, the member is + still handed its role line with it. The first work starts when you ask the manager for it and it sends a directive. A member the manager starts itself with `team_start`, or one you add with a brief from the crew's page, diff --git a/internal/session/hermetic_test.go b/internal/session/hermetic_test.go index 29d7f35ff0..7f2edc6846 100644 --- a/internal/session/hermetic_test.go +++ b/internal/session/hermetic_test.go @@ -71,7 +71,9 @@ func runTests(m *testing.M) int { // could start and assert nothing about the outcome, so the package waits a // quarter of a second; the tests that do read the outcome take their own // wait ([fastTeamWake]). + teamWatchClockMu.Lock() teamSendSettle, teamSendLook = 250*time.Millisecond, 5*time.Millisecond + teamWatchClockMu.Unlock() real := home.InheritedDir() before := journalTrees(real) // AND THE CHECKOUT THIS BINARY IS RUNNING IN, for the same reason and at the diff --git a/internal/session/team.go b/internal/session/team.go index 49ebee1ee8..fc199334b5 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -469,6 +469,18 @@ func rolesFor(file *teams.File, keys []string, d teams.Defaults) []teamRole { } roles = append(roles, role) } + // A PAUSE HOLDS THE CONVERSATION IN EVERY TEAM. The person paused the + // member, not one of its memberships, and an interface that finds the + // member paused ends a turn another team's traffic started; so no team's + // traffic starts one. A team this conversation manages is not held. + for _, role := range roles { + if role.paused { + for i := range roles { + roles[i].paused = !roles[i].manager + } + break + } + } return roles } @@ -742,6 +754,10 @@ func (a *Agent) teamNewsLocked(profile string, roles []teamRole) string { if teamWakes(role, entry) { save = true } + if role.standby && entry.Kind == teams.KindStart && entry.ID == role.startID { + // Its start line is being handed over: standby is over. + a.teamStandbyOver(profile, role) + } if !role.joinedAt.IsZero() && entry.At.Before(role.joinedAt) && !a.teamOwnStart(role, entry) { continue } @@ -797,6 +813,14 @@ func (a *Agent) teamOwnStart(role teamRole, entry teams.Entry) bool { // cursor for. A fresh conversation skips the team's earlier history except // its own start, whose brief is handed over as the manager's words. func (a *Agent) firstTeamCursor(profile string, role teamRole) string { + // A MEMBER ON STANDBY HAS NOT BEEN HANDED ITS START LINE, however long ago + // it was written and however many times its conversation has been opened + // since: it takes no turn until its manager's first directive, so no + // boundary has saved a cursor for it. It starts just before that line, and + // reads it and everything sent to it since. + if role.standby && !role.manager && role.startID != "" { + return teamCursorBefore(role.startID) + } tail, err := teams.ReadTraffic(profile, role.id, "", teamFirstLook) if err != nil { return teamLogStart @@ -1249,6 +1273,7 @@ func (a *Agent) teamDigestWithSharing(profile string, sharing bool) string { log, _ := teams.ReadHistory(profile, role.id, teamStateLook, sharing) states := memberStates(team, keys, now, log, &a.team.journals) markShared(file, team, states) + markPaused(file, team, states) parts = append(parts, teams.Digest(team, states, recentOf(log), teamDigestBudget)) } return strings.TrimSpace(strings.Join(parts, "\n\n")) @@ -1734,7 +1759,7 @@ func teamRoster(role teamRole, file *teams.File) string { // The role is what the manager chooses a member by, so it comes before // the title, which is only the start of whatever the member was first told. if roleName := strings.TrimSpace(member.Role); roleName != "" { - who += ", " + cutRunesTeam(roleName, teamRosterWord) + who += " (" + cutRunesTeam(roleName, teamRosterWord) + ")" } else if word := strings.TrimSpace(member.Word); word != "" { who += " (" + cutRunesTeam(word, teamRosterWord) + ")" } diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 7e7faabe24..0893be8d64 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -14,8 +14,14 @@ package session // for a paused membership: the watch remembers that something asked for one, // leaves the lines undelivered, and starts the turn on the first look that // finds the pause lifted. A conversation that is not open is not opened for -// traffic it would only hold ([TeamOpenPending]), and the writer's rouse -// leaves it closed ([Agent.teamRouse]). +// traffic it would only hold ([TeamOpenPending]), and `team_send` does not ask +// for it to be opened. Something else may still open it (a question's answer, +// a wake the retry queue kept); it is then open and held, which costs nothing. +// +// A PAUSE IS THE PERSON'S WORD ABOUT THE CONVERSATION, so it holds in every +// team the conversation is a member of ([teams.File.PausedAnywhere]), not only +// the one it was pressed in: an interface that finds the member paused ends a +// turn it did not start, whichever team's traffic began it. // // THE SENDER SAYS SO, ONCE, AT THE SEND. `team_send` reads the same record and // answers that the member is paused, and writes the one traffic line that says @@ -26,7 +32,12 @@ package session // person typing into a paused member's conversation starts its turn, and that // turn reads what was waiting. -import "github.com/Agent-Field/codeaf/internal/teams" +import ( + "strings" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/teams" +) // teamPausedWhy is why a paused member did not start, in the words the manager // and the traffic are both given. @@ -34,7 +45,9 @@ const teamPausedWhy = "the person paused it; it starts on this when they resume // teamHeldPausedText is the traffic line for a directive a paused member was // sent: "held @mac-dev: the person paused it; …". -func teamHeldPausedText(handle string) string { return "held @" + handle + ": " + teamPausedWhy } +func teamHeldPausedText(handle string) string { + return teamHeldPrefix + "@" + handle + ": " + teamPausedWhy +} // teamPauseHoldLocked reports whether role is paused, and remembers that its // traffic asked for a turn when asked is true. The caller holds a.team.mu. @@ -48,6 +61,15 @@ func (a *Agent) teamPauseHoldLocked(role teamRole, asked bool) bool { w.pausedHeld = map[string]bool{} } w.pausedHeld[role.id] = true + // THE HOLD OUTLIVES THIS PROCESS. A member that never took a turn in + // this team has no cursor written down, and one opened later would + // start reading after the line it is held on. So the place it would + // have started from is written now, once. + a.readTeamCursorsLocked() + if _, known := a.team.cursors[role.id]; !known { + a.team.cursors[role.id] = a.firstTeamCursor(a.config.teamProfile(), role) + a.saveTeamCursorsLocked() + } } return true } @@ -95,3 +117,111 @@ func (a *Agent) teamStandbySay(profile string, role teamRole) { State: teams.StateIdle, Text: text, }) } + +// teamStandbyOver clears a member's standby once its start line is handed to +// it ([teams.Member.Standby]), off the boundary's lock. A write that fails +// leaves the record saying standby a little longer; the line was delivered. +func (a *Agent) teamStandbyOver(profile string, role teamRole) { + id, key := role.id, role.key + guard.Go("team standby over", func() { + _ = teams.UpdateOpen(profile, func(file *teams.File) error { return file.SetStandby(id, key, false) }) + }) +} + +// markPaused marks each member of team the person paused in another of its +// teams ([teams.MemberState].Paused), so this team's manager reads why its +// directive does not start. +func markPaused(file *teams.File, team teams.Team, states map[string]teams.MemberState) { + if file == nil { + return + } + for _, member := range team.Members { + if member.Key == team.Manager || member.Paused { + continue + } + if _, paused := file.PausedAnywhere(member.Key); paused { + state := states[member.Key] + state.Paused = true + states[member.Key] = state + } + } +} + +// teamAt is members as their handles, "@web, @api". +func teamAt(members []teams.Member) string { + var out []string + for _, member := range members { + out = append(out, "@"+member.Handle) + } + return strings.Join(out, ", ") +} + +// teamStoppedByPersonLine is what a manager is told, after the member's +// handle, when the person stopped a turn the manager's traffic had started. +const teamStoppedByPersonLine = "'s turn on what you handed it was " + teams.StoppedByPerson + " before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask." + +// teamPausedSince reads the teams file afresh and returns the roles among +// roles that are still not paused, remembering a hold for each that now is. +func (a *Agent) teamPausedSince(profile string, roles []teamRole) []teamRole { + a.team.mu.Lock() + defer a.team.mu.Unlock() + fresh := map[string]teamRole{} + for _, role := range a.teamRolesLocked(profile) { + fresh[role.id] = role + } + kept := roles[:0:0] + for _, role := range roles { + now, still := fresh[role.id] + if !still { + continue + } + if a.teamPauseHoldLocked(now, true) { + continue + } + kept = append(kept, now) + } + return kept +} + +// teamStoppedByPerson reports whether a stopped turn's ending is said as the +// person's ([teams.StoppedByPerson]), which wakes the manager: the person +// stopped work that team traffic had started, and nothing else tells the +// manager it ended without a report. +// +// THREE THINGS MUST HOLD. The cancel came through the person's door. The turn +// was not opened by the person's own message: a person who types into a member +// and stops it has stopped their own request, which the manager never handed +// out. And no manager's stop is on the log for this turn: an interface holding +// the member performs the manager's `team_stop` through the same door as the +// person's stop key (the app, the terminal, a remote window), usually before +// the member's own session reads the line, so the door alone would call the +// manager's stop the person's. +func (a *Agent) teamStoppedByPerson(door StopDoor, origin turnOrigin) bool { + if door != StopByPerson || origin.turn != "" { + return false + } + profile := a.config.teamProfile() + if profile == "" { + return false + } + a.mu.Lock() + turnAt := a.teamTurnAt + a.mu.Unlock() + for _, role := range a.teamRoles() { + if !role.managed || role.manager || role.handle == "" { + continue + } + tail, err := teams.ReadTraffic(profile, role.id, "", teamFirstLook) + if err != nil { + continue + } + for _, entry := range tail { + if entry.Kind == teams.KindStop && entry.From == teams.FromManager && + (entry.Member == role.key || entry.Member == "" && entry.To == role.handle) && + !entry.At.Before(turnAt) { + return false + } + } + } + return true +} diff --git a/internal/session/team_pause_test.go b/internal/session/team_pause_test.go index aa3c098da2..a13c503f5a 100644 --- a/internal/session/team_pause_test.go +++ b/internal/session/team_pause_test.go @@ -29,7 +29,6 @@ func TestTeamDirectiveToAPausedMemberWaitsForResume(t *testing.T) { webCalls := oneAnswer(1) teamAgent(t, fixture, fixture.web, webCalls, nil) - begun := time.Now() said := sendDirective(t, manager, "web") if !strings.Contains(said, "@web did NOT start: "+teamPausedWhy) || !strings.Contains(said, teamNotUnderWayRule) { t.Fatalf("the send does not say the member is paused: %s", said) @@ -37,9 +36,6 @@ func TestTeamDirectiveToAPausedMemberWaitsForResume(t *testing.T) { if strings.Contains(said, "started a turn") { t.Fatalf("the send reports a start for a paused member: %s", said) } - if took := time.Since(begun); took > teamSendSettle/2 { - t.Fatalf("a paused member is known from the teams file, yet the send waited %s", took) - } quietFor() if got := webCalls.requests(); got != 0 { t.Fatalf("the paused member made %d model calls", got) @@ -150,6 +146,10 @@ func TestTeamStandbyMemberStartsOnItsFirstDirective(t *testing.T) { if said := trafficEvents(t, fixture, teamStandbyText("web")); len(said) != 1 { t.Fatalf("standby was said %d times in the traffic, want once", len(said)) } + // The manager's own view says so, through the tool it reads its team with. + if status, failed := callTool(t, manager.teamStatusTool, `{}`); failed || !strings.Contains(status, "- @web, Frontend developer \"web frontend\": "+teams.DigestStandby) { + t.Fatalf("team_status does not show the member on standby:\n%s", status) + } if said := sendDirective(t, manager, "web"); !strings.Contains(said, "@web started a turn on it.") { t.Fatalf("the first directive did not start the standby member: %s", said) @@ -164,35 +164,225 @@ func TestTeamStandbyMemberStartsOnItsFirstDirective(t *testing.T) { if strings.Contains(asked, teamBriefWord+" #") { t.Fatalf("a standby start was handed over as a brief to begin:\n%s", asked) } + // The surface draws the role line as the manager's start, not as nothing. + drawn := false + for _, line := range teamNewsLines(asked) { + drawn = drawn || (line.Kind == teams.KindStart && line.From == teams.FromManager && strings.Contains(line.Text, "Owns the web frontend")) + } + if !drawn { + t.Fatalf("the delivery card lost the standing role line: %+v", teamNewsLines(asked)) + } + // Standby is over once the line is handed to it, and the manager's view stops saying it. + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + file, err := teams.Load(fixture.profile) + if err != nil { + t.Fatal(err) + } + if member, _ := file.Teams[0].ByHandle("web"); !member.Standby { + break + } + time.Sleep(10 * time.Millisecond) + } + if status, _ := callTool(t, manager.teamStatusTool, `{}`); strings.Contains(status, teams.DigestStandby) { + t.Fatalf("a member that has been handed its role still reads as on standby:\n%s", status) + } +} + +// STANDBY OUTLIVES A RESTART. A crew made today and first given work after the +// app was relaunched still hands each helper its role line with the directive, +// however old the start line is by then. +func TestTeamStandbyRoleLineSurvivesALateStart(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + long := time.Now().Add(-3 * time.Hour) + start, err := teams.AppendTrafficID(fixture.profile, fixture.teamID, teams.Entry{ + Kind: teams.KindStart, From: teams.FromManager, To: "web", Text: "Owns the web frontend and its tests.", At: long, + }) + if err != nil { + t.Fatal(err) + } + // A directive sent while nothing had the member open, also long ago. + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header.", At: long.Add(time.Minute)}) + err = teams.Update(fixture.profile, func(file *teams.File) error { + team := &file.Teams[0] + for i := range team.Members { + if team.Members[i].Handle == "web" { + team.Members[i].Standby = true + team.Members[i].Started, team.Members[i].StartEntry, team.Members[i].StartID = true, start, start + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + file, err := teams.Load(fixture.profile) + if err != nil { + t.Fatal(err) + } + if !TeamOpenPending(fixture.profile, fixture.web, file, teams.Defaults{Wake: true}, time.Now()) { + t.Fatal("a directive to a standby member that was never opened does not ask for it to be opened") + } + webCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.web, webCalls, nil) + waitRequests(t, webCalls, 1) + asked := userTextIn(webCalls.request(0)) + for _, want := range []string{teamStandbyBriefWord, "Owns the web frontend and its tests.", "Fix the header."} { + if !strings.Contains(asked, want) { + t.Fatalf("the late first turn lacks %q:\n%s", want, asked) + } + } +} + +// A HELD DIRECTIVE OUTLIVES A RESTART TOO, for a member that had never taken a +// turn in the team and so had no cursor written down. +func TestTeamHeldDirectiveSurvivesARestartOfAMemberThatNeverRan(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) + first := teamAgent(t, fixture, fixture.web, oneAnswer(1), nil) + sendDirective(t, manager, "web") + quietFor() + if err := first.Close(); err != nil { + t.Fatal(err) + } + // Much later, in another process: the directive is older than anything a + // fresh conversation would look back to. + setPaused(t, fixture, fixture.web, false) + file, err := teams.Load(fixture.profile) + if err != nil { + t.Fatal(err) + } + if !TeamOpenPending(fixture.profile, fixture.web, file, teams.Defaults{Wake: true}, time.Now().Add(time.Hour)) { + t.Fatal("the held directive does not ask for the resumed member to be opened") + } + webCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.web, webCalls, func(config *Config) { config.TeamListeningSince = time.Now().Add(time.Hour) }) + waitRequests(t, webCalls, 1) + if asked := userTextIn(webCalls.request(0)); strings.Count(asked, "Fix the header.") != 1 { + t.Fatalf("the member reopened after the resume was not handed the held directive once:\n%s", asked) + } +} + +// A DIRECTIVE SENT IN THE SAME BREATH AS THE PAUSE IS HELD, not started on a +// reading of the teams file from before the pause. +func TestTeamDirectiveRightAfterThePauseIsHeld(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) + webCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.web, webCalls, nil) + quietFor() // both conversations have read the teams file with nobody paused + setPaused(t, fixture, fixture.web, true) + if said := sendDirective(t, manager, "web"); !strings.Contains(said, "@web did NOT start: "+teamPausedWhy) { + t.Fatalf("the send does not say the member is paused: %s", said) + } + quietFor() + if got := webCalls.requests(); got != 0 { + t.Fatalf("the member paused a moment before the directive made %d model calls", got) + } + if woke := trafficEvents(t, fixture, "woke @web"); len(woke) != 0 { + t.Fatalf("the traffic says it woke: %+v", woke) + } + setPaused(t, fixture, fixture.web, false) + waitRequests(t, webCalls, 1) + if asked := userTextIn(webCalls.request(0)); !strings.Contains(asked, "Fix the header.") { + t.Fatalf("the resumed member was not handed the directive:\n%s", asked) + } } -// THE PERSON'S STOP OF A MEMBER'S TURN REACHES ITS MANAGER, which handed that -// work out and is told nothing else about its ending. +// THE PERSON'S STOP OF A TURN THE TEAM STARTED REACHES ITS MANAGER, which +// handed that work out and is told nothing else about its ending. func TestTeamPersonStopWakesTheManager(t *testing.T) { fastTeamWake(t) fixture := newWakingTeamFixture(t) managerCalls := oneAnswer(1) - teamAgent(t, fixture, fixture.manager, managerCalls, nil) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) streaming := make(chan struct{}) web := teamAgent(t, fixture, fixture.web, &scriptedCompleter{steps: []step{thinkingStep(streaming)}}, nil) - events := mustSubmit(t, web, "work on the header") + sendDirective(t, manager, "web") select { case <-streaming: case <-time.After(5 * time.Second): - t.Fatal("the member did not start") + t.Fatal("the member did not start on the directive") } web.Interrupt() - collect(t, events) waitRequests(t, managerCalls, 1) asked := userTextIn(managerCalls.request(0)) - if !strings.Contains(asked, "@web's turn was "+teams.StoppedByPerson+" before it finished") { - t.Fatalf("the manager was not told the person stopped its member:\n%s", asked) + if !strings.Contains(asked, "@web"+teamStoppedByPersonLine) { + t.Fatalf("the manager was not told the person stopped the work it handed out:\n%s", asked) } if stopped := trafficEvents(t, fixture, teams.StoppedByPerson); len(stopped) != 1 || stopped[0].State != teams.StateIdle { t.Fatalf("the stop was logged as %+v", stopped) } } +// A TURN THE PERSON OPENED AND STOPPED IS THEIR OWN REQUEST, which the manager +// never handed out: it ends "stopped" and wakes nobody. +func TestTeamPersonStopOfTheirOwnTurnTellsTheManagerNothing(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.manager, managerCalls, nil) + streaming := make(chan struct{}) + web := teamAgent(t, fixture, fixture.web, &scriptedCompleter{steps: []step{thinkingStep(streaming)}}, nil) + events := mustSubmit(t, web, "work on the header") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start") + } + web.Interrupt() + collect(t, events) + web.settleTeamEvents() + quietFor() + if got := managerCalls.requests(); got != 0 { + t.Fatalf("the manager was woken %d times by a stop of the person's own turn", got) + } + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 0 { + t.Fatalf("the person's own turn was logged as work stopped by the person: %+v", said) + } + if said := trafficEvents(t, fixture, "stopped"); len(said) != 1 { + t.Fatalf("the ending was logged %d times, want once as stopped", len(said)) + } +} + +// AN INTERFACE PERFORMS A MANAGER'S STOP THROUGH THE PERSON'S DOOR (the app, the +// terminal and a remote window all call Interrupt on reading the stop line), +// usually before the member's own session reads that line. The ending is the +// manager's all the same: the log says who stopped it. +func TestTeamManagerStopPerformedByAnInterfaceIsNotThePersons(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(1) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + streaming := make(chan struct{}) + web := teamAgent(t, fixture, fixture.web, &scriptedCompleter{steps: []step{thinkingStep(streaming)}}, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + // The manager's stop line, then the interface's cancel, in one breath. + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindStop, From: teams.FromManager, To: "web", Member: convKeyOf(t, fixture.web), Text: "wrong way", At: time.Now()}) + web.Interrupt() + deadline := time.Now().Add(5 * time.Second) + for len(trafficEvents(t, fixture, "stopped")) == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + web.settleTeamEvents() + quietFor() + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 0 { + t.Fatalf("the manager's own stop was logged as the person's: %+v", said) + } + if got := managerCalls.requests(); got != 0 { + t.Fatalf("the manager was woken %d times by its own stop", got) + } +} + // AND ITS OWN STOP DOES NOT: the manager performed it and knows. func TestTeamEventWakesManager(t *testing.T) { for _, c := range []struct { diff --git a/internal/session/team_sendoutcome.go b/internal/session/team_sendoutcome.go index 94be2aed05..d901ca5dbc 100644 --- a/internal/session/team_sendoutcome.go +++ b/internal/session/team_sendoutcome.go @@ -34,26 +34,37 @@ import ( // one that has to be opened first took half a second where it was measured. // Four seconds covers both with room, and is short enough that a manager does // not read the wait as a stall. teamSendLook is how often the traffic is read -// while waiting. Both are vars so a test does not sleep. +// while waiting. Both are vars so a test does not sleep, read under +// teamWatchClockMu like the watch's own clocks ([teamSendWait]). var ( teamSendSettle = 4 * time.Second teamSendLook = 200 * time.Millisecond ) -// The traffic lines a wake writes, as the send reads them back. They are the -// prefixes of the texts team_wakewatch.go and team_pause.go write. +// teamSendWait is the two waits as this moment has them. +func teamSendWait() (settle, look time.Duration) { + teamWatchClockMu.RLock() + defer teamWatchClockMu.RUnlock() + return teamSendSettle, teamSendLook +} + +// How the traffic lines about a wake open. The writers (team_wakewatch.go, +// team_pause.go) and the send that reads them back use these, so neither can +// drift from the other. const ( - teamWokePrefix = "woke @" - teamCouldNotPrefix = "could not wake " - teamHeldPrefix = "held " - teamNotUnderWayRule = "Do not tell the person this work is under way." + teamWokePrefix = "woke " + teamCouldNotPrefix = "could not wake " + teamHeldPrefix = "held " ) +// teamNotUnderWayRule closes an answer in which some member did not start. +const teamNotUnderWayRule = "Do not tell the person this work is under way." + // teamSendOutcome is the sentences that follow "Sent a directive to …": what // became of it for each member it was sent to on this computer. ready are the // members a wake was asked for and paused the ones the person paused. func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams.Team, id string, ready, paused []teams.Member) string { - var started, busy, unseen []string + var started, busy, asking, unseen []string refused := map[string]string{} var refusedOrder []string waiting := map[string]teams.Member{} @@ -62,14 +73,20 @@ func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams. if member.Handle == "" { continue } - if state, _, ok := a.team.journals.stateOf(member.File, now); ok && - (state.State == teams.StateRunning || state.State == teams.StateAsking) { - busy = append(busy, "@"+member.Handle) - continue + if state, _, ok := a.team.journals.stateOf(member.File, now); ok { + switch state.State { + case teams.StateRunning: + busy = append(busy, "@"+member.Handle) + continue + case teams.StateAsking: + asking = append(asking, "@"+member.Handle) + continue + } } waiting[member.Key] = member } - deadline := now.Add(teamSendSettle) + settle, look := teamSendWait() + deadline := now.Add(settle) for len(waiting) > 0 { entries, err := teams.ReadTraffic(profile, team.ID, id, teamPageLimit) if err == nil { @@ -80,7 +97,7 @@ func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams. } text := strings.TrimSpace(entry.Text) switch { - case entry.State == teams.StateRunning && strings.HasPrefix(text, teamWokePrefix): + case entry.State == teams.StateRunning && strings.HasPrefix(text, teamWokePrefix+"@"): started = append(started, "@"+member.Handle) delete(waiting, entry.Member) delete(refused, member.Handle) @@ -99,7 +116,7 @@ func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams. select { case <-ctx.Done(): deadline = time.Time{} - case <-time.After(teamSendLook): + case <-time.After(look): } } for _, member := range ready { @@ -116,7 +133,10 @@ func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams. if len(busy) > 0 { said = append(said, strings.Join(busy, ", ")+" "+isAre(len(busy))+" in a turn and "+readsRead(len(busy))+" it at the next step.") } - if len(started)+len(busy) > 0 { + if len(asking) > 0 { + said = append(said, strings.Join(asking, ", ")+" "+isAre(len(asking))+" waiting on the person and "+readsRead(len(asking))+" it once they answer.") + } + if len(started)+len(busy)+len(asking) > 0 { said = append(said, "Replies and endings wake you when they arrive, so there is no need to wait or poll.") } for _, member := range paused { @@ -142,10 +162,12 @@ func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams. } // splitPaused divides a directive's local targets into the members the person -// paused and the rest. The manager is never paused. -func splitPaused(team teams.Team, targets []teams.Member) (ready, paused []teams.Member) { +// paused, in this team or another of theirs ([teams.File.PausedAnywhere]), and +// the rest. The manager is never paused. +func splitPaused(file *teams.File, team teams.Team, targets []teams.Member) (ready, paused []teams.Member) { for _, member := range targets { - if member.Paused && member.Key != team.Manager { + _, elsewhere := file.PausedAnywhere(member.Key) + if (member.Paused || elsewhere) && member.Key != team.Manager { paused = append(paused, member) continue } diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 753cbe4a5e..cc8878270d 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -494,6 +494,14 @@ func (a *Agent) teamWakeMember(profile string, roles []teamRole, now time.Time) a.teamCapSay(profile, roles, reason) return } + // THE PAUSE IS READ AGAIN, FRESH, BEFORE ANYTHING IS HANDED OVER. The look + // that chose these roles read the teams file through a memo up to a tick + // old ([sharedTeamsStamp]), so a directive sent in the second after the + // person pressed Pause reached here as if nothing held it, and the turn it + // started consumed the directive the pause was meant to keep. + if roles = a.teamPausedSince(profile, roles); len(roles) == 0 { + return + } news := a.teamBoundary() if news == "" { // A boundary that ran in the moment between the look and here has @@ -513,14 +521,14 @@ func (a *Agent) teamWakeMember(profile string, roles []teamRole, now time.Time) if woke { a.teamSay(profile, role.id, teams.Entry{ Kind: teams.KindEvent, From: teams.FromManager, To: role.handle, Member: role.key, - State: teams.StateRunning, Text: "woke @" + role.handle, Answers: answers, + State: teams.StateRunning, Text: teamWokePrefix + "@" + role.handle, Answers: answers, }) continue } if reason != "" { a.teamSay(profile, role.id, teams.Entry{ Kind: teams.KindEvent, From: teams.FromSystem, To: role.handle, Member: role.key, - State: teams.StateIdle, Text: "could not wake @" + role.handle + ": " + reason, Answers: answers, + State: teams.StateIdle, Text: teamCouldNotPrefix + "@" + role.handle + ": " + reason, Answers: answers, }) } } @@ -587,7 +595,7 @@ func (a *Agent) teamWakeManager(profile string, roles []teamRole, batch map[stri if reason != "" { a.teamSay(profile, id, teams.Entry{ Kind: teams.KindEvent, From: teams.FromSystem, To: teams.ToManager, Member: role.key, - State: teams.StateIdle, Text: "could not wake ◆: " + reason, + State: teams.StateIdle, Text: teamCouldNotPrefix + "◆: " + reason, }) } } @@ -675,7 +683,7 @@ func (a *Agent) teamCapSay(profile string, roles []teamRole, reason string) { } a.teamSay(profile, role.id, teams.Entry{ Kind: teams.KindEvent, From: teams.FromSystem, To: to, Member: role.key, - State: teams.StateIdle, Text: "held " + who + ": " + reason, + State: teams.StateIdle, Text: teamHeldPrefix + who + ": " + reason, }) } } @@ -698,7 +706,7 @@ func (a *Agent) teamWakeLimitSay(profile string, roles []teamRole, reason string } a.teamSay(profile, role.id, teams.Entry{ Kind: teams.KindEvent, From: teams.FromSystem, To: to, Member: role.key, - State: teams.StateIdle, Text: "could not wake " + who + ": " + reason, + State: teams.StateIdle, Text: teamCouldNotPrefix + who + ": " + reason, }) } } @@ -770,7 +778,7 @@ func teamEventLines(entries []teams.Entry) []string { lines = append(lines, who+" is waiting on the person: "+strings.TrimPrefix(text, "asks: ")) case teams.StateIdle: if text == teams.StoppedByPerson { - lines = append(lines, who+"'s turn was "+teams.StoppedByPerson+" before it finished; it reported nothing, so what you handed it is not done") + lines = append(lines, who+teamStoppedByPersonLine) } } } @@ -908,7 +916,7 @@ func (a *Agent) teamRouse(profile string, team teams.Team, wakes bool, targets [ if to == "" { who, to = "a member with no handle", teams.ToRoom } - text := "could not wake " + who + ": " + reason + text := teamCouldNotPrefix + who + ": " + reason if kept { text += teamRouseKept } diff --git a/internal/session/team_wakewatch_test.go b/internal/session/team_wakewatch_test.go index 907bfd6dab..9c02102fd4 100644 --- a/internal/session/team_wakewatch_test.go +++ b/internal/session/team_wakewatch_test.go @@ -26,18 +26,18 @@ func fastTeamWake(t *testing.T) { teamWatchClockMu.Lock() every, settle, retry, longest := teamWatchEvery, teamWakeSettle, teamRouseRetry, teamRouseRetryMax teamWatchEvery, teamWakeSettle, teamRouseRetry, teamRouseRetryMax = 20*time.Millisecond, 300*time.Millisecond, 50*time.Millisecond, 200*time.Millisecond - teamWatchClockMu.Unlock() - // A send waits to see its members start; with the watch this fast a second - // and a half is many looks, and a test of a member that never starts does - // not sit out the shipped four seconds. + // A send waits to see its members start. With the watch this fast three + // seconds is over a hundred looks, room enough on a loaded machine, and a + // send whose member starts returns as soon as it has. sendSettle, sendLook := teamSendSettle, teamSendLook - teamSendSettle, teamSendLook = 1500*time.Millisecond, 5*time.Millisecond + teamSendSettle, teamSendLook = 3*time.Second, 5*time.Millisecond + teamWatchClockMu.Unlock() t.Cleanup(func() { forgetRouses() teamWatchClockMu.Lock() teamWatchEvery, teamWakeSettle, teamRouseRetry, teamRouseRetryMax = every, settle, retry, longest - teamWatchClockMu.Unlock() teamSendSettle, teamSendLook = sendSettle, sendLook + teamWatchClockMu.Unlock() }) } diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index 12ca581556..bc1a02b37a 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -207,12 +207,8 @@ func (a *Agent) teamTurnEnded(ctx context.Context, hub *eventHub) { return } if door, stopped := stopCause(ctx); stopped { - // THE PERSON'S STOP IS SAID AS THE PERSON'S. The manager performed its - // own stop and knows of it; a turn the person ended is work the manager - // handed out ending without a report, which nothing else tells it - // ([teams.StoppedByPerson] wakes it, team_wakewatch.go). text := "stopped" - if door == StopByPerson { + if a.teamStoppedByPerson(door, origin) { text = teams.StoppedByPerson } a.teamEventOwed(origin, teams.StateIdle, text) diff --git a/internal/session/teamshape.go b/internal/session/teamshape.go index e74377f4a2..660c681fb0 100644 --- a/internal/session/teamshape.go +++ b/internal/session/teamshape.go @@ -111,6 +111,8 @@ func teamLineParts(line string) (TeamLine, bool) { if rest != "" { head = " #" + rest } + case strings.HasPrefix(head, teamStandbyBriefWord): + parsed.From, parsed.Kind, head = teams.FromManager, teams.KindStart, strings.TrimPrefix(head, teamStandbyBriefWord) case strings.HasPrefix(head, teamBriefWord): parsed.From, parsed.Kind, head = teams.FromManager, teams.KindStart, strings.TrimPrefix(head, teamBriefWord) case strings.HasPrefix(head, "◆ directive from manager"): diff --git a/internal/session/tools_team.go b/internal/session/tools_team.go index 6ef42f6de4..c5a4a07b02 100644 --- a/internal/session/tools_team.go +++ b/internal/session/tools_team.go @@ -77,8 +77,8 @@ var teamToolNames = []string{ // out there is answered with the names to choose from. const teamArgSchema = `"team":{"type":"string","description":"Team name or id. Needed only when you are in more than one."}` -const teamStatusDescription = "Your team as it stands: every member's handle, title and state (running, asking, idle, failed), " + - "the question a member is waiting on, the files each has touched, and the recent traffic. States are read from each member's saved conversation. " + +const teamStatusDescription = "Your team as it stands: every member's handle, role, title and state (running, asking, idle, failed, paused by the person, on standby), " + + "a directive it has not started on, the question a member is waiting on, the files each has touched, and the recent traffic. States are read from each member's saved conversation. " + "Use it before handing out work and when the person asks how the team is doing." const teamStatusSchema = `{"type":"object","properties":{` + teamArgSchema + `},"additionalProperties":false}` @@ -91,7 +91,7 @@ var teamReadSchema = `{"type":"object","properties":{"handle":{"type":"string"," teamArgSchema + `},"required":["handle"],"additionalProperties":false}` const teamSendDescription = "Send a message to one member, to several (one message with every handle in to), or to everyone in the team. It arrives at the start of the member's next step, marked as from the manager, never as the person. " + - "kind note is information and waits for the member's next turn; kind directive is an instruction the member should follow unless the person said otherwise in its own conversation, and it starts an idle member's turn. The answer to a directive says, for each member, whether it started, is already in a turn, or did not start and why (the person paused it, the team is at its cap, it could not be opened); report work as under way only for a member the answer says started. " + + "kind note is information and waits for the member's next turn; kind directive is an instruction the member should follow unless the person said otherwise in its own conversation, and it starts an idle member's turn. The answer to a directive says, for each member, whether it started, is already in a turn, did not start and why (the person paused it, it could not be woken), or has shown no sign of starting yet; report work as under way only for a member the answer says started. " + "A member busy in a long tool call reads it when that returns; use team_stop to end its turn first." const teamSendSchema = `{"type":"object","properties":{"to":{"type":"string","description":"A member's handle, several separated by spaces, or everyone."},` + @@ -273,6 +273,7 @@ func (a *Agent) teamStatusTool(ctx context.Context, args json.RawMessage) (strin file, _, _, _ := a.teamSnapshot(profile) states := memberStates(team, keys, time.Now(), log, &a.team.journals) markShared(file, team, states) + markPaused(file, team, states) return teams.Digest(team, states, recentOf(log), teamStatusBudget) + waitingOn(profile, team), false, nil } @@ -507,22 +508,28 @@ func (a *Agent) teamSendTool(ctx context.Context, args json.RawMessage) (said st // the directive is held for it (team_pause.go). The answer then says // what became of the directive for each member (team_sendoutcome.go). profile := a.config.teamProfile() - ready, paused := splitPaused(team, local) - for _, member := range paused { - a.teamSay(profile, team.ID, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromSystem, To: member.Handle, Member: member.Key, - State: teams.StateIdle, Text: teamHeldPausedText(member.Handle), Answers: id, Provenance: prov, - }) - } - a.teamRouse(profile, team, role.wakes, ready, id, prov) + ready, paused := splitPaused(file, team, local) sent := fmt.Sprintf("Sent a directive to %s.", who) if len(shared) > 0 { sent = fmt.Sprintf("Sent a directive to %d member(s) of %q who report to you: %s. Not sent to %s: they report to another team's manager; send them a note.", len(entry.Recipients()), team.Name, who, strings.Join(shared, ", ")) } if !role.wakes { - return sent + " This team's auto-wake is off, so a member that is idle reads it when its conversation next runs; a busy one at its next step.", false, nil + // With the auto-wake off nothing starts on a directive, paused or + // not, so no hold is promised: only that the pause is there. + sent += " This team's auto-wake is off, so a member that is idle reads it when its conversation next runs; a busy one at its next step." + if len(paused) > 0 { + sent += " " + teamAt(paused) + " " + isAre(len(paused)) + " also paused by the person." + } + return sent, false, nil } + for _, member := range paused { + a.teamSay(profile, team.ID, teams.Entry{ + Kind: teams.KindEvent, From: teams.FromSystem, To: member.Handle, Member: member.Key, + State: teams.StateIdle, Text: teamHeldPausedText(member.Handle), Answers: id, Provenance: prov, + }) + } + a.teamRouse(profile, team, role.wakes, ready, id, prov) return sent + " " + a.teamSendOutcome(ctx, profile, team, id, ready, paused), false, nil } return fmt.Sprintf("Sent a note to %s. It arrives at the start of their next step; a note wakes nobody, so a member that is idle reads it when its conversation next runs.", who), false, nil diff --git a/internal/teams/digest.go b/internal/teams/digest.go index f37a862037..9be1b010c5 100644 --- a/internal/teams/digest.go +++ b/internal/teams/digest.go @@ -44,6 +44,9 @@ type MemberState struct { // team's manager may read and send a note to, and not direct. A shared // member that is running is drawn busy for that team. ReportsTo string + // Paused says the person paused this conversation in another of its teams + // ([File.PausedAnywhere]); the member's own record says it for this one. + Paused bool } // Digest limits. @@ -117,9 +120,9 @@ func address(m Member) string { // who caused it and what ends it. const ( // DigestPaused is a member the person paused ([Member.Paused]). - DigestPaused = "paused by the person; a directive waits until they resume it" - // DigestStandby is a member made without work that has not run yet - // ([Member.Standby]). + DigestPaused = "paused by the person; it starts nothing until they resume it" + // DigestStandby is a member made without work that has not been handed its + // start line yet ([Member.Standby]). DigestStandby = "on standby; no work handed out yet" ) @@ -144,12 +147,23 @@ func lastWord(m Member, recent []Entry) string { // The wake line: the member started on what it was sent. return "" case e.Kind == KindDirective && e.From == FromManager && e.Addressed(m.Handle): - return "has not started on " + ThreadNumber(e.ID) + return digestNotStarted + ThreadNumber(e.ID) } } return "" } +// digestNotStarted opens the digest's word for a directive nobody began. +const digestNotStarted = "has not started on " + +// lastNotStarted is last when it is that word, "" otherwise. +func lastNotStarted(last string) string { + if strings.HasPrefix(last, digestNotStarted) { + return last + } + return "" +} + func memberLine(m Member, s MemberState, manager bool, last string) string { var b strings.Builder b.WriteString("- " + address(m)) @@ -169,17 +183,20 @@ func memberLine(m Member, s MemberState, manager bool, last string) string { if s.ReportsTo != "" && state == StateRunning { state = "busy for " + s.ReportsTo } + resting := state == StateIdle || state == "unknown" switch { case manager: - case m.Paused && (state == StateIdle || state == "unknown"): + case (m.Paused || s.Paused) && resting: state = DigestPaused - case m.Paused: + case m.Paused || s.Paused: state += ", " + DigestPaused - case m.Standby && s.SinceActive == 0 && (state == StateIdle || state == "unknown"): + case m.Standby && resting: state = DigestStandby } b.WriteString(": " + state) - if last != "" && !manager { + // A directive a member in a turn has not answered yet is not one it has + // not started on: it reads it at its next step. + if last != "" && !manager && (resting || last != lastNotStarted(last)) { b.WriteString(", " + last) } if m.Independent { diff --git a/internal/teams/digest_test.go b/internal/teams/digest_test.go index 18780a5f13..2f7b8956f4 100644 --- a/internal/teams/digest_test.go +++ b/internal/teams/digest_test.go @@ -95,6 +95,8 @@ func TestDigestSaysPausedStandbyAndUnstartedWork(t *testing.T) { {Key: "b", Handle: "review", Role: "Reviewer", Standby: true}, {Key: "c", Handle: "design", Word: "Design the tiles"}, {Key: "d", Handle: "docs", Word: "Write the guide"}, + {Key: "e", Handle: "busy", Word: "Port the parser"}, + {Key: "f", Handle: "shared", Word: "Shared helper"}, }} at := time.Date(2026, 11, 23, 22, 2, 0, 0, time.UTC) recent := []Entry{ @@ -103,30 +105,38 @@ func TestDigestSaysPausedStandbyAndUnstartedWork(t *testing.T) { {ID: "000000000023", At: at, Kind: KindEvent, From: FromSystem, To: "dev", Member: "a", State: StateIdle, Text: "held @dev: the person paused it", Answers: "000000000022"}, {ID: "000000000024", At: at, Kind: KindEvent, From: FromManager, To: "docs", Member: "d", State: StateRunning, Text: "woke @docs", Answers: "000000000021"}, {ID: "000000000025", At: at, Kind: KindEvent, From: "design", To: ToManager, Member: "c", State: StateIdle, Text: StoppedByPerson}, + // Sent to a member in a turn: it reads it at its next step, with no wake line. + {ID: "000000000026", At: at, Kind: KindDirective, From: FromManager, To: "busy", Text: "Then the lexer."}, } states := map[string]MemberState{ "m": {State: StateRunning}, "a": {State: StateIdle, SinceActive: time.Hour}, - "b": {State: StateIdle}, + // The journal of a member that never ran still has an age: its file's. + "b": {State: StateIdle, SinceActive: time.Minute}, "c": {State: StateIdle, SinceActive: time.Minute}, "d": {State: StateRunning, SinceActive: time.Minute}, + "e": {State: StateRunning, SinceActive: time.Minute}, + "f": {State: StateIdle, SinceActive: time.Minute, Paused: true}, } got := Digest(team, states, recent, 0) for _, want := range []string{ `- @boss (manager) "Harbor manager": running`, `- @dev, macOS developer "Scaffold the app": ` + DigestPaused + `, has not started on #22, active 1h ago`, - `- @review, Reviewer: ` + DigestStandby, + `- @review, Reviewer: ` + DigestStandby + `, active within the hour`, `- @design "Design the tiles": idle, its last turn was ` + StoppedByPerson + `, active within the hour`, `- @docs "Write the guide": running, active within the hour`, + `- @busy "Port the parser": running, active within the hour`, + // Paused by the person in another of its teams. + `- @shared "Shared helper": ` + DigestPaused + `, active within the hour`, } { if !strings.Contains(got, want+"\n") { t.Errorf("the digest lacks the line\n%s\nin\n%s", want, got) } } - // A member that ran is no longer on standby, whatever its record says. - states["b"] = MemberState{State: StateIdle, SinceActive: time.Minute} + // Standby is the member's record, cleared when its role line is handed to it. + team.Members[2].Standby = false if got := Digest(team, states, nil, 0); strings.Contains(got, DigestStandby) { - t.Errorf("a member that has run still reads as on standby:\n%s", got) + t.Errorf("a member whose standby is over still reads as on standby:\n%s", got) } } diff --git a/internal/teams/root.go b/internal/teams/root.go index dab7080564..fc1e5115df 100644 --- a/internal/teams/root.go +++ b/internal/teams/root.go @@ -151,6 +151,8 @@ func seatTopManagers(teams []Team, rootID string) bool { continue } m.Home, m.Started, m.StartEntry, m.StartID = false, false, "", "" + // What the person said of it in its own team is not said of its seat here. + m.Paused, m.Standby, m.Role = false, false, "" if m.Handle != "" && handleProblem(teams[r], m.Key, m.Handle) != nil { m.Handle = "" } diff --git a/internal/teams/teams.go b/internal/teams/teams.go index c6c51eb1ad..1df36e78a8 100644 --- a/internal/teams/teams.go +++ b/internal/teams/teams.go @@ -87,9 +87,11 @@ type Member struct { // member in its role note and shown to the manager beside the handle. Empty // on a membership nobody gave one. Role string `json:"role,omitempty"` - // Standby says this membership was made without work to start on: its start - // line is a standing description of the role, read at the member's first - // turn, and that line starts no turn. The first directive does. + // Standby says this membership was made without work to start on and has + // not been handed its start line yet: that line is a standing description + // of the role, read at the member's first turn, and starts no turn. The + // first directive does, and the member's session clears this once the line + // is handed over ([File.SetStandby]). Standby bool `json:"standby,omitempty"` // Unknown membership fields survive whole-file updates from this build. extra map[string]json.RawMessage @@ -590,6 +592,10 @@ func (f *File) SetManager(id, key string) error { f.Teams[idx].FormerManager = old } f.Teams[idx].Manager = key + // A manager is neither paused nor on standby: the person talks to it. + if j := f.Teams[idx].member(key); j >= 0 { + f.Teams[idx].Members[j].Paused, f.Teams[idx].Members[j].Standby = false, false + } assignHandles(&f.Teams[idx]) if f.Teams[idx].Root { // Explicitly assigning the optional global role reconnects its current @@ -662,6 +668,42 @@ func (f *File) SetPaused(id, key string, paused bool) error { return nil } +// SetStandby marks or clears the member with key in team id as waiting for its +// first work ([Member.Standby]). +func (f *File) SetStandby(id, key string, standby bool) error { + i, err := f.at(id) + if err != nil { + return err + } + t := &f.Teams[i] + j := t.member(key) + if j < 0 { + return fmt.Errorf("%s is not in team %s", key, t.Name) + } + t.Members[j].Standby = standby && t.Manager != key + return nil +} + +// PausedAnywhere reports whether the person paused the conversation with key in +// any open team it is a member (and not the manager) of, and that team's name. +// A pause is the person's word about the conversation: while it holds, no +// team's traffic starts its turn, so a team that did not write the pause reads +// it here. +func (f *File) PausedAnywhere(key string) (string, bool) { + if f == nil { + return "", false + } + for _, t := range f.Teams { + if t.Closed() || t.Manager == key { + continue + } + if m, ok := t.Member(key); ok && m.Paused { + return t.Name, true + } + } + return "", false +} + // SetRole names what the member with key in team id is there for // ([Member.Role]); "" clears it. func (f *File) SetRole(id, key, role string) error { From a2b9c998ad15fb5d88ec0e6490e8c00f1330ca95 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:24:40 -0500 Subject: [PATCH 04/37] teams: review round 2 repairs - Whether a stop is the person's stop of handed-out work is decided per team by what the turn was handed, not by who opened it: a directive read inside a turn the person had started counts, a turn that carried only the person's request does not, and a manager's stop on the log since the hand-over still makes it the manager's. - The app's own stops no longer use the person's door: quitting cancels through StopByClosing and a paused member's stray wake through StopByWorkStopped, so neither is told to a manager as the person's choice. - A directive held for a paused member that nothing had open is found again after a restart from the sender's "held" line. - A standby member renamed before its first work still gets its role line: its start is its own by identity. - A conversation that manages a team is not paused; a resume lifts the pause in every team; the app shows a member paused in each of its crews. - The digest keeps "its last turn was stopped by the person" after the manager's own wake line, and says "has not started on #N" for a member whose last turn failed. Co-Authored-By: Claude Fable 5.2 --- cmd/codeaf/app.go | 3 +- cmd/codeaf/appcrewmembers.go | 3 +- cmd/codeaf/appcrews.go | 5 + cmd/codeaf/appwakes.go | 26 ++- .../unreleased/2897-crew-handoff-outcome.md | 6 +- internal/manual/chat/team-manager.md | 26 ++- internal/session/hermetic_test.go | 12 +- internal/session/team.go | 21 +- internal/session/team_pause.go | 103 +++++++--- internal/session/team_pause_test.go | 191 ++++++++++++++++++ internal/session/team_pending.go | 2 +- internal/session/teamevent.go | 34 +++- internal/teams/digest.go | 10 +- internal/teams/digest_test.go | 59 ++++++ internal/teams/teams.go | 29 ++- 15 files changed, 462 insertions(+), 68 deletions(-) diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 45ab00baab..92344af9bf 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -5002,7 +5002,8 @@ func (b *appBackend) Close() error { // A conversation joined on a window's host is that window's, and // is only detached from. if live := b.liveOf(a); live != nil && live.conn.Assembled { - live.conn.Conv.Interrupt() + // The app is leaving; the person did not press stop. + appInterruptFor(live.conn.Conv, session.StopByClosing, "") } b.letGoTimed(a, os.Stderr) }) diff --git a/cmd/codeaf/appcrewmembers.go b/cmd/codeaf/appcrewmembers.go index 82ba9c6004..5160d47fbe 100644 --- a/cmd/codeaf/appcrewmembers.go +++ b/cmd/codeaf/appcrewmembers.go @@ -66,7 +66,8 @@ func (b *appBackend) Member(verb string, ask appwire.MemberAsk) (appwire.CrewMem err = b.memberStop(t, m, agent, "paused") } case "resume": - if err = b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, false) }); err == nil && m.Paused { + pausedSomewhere := m.Paused || b.crewPaused(agent) + if err = b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, false) }); err == nil && pausedSomewhere { // The resume is said on the crew's log beside the pause. What // waited there starts the member's turn on its session's next look. err = appEngineErrorOrNil(teamstore.AppendTraffic(b.crewProfile(), t.ID, teamstore.Entry{ diff --git a/cmd/codeaf/appcrews.go b/cmd/codeaf/appcrews.go index 2d33e609fa..a515079724 100644 --- a/cmd/codeaf/appcrews.go +++ b/cmd/codeaf/appcrews.go @@ -696,7 +696,12 @@ func (b *appBackend) memberView(read appCrewRead, t teamstore.Team, m teamstore. if usd, set := b.agentBudget(agent, b.now()); set { view.CapUSD = &usd } + // Paused wherever the person paused it: the pause holds the conversation in + // every crew, and Resume here lifts it. view.Paused = m.Paused + if _, elsewhere := read.file.PausedAnywhere(m.Key); elsewhere && m.Key != t.Manager { + view.Paused = true + } if extra := read.layer.Members[appMemberKey(t.ID, agent)]; extra != nil { view.Role, view.Was = extra.Role, extra.Was if role := read.layer.Roles[extra.Role]; role != nil { diff --git a/cmd/codeaf/appwakes.go b/cmd/codeaf/appwakes.go index c93ab536cc..360e13c9f3 100644 --- a/cmd/codeaf/appwakes.go +++ b/cmd/codeaf/appwakes.go @@ -25,6 +25,26 @@ import ( // before a turn starts; a turn woken some other way while it holds is stopped // here at once. A turn the person's own words opened is not. +// appPausedStop is what a turn ended because its member is paused is told. +const appPausedStop = "this member is paused, so the turn stopped before it did anything; resume it to let it run" + +// appInterruptFor ends a conversation's turn through a named door, for a stop +// that is the app's own doing and not the person's stop key. A conversation +// that cannot name a door is stopped the plain way. +func appInterruptFor(conv appConversation, door session.StopDoor, why string) { + if named, ok := conv.(interface { + InterruptNamed(session.StopDoor, string) + }); ok && why != "" { + named.InterruptNamed(door, why) + return + } + if doored, ok := conv.(interface{ InterruptFor(session.StopDoor) }); ok { + doored.InterruptFor(door) + return + } + conv.Interrupt() +} + // appWakeDoor is a conversation held in this process that hands over the // turns it starts itself. type appWakeDoor interface { @@ -166,8 +186,10 @@ func (b *appBackend) wokenTurn(a *appAgent, live *appLive, elsewhere appTurnElse // turn starts (internal/session's team_pause.go), so what reaches here // is another wake: a background process ending, a task landing. It ends // before it does anything. A turn the person's own words opened, from - // any window, is theirs and runs. - live.conn.Conv.Interrupt() + // any window, is theirs and runs. The stop is the app's and says so: + // through the person's door it would be told to the member's manager + // as work the person had stopped. + appInterruptFor(live.conn.Conv, session.StopByWorkStopped, appPausedStop) } live.box.Event(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) live.box.Event(appwire.EventTurnStarted, appwire.TurnStarted{Agent: id, Turn: turn}) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 4f12d36fbe..f5e3abbb22 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -5,15 +5,15 @@ pr: 2897 surface: [engine, app, chat] invalidates: - "team_send answered every directive with \"A member that is idle starts a turn on it now, and a busy one reads it at its next step\" whatever happened. It now waits up to four seconds on the team's traffic and says for each member one of: \"@web started a turn on it.\", \"@web is in a turn and reads it at the next step.\", \"@web did NOT start: .\", \"@web is waiting on the person and reads it once they answer.\", or \"@web has shown no sign of starting yet; team_status says whether it did.\" Where a member did not start, the answer also tells the manager not to tell the person the work is under way." - - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A member paused in any of its teams is not opened or woken by any team's traffic (File.PausedAnywhere); the directive stays undelivered and starts the member's turn when the person resumes it, including after a restart. The app carries an earlier build's pause onto the team's record once." + - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A member paused in any of its teams is not opened or woken by any team's traffic (File.PausedAnywhere), shows as paused in each of its crews, and is resumed from any of them (SetPaused false clears every membership); the directive stays undelivered and starts the member's turn when the person resumes it, including after a restart. The app carries an earlier build's pause onto the team's record once." - "A directive to a paused member wrote \"woke @x\" then \"stopped\" to the traffic. It now writes one line from system, \"held @x: the person paused it; it starts on this when they resume it\", answering the directive, and Resume writes an event from you with the text \"resumed\"." - - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A turn that team traffic started and the person then stops now ends \"stopped by the person\" (teams.StoppedByPerson); it wakes the manager and is delivered as \"@x's turn on what you handed it was stopped by the person before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask.\" A turn the person opened with their own message and then stopped, and a stop by the manager's team_stop (whichever interface performs it), still end \"stopped\" and still wake nobody. The global manager is not woken by either." + - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A turn that was handed its manager's work (a directive, or the brief a started member begins on) and that the person then stops now ends \"stopped by the person\" (teams.StoppedByPerson); it wakes the manager and is delivered as \"@x's turn on what you handed it was stopped by the person before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask.\" A stopped turn that carried only the person's own request, a stop by the manager's team_stop (whichever interface performs it), the desktop app quitting, and the app ending a paused member's stray wake still end \"stopped\" and still wake nobody; the app's two stops now cancel through StopByClosing and StopByWorkStopped, where they used the person's door. The global manager is not woken by either." - "team_status and the manager's digest gave a member's state as running, asking, idle or failed only. A member's line may now read \"paused by the person; it starts nothing until they resume it\" or \"on standby; no work handed out yet\", carries the member's role after its handle (\"- @dev, macOS developer\"), and may add \"has not started on #22\" (only for a member that is not in a turn) or \"its last turn was stopped by the person\"." - "Accepting a crew proposal (crews.create from proposal) started every helper at once on its brief. Each helper now joins on standby (teams.Member.Standby, cleared by the member's session once its start line is handed to it): its start line starts no turn, however much later the first directive comes, the traffic says \"opened @x on standby; it starts on its manager's first directive\", and the first directive hands it that line marked \"◆ your standing role from manager (what you are here for, not work to begin; work arrives as a directive)\" in place of \"◆ brief from manager\". team_start and members.start still start a member on its brief at once." - "A proposal's role name was kept only as an app-layer role with no instructions, so it reached neither the member nor the manager. It is now also the team's record (teams.Member.Role, File.SetRole): the member's team note says \"Your role in this team: .\", and the manager's roster shows the role in place of the title (\"@dev (macOS developer)\"). members.role and a role's rename write it too." - "The crew proposal prompt asked for each helper's brief as the \"whole assignment\". It now asks for \"what this helper is responsible for\", and says an accepted crew joins on standby." - "The desktop app stopped every turn it had not started itself on a paused member, including one the person opened by typing to that member from another window. It now leaves a turn the person's own words opened alone, and still stops any other wake (a background process ending, a task landing)." - - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\"." + - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\". It also refuses a member that manages another open team (\"@lead manages and is not paused; stop its turn instead\"), and making a conversation a manager lifts its pause." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 3fdce12fca..e6ef44d924 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -333,9 +333,10 @@ A deliberate message jump opens the activity and tool-call groups that contain t A member of a team that has a manager tells the manager, through the traffic, three things it would never write in a message: -- `finished` when a turn ends, `stopped` when its manager or codeaf itself ended it or you - stopped a turn you had started yourself, `stopped by the person` when you stopped a turn the - team's traffic had started, and `failed: ` with the error's first line when a turn ends on one; +- `finished` when a turn ends, `stopped by the person` when you stopped a turn that had been + handed its manager's work (a directive, or the brief it was started on), `stopped` for every + other stop (its manager's, codeaf ending it, or your stop of a turn that carried only your own + request), and `failed: ` with the error's first line when a turn ends on one; - when it starts waiting on you: the permission line for a permission prompt (`needs your ok to run bash`), or `asks: ` and the question for anything else; - `no longer waiting` when the last of those questions comes down. @@ -345,6 +346,11 @@ nothing you type is ever written to the traffic. `team_status` reads them too, s on a permission prompt shows as `asking` rather than `running`, for as long as some process holds that conversation's transcript and the wait is under 30 minutes. +When you stop a member's turn that had been handed the manager's work, its manager is woken +and told the work is not done, that you chose to stop it, and not to hand it out again unless +you ask. Stopping a turn that carried only what you typed to the member tells the manager +nothing, and neither does codeaf quitting or a paused member's stray wake being ended. + ## Why a member stays asking after it crashed It does not. `asking` means a live process is held on the prompt. If that process dies, the @@ -561,8 +567,8 @@ working, that is straight away. When it is idle, it depends on the kind of messa start (see **Pausing a crew member**). - A **note** wakes nobody. An idle member reads it when it next runs, for whatever reason. - A member's **reply to the manager** (`team_post` to the manager), and a member finishing - without a reply, failing, starting to wait on you, or having a turn the team started stopped - by you, start an idle manager's turn. A reply + without a reply, failing, starting to wait on you, or having a turn that carried the + manager's work stopped by you, start an idle manager's turn. A reply and the end of the same turn are one wake, even if the ending arrives after the manager already ran. Replies arriving within a few seconds are gathered into one turn. @@ -577,10 +583,6 @@ next step`, `@web is waiting on the person and reads it once they answer`, `@web start:` with the reason, or `@web has shown no sign of starting yet`. A manager reports work as under way only where the answer says a member started. -When you stop a member's turn that the team's traffic had started, its manager is woken and -told the work is not done, that you chose to stop it, and not to hand it out again unless you -ask. Stopping a turn you started by typing to the member tells the manager nothing. - ## could not wake ◆ — a wake that cannot be delivered is kept, not dropped When a wake cannot be delivered (the conversation is held by a window that is closing, or @@ -609,9 +611,11 @@ The ten wakes count ten replies when each member turn replies and then finishes. You can pause a member of a crew in the desktop app: **Pause** on its row in the Members tab or in the member's menu, and **Resume** to lift it. A pause stops the member's current turn and is kept on the team's own record, so the member's session, its manager and every window -read the same answer. The manager itself cannot be paused; stop its turn instead. +read the same answer. A crew's manager, and a member that manages a crew of its own, cannot +be paused; stop its turn instead. -While a member is paused, team traffic starts no turn for it, in any crew it belongs to: +While a member is paused, team traffic starts no turn for it, in any crew it belongs to, and +Resume from any of those crews lifts it: - A directive waits on the crew's log, unread. The traffic says `held @web: the person paused it; it starts on this when they resume it`, once per directive. diff --git a/internal/session/hermetic_test.go b/internal/session/hermetic_test.go index 7f2edc6846..286278d463 100644 --- a/internal/session/hermetic_test.go +++ b/internal/session/hermetic_test.go @@ -60,12 +60,6 @@ func runTests(m *testing.M) int { fmt.Fprintf(os.Stderr, "session tests: %v\n", err) return 1 } - // The guard watches wherever this machine actually keeps its state: the real - // home, or the CODEAF_HOME a developer had already pointed somewhere else. - // It asks [home.InheritedDir] rather than [home.Dir] because Dir hands a - // test binary a throwaway root of its own (internal/home/undertest.go), and - // a guard watching that would be watching the very directory it exists to - // keep the files out of. // A DIRECTIVE'S ANSWER WAITS TO SEE ITS MEMBERS START (team_sendoutcome.go), // four seconds as shipped. Most tests that send one have no member that // could start and assert nothing about the outcome, so the package waits a @@ -74,6 +68,12 @@ func runTests(m *testing.M) int { teamWatchClockMu.Lock() teamSendSettle, teamSendLook = 250*time.Millisecond, 5*time.Millisecond teamWatchClockMu.Unlock() + // The guard watches wherever this machine actually keeps its state: the real + // home, or the CODEAF_HOME a developer had already pointed somewhere else. + // It asks [home.InheritedDir] rather than [home.Dir] because Dir hands a + // test binary a throwaway root of its own (internal/home/undertest.go), and + // a guard watching that would be watching the very directory it exists to + // keep the files out of. real := home.InheritedDir() before := journalTrees(real) // AND THE CHECKOUT THIS BINARY IS RUNNING IN, for the same reason and at the diff --git a/internal/session/team.go b/internal/session/team.go index fc199334b5..42b032a745 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -258,6 +258,11 @@ type teamSeat struct { // thread.go). Memory only: a conversation reopened answers nothing until // the manager next speaks to it, which reads as a thread of its own. answering map[string]string + // handed is, per team, when this conversation was first handed work by + // that team's manager (a directive, or the brief it was started on) since + // its last turn ended. A turn's ending takes it ([Agent.teamHandedTake]): + // it is what makes a stop of that turn the stop of handed-out work. + handed map[string]time.Time } // teamAnsweringLocked is the id this conversation's replies in team id answer @@ -754,15 +759,16 @@ func (a *Agent) teamNewsLocked(profile string, roles []teamRole) string { if teamWakes(role, entry) { save = true } - if role.standby && entry.Kind == teams.KindStart && entry.ID == role.startID { - // Its start line is being handed over: standby is over. - a.teamStandbyOver(profile, role) - } if !role.joinedAt.IsZero() && entry.At.Before(role.joinedAt) && !a.teamOwnStart(role, entry) { continue } if line := a.teamEntryLineLocked(profile, role, entry); line != "" { lines = append(lines, line) + if role.standby && entry.Kind == teams.KindStart && !role.manager { + // Its start line is handed over: standby is over. + a.teamStandbyOver(profile, role) + } + a.teamHandedLocked(role, entry) // WHAT THE MANAGER LAST SAID TO IT IS WHAT IT ANSWERS, until the // manager says something else: its next reply to the manager, and // the events its turn raises, name it. @@ -825,6 +831,13 @@ func (a *Agent) firstTeamCursor(profile string, role teamRole) string { if err != nil { return teamLogStart } + // AND A MEMBER WITH DIRECTIVES HELD BY A PAUSE STARTS BEFORE THE OLDEST OF + // THEM. A paused member is left closed, so nothing of its own wrote down + // where it was; the sender's "held" line is the record that a directive is + // owed to it, and with no cursor saved none of them was ever delivered. + if held := teamHeldFirst(role, tail); held != "" { + return teamCursorBefore(held) + } born := a.startedAt if since := a.config.TeamListeningSince; !since.IsZero() && since.Before(born) { born = since diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 0893be8d64..25021dc4f4 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -34,6 +34,7 @@ package session import ( "strings" + "time" "github.com/Agent-Field/codeaf/internal/guard" "github.com/Agent-Field/codeaf/internal/teams" @@ -183,45 +184,99 @@ func (a *Agent) teamPausedSince(profile string, roles []teamRole) []teamRole { return kept } -// teamStoppedByPerson reports whether a stopped turn's ending is said as the -// person's ([teams.StoppedByPerson]), which wakes the manager: the person -// stopped work that team traffic had started, and nothing else tells the +// teamHandedLocked notes that role's manager handed this conversation work: +// a directive, or the brief a started member begins on. A standby member's +// start line is its role, not work. The caller holds a.team.mu. +func (a *Agent) teamHandedLocked(role teamRole, entry teams.Entry) { + if role.manager || entry.From != teams.FromManager { + return + } + if entry.Kind != teams.KindDirective && (entry.Kind != teams.KindStart || role.standby) { + return + } + if a.team.handed == nil { + a.team.handed = map[string]time.Time{} + } + if _, already := a.team.handed[role.id]; !already { + a.team.handed[role.id] = time.Now() + } +} + +// teamHandedTake is the teams that handed this conversation work since its +// last turn ended, with when, taken: the turn now ending is the one that had it. +func (a *Agent) teamHandedTake() map[string]time.Time { + a.team.mu.Lock() + defer a.team.mu.Unlock() + handed := a.team.handed + a.team.handed = nil + return handed +} + +// teamStoppedByPerson is the teams in which a stopped turn's ending is said as +// the person's ([teams.StoppedByPerson]), which wakes that team's manager: the +// person stopped work the manager had handed out, and nothing else tells the // manager it ended without a report. // -// THREE THINGS MUST HOLD. The cancel came through the person's door. The turn -// was not opened by the person's own message: a person who types into a member -// and stops it has stopped their own request, which the manager never handed -// out. And no manager's stop is on the log for this turn: an interface holding -// the member performs the manager's `team_stop` through the same door as the -// person's stop key (the app, the terminal, a remote window), usually before -// the member's own session reads the line, so the door alone would call the -// manager's stop the person's. -func (a *Agent) teamStoppedByPerson(door StopDoor, origin turnOrigin) bool { - if door != StopByPerson || origin.turn != "" { - return false - } +// THREE THINGS MUST HOLD, PER TEAM. The cancel came through the person's door; +// the app's own stops (quitting, a paused member's stray wake) name another. +// The turn was handed that manager's work, whoever opened it: a directive read +// at a step of a turn the person had started is as undone by their stop as one +// that woke the member, and a turn that carried only the person's own request +// is theirs alone. And no manager's stop is on that team's log since the work +// was handed over: an interface holding the member performs the manager's +// `team_stop` through the same door as the person's stop key (the app, the +// terminal, a remote window), usually before the member's own session reads +// the line, so the door alone would call the manager's stop the person's. +func (a *Agent) teamStoppedByPerson(door StopDoor, handed map[string]time.Time) map[string]bool { profile := a.config.teamProfile() - if profile == "" { - return false + if door != StopByPerson || profile == "" || len(handed) == 0 { + return nil } - a.mu.Lock() - turnAt := a.teamTurnAt - a.mu.Unlock() + var by map[string]bool for _, role := range a.teamRoles() { - if !role.managed || role.manager || role.handle == "" { + since, was := handed[role.id] + if !was || !role.managed || role.manager || role.shared || role.handle == "" { continue } tail, err := teams.ReadTraffic(profile, role.id, "", teamFirstLook) if err != nil { continue } + managers := false for _, entry := range tail { if entry.Kind == teams.KindStop && entry.From == teams.FromManager && (entry.Member == role.key || entry.Member == "" && entry.To == role.handle) && - !entry.At.Before(turnAt) { - return false + !entry.At.Before(since) { + managers = true + } + } + if !managers { + if by == nil { + by = map[string]bool{} } + by[role.id] = true } } - return true + return by +} + +// teamHeldFirst is the oldest directive in tail that was held for role because +// the person had paused it ([teamHeldPausedText]), "" when there is none. +func teamHeldFirst(role teamRole, tail []teams.Entry) string { + if role.manager || role.handle == "" { + return "" + } + first := "" + for _, entry := range tail { + if entry.Kind != teams.KindEvent || entry.From != teams.FromSystem || entry.Member != role.key || entry.Answers == "" { + continue + } + if !strings.HasPrefix(entry.Text, teamHeldPrefix) || !strings.HasSuffix(entry.Text, teamPausedWhy) { + continue + } + if first == "" || entry.Answers < first { + first = entry.Answers + } + } + return first } diff --git a/internal/session/team_pause_test.go b/internal/session/team_pause_test.go index a13c503f5a..9e10c53690 100644 --- a/internal/session/team_pause_test.go +++ b/internal/session/team_pause_test.go @@ -401,3 +401,194 @@ func TestTeamEventWakesManager(t *testing.T) { } } } + +// A DIRECTIVE READ INSIDE A TURN THE PERSON OPENED is handed-out work all the +// same: stopping that turn leaves it undone, and the manager was told the +// member would read it. The ending is the person's stop of that work. +func TestTeamPersonStopOfATurnThatWasHandedADirective(t *testing.T) { + fastTeamWake(t) + // Auto-wake off, so the directive waits for the turn the person starts. + fixture := makeTeamFixture(t, true, false) + streaming := make(chan struct{}) + web := teamAgent(t, fixture, fixture.web, &scriptedCompleter{steps: []step{thinkingStep(streaming)}}, nil) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header.", At: time.Now()}) + events := mustSubmit(t, web, "what are you working on?") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start") + } + web.Interrupt() + collect(t, events) + web.settleTeamEvents() + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 1 { + t.Fatalf("a stopped turn that had been handed a directive was logged as %+v", trafficEvents(t, fixture, "stopped")) + } +} + +// THE APP'S OWN STOPS ARE NOT THE PERSON'S. Quitting, and ending a paused +// member's stray wake, cancel through another door; the manager is told +// nothing about a choice the person did not make. +func TestTeamMachineryStopIsNotThePersons(t *testing.T) { + for _, door := range []StopDoor{StopByClosing, StopByWorkStopped, StopByTakeover} { + t.Run(string(door), func(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(1) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + streaming := make(chan struct{}) + web := teamAgent(t, fixture, fixture.web, &scriptedCompleter{steps: []step{thinkingStep(streaming)}}, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + web.InterruptFor(door) + deadline := time.Now().Add(5 * time.Second) + for len(trafficEvents(t, fixture, "stopped")) == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + web.settleTeamEvents() + quietFor() + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 0 { + t.Fatalf("a stop through %q was logged as the person's: %+v", door, said) + } + if got := managerCalls.requests(); got != 0 { + t.Fatalf("the manager was woken %d times by a stop through %q", got, door) + } + }) + } +} + +// A STANDBY MEMBER RENAMED BEFORE ITS FIRST WORK still gets its role line: the +// start that made the membership is its own by identity, not by the handle it +// was addressed to. +func TestTeamStandbyRoleLineSurvivesARename(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + start, err := teams.AppendTrafficID(fixture.profile, fixture.teamID, teams.Entry{ + Kind: teams.KindStart, From: teams.FromManager, To: "web", Text: "Owns the web frontend and its tests.", At: time.Now(), + }) + if err != nil { + t.Fatal(err) + } + err = teams.Update(fixture.profile, func(file *teams.File) error { + team := &file.Teams[0] + for i := range team.Members { + if team.Members[i].Handle == "web" { + team.Members[i].Standby = true + team.Members[i].Started, team.Members[i].StartEntry, team.Members[i].StartID = true, start, start + } + } + return file.SetHandle(fixture.teamID, convKeyOf(t, fixture.web), "front") + }) + if err != nil { + t.Fatal(err) + } + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) + webCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.web, webCalls, nil) + sendDirective(t, manager, "front") + waitRequests(t, webCalls, 1) + asked := userTextIn(webCalls.request(0)) + for _, want := range []string{teamStandbyBriefWord, "Owns the web frontend and its tests.", "Fix the header."} { + if !strings.Contains(asked, want) { + t.Fatalf("the renamed member's first turn lacks %q:\n%s", want, asked) + } + } +} + +// A DIRECTIVE HELD FOR A PAUSED MEMBER NOTHING HAD OPEN outlives a restart: the +// sender's "held" line is the record that it is owed. +func TestTeamHeldDirectiveSurvivesForAMemberThatWasNeverOpen(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) + sendDirective(t, manager, "web") + setPaused(t, fixture, fixture.web, false) + file, err := teams.Load(fixture.profile) + if err != nil { + t.Fatal(err) + } + // Opened long after: nothing but the held line says the directive is owed. + late := time.Now().Add(time.Hour) + if !TeamOpenPending(fixture.profile, fixture.web, file, teams.Defaults{Wake: true}, late) { + t.Fatal("the held directive does not ask for the resumed member to be opened") + } + webCalls := oneAnswer(1) + teamAgent(t, fixture, fixture.web, webCalls, func(config *Config) { config.TeamListeningSince = late }) + waitRequests(t, webCalls, 1) + if asked := userTextIn(webCalls.request(0)); strings.Count(asked, "Fix the header.") != 1 { + t.Fatalf("the member opened after the resume was not handed the held directive once:\n%s", asked) + } +} + +// THE PAUSE IS READ AGAIN BEFORE A WAKE HANDS ANYTHING OVER, whatever the look +// that chose the wake had read: called with roles from before the pause, the +// wake holds. +func TestTeamWakeMemberReadsThePauseAfresh(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + webCalls := oneAnswer(1) + web := teamAgent(t, fixture, fixture.web, webCalls, func(config *Config) { config.teamWatchManual = true }) + var stale []teamRole + for _, role := range web.teamRoles() { + if !role.manager { + stale = append(stale, role) + } + } + if len(stale) != 1 || stale[0].paused { + t.Fatalf("the member's roles before the pause are %+v", stale) + } + setPaused(t, fixture, fixture.web, true) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header.", At: time.Now()}) + web.teamWakeMember(fixture.profile, stale, time.Now()) + quietFor() + if got := webCalls.requests(); got != 0 { + t.Fatalf("a wake chosen before the pause started %d turns", got) + } + if woke := trafficEvents(t, fixture, "woke @web"); len(woke) != 0 { + t.Fatalf("the traffic says it woke: %+v", woke) + } + // And the directive is still there for the resume. + setPaused(t, fixture, fixture.web, false) + web.teamWatchTick(fixture.profile, time.Now()) + waitRequests(t, webCalls, 1) + if asked := userTextIn(webCalls.request(0)); !strings.Contains(asked, "Fix the header.") { + t.Fatalf("the resumed member was not handed the directive:\n%s", asked) + } +} + +// A PAUSE HOLDS THE CONVERSATION IN EVERY TEAM, a resume lifts it wherever it +// is pressed, and a conversation that manages a team is not paused at all. +func TestTeamPauseIsTheConversations(t *testing.T) { + fixture, sharedTeam, _ := linkedFixture(t) + key := convKeyOf(t, fixture.web) + roles := func() []teamRole { + file, err := teams.Load(fixture.profile) + if err != nil { + t.Fatal(err) + } + return rolesFor(file, []string{key}, teams.Defaults{Wake: true}) + } + if got := len(roles()); got != 2 { + t.Fatalf("the fixture's web member is in %d teams, want two", got) + } + setPaused(t, fixture, fixture.web, true) + for _, role := range roles() { + if !role.manager && !role.paused { + t.Fatalf("paused in one team, the member is not held in %q", role.name) + } + } + // Resumed from the other team. + if err := teams.Update(fixture.profile, func(file *teams.File) error { return file.SetPaused(sharedTeam, key, false) }); err != nil { + t.Fatal(err) + } + for _, role := range roles() { + if role.paused { + t.Fatalf("resumed from another team, the member is still held in %q", role.name) + } + } +} diff --git a/internal/session/team_pending.go b/internal/session/team_pending.go index 54e2d435a9..7c8ce7dd10 100644 --- a/internal/session/team_pending.go +++ b/internal/session/team_pending.go @@ -52,7 +52,7 @@ func pendingTeamEntry(profile string, role teamRole, entry teams.Entry) bool { if role.manager && entry.Kind == teams.KindEvent && entry.State == teams.StateFinished && teamFinishedAfterReply(profile, role.id, entry) { return false } - if !role.manager && entry.Kind == teams.KindStart && entry.To == role.handle { + if !role.manager && entry.Kind == teams.KindStart && (entry.To == role.handle || (role.startID != "" && entry.ID == role.startID)) { // A standby start is a role to read at the first turn, not work that // needs the conversation open. return !role.standby diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index bc1a02b37a..a92a176d2e 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -76,6 +76,10 @@ type teamEvent struct { // and another has begun, so it reads this copy and nothing about the // agent's current turn (turn_origin.go). origin turnOrigin + // byPerson is the teams in which this ending is the person stopping work + // that team's manager had handed out ([Agent.teamStoppedByPerson]): there + // the text is [teams.StoppedByPerson] and the manager is woken. + byPerson map[string]bool } // eventfulRoles reports whether roles make this conversation one whose events @@ -91,13 +95,19 @@ func eventfulRoles(roles []teamRole) bool { // teamEventOwed queues one event, and starts the writer when none is running. func (a *Agent) teamEventOwed(origin turnOrigin, state, text string) { + a.teamEventOwedFor(origin, state, text, nil) +} + +// teamEventOwedFor is [Agent.teamEventOwed] for a stopped turn, with the teams +// in which the stop is the person's stop of handed-out work. +func (a *Agent) teamEventOwedFor(origin turnOrigin, state, text string, byPerson map[string]bool) { if !a.team.events.member.Load() || a.config.teamProfile() == "" { return } lane := &a.team.events lane.mu.Lock() defer lane.mu.Unlock() - lane.queue = append(lane.queue, teamEvent{state: state, text: cutRunesTeam(oneLineTeam(text), teamEventText), at: time.Now(), origin: origin}) + lane.queue = append(lane.queue, teamEvent{state: state, text: cutRunesTeam(oneLineTeam(text), teamEventText), at: time.Now(), origin: origin, byPerson: byPerson}) if lane.done == nil { done := make(chan struct{}) lane.done = done @@ -136,6 +146,10 @@ func (a *Agent) writeTeamEvent(event teamEvent) { if !role.managed || role.manager || role.handle == "" { continue } + text := event.text + if event.byPerson[role.id] { + text = teams.StoppedByPerson + } // The event answers what the member was last told by its manager, so // the rail folds it into that thread's reply (internal/teams' thread.go). err := teams.AppendTraffic(profile, role.id, teams.Entry{ @@ -144,7 +158,7 @@ func (a *Agent) writeTeamEvent(event teamEvent) { From: role.handle, To: teams.ToManager, Member: role.key, - Text: event.text, + Text: text, State: event.state, Answers: a.teamAnswering(role.id), // The run is the one that was current when the event was QUEUED; @@ -154,7 +168,7 @@ func (a *Agent) writeTeamEvent(event teamEvent) { if err != nil || !role.wakes { continue } - if teamEventWakesManager(event.state, event.text) && !(role.root && event.state == teams.StateIdle) { + if teamEventWakesManager(event.state, text) && !(role.root && event.state == teams.StateIdle) { // These wake the manager, so a manager nobody has open is opened // (team_wakewatch.go). a.rouseManager(profile, role, event.origin.provenance(role.key)) @@ -203,15 +217,13 @@ func (a *Agent) teamTurnEnded(ctx context.Context, hub *eventHub) { a.dropOwedResume() origin := turnOriginFrom(ctx) if err := hub.turnError(); err != nil { + a.teamHandedTake() a.teamEventOwed(origin, teams.StateFailed, "failed: "+firstLineTeam(err.Error())) return } + handed := a.teamHandedTake() if door, stopped := stopCause(ctx); stopped { - text := "stopped" - if a.teamStoppedByPerson(door, origin) { - text = teams.StoppedByPerson - } - a.teamEventOwed(origin, teams.StateIdle, text) + a.teamEventOwedFor(origin, teams.StateIdle, "stopped", a.teamStoppedByPerson(door, handed)) return } a.teamEventOwed(origin, teams.StateFinished, "finished") @@ -381,7 +393,11 @@ const teamBriefText = teams.BriefTextMax // manager wrote; every other reader is told nothing, because the interface // performs a start and the manager already knows what it asked for. func teamBriefLine(role teamRole, entry teams.Entry) string { - if role.manager || role.handle == "" || entry.From != teams.FromManager || entry.To != role.handle { + // The start that made this membership is its own by identity, whatever + // the member has been renamed to since; one written before that was kept + // is its own by the handle it was addressed to. + own := entry.To == role.handle || (role.startID != "" && entry.ID == role.startID) + if role.manager || role.handle == "" || entry.From != teams.FromManager || !own { return "" } text := strings.TrimSpace(entry.Text) diff --git a/internal/teams/digest.go b/internal/teams/digest.go index 9be1b010c5..9a326b1810 100644 --- a/internal/teams/digest.go +++ b/internal/teams/digest.go @@ -138,6 +138,9 @@ func lastWord(m Member, recent []Entry) string { for i := len(recent) - 1; i >= 0; i-- { e := recent[i] switch { + case e.From == m.Handle && e.Member != "" && e.Member != m.Key: + // A line under this member's name about somebody else: the wake + // its reply gave the manager ("woke ◆"). case e.From == m.Handle: if e.Kind == KindEvent && e.State == StateIdle && e.Text == StoppedByPerson { return "its last turn was " + StoppedByPerson @@ -183,14 +186,15 @@ func memberLine(m Member, s MemberState, manager bool, last string) string { if s.ReportsTo != "" && state == StateRunning { state = "busy for " + s.ReportsTo } - resting := state == StateIdle || state == "unknown" + resting := state != StateRunning && state != StateAsking && !strings.HasPrefix(state, "busy for ") + quiet := state == StateIdle || state == "unknown" switch { case manager: - case (m.Paused || s.Paused) && resting: + case (m.Paused || s.Paused) && quiet: state = DigestPaused case m.Paused || s.Paused: state += ", " + DigestPaused - case m.Standby && resting: + case m.Standby && quiet: state = DigestStandby } b.WriteString(": " + state) diff --git a/internal/teams/digest_test.go b/internal/teams/digest_test.go index 2f7b8956f4..1504d48b28 100644 --- a/internal/teams/digest_test.go +++ b/internal/teams/digest_test.go @@ -166,3 +166,62 @@ func TestSetPausedAndSetRole(t *testing.T) { t.Fatalf("a member did not survive its own JSON: %+v, %v (%s)", back, err, raw) } } + +// A manager woken by its member's stopped turn still reads that it was stopped: +// the wake line is written under the member's name, about the manager. +func TestDigestKeepsTheStoppedTurnAfterTheManagersWake(t *testing.T) { + team := Team{Name: "harbor", Manager: "m", Members: []Member{{Key: "m", Handle: "boss"}, {Key: "a", Handle: "web"}, {Key: "b", Handle: "api"}}} + at := time.Date(2026, 11, 23, 22, 2, 0, 0, time.UTC) + recent := []Entry{ + {ID: "000000000001", At: at, Kind: KindDirective, From: FromManager, To: "web", Text: "Build it."}, + {ID: "000000000002", At: at, Kind: KindEvent, From: FromManager, To: "web", Member: "a", State: StateRunning, Text: "woke @web"}, + {ID: "000000000003", At: at, Kind: KindEvent, From: "web", To: ToManager, Member: "a", State: StateIdle, Text: StoppedByPerson}, + {ID: "000000000004", At: at, Kind: KindEvent, From: "web", To: ToManager, Member: "m", State: StateRunning, Text: "woke ◆"}, + {ID: "000000000005", At: at, Kind: KindDirective, From: FromManager, To: "api", Text: "Then this."}, + } + states := map[string]MemberState{"a": {State: StateIdle}, "b": {State: StateFailed}} + got := Digest(team, states, recent, 0) + for _, want := range []string{ + "- @web: idle, its last turn was " + StoppedByPerson, + // A member whose last turn failed is not in a turn either. + "- @api: failed, has not started on #5", + } { + if !strings.Contains(got, want+"\n") { + t.Errorf("the digest lacks the line\n%s\nin\n%s", want, got) + } + } +} + +// A conversation that manages a team anywhere is not paused, a resume lifts a +// pause in every team, and becoming a manager lifts it too. +func TestPauseAcrossTeams(t *testing.T) { + file := &File{Teams: []Team{ + {ID: "top", Name: "harbor", Manager: "m", Members: []Member{{Key: "m", Handle: "boss"}, {Key: "lead", Handle: "lead"}, {Key: "a", Handle: "dev"}}}, + {ID: "sub", Name: "dock", Parent: "top", Manager: "lead", Members: []Member{{Key: "lead", Handle: "lead"}, {Key: "a", Handle: "dev"}}}, + }} + if err := file.SetPaused("top", "lead", true); err == nil || !strings.Contains(err.Error(), "manages dock") { + t.Fatalf("pausing a sub-team's manager in the team above answered %v", err) + } + if err := file.SetPaused("top", "a", true); err != nil { + t.Fatal(err) + } + if name, paused := file.PausedAnywhere("a"); !paused || name != "harbor" { + t.Fatalf("paused anywhere: %q %v", name, paused) + } + if err := file.SetPaused("sub", "a", false); err != nil { + t.Fatal(err) + } + if _, paused := file.PausedAnywhere("a"); paused { + t.Fatal("a resume from another team left the pause") + } + if err := file.SetPaused("top", "a", true); err != nil { + t.Fatal(err) + } + file.Teams = append(file.Teams, Team{ID: "new", Name: "pier", Members: []Member{{Key: "a", Handle: "dev"}}}) + if err := file.SetManager("new", "a"); err != nil { + t.Fatal(err) + } + if _, paused := file.PausedAnywhere("a"); paused { + t.Fatal("a conversation made a manager is still paused") + } +} diff --git a/internal/teams/teams.go b/internal/teams/teams.go index 1df36e78a8..b18f05835d 100644 --- a/internal/teams/teams.go +++ b/internal/teams/teams.go @@ -592,9 +592,15 @@ func (f *File) SetManager(id, key string) error { f.Teams[idx].FormerManager = old } f.Teams[idx].Manager = key - // A manager is neither paused nor on standby: the person talks to it. + // A manager is neither paused nor on standby, here or as a member of + // another team: the person talks to it. if j := f.Teams[idx].member(key); j >= 0 { - f.Teams[idx].Members[j].Paused, f.Teams[idx].Members[j].Standby = false, false + f.Teams[idx].Members[j].Standby = false + } + for ti := range f.Teams { + if k := f.Teams[ti].member(key); k >= 0 { + f.Teams[ti].Members[k].Paused = false + } } assignHandles(&f.Teams[idx]) if f.Teams[idx].Root { @@ -664,7 +670,24 @@ func (f *File) SetPaused(id, key string, paused bool) error { if paused && t.Manager == key { return fmt.Errorf("the manager of %s is not paused; stop its turn instead", t.Name) } - t.Members[j].Paused = paused + if paused { + // A conversation that manages a team anywhere is the person's to talk + // to, and its own team's replies wake it: a pause in the team above + // would hold some of its wakes and not others. + if managed := f.ManagedTeams(key); len(managed) > 0 { + return fmt.Errorf("%s manages %s and is not paused; stop its turn instead", address(t.Members[j]), managed[0].Name) + } + t.Members[j].Paused = true + return nil + } + // A RESUME LIFTS THE PAUSE WHEREVER IT WAS PRESSED. The pause holds the + // conversation in every team it is a member of ([File.PausedAnywhere]), so + // the team the person resumes it from need not be the one they paused it in. + for ti := range f.Teams { + if k := f.Teams[ti].member(key); k >= 0 { + f.Teams[ti].Members[k].Paused = false + } + } return nil } From 6f45b54a758aeb770d1f83bc344c19cd25a40632 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:54:20 -0500 Subject: [PATCH 05/37] teams: a stop in a team holds when a background command ends A stop leaves background commands running, and a command's ending starts a turn. In a team the two undid the stop: a stopped member whose command later exited was woken and reported the stopped work done. From a stop of a running turn until a turn next begins, a conversation with a team role now keeps such an ending, and a watch's firing, as a record that starts no turn. The command is still left running, and a conversation in no team is unchanged. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2897-crew-handoff-outcome.md | 1 + internal/manual/chat/team-manager.md | 15 ++++ internal/session/agent.go | 11 +++ internal/session/image.go | 1 + internal/session/team.go | 5 ++ internal/session/team_stophold.go | 67 ++++++++++++++ internal/session/team_stophold_test.go | 87 +++++++++++++++++++ 7 files changed, 187 insertions(+) create mode 100644 internal/session/team_stophold.go create mode 100644 internal/session/team_stophold_test.go diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index f5e3abbb22..b1400bd5e9 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -14,6 +14,7 @@ invalidates: - "The crew proposal prompt asked for each helper's brief as the \"whole assignment\". It now asks for \"what this helper is responsible for\", and says an accepted crew joins on standby." - "The desktop app stopped every turn it had not started itself on a paused member, including one the person opened by typing to that member from another window. It now leaves a turn the person's own words opened alone, and still stops any other wake (a background process ending, a task landing)." - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\". It also refuses a member that manages another open team (\"@lead manages and is not paused; stop its turn instead\"), and making a conversation a manager lifts its pause." + - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop that an interface performs) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. The command is still left running by the stop, and a conversation in no team is unchanged." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index e6ef44d924..041402bb86 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -351,6 +351,21 @@ and told the work is not done, that you chose to stop it, and not to hand it out you ask. Stopping a turn that carried only what you typed to the member tells the manager nothing, and neither does codeaf quitting or a paused member's stray wake being ended. +## A stopped member's command is still running — why it did not start again when the command ended + +Stopping a turn leaves a command it started in the background running, as it does in any +conversation. In a crew, that command's ending does not start the conversation again. From +a stop of a running turn (yours, or the manager's `team_stop`) until a turn next begins, the +ending of a background command, or a watch firing, is written into the conversation as a +record and starts no turn. This holds for a member and for the manager. + +The conversation starts again when somebody means it to: your own message to it, or the +manager's next hand-off. That turn reads the record, which says it arrived after the stop +and is no reason to take the stopped work up again. + +To end the command itself, use **Stop all** on the conversation's Processes tab. A +conversation in no crew is unchanged: there a command's ending still starts its turn. + ## Why a member stays asking after it crashed It does not. `asking` means a live process is held on the prompt. If that process dies, the diff --git a/internal/session/agent.go b/internal/session/agent.go index 36066243eb..984133b043 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -2104,6 +2104,7 @@ func (a *Agent) startTurnLocked(ctx context.Context, user userMessage, watcher * a.rebindClientLocked(a.model) a.stopJobWakeLocked() a.running = true + a.teamStopHoldOver() a.takeHeldNotesLocked() a.factoryAutomaticTurn = user.factoryWork || user.wake && !user.answersPerson && !user.answer a.runnerTurn = user.runner @@ -2647,6 +2648,7 @@ func (a *Agent) interruptNamed(door StopDoor, name string) { a.interrupt.begin() a.mu.Lock() cancel := a.cancel + a.teamStopHoldLocked(door) cutPass := a.cutManualPassLocked() a.dropFollowUpsLocked() // AND THE SECOND LOOK AT A YOUNG COMMAND IS RELEASED BEFORE THIS LOCK IS, @@ -4233,12 +4235,18 @@ func (a *Agent) enqueueSettleSteering(text string, ceiling int) { // as [jobRegistry.settleExit] composed it. The whole log remains available // through `jobs output` for anything past the tail. func (a *Agent) enqueueJobNote(text string) { + if a.teamStopHeldNote(text) { + return + } a.enqueueNote(jobNote(text)) } // enqueueJobNoteUnowed carries the registry's unowed process ending to the // same queue, retaining the one fact the idle wake scheduler needs. func (a *Agent) enqueueJobNoteUnowed(text string) { + if a.teamStopHeldNote(text) { + return + } note := jobNote(text) note.deferJobWake = true a.enqueueNote(note) @@ -4288,6 +4296,9 @@ func (a *Agent) enqueueJobNoteQuiet(text string) { // news does not carry one. func (a *Agent) enqueueWatchNote(name, text string, fired bool) { if fired { + if a.teamStopHeldNote(text) { + return + } note := wakeNote(text) note.otherResults = true note.attention = true diff --git a/internal/session/image.go b/internal/session/image.go index 7180988a3d..c668417ebb 100644 --- a/internal/session/image.go +++ b/internal/session/image.go @@ -449,6 +449,7 @@ func (a *Agent) startVisionTurnLocked(ctx context.Context, kept userMessage, liv return refusedStream(err) } a.running = true + a.teamStopHoldOver() a.runnerTurn = false hub := a.newReplayHubLocked() a.hub = hub diff --git a/internal/session/team.go b/internal/session/team.go index 42b032a745..96628cf284 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -263,6 +263,9 @@ type teamSeat struct { // its last turn ended. A turn's ending takes it ([Agent.teamHandedTake]): // it is what makes a stop of that turn the stop of handed-out work. handed map[string]time.Time + // stopHold is the person's stop of this conversation's turn while it sat + // in a team, kept until a turn next begins (team_stophold.go). + stopHold teamStopHold } // teamAnsweringLocked is the id this conversation's replies in team id answer @@ -375,6 +378,7 @@ func (a *Agent) teamRolesLocked(profile string) []teamRole { if !now.present { a.team.teamsAt, a.team.roles, a.team.file = now, nil, nil a.team.events.member.Store(false) + a.team.stopHold.seated.Store(false) return nil } file, err := teamView(profile, keys) @@ -388,6 +392,7 @@ func (a *Agent) teamRolesLocked(profile string) []teamRole { a.team.roles = rolesFor(file, keys, a.team.defaults) a.team.file = file a.team.events.member.Store(eventfulRoles(a.team.roles)) + a.team.stopHold.seated.Store(len(a.team.roles) > 0) return a.team.roles } diff --git a/internal/session/team_stophold.go b/internal/session/team_stophold.go new file mode 100644 index 0000000000..9a3a0abe4e --- /dev/null +++ b/internal/session/team_stophold.go @@ -0,0 +1,67 @@ +package session + +// A stop in a team holds until a turn next begins. +// +// An interrupt leaves background commands running (jobstop.go), and a +// command's ending is news that starts a turn ([Agent.enqueueJobNote]). In a +// team the two together undid the stop. Measured 2026-11-24 in the desktop +// app: the person stopped two members that had each started `sleep 200` with +// notify, the manager was told the work was stopped and not to hand it out +// again, and three minutes later both commands ended, woke their members and +// each reported the stopped work done. A crew's Stop used to leave a pause +// that ended such wakes (cmd/codeaf's appwakes.go); it no longer pauses. +// +// So in a team, from a stop of a running turn until a turn next begins, the +// ending of a background command and a watch's firing are kept as a record and +// start no turn. The stop is the one that comes through the person's door: the +// person's own, and a manager's team_stop, which an interface performs through +// that door (teamevent.go). The command itself is left running, as an interrupt +// always leaves it. What starts the conversation again is somebody meaning to: +// the person's own words, or the manager's next hand-off. +// +// A conversation in no team is untouched: there the ending of a command the +// person asked to hear about still starts its turn. + +import ( + "strings" + "sync/atomic" +) + +// teamStopHeldRule is said with a command's ending that started no turn. +const teamStopHeldRule = "This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it." + +// teamStopHold is one conversation's hold. +type teamStopHold struct { + // seated is whether this conversation has a role in any team, as of the + // last time its roles were read. Read without a lock or a disk. + seated atomic.Bool + // held is set by a stop of a running turn through the person's door and + // cleared when a turn next begins. + held atomic.Bool +} + +// teamStopHoldLocked begins the hold when the stop came through the person's +// door and a turn is running. The caller holds a.mu. +func (a *Agent) teamStopHoldLocked(door StopDoor) { + if door != StopByPerson || !a.running || !a.team.stopHold.seated.Load() { + return + } + a.team.stopHold.held.Store(true) +} + +// teamStopHoldOver ends the hold: a turn has begun. +func (a *Agent) teamStopHoldOver() { a.team.stopHold.held.Store(false) } + +// teamStopHeldNote keeps one piece of background news as a record when the +// hold stands, and reports whether it did. A worker parked on the command is +// released with it, as the waking note would have released it. +func (a *Agent) teamStopHeldNote(text string) bool { + if !a.team.stopHold.held.Load() { + return false + } + a.mu.Lock() + a.releaseTaskWaitLocked() + a.mu.Unlock() + a.enqueueJobNoteQuiet(strings.TrimSpace(text) + "\n" + teamStopHeldRule) + return true +} diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go new file mode 100644 index 0000000000..52a9bbfa21 --- /dev/null +++ b/internal/session/team_stophold_test.go @@ -0,0 +1,87 @@ +package session + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" +) + +func okStep() step { + return func(context.Context, []ai.Message) (*ai.Response, error) { return textResponse("ok"), nil } +} + +// A STOP OF A MEMBER HOLDS. A command the stopped turn left running +// ends later, and its ending is a record that starts no turn: not the lane a +// failure takes, not the one a command the work waited on takes, not a watch's +// firing. The manager's next hand-off starts the member, and from then on a +// command's ending starts its turn again. +func TestTeamPersonStopKeepsACommandEndingFromStartingATurn(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(8), nil) + streaming := make(chan struct{}) + calls := &scriptedCompleter{steps: []step{thinkingStep(streaming), okStep(), okStep(), okStep()}} + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + one := settlementJob(t, web.jobs) + web.Interrupt() + waitQuiet(t, web) + + web.jobs.settleExit(one, 7) + web.enqueueJobNote("job 8 exited 0") + web.enqueueWatchNote("checks", "the checks settled", true) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times, want only the turn the person stopped", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"job 1 exited 7", "job 8 exited 0", "the checks settled"} { + if !strings.Contains(string(journal), want) { + t.Fatalf("the ending %q was not kept as a record:\n%s", want, journal) + } + } + if got := strings.Count(string(journal), teamStopHeldRule); got != 3 { + t.Fatalf("the record said why it started no turn %d times, want 3", got) + } + + sendDirective(t, manager, "web") + waitRequests(t, calls, 2) + waitQuiet(t, web) + web.enqueueJobNote("job 9 exited 0") + waitRequests(t, calls, 3) +} + +// A CONVERSATION IN NO TEAM IS UNTOUCHED: the ending of a command still starts +// its turn after the person stopped the one before. +func TestPersonStopOutsideATeamStillHearsACommandEnd(t *testing.T) { + a, client, _, wakes, _ := jobWakeFixture(t) + streaming := make(chan struct{}) + client.steps = []step{thinkingStep(streaming), okStep()} + events := mustSubmit(t, a, "think about this for a while") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the turn did not start") + } + a.Interrupt() + collect(t, events) + a.enqueueJobNote("job 1 exited 0") + select { + case stream := <-wakes: + collect(t, stream) + case <-time.After(5 * time.Second): + t.Fatal("a command's ending started no turn in a conversation that is in no team") + } +} From 800bc610fefbb3e5bcb531be770e9696887021a8 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:13:51 -0500 Subject: [PATCH 06/37] teams: a stop also holds a member that only waits on its command A member often starts a long command in the background, ends its turn and waits to be told how it ended. A stop found no turn to end, so the command's ending woke the member and it reported the stopped work done. A stop through the person's door that finds a command or watch still running now begins the same hold, and the manager that handed out what the last finished turn carried is told the work was stopped. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2897-crew-handoff-outcome.md | 2 +- internal/manual/chat/team-manager.md | 5 + internal/session/agent.go | 5 +- internal/session/team_stophold.go | 98 +++++++++++++++++-- internal/session/team_stophold_test.go | 64 ++++++++++++ internal/session/teamevent.go | 19 +++- 6 files changed, 182 insertions(+), 11 deletions(-) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index b1400bd5e9..941a0d8fb8 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -14,7 +14,7 @@ invalidates: - "The crew proposal prompt asked for each helper's brief as the \"whole assignment\". It now asks for \"what this helper is responsible for\", and says an accepted crew joins on standby." - "The desktop app stopped every turn it had not started itself on a paused member, including one the person opened by typing to that member from another window. It now leaves a turn the person's own words opened alone, and still stops any other wake (a background process ending, a task landing)." - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\". It also refuses a member that manages another open team (\"@lead manages and is not paused; stop its turn instead\"), and making a conversation a manager lifts its pause." - - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop that an interface performs) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. The command is still left running by the stop, and a conversation in no team is unchanged." + - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop that an interface performs) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A stop that finds no turn running but a command or watch still running begins the same hold, and writes \"stopped by the person\" to the teams whose manager handed out what the conversation's last finished turn carried, which wakes that manager. The command is still left running by the stop, and a conversation in no team is unchanged." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 041402bb86..e3c5b70058 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -359,6 +359,11 @@ a stop of a running turn (yours, or the manager's `team_stop`) until a turn next ending of a background command, or a watch firing, is written into the conversation as a record and starts no turn. This holds for a member and for the manager. +A member often starts a long command, ends its turn and waits to be told how it ended. It +reads idle, and a stop still reaches it: **Stop** on a crew's row stops such a member too, +the command's ending starts no turn, and its manager is told the work it handed out was +stopped, as for a stopped turn. + The conversation starts again when somebody means it to: your own message to it, or the manager's next hand-off. That turn reads the record, which says it arrived after the stop and is no reason to take the stopped work up again. diff --git a/internal/session/agent.go b/internal/session/agent.go index 984133b043..15cb0b6b72 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -2648,7 +2648,7 @@ func (a *Agent) interruptNamed(door StopDoor, name string) { a.interrupt.begin() a.mu.Lock() cancel := a.cancel - a.teamStopHoldLocked(door) + waiting := a.teamStopHoldLocked(door) cutPass := a.cutManualPassLocked() a.dropFollowUpsLocked() // AND THE SECOND LOOK AT A YOUNG COMMAND IS RELEASED BEFORE THIS LOCK IS, @@ -2666,6 +2666,9 @@ func (a *Agent) interruptNamed(door StopDoor, name string) { if cancel != nil { cancel(stopAs(door, name)) } + if waiting { + a.teamStopHoldSaid() + } } // Title is the session's name, empty until it has one (title.go). diff --git a/internal/session/team_stophold.go b/internal/session/team_stophold.go index 9a3a0abe4e..5bbb150b8a 100644 --- a/internal/session/team_stophold.go +++ b/internal/session/team_stophold.go @@ -21,10 +21,23 @@ package session // // A conversation in no team is untouched: there the ending of a command the // person asked to hear about still starts its turn. +// +// The stop may also find no turn running. A member commonly starts a long +// command in the background, asks to be told when it ends, and ends its turn: +// measured the same day, a crew's Stop passed over such a member and it +// reported the work done when its command ended. So a stop that finds no turn +// but a command or a watch still running begins the hold too, and the manager +// that handed out the work the last turn carried is told it was stopped, in +// the words a stopped turn uses. import ( "strings" + "sync" "sync/atomic" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/teams" ) // teamStopHeldRule is said with a command's ending that started no turn. @@ -35,22 +48,91 @@ type teamStopHold struct { // seated is whether this conversation has a role in any team, as of the // last time its roles were read. Read without a lock or a disk. seated atomic.Bool - // held is set by a stop of a running turn through the person's door and - // cleared when a turn next begins. + // held is set by a stop through the person's door and cleared when a turn + // next begins. held atomic.Bool + + mu sync.Mutex + // last is what the turn that last finished had been handed, per team, and + // origin is that turn's. It is what a stop that finds no turn running is + // the stop of. A turn beginning forgets it. + last map[string]time.Time + origin turnOrigin } // teamStopHoldLocked begins the hold when the stop came through the person's -// door and a turn is running. The caller holds a.mu. -func (a *Agent) teamStopHoldLocked(door StopDoor) { - if door != StopByPerson || !a.running || !a.team.stopHold.seated.Load() { - return +// door and there is something to hold: a turn running, or a command or watch +// whose ending would be news. It reports whether it began with no turn running, +// which is the stop the manager has yet to be told of ([Agent.teamStopHoldSaid]). +// The caller holds a.mu. +func (a *Agent) teamStopHoldLocked(door StopDoor) bool { + hold := &a.team.stopHold + if door != StopByPerson || !hold.seated.Load() { + return false } - a.team.stopHold.held.Store(true) + if a.running { + hold.held.Store(true) + return false + } + if a.jobs == nil || !a.jobs.newsPending() { + return false + } + return !hold.held.Swap(true) } // teamStopHoldOver ends the hold: a turn has begun. -func (a *Agent) teamStopHoldOver() { a.team.stopHold.held.Store(false) } +func (a *Agent) teamStopHoldOver() { + hold := &a.team.stopHold + hold.held.Store(false) + hold.mu.Lock() + hold.last = nil + hold.mu.Unlock() +} + +// teamStopHoldFinished remembers what a turn that finished had been handed. +func (a *Agent) teamStopHoldFinished(handed map[string]time.Time, origin turnOrigin) { + hold := &a.team.stopHold + hold.mu.Lock() + hold.last, hold.origin = handed, origin + hold.mu.Unlock() +} + +// teamStopHoldSaid tells the managers whose work the last turn carried that +// it was stopped while it waited on a command. It reads the teams' logs, so it +// runs away from the stop's own path. +func (a *Agent) teamStopHoldSaid() { + hold := &a.team.stopHold + hold.mu.Lock() + handed, origin := hold.last, hold.origin + hold.last = nil + hold.mu.Unlock() + if len(handed) == 0 { + return + } + guard.Go("team stop of waiting work", func() { + by := a.teamStoppedByPerson(StopByPerson, handed) + if len(by) == 0 { + return + } + a.teamEventOwedOnly(origin, teams.StateIdle, "stopped", by) + }) +} + +// newsPending reports whether a background command or a watch is still +// running: something whose ending would start a turn. +func (r *jobRegistry) newsPending() bool { + for _, one := range r.all() { + if one.kind != jobKindBash && one.kind != jobKindWatch { + continue + } + select { + case <-one.done: + default: + return true + } + } + return false +} // teamStopHeldNote keeps one piece of background news as a record when the // hold stands, and reports whether it did. A worker parked on the command is diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go index 52a9bbfa21..3bd4b3c0e3 100644 --- a/internal/session/team_stophold_test.go +++ b/internal/session/team_stophold_test.go @@ -8,6 +8,8 @@ import ( "time" "github.com/Agent-Field/agentfield/sdk/go/ai" + + "github.com/Agent-Field/codeaf/internal/teams" ) func okStep() step { @@ -85,3 +87,65 @@ func TestPersonStopOutsideATeamStillHearsACommandEnd(t *testing.T) { t.Fatal("a command's ending started no turn in a conversation that is in no team") } } + +// A STOP THAT FINDS NO TURN BUT A COMMAND STILL RUNNING HOLDS TOO. The member +// started its command, finished its turn and waits to be told how it ended; +// the person's stop then is the stop of that work. Its manager is told so in +// the words a stopped turn uses, and the command's ending starts no turn. +func TestTeamPersonStopOfAMemberWaitingOnACommandHolds(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(8) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + calls := oneAnswer(4) + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + waitRequests(t, calls, 1) + waitQuiet(t, web) + web.settleTeamEvents() + one := settlementJob(t, web.jobs) + + web.Interrupt() + deadline := time.Now().Add(5 * time.Second) + for len(trafficEvents(t, fixture, teams.StoppedByPerson)) == 0 { + if time.Now().After(deadline) { + t.Fatal("the manager's log was not told the person stopped the member's waiting work") + } + time.Sleep(10 * time.Millisecond) + } + web.jobs.settleExit(one, 0) + web.enqueueJobNote("job 8 exited 0") + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times, want only its first turn", got) + } + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 1 { + t.Fatalf("the stop was logged %d times, want once", len(said)) + } + told := false + for i := 0; i < managerCalls.requests(); i++ { + told = told || strings.Contains(userTextIn(managerCalls.request(i)), "@web"+teamStoppedByPersonLine) + } + if !told { + t.Fatal("the manager was not told the work it handed out was stopped") + } +} + +// A STOP WITH NOTHING RUNNING AND NOTHING PENDING HOLDS NOTHING: a command the +// member starts in a later turn still wakes it. +func TestTeamPersonStopOfAnIdleMemberHoldsNothing(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(8), nil) + calls := oneAnswer(4) + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + waitRequests(t, calls, 1) + waitQuiet(t, web) + web.Interrupt() + web.enqueueJobNote("job 8 exited 0") + waitRequests(t, calls, 2) + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 0 { + t.Fatalf("a stop of a member with nothing running was logged as work stopped: %+v", said) + } +} diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index a92a176d2e..4fd13b6bf3 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -80,6 +80,8 @@ type teamEvent struct { // that team's manager had handed out ([Agent.teamStoppedByPerson]): there // the text is [teams.StoppedByPerson] and the manager is woken. byPerson map[string]bool + // only writes the event in the byPerson teams and no other. + only bool } // eventfulRoles reports whether roles make this conversation one whose events @@ -101,13 +103,24 @@ func (a *Agent) teamEventOwed(origin turnOrigin, state, text string) { // teamEventOwedFor is [Agent.teamEventOwed] for a stopped turn, with the teams // in which the stop is the person's stop of handed-out work. func (a *Agent) teamEventOwedFor(origin turnOrigin, state, text string, byPerson map[string]bool) { + a.teamEventQueued(teamEvent{state: state, text: text, origin: origin, byPerson: byPerson}) +} + +// teamEventOwedOnly is [Agent.teamEventOwedFor] written in those teams alone: +// a stop that found no turn running ended nothing in the others. +func (a *Agent) teamEventOwedOnly(origin turnOrigin, state, text string, byPerson map[string]bool) { + a.teamEventQueued(teamEvent{state: state, text: text, origin: origin, byPerson: byPerson, only: true}) +} + +func (a *Agent) teamEventQueued(event teamEvent) { if !a.team.events.member.Load() || a.config.teamProfile() == "" { return } + event.text, event.at = cutRunesTeam(oneLineTeam(event.text), teamEventText), time.Now() lane := &a.team.events lane.mu.Lock() defer lane.mu.Unlock() - lane.queue = append(lane.queue, teamEvent{state: state, text: cutRunesTeam(oneLineTeam(text), teamEventText), at: time.Now(), origin: origin, byPerson: byPerson}) + lane.queue = append(lane.queue, event) if lane.done == nil { done := make(chan struct{}) lane.done = done @@ -146,6 +159,9 @@ func (a *Agent) writeTeamEvent(event teamEvent) { if !role.managed || role.manager || role.handle == "" { continue } + if event.only && !event.byPerson[role.id] { + continue + } text := event.text if event.byPerson[role.id] { text = teams.StoppedByPerson @@ -226,6 +242,7 @@ func (a *Agent) teamTurnEnded(ctx context.Context, hub *eventHub) { a.teamEventOwedFor(origin, teams.StateIdle, "stopped", a.teamStoppedByPerson(door, handed)) return } + a.teamStopHoldFinished(handed, origin) a.teamEventOwed(origin, teams.StateFinished, "finished") } From 2bccf57ca721aedba2d1b2319b6017c3e38dba24 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:11:25 -0500 Subject: [PATCH 07/37] teams: the global manager is not woken by a top-level manager's turn ending Its members are the managers of whole teams, each a conversation the person talks to, and every answer one of them gave ended a turn that woke the global manager. Measured in the desktop app: 22 wakes in one afternoon, 803,496 input tokens, all answered "[no change]"; one such wake had it send the person's own request back to a manager as a directive. It is still woken by a manager's post, question or failure, and it is told never to re-issue the person's request. Co-Authored-By: Claude Fable 5.2 --- internal/manual/chat/team-manager.md | 7 +++ internal/session/team.go | 15 +++++-- internal/session/team_nest_test.go | 66 ++++++++++++++++++++++++++++ internal/session/team_wakewatch.go | 29 +++++++++--- internal/session/teamevent.go | 2 +- 5 files changed, 109 insertions(+), 10 deletions(-) diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index e3c5b70058..eb866f4282 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -532,6 +532,13 @@ report to it, so their questions and conflicts between teams come to it before t you. It can start a new top-level team with `team_start` of kind `team`. Without a global manager, nothing here changes: each top-level manager reports to you. +A top-level manager's turn ending does not start the global manager's turn. You talk to +those managers directly and each answer ends a turn, so the endings stay in `All teams`' +traffic, where `team_status` reads them. The global manager is woken by what a manager posts +to it with `team_post`, by a manager's question or a permission it is held on, and by a +manager's turn failing. It is told never to send a manager your own request to that manager +back as a directive. + ## Conflicts between members and teams When two or more conversations need incompatible things (the form posts JSON, the endpoint diff --git a/internal/session/team.go b/internal/session/team.go index 96628cf284..2421b6f511 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -1712,7 +1712,9 @@ func teamManagerScope(role teamRole, file *teams.File) string { var parts []string if role.root { parts = append(parts, fmt.Sprintf("You are the global manager: %q holds every team, and your members are the managers of the top-level teams, never their members. "+ - "Direct those managers and they pass it on. Their questions and conflicts between teams come to you before the person. team_start with kind team starts a new top-level team.", role.name)) + "Direct those managers and they pass it on. Their questions and conflicts between teams come to you before the person. team_start with kind team starts a new top-level team. "+ + "A manager's turn ending does not start yours; team_status says where each of them stands. "+ + "The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.", role.name)) } else if home, ok := file.Home(role.key); ok && home.Team != role.id { boss := "its manager" if t, ok := file.Team(home.Team); ok { @@ -1751,7 +1753,13 @@ func teamManagerDelivery(role teamRole) string { if !role.wakes { return "This team's auto-wake is off: what you send, and your members' replies, wait for each conversation's next turn, so an idle member does not start on a directive until it next runs." } - return "A directive (team_send kind directive) starts an idle member's turn; a note waits for its next turn. team_send's answer says whether each member started: one the person paused does not start until they resume it, and work is under way only where the answer says so. Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle, so do not wait or poll for them." + // The global manager's turn is not started by a member's turn ending + // ([teamEventWakesManagerOf]). + back := "Members' replies to you, and their finishing, failing or asking," + if role.root { + back = "Members' replies to you, and their failing or asking," + } + return "A directive (team_send kind directive) starts an idle member's turn; a note waits for its next turn. team_send's answer says whether each member started: one the person paused does not start until they resume it, and work is under way only where the answer says so. " + back + " come back to you and start your turn when you are idle, so do not wait or poll for them." } // teamRoster names the manager's members by handle, with the start of each @@ -1806,7 +1814,8 @@ func teamMemberRole(role teamRole) string { } if role.root { return fmt.Sprintf("You are %s in %q because you manage a top-level team: you report to its manager, the global manager. Its directives reach you marked \"◆ from manager\", "+ - "your questions go to it before the person, and you report to it with team_post to the manager.", you, role.name) + "your questions go to it before the person, and you report to it with team_post to the manager. "+ + "Your turn ending does not start its turn: post what it should act on or tell the person, and nothing the person already has from you here.", you, role.name) } if role.boss != "" && role.boss != role.id && !role.shared { said := fmt.Sprintf("You are %s in the team %q, which has no manager of its own, so you answer to the manager of %q: team_post to the manager reaches it, and to the room or a teammate stays in %q.", diff --git a/internal/session/team_nest_test.go b/internal/session/team_nest_test.go index 3d76796870..cffd0dc14e 100644 --- a/internal/session/team_nest_test.go +++ b/internal/session/team_nest_test.go @@ -520,3 +520,69 @@ func TestAnUnmanagedSubTeamsMemberAnswersToTheManagerAbove(t *testing.T) { t.Fatalf("the question's packet: %+v", p) } } + +// THE GLOBAL MANAGER IS NOT WOKEN BY A TOP-LEVEL MANAGER'S TURN ENDING. The +// person talks to that manager directly and each answer ends a turn; what the +// global manager should act on is posted to it, and that still wakes it. +func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { + fastTeamWake(t) + n := newTeamTree(t, "gm", "boss", "web") + n.team(t, "harbor", "", "boss", n.member(t, "boss", "boss"), n.member(t, "web", "web")) + root := "" + if err := teams.Update(n.fixture.profile, func(f *teams.File) error { + root = f.MakeRoot(f.Teams[0].Made) + if err := f.AddMember(root, n.member(t, "gm", "all")); err != nil { + return err + } + return f.SetManager(root, n.key(t, "gm")) + }); err != nil { + t.Fatal(err) + } + gmCalls := oneAnswer(4) + teamAgent(t, n.fixture, n.paths["gm"], gmCalls, nil) + boss := teamAgent(t, n.fixture, n.paths["boss"], oneAnswer(4), nil) + + submitAndWait(t, boss, "plan the release") + boss.settleTeamEvents() + quietFor() + all := teamFixture{profile: n.fixture.profile, teamID: root} + if ended := trafficEvents(t, all, "finished"); len(ended) != 1 { + t.Fatalf("the top-level manager's ending was logged %d times in the team that holds every team, want once", len(ended)) + } + if got := gmCalls.requests(); got != 0 { + t.Fatalf("the global manager was woken %d times by a top-level manager's turn ending", got) + } + + if said, failed := callTool(t, boss.teamPostTool, `{"to":"manager","text":"harbor shipped"}`); failed { + t.Fatalf("the report to the global manager was refused: %q", said) + } + waitRequests(t, gmCalls, 1) + asked := userTextIn(gmCalls.request(0)) + for _, want := range []string{"from @boss: harbor shipped", "A manager's turn ending does not start yours", "and their failing or asking, come back to you"} { + if !strings.Contains(asked, want) { + t.Fatalf("the global manager's turn lacks %q:\n%s", want, asked) + } + } + if strings.Contains(asked, "their finishing") { + t.Fatalf("the global manager is still told a member's finishing starts its turn:\n%s", asked) + } +} + +func TestTeamEventWakesTheGlobalManager(t *testing.T) { + for _, c := range []struct { + state, text string + root, want bool + }{ + {teams.StateFinished, "finished", false, true}, + {teams.StateFinished, "finished", true, false}, + {teams.StateIdle, teams.StoppedByPerson, false, true}, + {teams.StateIdle, teams.StoppedByPerson, true, false}, + {teams.StateFailed, "failed: no key", true, true}, + {teams.StateAsking, "asks: which branch?", true, true}, + {teams.StateRunning, "no longer waiting", true, false}, + } { + if got := teamEventWakesManagerOf(c.root, c.state, c.text); got != c.want { + t.Errorf("root %v, %s %q wakes the manager: %v, want %v", c.root, c.state, c.text, got, c.want) + } + } +} diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index cc8878270d..0e548ef78a 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -441,6 +441,28 @@ func teamEventWakesManager(state, text string) bool { return false } +// teamEventWakesManagerOf is [teamEventWakesManager] for the manager of one +// team, root when that team is the one that holds every team. +// +// The global manager is not woken by a top-level manager's turn ending, +// finished or stopped. Its members are the managers of whole teams, each a +// conversation the person talks to, and every answer one of them gave the +// person ended a turn. Measured 2026-11-24 in the desktop app: one afternoon +// of the person talking to two crew managers woke the global manager 22 times, +// 803,496 input tokens, and it answered "[no change]" to all 22; the day +// before, one such wake had it read a manager's conversation and send the +// person's own request back to that manager as a directive. What a top-level +// manager wants the global manager to act on it posts (a note wakes), and what +// needs somebody still wakes: a failure, and a question or a permission it is +// held on. The ending itself stays in the team's traffic, where team_status +// reads it. +func teamEventWakesManagerOf(root bool, state, text string) bool { + if root { + return state == teams.StateFailed || state == teams.StateAsking + } + return teamEventWakesManager(state, text) +} + // teamWakes reports whether an entry starts this conversation's turn when it // is idle: a directive from the manager to its handle or to everyone, for a // member; a member's post to the manager, or a member's finished, failed or @@ -467,12 +489,7 @@ func teamWakes(role teamRole, entry teams.Entry) bool { case teams.KindNote: return entry.To == teams.ToManager && strings.TrimSpace(entry.Text) != "" case teams.KindEvent: - // The global manager is not woken by a stop the person made in a - // conversation they were talking to directly. - if role.root && entry.State == teams.StateIdle { - return false - } - return teamEventWakesManager(entry.State, entry.Text) + return teamEventWakesManagerOf(role.root, entry.State, entry.Text) } return false } diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index 4fd13b6bf3..697c2b9d8c 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -184,7 +184,7 @@ func (a *Agent) writeTeamEvent(event teamEvent) { if err != nil || !role.wakes { continue } - if teamEventWakesManager(event.state, text) && !(role.root && event.state == teams.StateIdle) { + if teamEventWakesManagerOf(role.root, event.state, text) { // These wake the manager, so a manager nobody has open is opened // (team_wakewatch.go). a.rouseManager(profile, role, event.origin.provenance(role.key)) From 9ff0c232bbf954d429cff33c1ddc005ce832a733 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:12:06 -0500 Subject: [PATCH 08/37] docs: change entry for the quiet global manager (#2906) Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2906-global-manager-quiet.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 docs/changes/unreleased/2906-global-manager-quiet.md diff --git a/docs/changes/unreleased/2906-global-manager-quiet.md b/docs/changes/unreleased/2906-global-manager-quiet.md new file mode 100644 index 0000000000..5de538a807 --- /dev/null +++ b/docs/changes/unreleased/2906-global-manager-quiet.md @@ -0,0 +1,16 @@ +--- +kind: changed +title: The global manager is not woken each time a top-level team's manager ends a turn +pr: 2906 +surface: [engine, chat] +invalidates: + - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team a member's finished event no longer starts the global manager's turn either (teamEventWakesManagerOf): it is woken by a top-level manager's team_post to it, by that manager's failed or asking event, and by nothing else that manager's turn does. A manager nobody has open is likewise no longer opened by a finished event there. Every other team is unchanged." + - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\", and its scope adds \"A manager's turn ending does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\"" + - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending does not start its turn: post what it should act on or tell the person, and nothing the person already has from you here.\"" +--- + +The global manager's members are the managers of whole teams, each a conversation +the person talks to, and every answer one of them gave ended a turn. Measured in +the desktop app, one afternoon of that woke the global manager 22 times for +803,496 input tokens, each answered "[no change]", and one earlier wake had it +send the person's own request back to a manager as a directive. From 4ea2a1238efa3b3ce445a9aeca50fade5e10085e Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:12:26 -0500 Subject: [PATCH 09/37] docs: end each changed statement in the quiet global manager entry with a full stop Co-Authored-By: Claude Fable 5.2 --- docs/changes/unreleased/2906-global-manager-quiet.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changes/unreleased/2906-global-manager-quiet.md b/docs/changes/unreleased/2906-global-manager-quiet.md index 5de538a807..fd50fd4b44 100644 --- a/docs/changes/unreleased/2906-global-manager-quiet.md +++ b/docs/changes/unreleased/2906-global-manager-quiet.md @@ -5,8 +5,8 @@ pr: 2906 surface: [engine, chat] invalidates: - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team a member's finished event no longer starts the global manager's turn either (teamEventWakesManagerOf): it is woken by a top-level manager's team_post to it, by that manager's failed or asking event, and by nothing else that manager's turn does. A manager nobody has open is likewise no longer opened by a finished event there. Every other team is unchanged." - - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\", and its scope adds \"A manager's turn ending does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\"" - - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending does not start its turn: post what it should act on or tell the person, and nothing the person already has from you here.\"" + - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\", and its scope adds \"A manager's turn ending does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the note every turn of the global manager carries." + - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending does not start its turn: post what it should act on or tell the person, and nothing the person already has from you here.\" The rest of that note is as it was." --- The global manager's members are the managers of whole teams, each a conversation From aeb3e9e6960cd8d7f076fb840cc87a2847157a64 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:08:33 -0500 Subject: [PATCH 10/37] tasks: a task that only reads its ground says so when it starts, to its worker, and when it lands A proposal gave a repository as its ground and named no file by path, so the task was a reference: an empty folder of its own, the repository left alone. The receipt said "It works in ", the worker was told nothing, built the project in its own folder and reported it integrated, and the landing had no line. The conversation told the person to run it from the repository. All three now say the ground does not change and where the work is. A manager is also told a task is not a way round a member that did not start. Co-Authored-By: Claude Fable 5.2 --- internal/manual/chat/how-tasks-run.md | 16 +++++ internal/manual/chat/team-manager.md | 5 ++ internal/session/task.go | 16 +++++ internal/session/task_brief.go | 40 +++++++++---- internal/session/task_home_copy_test.go | 9 ++- internal/session/task_reference_test.go | 77 +++++++++++++++++++++++++ internal/session/task_run_belt.go | 27 +++++++++ internal/session/team.go | 3 +- internal/session/workspace_ownership.go | 7 ++- 9 files changed, 182 insertions(+), 18 deletions(-) create mode 100644 internal/session/task_reference_test.go diff --git a/internal/manual/chat/how-tasks-run.md b/internal/manual/chat/how-tasks-run.md index 68e56eb455..28f4f1fdf3 100644 --- a/internal/manual/chat/how-tasks-run.md +++ b/internal/manual/chat/how-tasks-run.md @@ -108,6 +108,22 @@ something the evidence did not — though nothing ever overrides a path you name The check runs where the work stood, cut from the same ground; the card and the `/history` row carry the ground and how the task stood on it. +## A task built my project somewhere else — it only read my repository, nothing changed in my folder, where is what the task made + +A task whose whole contract names no file to make or change is treated as reading its +repository: it gets an empty folder of its own and the repository is left alone. Naming a +project in words is not naming a file, so a brief such as "build the app in the MacStats +repo" reads this way. + +Such a task says so three times. Its receipt reads `It reads and writes only in a +folder of its own, so nothing in changes`, and says to stop it and propose it again +naming the files under that folder it makes or changes. Its worker is told the folder is to +read, not to change, and never to report the work as being there. Its landing ends `it +changed nothing in : what it made is in `. + +To have the work done in the repository, name a file under it in the brief, in what to +produce or in the done-when, as a path such as `Sources/App/main.swift`, or say "work here". + ## Does a task touch my working copy? — where does my task work, what the card calls the task's directory **A quick task is the exception, and not a small one.** It has no checkout and no branch diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index eb866f4282..637f7f11b2 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -417,6 +417,11 @@ on one waits for you. | `team_link` | records a file, pull request, issue or job the crew made as the crew's work, so the desktop app lists it with the crew (see **Link what the crew made**) | no | | `team_raise` | raises a conflict to the manager above every party (see **Conflicts between members and teams**); members have it too | no | +A manager hands work to members. It is told a task (`propose_task`) is not a member: a task +is for work no member is there for, or for when you ask for one, and never a way round a +member that did not start. When a member did not start, `team_send` says why, and the +manager is to tell you that. + ## Link what the crew made — team_link, add a file or pull request to the crew A manager records what its crew produced with `team_link`: `ref` is a file path (relative to diff --git a/internal/session/task.go b/internal/session/task.go index fe850994a5..731d1918db 100644 --- a/internal/session/task.go +++ b/internal/session/task.go @@ -1233,6 +1233,12 @@ func taskStandSentence(stand taskStand) string { switch { case stand.dir == "": return "" + case stand.mode == TaskModeReference && !HoldsHomeFolder(stand.dir): + // A REFERENCE IS SAID AS ONE, in the same breath as the start. "It + // works in " was true of where the task looks and false of + // where its work goes, and the proposer told the person the work was + // in the ground (task_brief.go's [copyOnto] has the run). + return taskReadsSentence(stand.dir) case stand.rung == taskGroundBrief: return "It works in " + stand.dir + ", the one folder its brief names the work in." case stand.rung == taskGroundSaid && !stand.kept: @@ -1241,6 +1247,16 @@ func taskStandSentence(stand taskStand) string { return "" } +// taskReadsSentence is what a proposer reads when its task only reads the +// ground: where the work will be, that the ground does not change, and what to +// do when that is not what was meant. The home folder has its own sentence +// ([homeTaskRedirect]). +func taskReadsSentence(dir string) string { + dir = cleanFolder(dir) + return "It reads " + dir + " and writes only in a folder of its own, so nothing in " + dir + " changes: this proposal named no file to make or change there. " + + "If the work is meant to change " + dir + ", stop this task and propose it again naming the files under " + dir + " it makes or changes." +} + // taskHandoffWakeSentence is what EVERY handoff receipt ends with, and it is one // sentence because it answers one question: what does the model do now? // diff --git a/internal/session/task_brief.go b/internal/session/task_brief.go index 310247e163..5ead88089b 100644 --- a/internal/session/task_brief.go +++ b/internal/session/task_brief.go @@ -376,9 +376,11 @@ type taskCopy struct { // the ground's to bind, and only what that rule leaves behind may be // considered as another task's tree. trees string - // readsHome is the home folder, or a folder holding it, when this task reads it - // from a folder of its own. It binds nothing: the folder is not a copy. - readsHome string + // reads is the ground this task only reads, from a folder of its own + // ([TaskModeReference]): the home folder or one holding it, or a repository + // its contract named no file to make or change in. It binds nothing: the + // folder is not a copy. + reads string } // newTaskCopy is the ONE PLACE A FOLDER IS SPELLED FOR THIS TYPE, and it exists @@ -651,11 +653,18 @@ func copyOnto(ground string, mode TaskMode, dir string, place Place) taskCopy { case TaskModeWorktree, TaskModeMirror: return newTaskCopyOf(ground, dir, place.Work(), place.Trees()) case TaskModeReference: - if HoldsHomeFolder(ground) { - own := standingOn(dir) - own.readsHome = cleanFolder(ground) - return own + // A REFERENCE WORKER IS TOLD ITS GROUND IS NOT ITS FOLDER, whatever the + // ground is. It used to be told only over the home folder. Measured + // 2026-11-23: a task whose proposal gave a repository as its ground, + // and whose brief named no file by path, was a reference; its worker + // woke in an empty folder, built the whole project there, and reported + // it "integrated", and the conversation told the person to run it from + // the repository, where nothing had changed. + own := standingOn(dir) + if canonicalPath(cleanFolder(ground)) != canonicalPath(cleanFolder(dir)) { + own.reads = cleanFolder(ground) } + return own } return standingOn(dir) } @@ -867,14 +876,21 @@ func (c taskCopy) note(sections ...string) string { return note } -// ownFolderNote tells a worker on the home folder where its output belongs, since -// the task was given no copy to work in and a person has to find what it made. +// ownFolderNote tells a worker that only reads its ground where its output +// belongs, since the task was given no copy to work in and a person has to find +// what it made. func (c taskCopy) ownFolderNote() string { - if c.readsHome == "" { + if c.reads == "" { return "" } - return c.readsHome + " is yours to read, not to change. Everything you make goes in " + c.dir + - ", your own folder. In your report, say where in that folder the results are." + return taskReadsNote(c.reads, c.dir) +} + +// taskReadsNote is the one sentence a worker that only reads its ground is +// given, for a node and for a run alike. +func taskReadsNote(ground, dir string) string { + return ground + " is yours to read, not to change. Everything you make goes in " + dir + + ", your own folder, and stays there: nothing you make reaches " + ground + ". In your report, say where in that folder the results are, and never say the work is in " + ground + "." } // names answers whether EITHER folder this map moves is spelled as a whole path diff --git a/internal/session/task_home_copy_test.go b/internal/session/task_home_copy_test.go index 3750f4fad6..68a35ff767 100644 --- a/internal/session/task_home_copy_test.go +++ b/internal/session/task_home_copy_test.go @@ -95,8 +95,13 @@ func TestWorkerOnHomeIsToldWhereOutputGoesAndToReportIt(t *testing.T) { project := filepath.Join(home, "project") plain := composeBrief(briefWhole, "read the docs", "summarise", "", "", "", AdmissionContext{}, taskOrigin{}, taskCopyFor(taskTree{dir: dir, ground: project, mode: TaskModeReference})) - if strings.Contains(plain, "yours to read") { - t.Fatalf("a reference on a project changed its brief:\n%s", plain) + // A reference on a project is told the same: its folder is not the project + // either, and a worker told nothing built there and reported the project + // changed (task_reference_test.go). + for _, want := range []string{project + " is yours to read", "Everything you make goes in " + dir, "never say the work is in " + project} { + if !strings.Contains(plain, want) { + t.Fatalf("a reference on a project lacks %q:\n%s", want, plain) + } } } diff --git a/internal/session/task_reference_test.go b/internal/session/task_reference_test.go new file mode 100644 index 0000000000..00990f301f --- /dev/null +++ b/internal/session/task_reference_test.go @@ -0,0 +1,77 @@ +package session + +import ( + "path/filepath" + "strings" + "testing" +) + +// A TASK THAT ONLY READS ITS GROUND SAYS SO AT ALL THREE ENDS: the proposer's +// receipt, the worker's own words, and the landing. The run this is from: a +// proposal gave a repository as its ground and named no file by path, the +// worker built the project in its own empty folder and reported it +// "integrated", and nothing told anybody the repository was untouched. +func TestAReferenceTaskSaysItsGroundDoesNotChange(t *testing.T) { + root := t.TempDir() + ground, own := filepath.Join(root, "MacStats"), filepath.Join(root, "trees", "1") + + said := taskStandSentence(taskStand{dir: ground, rung: taskGroundSaid, mode: TaskModeReference}) + for _, want := range []string{"It reads " + ground, "nothing in " + ground + " changes", "propose it again naming the files"} { + if !strings.Contains(said, want) { + t.Errorf("the receipt lacks %q:\n%s", want, said) + } + } + if strings.Contains(said, "It works in") { + t.Errorf("the receipt still says the task works in the ground it only reads:\n%s", said) + } + if got := taskStandSentence(taskStand{dir: ground, rung: taskGroundSaid, mode: TaskModeWorktree}); !strings.HasPrefix(got, "It works in "+ground) { + t.Errorf("a task that works in its ground is said as %q", got) + } + + note := copyOnto(ground, TaskModeReference, own, Place{}).ownFolderNote() + for _, want := range []string{ground + " is yours to read, not to change", "Everything you make goes in " + own, "never say the work is in " + ground} { + if !strings.Contains(note, want) { + t.Errorf("the worker's note lacks %q:\n%s", want, note) + } + } + if got := copyOnto(ground, TaskModeReference, ground, Place{}).ownFolderNote(); got != "" { + t.Errorf("a reference standing in its own ground was given a note: %q", got) + } + if got := copyOnto(ground, TaskModeWorktree, own, Place{}).ownFolderNote(); got != "" { + t.Errorf("a worktree was told its ground is read-only: %q", got) + } + + line := referenceLandingLine(taskTree{dir: own, ground: ground, mode: TaskModeReference}) + if line != "it changed nothing in "+ground+": what it made is in "+own { + t.Errorf("the landing line is %q", line) + } + if got := beltLandingLine(RunLanding{Line: line}); got != line { + t.Errorf("the landing's one line is %q", got) + } + for _, tree := range []taskTree{ + {dir: own, ground: ground, mode: TaskModeWorktree}, + {dir: ground, ground: ground, mode: TaskModeReference}, + {dir: own, mode: TaskModeReference}, + } { + if got := referenceLandingLine(tree); got != "" { + t.Errorf("%+v was given a reference landing: %q", tree, got) + } + } + + brief := withHomeReadingNote(Place{}, "Build it.", taskStand{dir: ground, mode: TaskModeReference}) + if !strings.Contains(brief, ground+" is yours to read, not to change") || !strings.Contains(brief, "your assigned working directory") { + t.Errorf("a run's workers are not told their ground is read-only:\n%s", brief) + } + if got := withHomeReadingNote(Place{}, "Build it.", taskStand{dir: ground, mode: TaskModeWorktree}); got != "Build it." { + t.Errorf("a run that works in its ground was told otherwise:\n%s", got) + } +} + +// A MANAGER IS TOLD A TASK IS NOT A WAY ROUND A MEMBER THAT DID NOT START. +func TestTheManagersLawsSayWhenATaskIsUsed(t *testing.T) { + for _, want := range []string{"A task (propose_task) is not a member", "never to get round a member that did not start"} { + if !strings.Contains(teamManagerLaws, want) { + t.Errorf("the manager's laws lack %q", want) + } + } +} diff --git a/internal/session/task_run_belt.go b/internal/session/task_run_belt.go index 09d2f61f6e..25515a4f35 100644 --- a/internal/session/task_run_belt.go +++ b/internal/session/task_run_belt.go @@ -2328,6 +2328,29 @@ func (a *Agent) releaseBeltRun(run *beltRun) { // branch the conversation's note names is the ground's, and a merge that would // not go in answers with the sentence that names the kept branch and the files. func (a *Agent) landBeltRun(ctx context.Context, engine RunEngine, run *beltRun) RunLanding { + landing := a.landBeltRunHome(ctx, engine, run) + // A RUN THAT ONLY READ ITS GROUND SAYS WHERE ITS WORK IS. It has no branch + // and nothing to merge, so its landing had no line at all, and the + // conversation was handed the worker's own account of the work with nothing + // saying the ground was untouched (task_brief.go's [copyOnto] has the run). + if line := referenceLandingLine(run.tree); line != "" { + landing.Line = line + } + return landing +} + +// referenceLandingLine is the landing of a tree that only read its ground: +// where what it made is, and that the ground did not change. Empty for every +// other tree. +func referenceLandingLine(tree taskTree) string { + if tree.mode != TaskModeReference || tree.workspaceSet != nil || tree.dir == "" || tree.ground == "" || + canonicalPath(cleanFolder(tree.dir)) == canonicalPath(cleanFolder(tree.ground)) { + return "" + } + return "it changed nothing in " + cleanFolder(tree.ground) + ": what it made is in " + cleanFolder(tree.dir) +} + +func (a *Agent) landBeltRunHome(ctx context.Context, engine RunEngine, run *beltRun) RunLanding { if run.tree.workspaceSet != nil { return a.landWorkspaceSet(ctx, engine, run) } @@ -2378,6 +2401,10 @@ func (a *Agent) bringBeltRunHome(run *beltRun, landing RunLanding) RunLanding { landing.Branch = branch } home := withReport("its work is in "+run.ground+" on "+landing.Branch, said) + if line := referenceLandingLine(run.tree); line != "" { + // A run that only read its ground left nothing in it to point at. + home = line + } if _, err := run.store.AddNote(run.root, run.root, home); err != nil { if g := a.graph(); g != nil { g.planNote("the run's homecoming note failed: " + err.Error()) diff --git a/internal/session/team.go b/internal/session/team.go index 2421b6f511..844816db16 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -1596,7 +1596,8 @@ const teamRoleWithdrawn = "You are no longer the manager or a member of any team // teamManagerLaws is how a manager works, stated once in the role. The verbs' // own descriptions carry how each is called. const teamManagerLaws = "Seven laws:\n" + - "1. Hand real work to members with team_send, or team_start for a new member, rather than doing it yourself, and keep track with team_status and team_read. Use team_add for an existing conversation and team_remove to release a membership without stopping work. Asked what is happening, answer from the team.\n" + + "1. Hand real work to members with team_send, or team_start for a new member, rather than doing it yourself, and keep track with team_status and team_read. Use team_add for an existing conversation and team_remove to release a membership without stopping work. Asked what is happening, answer from the team. " + + "A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\n" + "2. The person outranks you: what they say in a member's own conversation stands over your directive, and a conflict goes to them.\n" + "3. You cannot answer a member's permission prompt; tell the person it is waiting.\n" + "4. You direct only the members who report to you, one level down: a team under yours is its manager's to run, so you direct that manager, never its members. A member team_status marks `reports to` another team is shared: read it and send it notes, never a directive or a stop.\n" + diff --git a/internal/session/workspace_ownership.go b/internal/session/workspace_ownership.go index 24d29e62ab..fe8f9a985f 100644 --- a/internal/session/workspace_ownership.go +++ b/internal/session/workspace_ownership.go @@ -101,11 +101,12 @@ func homeTaskRedirect(dir string) string { } // withHomeReadingNote is [taskCopy.ownFolderNote] for a run, whose workers learn -// their folder as the assigned working directory and read the run's words. +// their folder as the assigned working directory and read the run's words. It +// is said over every ground a run only reads, the home folder or not. func withHomeReadingNote(place Place, brief string, stand taskStand) string { ground := canonicalPath(strings.TrimSpace(stand.dir)) - if stand.workspaceSet != nil || preparedTaskMode(place, ground, stand.mode) != TaskModeReference || !HoldsHomeFolder(ground) { + if stand.workspaceSet != nil || ground == "" || preparedTaskMode(place, ground, stand.mode) != TaskModeReference { return brief } - return brief + "\n\n" + cleanFolder(stand.dir) + " is yours to read, not to change. Everything you make goes in your assigned working directory. In your report, say where in that folder the results are." + return brief + "\n\n" + taskReadsNote(cleanFolder(stand.dir), "your assigned working directory") } From 025de95cceb4fd5bc25691a21923dd25647323bc Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:09:11 -0500 Subject: [PATCH 11/37] docs: change entry for a reference task saying so (#2909) Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2909-reference-task-says-so.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 docs/changes/unreleased/2909-reference-task-says-so.md diff --git a/docs/changes/unreleased/2909-reference-task-says-so.md b/docs/changes/unreleased/2909-reference-task-says-so.md new file mode 100644 index 0000000000..89d630dca3 --- /dev/null +++ b/docs/changes/unreleased/2909-reference-task-says-so.md @@ -0,0 +1,16 @@ +--- +kind: changed +title: A task that only reads its folder says so when it starts, to its worker, and when it lands +pr: 2909 +surface: [engine, chat] +invalidates: + - "A task whose stand is a reference (TaskModeReference, a ground it only reads) got the same receipt as any task: \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\" Outside the home folder its receipt now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file to make or change there. If the work is meant to change , stop this task and propose it again naming the files under it makes or changes.\" The home folder's sentence is as it was." + - "A reference worker was told \" is yours to read, not to change. Everything you make goes in , your own folder. In your report, say where in that folder the results are.\" only when its ground held the home folder (taskCopy.readsHome, withHomeReadingNote); over any other ground it was told nothing. Every reference worker whose folder is not its ground is now told \" is yours to read, not to change. Everything you make goes in , your own folder, and stays there: nothing you make reaches . In your report, say where in that folder the results are, and never say the work is in .\" (taskReadsNote; the field is taskCopy.reads)." + - "A run that only read its ground landed with no line of its own (RunLanding.Line empty, no branch), and its page's homecoming note read \"its work is in on \". Its landing line and that note now read \"it changed nothing in : what it made is in \" (referenceLandingLine)." + - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." +--- + +A proposal that named a repository as its ground and no file by path was read as +work that only reads it. The worker built the project in its own folder, reported +it integrated, and the conversation told the person to run it from a repository +nothing had been written to. From cedee0295bd879c0bf42ccea594a118e182f5f78 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:03:15 -0500 Subject: [PATCH 12/37] teams: review round 1 repairs for the quiet global manager The rule now covers only members that manage a top-level team, not everyone seated in the team that holds every team. team_send's answer no longer tells the global manager that endings wake it. The test that guarded the rule passed with the rule removed; it now waits past the settle, and a second test covers a global manager nobody has open. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2906-global-manager-quiet.md | 3 +- internal/manual/chat/team-manager.md | 10 ++- internal/session/team.go | 7 ++ internal/session/team_nest_test.go | 74 +++++++++++++++++-- internal/session/team_sendoutcome.go | 12 ++- internal/session/team_wakewatch.go | 34 +++++++-- internal/session/teamevent.go | 2 +- 7 files changed, 125 insertions(+), 17 deletions(-) diff --git a/docs/changes/unreleased/2906-global-manager-quiet.md b/docs/changes/unreleased/2906-global-manager-quiet.md index fd50fd4b44..4f06f87523 100644 --- a/docs/changes/unreleased/2906-global-manager-quiet.md +++ b/docs/changes/unreleased/2906-global-manager-quiet.md @@ -4,7 +4,8 @@ title: The global manager is not woken each time a top-level team's manager ends pr: 2906 surface: [engine, chat] invalidates: - - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team a member's finished event no longer starts the global manager's turn either (teamEventWakesManagerOf): it is woken by a top-level manager's team_post to it, by that manager's failed or asking event, and by nothing else that manager's turn does. A manager nobody has open is likewise no longer opened by a finished event there. Every other team is unchanged." + - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team the finished event of a member that manages a top-level team (teams.File.TopManagers, teamRole.quietEnding) no longer starts the global manager's turn either (teamEventWakesManagerOf): of that manager's events only failed and asking do, and its team_post, a decision packet it raises and a conflict it declares wake the global manager as before. A global manager nobody has open is likewise no longer opened by such a finished event. A member of that team that manages nothing, and every other team, are unchanged, so a stopped-by-the-person event from such a member wakes the global manager where the earlier rule kept every idle event in that team from doing so." + - "team_send answered every manager \"Replies and endings wake you when they arrive, so there is no need to wait or poll.\" In the team that holds every team it now answers \"Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A manager's turn ending on its own does not wake you: team_status says where it stands.\" The answer in every other team is as it was." - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\", and its scope adds \"A manager's turn ending does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the note every turn of the global manager carries." - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending does not start its turn: post what it should act on or tell the person, and nothing the person already has from you here.\" The rest of that note is as it was." --- diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index eb866f4282..f95477b035 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -349,7 +349,8 @@ holds that conversation's transcript and the wait is under 30 minutes. When you stop a member's turn that had been handed the manager's work, its manager is woken and told the work is not done, that you chose to stop it, and not to hand it out again unless you ask. Stopping a turn that carried only what you typed to the member tells the manager -nothing, and neither does codeaf quitting or a paused member's stray wake being ended. +nothing, and neither does codeaf quitting or a paused member's stray wake being ended. The global +manager is not woken by a top-level team's manager being stopped (see **The global manager**). ## A stopped member's command is still running — why it did not start again when the command ended @@ -537,7 +538,8 @@ those managers directly and each answer ends a turn, so the endings stay in `All traffic, where `team_status` reads them. The global manager is woken by what a manager posts to it with `team_post`, by a manager's question or a permission it is held on, and by a manager's turn failing. It is told never to send a manager your own request to that manager -back as a directive. +back as a directive. A member of `All teams` that manages no team is an ordinary member +there: its turn ending wakes the global manager as in any team. ## Conflicts between members and teams @@ -597,7 +599,9 @@ working, that is straight away. When it is idle, it depends on the kind of messa without a reply, failing, starting to wait on you, or having a turn that carried the manager's work stopped by you, start an idle manager's turn. A reply and the end of the same turn are one wake, even if the ending arrives after the manager - already ran. Replies arriving within a few seconds are gathered into one turn. + already ran. Replies arriving within a few seconds are gathered into one turn. The global + manager is the exception: a top-level team's manager finishing or being stopped does not + start its turn (see **The global manager**). A member no window has open is opened by codeaf in the background so it can run, and a window that opens it later joins the running conversation. A manager that moved to another window, and diff --git a/internal/session/team.go b/internal/session/team.go index 2421b6f511..4138ba44b9 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -124,6 +124,12 @@ type teamRole struct { // manager is the global manager, and its other members are the top-level // teams' managers. root bool + // tops is, for the root, the keys of the members that manage a top-level + // team now ([teams.File.TopManagers]). The root can hold others, a manager + // that stopped being one or a conversation the person put there, and the + // rule that keeps a manager's turn ending from waking the global manager is + // about these members alone ([teamRole.quietEnding]). + tops map[string]bool // dissolvable says this conversation manages the team and the team has // never held anyone but it ([teams.File.Dissolvable]), which is when its // manager is given team_dissolve (team_dissolve.go). @@ -454,6 +460,7 @@ func rolesFor(file *teams.File, keys []string, d teams.Defaults) []teamRole { boss: boss, bossName: bossName, root: team.Root, + tops: topManagerKeys(file, team), key: member.Key, wakes: effective.Wake, questionsUp: effective.QuestionsUp, diff --git a/internal/session/team_nest_test.go b/internal/session/team_nest_test.go index cffd0dc14e..756161e6a9 100644 --- a/internal/session/team_nest_test.go +++ b/internal/session/team_nest_test.go @@ -13,6 +13,7 @@ import ( "path/filepath" "strings" "testing" + "time" "github.com/Agent-Field/codeaf/internal/teams" ) @@ -539,12 +540,14 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { t.Fatal(err) } gmCalls := oneAnswer(4) - teamAgent(t, n.fixture, n.paths["gm"], gmCalls, nil) + gm := teamAgent(t, n.fixture, n.paths["gm"], gmCalls, nil) boss := teamAgent(t, n.fixture, n.paths["boss"], oneAnswer(4), nil) submitAndWait(t, boss, "plan the release") boss.settleTeamEvents() - quietFor() + // Past the settle a wake waits out, with room: a wake the ending had armed + // would have fired by now. + time.Sleep(teamWakeDelay() + 15*teamWatchInterval()) all := teamFixture{profile: n.fixture.profile, teamID: root} if ended := trafficEvents(t, all, "finished"); len(ended) != 1 { t.Fatalf("the top-level manager's ending was logged %d times in the team that holds every team, want once", len(ended)) @@ -552,6 +555,9 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { if got := gmCalls.requests(); got != 0 { t.Fatalf("the global manager was woken %d times by a top-level manager's turn ending", got) } + if woke := trafficEvents(t, all, teamWokePrefix); len(woke) != 0 { + t.Fatalf("the traffic says the global manager was woken by the ending: %+v", woke) + } if said, failed := callTool(t, boss.teamPostTool, `{"to":"manager","text":"harbor shipped"}`); failed { t.Fatalf("the report to the global manager was refused: %q", said) @@ -566,12 +572,70 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { if strings.Contains(asked, "their finishing") { t.Fatalf("the global manager is still told a member's finishing starts its turn:\n%s", asked) } + if strings.Contains(asked, "finished its turn") || strings.Contains(asked, "What your members in") { + t.Fatalf("the ending rode into the global manager's turn as something that woke it:\n%s", asked) + } + // Its own send's answer does not promise that an ending wakes it. + if said := sendDirective(t, gm, "boss"); strings.Contains(said, "endings wake you") || !strings.Contains(said, "A manager's turn ending on its own does not wake you") { + t.Fatalf("the global manager's send says endings wake it: %s", said) + } +} + +// A GLOBAL MANAGER NOBODY HAS OPEN IS NOT OPENED BY THE ENDING EITHER, and is +// still opened by a top-level manager's failure. A member of the team that +// holds every team that manages nothing is an ordinary member there: its +// ending opens the manager as it does in any team. +func TestAClosedGlobalManagerIsNotOpenedByATopLevelManagersTurnEnding(t *testing.T) { + fastTeamWake(t) + n := newTeamTree(t, "gm", "boss", "web", "guest") + n.team(t, "harbor", "", "boss", n.member(t, "boss", "boss"), n.member(t, "web", "web")) + root := "" + if err := teams.Update(n.fixture.profile, func(f *teams.File) error { + root = f.MakeRoot(f.Teams[0].Made) + for _, m := range []teams.Member{n.member(t, "gm", "all"), n.member(t, "guest", "guest")} { + if err := f.AddMember(root, m); err != nil { + return err + } + } + return f.SetManager(root, n.key(t, "gm")) + }); err != nil { + t.Fatal(err) + } + recorder := &recordedResume{} + withTeamResume(t, recorder.open) + opened := func() int { + count := 0 + for _, seen := range recorder.seen() { + if strings.HasPrefix(seen, n.paths["gm"]+"|") { + count++ + } + } + return count + } + boss := teamAgent(t, n.fixture, n.paths["boss"], oneAnswer(2), nil) + submitAndWait(t, boss, "plan the release") + boss.settleTeamEvents() + time.Sleep(teamWakeDelay() + 15*teamWatchInterval()) + if got := opened(); got != 0 { + t.Fatalf("a closed global manager was opened %d times by a top-level manager's turn ending", got) + } + + guest := teamAgent(t, n.fixture, n.paths["guest"], oneAnswer(2), nil) + submitAndWait(t, guest, "tidy the notes") + guest.settleTeamEvents() + deadline := time.Now().Add(5 * time.Second) + for opened() == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if got := opened(); got == 0 { + t.Fatal("a member of the team that holds every team that manages nothing ended its turn and its manager was not opened") + } } func TestTeamEventWakesTheGlobalManager(t *testing.T) { for _, c := range []struct { state, text string - root, want bool + top, want bool }{ {teams.StateFinished, "finished", false, true}, {teams.StateFinished, "finished", true, false}, @@ -581,8 +645,8 @@ func TestTeamEventWakesTheGlobalManager(t *testing.T) { {teams.StateAsking, "asks: which branch?", true, true}, {teams.StateRunning, "no longer waiting", true, false}, } { - if got := teamEventWakesManagerOf(c.root, c.state, c.text); got != c.want { - t.Errorf("root %v, %s %q wakes the manager: %v, want %v", c.root, c.state, c.text, got, c.want) + if got := teamEventWakesManagerOf(c.top, c.state, c.text); got != c.want { + t.Errorf("top-level manager %v, %s %q wakes the manager: %v, want %v", c.top, c.state, c.text, got, c.want) } } } diff --git a/internal/session/team_sendoutcome.go b/internal/session/team_sendoutcome.go index d901ca5dbc..8b643b7ae4 100644 --- a/internal/session/team_sendoutcome.go +++ b/internal/session/team_sendoutcome.go @@ -137,7 +137,7 @@ func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams. said = append(said, strings.Join(asking, ", ")+" "+isAre(len(asking))+" waiting on the person and "+readsRead(len(asking))+" it once they answer.") } if len(started)+len(busy)+len(asking) > 0 { - said = append(said, "Replies and endings wake you when they arrive, so there is no need to wait or poll.") + said = append(said, teamSendWakesSentence(team.Root)) } for _, member := range paused { said = append(said, fmt.Sprintf("@%s did NOT start: %s. Tell the person it is paused; only they can resume it.", member.Handle, teamPausedWhy)) @@ -203,3 +203,13 @@ func itThey(n int) string { } return "they" } + +// teamSendWakesSentence is what a send's answer says comes back on its own. +// The global manager is not woken by a top-level manager's turn ending +// ([teamEventWakesManagerOf]), so its answer does not promise that. +func teamSendWakesSentence(root bool) string { + if root { + return "Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A manager's turn ending on its own does not wake you: team_status says where it stands." + } + return "Replies and endings wake you when they arrive, so there is no need to wait or poll." +} diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 0e548ef78a..3ad9a38f47 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -441,8 +441,9 @@ func teamEventWakesManager(state, text string) bool { return false } -// teamEventWakesManagerOf is [teamEventWakesManager] for the manager of one -// team, root when that team is the one that holds every team. +// teamEventWakesManagerOf is [teamEventWakesManager] for one member's event, +// top when that member is a top-level team's manager seated in the team that +// holds every team ([teamRole.quietEnding]). // // The global manager is not woken by a top-level manager's turn ending, // finished or stopped. Its members are the managers of whole teams, each a @@ -456,18 +457,39 @@ func teamEventWakesManager(state, text string) bool { // needs somebody still wakes: a failure, and a question or a permission it is // held on. The ending itself stays in the team's traffic, where team_status // reads it. -func teamEventWakesManagerOf(root bool, state, text string) bool { - if root { +func teamEventWakesManagerOf(top bool, state, text string) bool { + if top { return state == teams.StateFailed || state == teams.StateAsking } return teamEventWakesManager(state, text) } +// quietEnding reports whether member is a top-level team's manager seated in +// the root: the one member whose turn ending does not wake the root's manager. +// Anybody else the root holds is an ordinary member there. +func (r teamRole) quietEnding(member string) bool { + return r.root && r.tops[member] +} + +// topManagerKeys is the keys [teamRole.tops] holds, nil for every team but the +// root. +func topManagerKeys(file *teams.File, team teams.Team) map[string]bool { + if file == nil || !team.Root { + return nil + } + tops := map[string]bool{} + for _, m := range file.TopManagers() { + tops[m.Key] = true + } + return tops +} + // teamWakes reports whether an entry starts this conversation's turn when it // is idle: a directive from the manager to its handle or to everyone, for a // member; a member's post to the manager, or a member's finished, failed or // asking event, for the manager. The watch suppresses a finished event when -// the same turn already posted a reply. +// the same turn already posted a reply, and the global manager is not woken by +// a top-level manager's turn ending ([teamEventWakesManagerOf]). func teamWakes(role teamRole, entry teams.Entry) bool { if !role.joinedAt.IsZero() && entry.At.Before(role.joinedAt) { return false @@ -489,7 +511,7 @@ func teamWakes(role teamRole, entry teams.Entry) bool { case teams.KindNote: return entry.To == teams.ToManager && strings.TrimSpace(entry.Text) != "" case teams.KindEvent: - return teamEventWakesManagerOf(role.root, entry.State, entry.Text) + return teamEventWakesManagerOf(role.quietEnding(entry.Member), entry.State, entry.Text) } return false } diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index 697c2b9d8c..80129ac866 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -184,7 +184,7 @@ func (a *Agent) writeTeamEvent(event teamEvent) { if err != nil || !role.wakes { continue } - if teamEventWakesManagerOf(role.root, event.state, text) { + if teamEventWakesManagerOf(role.quietEnding(role.key), event.state, text) { // These wake the manager, so a manager nobody has open is opened // (team_wakewatch.go). a.rouseManager(profile, role, event.origin.provenance(role.key)) From 7764a0f29179bc6336d6d035a36980c39ca46542 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:15:30 -0500 Subject: [PATCH 13/37] teams: final review round 1 repairs A paused member woken by anything but team traffic read the held directive at its turn's opening, so Resume replayed nothing; a paused role's traffic now stays undelivered unless the person opened the turn. A hold left over after the person's own turn read the directive started a turn on a note at Resume. A manager's team_stop performed by the member's own session now holds as the person's stop does. A stop that finds no turn running tells the manager only when the member is waiting on a command. Resume says so in every crew the member sits in. Co-Authored-By: Claude Fable 5.2 --- cmd/codeaf/appcrewmembers.go | 36 ++++++-- cmd/codeaf/appcrews.go | 10 ++- cmd/codeaf/appproposalaccept_test.go | 32 +++++++ .../unreleased/2897-crew-handoff-outcome.md | 6 +- internal/manual/chat/team-manager.md | 21 +++-- internal/session/agent.go | 16 ++-- internal/session/team.go | 23 ++++- internal/session/team_pause.go | 7 ++ internal/session/team_pause_test.go | 68 +++++++++++++++ internal/session/team_stophold.go | 79 ++++++++++++----- internal/session/team_stophold_test.go | 84 +++++++++++++++++++ internal/session/team_wakewatch.go | 26 ++++-- 12 files changed, 348 insertions(+), 60 deletions(-) diff --git a/cmd/codeaf/appcrewmembers.go b/cmd/codeaf/appcrewmembers.go index 5160d47fbe..e30c201ae2 100644 --- a/cmd/codeaf/appcrewmembers.go +++ b/cmd/codeaf/appcrewmembers.go @@ -66,12 +66,34 @@ func (b *appBackend) Member(verb string, ask appwire.MemberAsk) (appwire.CrewMem err = b.memberStop(t, m, agent, "paused") } case "resume": - pausedSomewhere := m.Paused || b.crewPaused(agent) - if err = b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, false) }); err == nil && pausedSomewhere { - // The resume is said on the crew's log beside the pause. What - // waited there starts the member's turn on its session's next look. - err = appEngineErrorOrNil(teamstore.AppendTraffic(b.crewProfile(), t.ID, teamstore.Entry{ - Kind: teamstore.KindEvent, From: teamstore.FromYou, To: m.Handle, ToKey: m.Key, Member: m.Key, + // THE RESUME IS SAID WHEREVER THE PAUSE HELD. A pause holds the + // member in every crew it is in, whichever one it was pressed in + // (teamstore's PausedAnywhere), so any of their logs may carry a + // "held" line for a directive sent meanwhile, and each is told the + // hold is over. What waited there starts the member's turn on its + // session's next look. + type seat struct{ crew, handle string } + var held []seat + err = b.crewEdit(func(f *teamstore.File) error { + held = nil + if _, paused := f.PausedAnywhere(m.Key); paused { + for _, other := range f.Teams { + if other.Closed() || other.Manager == m.Key { + continue + } + if in, ok := other.Member(m.Key); ok { + held = append(held, seat{other.ID, in.Handle}) + } + } + } + return f.SetPaused(crew, m.Key, false) + }) + for _, in := range held { + if err != nil { + break + } + err = appEngineErrorOrNil(teamstore.AppendTraffic(b.crewProfile(), in.crew, teamstore.Entry{ + Kind: teamstore.KindEvent, From: teamstore.FromYou, To: in.handle, ToKey: m.Key, Member: m.Key, State: teamstore.StateIdle, Text: appResumedText, })) } @@ -357,7 +379,7 @@ func (b *appBackend) memberRole(crew, agent, role, instructions, model string) e if t, _, err := b.crewTeam(crew); err == nil { if m, ok := b.crewMemberOf(t, agent); ok && m.Role != given.Name { if err := b.crewEdit(func(f *teamstore.File) error { return f.SetRole(crew, m.Key, given.Name) }); err != nil { - return err + return appEngineError(err) } } } diff --git a/cmd/codeaf/appcrews.go b/cmd/codeaf/appcrews.go index a515079724..a1bdc8fbb7 100644 --- a/cmd/codeaf/appcrews.go +++ b/cmd/codeaf/appcrews.go @@ -1029,10 +1029,12 @@ func (b *appBackend) crewStart(t teamstore.Team, manager teamstore.Member, e tea member.ReportsTo = pending.ReportsTo // What the start was made with: the role's name, and whether the member // waits for a directive rather than beginning on this line. - // Standby is what accepting a proposal asks for, and only that: a pending - // start left behind by a proposal that failed half-way must not put a - // member the manager starts later under the same handle on standby. - member.Role, member.Standby = pending.RoleName, pending.Standby && createdBy == appwire.CreatedByPerson + // Both are what accepting a proposal asks for, and only that: a pending + // start left behind by a proposal that failed half-way must not name, or + // put on standby, a member the manager starts later under the same handle. + if createdBy == appwire.CreatedByPerson { + member.Role, member.Standby = pending.RoleName, pending.Standby + } // THE MEMBERSHIP KEEPS THE ID OF THE LINE THAT MADE IT, so its brief is // that line by identity and survives a rename or a handle reused later. // Only a manager's start of this crew is recorded; the terminal's start diff --git a/cmd/codeaf/appproposalaccept_test.go b/cmd/codeaf/appproposalaccept_test.go index 868cd1c3e8..23677bed9a 100644 --- a/cmd/codeaf/appproposalaccept_test.go +++ b/cmd/codeaf/appproposalaccept_test.go @@ -434,6 +434,38 @@ func TestAppMemberPauseIsKeptInTheTeamStore(t *testing.T) { t.Fatalf("pausing the manager answered %v", err) } + // A PAUSE HOLDS THE MEMBER IN EVERY CREW IT IS IN, so the resume is said + // on each of their logs, whichever crew it was pressed in. + seat, second := stored(), teamstore.NewID() + if err := teamstore.Update(backend.profileDir, func(f *teamstore.File) error { + f.Teams = append(f.Teams, teamstore.Team{ID: second, Name: "second"}) + return f.AddMember(second, teamstore.Member{Key: seat.Key, File: seat.File, Handle: "scout"}) + }); err != nil { + t.Fatal(err) + } + if _, err := backend.Member("pause", appwire.MemberAsk{Crew: crew.ID, Agent: scout.Agent}); err != nil { + t.Fatal(err) + } + if again, err := backend.Member("resume", appwire.MemberAsk{Crew: second, Agent: scout.Agent}); err != nil || again.Paused || stored().Paused { + t.Fatalf("a resume pressed in another crew answered %+v, %v; the store has paused=%v", again, err, stored().Paused) + } + if got := texts(teamstore.KindEvent, teamstore.FromYou); len(got) != 2 || got[1] != appResumedText { + t.Fatalf("the crew the member was paused in says %v about a resume pressed in another", got) + } + entries, err := teamstore.ReadTraffic(backend.profileDir, second, "", 100) + if err != nil { + t.Fatal(err) + } + said := 0 + for _, entry := range entries { + if entry.Kind == teamstore.KindEvent && entry.From == teamstore.FromYou && entry.Text == appResumedText && entry.To == "scout" { + said++ + } + } + if said != 1 { + t.Fatalf("the crew the resume was pressed in was told of it %d times, want once", said) + } + // A pause an earlier build kept in the app's own file is carried over once. if err := backend.crewLayer().write(func(f *appCrewLayerFile) error { f.member(crew.ID, scout.Agent).Paused = true diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 941a0d8fb8..26c78b26c2 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -5,8 +5,8 @@ pr: 2897 surface: [engine, app, chat] invalidates: - "team_send answered every directive with \"A member that is idle starts a turn on it now, and a busy one reads it at its next step\" whatever happened. It now waits up to four seconds on the team's traffic and says for each member one of: \"@web started a turn on it.\", \"@web is in a turn and reads it at the next step.\", \"@web did NOT start: .\", \"@web is waiting on the person and reads it once they answer.\", or \"@web has shown no sign of starting yet; team_status says whether it did.\" Where a member did not start, the answer also tells the manager not to tell the person the work is under way." - - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A member paused in any of its teams is not opened or woken by any team's traffic (File.PausedAnywhere), shows as paused in each of its crews, and is resumed from any of them (SetPaused false clears every membership); the directive stays undelivered and starts the member's turn when the person resumes it, including after a restart. The app carries an earlier build's pause onto the team's record once." - - "A directive to a paused member wrote \"woke @x\" then \"stopped\" to the traffic. It now writes one line from system, \"held @x: the person paused it; it starts on this when they resume it\", answering the directive, and Resume writes an event from you with the text \"resumed\"." + - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A member paused in any of its teams is not opened or woken by any team's traffic (File.PausedAnywhere), shows as paused in each of its crews, and is resumed from any of them (SetPaused false clears every membership); the directive stays undelivered and starts the member's turn when the person resumes it, including after a restart. A turn something else starts in a paused member (a command's ending, a task landing) is handed none of its teams' traffic and moves no cursor; a turn the person's own words open still reads what waited, and Resume then starts no turn on lines already read. The app carries an earlier build's pause onto the team's record once." + - "A directive to a paused member wrote \"woke @x\" then \"stopped\" to the traffic. It now writes one line from system, \"held @x: the person paused it; it starts on this when they resume it\", answering the directive, and Resume writes an event from you with the text \"resumed\" to every open crew the member belongs to, whichever one it was pressed in." - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A turn that was handed its manager's work (a directive, or the brief a started member begins on) and that the person then stops now ends \"stopped by the person\" (teams.StoppedByPerson); it wakes the manager and is delivered as \"@x's turn on what you handed it was stopped by the person before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask.\" A stopped turn that carried only the person's own request, a stop by the manager's team_stop (whichever interface performs it), the desktop app quitting, and the app ending a paused member's stray wake still end \"stopped\" and still wake nobody; the app's two stops now cancel through StopByClosing and StopByWorkStopped, where they used the person's door. The global manager is not woken by either." - "team_status and the manager's digest gave a member's state as running, asking, idle or failed only. A member's line may now read \"paused by the person; it starts nothing until they resume it\" or \"on standby; no work handed out yet\", carries the member's role after its handle (\"- @dev, macOS developer\"), and may add \"has not started on #22\" (only for a member that is not in a turn) or \"its last turn was stopped by the person\"." - "Accepting a crew proposal (crews.create from proposal) started every helper at once on its brief. Each helper now joins on standby (teams.Member.Standby, cleared by the member's session once its start line is handed to it): its start line starts no turn, however much later the first directive comes, the traffic says \"opened @x on standby; it starts on its manager's first directive\", and the first directive hands it that line marked \"◆ your standing role from manager (what you are here for, not work to begin; work arrives as a directive)\" in place of \"◆ brief from manager\". team_start and members.start still start a member on its brief at once." @@ -14,7 +14,7 @@ invalidates: - "The crew proposal prompt asked for each helper's brief as the \"whole assignment\". It now asks for \"what this helper is responsible for\", and says an accepted crew joins on standby." - "The desktop app stopped every turn it had not started itself on a paused member, including one the person opened by typing to that member from another window. It now leaves a turn the person's own words opened alone, and still stops any other wake (a background process ending, a task landing)." - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\". It also refuses a member that manages another open team (\"@lead manages and is not paused; stop its turn instead\"), and making a conversation a manager lifts its pause." - - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop that an interface performs) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A stop that finds no turn running but a command or watch still running begins the same hold, and writes \"stopped by the person\" to the teams whose manager handed out what the conversation's last finished turn carried, which wakes that manager. The command is still left running by the stop, and a conversation in no team is unchanged." + - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop, whether an interface performs it or the member's own session does) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A stop by the person that finds no turn running but a command or watch still running begins the same hold. Only when the conversation is waiting on one of them (a command whose ending it is owed or asked to be notified of, or a watch that has not fired) does it also write \"stopped by the person\" to the teams whose manager handed out what the conversation's last finished turn carried, which wakes that manager; a command left running for its own sake, such as a dev server, tells no manager anything. The command is still left running by the stop, and a conversation in no team is unchanged." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index e3c5b70058..2713ab68f8 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -355,14 +355,17 @@ nothing, and neither does codeaf quitting or a paused member's stray wake being Stopping a turn leaves a command it started in the background running, as it does in any conversation. In a crew, that command's ending does not start the conversation again. From -a stop of a running turn (yours, or the manager's `team_stop`) until a turn next begins, the +a stop of a running turn (yours, or the manager's `team_stop`, with or without a window on +the member) until a turn next begins, the ending of a background command, or a watch firing, is written into the conversation as a record and starts no turn. This holds for a member and for the manager. A member often starts a long command, ends its turn and waits to be told how it ended. It reads idle, and a stop still reaches it: **Stop** on a crew's row stops such a member too, the command's ending starts no turn, and its manager is told the work it handed out was -stopped, as for a stopped turn. +stopped, as for a stopped turn. That is said only for a command the member asked to hear the +end of, or a watch that has not fired. A command left running for its own sake, such as a dev +server, is held the same way and the manager is told nothing: the work before it was finished. The conversation starts again when somebody means it to: your own message to it, or the manager's next hand-off. That turn reads the record, which says it arrived after the stop @@ -645,14 +648,16 @@ Resume from any of those crews lifts it: resume it`, with `has not started on #22` when a directive is waiting. - codeaf does not open the member's conversation for traffic it would only hold. -**Resume** writes `resumed` to the crew's log, and a directive that waited starts the member's -turn within a second or two, including after codeaf was closed in between. With the team's -auto-wake off, a resumed member reads it at its next turn like any other message. +**Resume** writes `resumed` to the log of each crew the member is in, and a directive that +waited starts the member's turn within a second or two, including after codeaf was closed in +between. With the team's auto-wake off, a resumed member reads it at its next turn like any +other message. Your own words are not held: typing into a paused member's conversation starts its turn, and -that turn reads what was waiting. Anything else that would wake it, such as one of its -background processes ending, is stopped at once in the desktop app. A pause made by an earlier -version of the app is carried onto the team's record the first time the updated app opens. +that turn reads what was waiting, so Resume starts nothing more on it. Any other wake, such as +a background process ending, reads none of the crew's lines and is stopped at once in the +desktop app. A pause made by an earlier version of the app is carried onto the team's record +the first time the updated app opens. ## A new crew's members wait on standby — why nobody started after Make the crew diff --git a/internal/session/agent.go b/internal/session/agent.go index 15cb0b6b72..1f1173ea0e 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -3861,7 +3861,7 @@ func (a *Agent) drainSteering(hub *eventHub) int { // turn's opening and at every step after it, which is what makes a line the // manager sends mid-turn land mid-turn. A conversation in no team pays one // stat, and one with no profile or a task node pays nothing. - if news := a.teamBoundary(); news != "" { + if news := a.teamBoundaryFor(a.team.person.opened.Load()); news != "" { a.enqueueNote(userText(news)) } sharing := a.config.teamProfile() != "" && a.teamsSharing() @@ -4258,16 +4258,18 @@ func (a *Agent) enqueueJobNoteUnowed(text string) { // enqueueJobNoteQuiet keeps each successful process ending as context without // waking the model. An idle chat journals it now so a handoff can carry it. func (a *Agent) enqueueJobNoteQuiet(text string) { - text = strings.TrimSpace(text) - if text == "" { - return - } - note := userMessage{message: textMessage("user", text), batch: true, authored: true} a.mu.Lock() defer a.mu.Unlock() - if a.closed { + a.quietNoteLocked(text) +} + +// quietNoteLocked is [Agent.enqueueJobNoteQuiet] for a caller holding a.mu. +func (a *Agent) quietNoteLocked(text string) { + text = strings.TrimSpace(text) + if text == "" || a.closed { return } + note := userMessage{message: textMessage("user", text), batch: true, authored: true} if a.running || !a.opened { a.ambient = append(a.ambient, note) return diff --git a/internal/session/team.go b/internal/session/team.go index 96628cf284..2b6c4537f4 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -521,7 +521,12 @@ func memberOf(team teams.Team, keys []string) (teams.Member, bool) { // costs; but a verb that cannot work must be absent, not broken (CLAUDE.md), // and a demotion is rare enough that paying once for it is cheap. A role // gained again appends its verbs at the tail as before. -func (a *Agent) teamBoundary() string { +func (a *Agent) teamBoundary() string { return a.teamBoundaryFor(false) } + +// teamBoundaryFor is [Agent.teamBoundary] for a turn that is running. person +// says the person's own words opened it, which is the one turn that reads what +// a paused membership is holding (team_pause.go). +func (a *Agent) teamBoundaryFor(person bool) string { a.clientToolsBoundary() profile := a.config.teamProfile() if profile == "" { @@ -531,7 +536,7 @@ func (a *Agent) teamBoundary() string { lead := a.factoryLead() a.team.mu.Lock() roles := a.teamRolesLocked(profile) - news := a.teamNewsLocked(profile, roles) + news := a.teamNewsLocked(profile, roles, person) claims := a.team.claims a.team.claims = nil if len(claims) > 0 { @@ -723,8 +728,9 @@ func (a *Agent) teamRetiredNotice(name string) (string, bool) { } // teamNewsLocked reads each team's Traffic past this conversation's cursor and -// composes what is addressed to it. The caller holds a.team.mu. -func (a *Agent) teamNewsLocked(profile string, roles []teamRole) string { +// composes what is addressed to it. person says the person's own words opened +// the turn this is read for. The caller holds a.team.mu. +func (a *Agent) teamNewsLocked(profile string, roles []teamRole, person bool) string { if len(roles) == 0 { return "" } @@ -743,6 +749,13 @@ func (a *Agent) teamNewsLocked(profile string, roles []teamRole) string { save := false var groups []string for _, role := range roles { + // A PAUSED MEMBERSHIP'S TRAFFIC WAITS FOR THE RESUME, whatever started + // this turn. A sub-task landing or a command ending is not the person + // lifting the pause, and a directive handed over here was gone when + // they did. Only a turn the person opened reads it (team_pause.go). + if role.paused && !role.manager && !person { + continue + } path := teams.TrafficPath(profile, role.id) stamp := stampOf(path) cursor, known := a.team.cursors[role.id] @@ -790,6 +803,8 @@ func (a *Agent) teamNewsLocked(profile string, roles []teamRole) string { // behind it, so the stamp is left unmatched and the next boundary reads on. if len(entries) < teamPageLimit { a.team.trafficAt[role.id] = stamp + // And nothing a pause held is still owed a turn: this one has it. + delete(a.team.watch.pausedHeld, role.id) } if len(lines) > 0 { groups = append(groups, teamNewsGroup(role, lines)) diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 25021dc4f4..0439094b24 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -18,6 +18,13 @@ package session // for it to be opened. Something else may still open it (a question's answer, // a wake the retry queue kept); it is then open and held, which costs nothing. // +// AND WHERE THE TRAFFIC IS DELIVERED. A turn something else starts in a paused +// member (a sub-task landing, a command ending) reads none of its teams' lines +// and moves no cursor ([Agent.teamNewsLocked]): its first request used to carry +// the held directive, and the resume then had nothing to start on. A turn that +// does deliver them, the person's own, ends the hold, so the resume starts no +// second turn on lines already read. +// // A PAUSE IS THE PERSON'S WORD ABOUT THE CONVERSATION, so it holds in every // team the conversation is a member of ([teams.File.PausedAnywhere]), not only // the one it was pressed in: an interface that finds the member paused ends a diff --git a/internal/session/team_pause_test.go b/internal/session/team_pause_test.go index 9e10c53690..74f9ead613 100644 --- a/internal/session/team_pause_test.go +++ b/internal/session/team_pause_test.go @@ -592,3 +592,71 @@ func TestTeamPauseIsTheConversations(t *testing.T) { } } } + +func sendTeamNote(t *testing.T, manager *Agent, to string) { + t.Helper() + if said, failed := callTool(t, manager.teamSendTool, `{"to":"`+to+`","text":"The header is blue now.","kind":"note"}`); failed { + t.Fatalf("team_send refused the note: %s", said) + } +} + +// A TURN SOMETHING ELSE STARTS IN A PAUSED MEMBER READS NONE OF ITS TEAM'S +// LINES. A command's ending woke the member, that turn's first request carried +// the held directive, and the resume then started nothing: the manager had been +// told the directive waited for it. +func TestTeamPausedMembersOtherWakeLeavesTheDirectiveHeld(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) + webCalls := oneAnswer(4) + web := teamAgent(t, fixture, fixture.web, webCalls, nil) + sendDirective(t, manager, "web") + quietFor() + + web.enqueueJobNote("job 8 exited 0") + waitRequests(t, webCalls, 1) + waitQuiet(t, web) + if asked := userTextIn(webCalls.request(0)); strings.Contains(asked, "Fix the header.") { + t.Fatalf("a paused member's turn on a command's ending was handed the held directive:\n%s", asked) + } + quietFor() + if got := webCalls.requests(); got != 1 { + t.Fatalf("the paused member made %d model calls, want only the command's turn", got) + } + + setPaused(t, fixture, fixture.web, false) + waitRequests(t, webCalls, 2) + asked := userTextIn(webCalls.request(1)) + if strings.Count(asked, "Fix the header.") != 1 || !strings.Contains(asked, teamWakeMemberLead) { + t.Fatalf("the resumed member was not started on the directive that waited, once:\n%s", asked) + } +} + +// A HOLD ENDS WHEN ITS LINES ARE READ. The person typed into the paused member +// and that turn read the held directive; a note sent afterwards wakes nobody, +// and the resume used to start a second turn on it because the hold still stood. +func TestTeamHeldDirectiveThePersonsTurnReadStartsNothingOnResume(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(1), nil) + webCalls := oneAnswer(4) + web := teamAgent(t, fixture, fixture.web, webCalls, nil) + sendDirective(t, manager, "web") + quietFor() + + collect(t, mustSubmit(t, web, "what is waiting for you?")) + if asked := userTextIn(webCalls.request(0)); strings.Count(asked, "Fix the header.") != 1 { + t.Fatalf("the person's own turn in a paused member did not read what was waiting:\n%s", asked) + } + waitQuiet(t, web) + sendTeamNote(t, manager, "web") + quietFor() + + setPaused(t, fixture, fixture.web, false) + quietFor() + if got := webCalls.requests(); got != 1 { + t.Fatalf("the resumed member made %d model calls, want only the person's turn: a note wakes nobody", got) + } +} diff --git a/internal/session/team_stophold.go b/internal/session/team_stophold.go index 5bbb150b8a..4d0e583bbd 100644 --- a/internal/session/team_stophold.go +++ b/internal/session/team_stophold.go @@ -13,11 +13,12 @@ package session // // So in a team, from a stop of a running turn until a turn next begins, the // ending of a background command and a watch's firing are kept as a record and -// start no turn. The stop is the one that comes through the person's door: the -// person's own, and a manager's team_stop, which an interface performs through -// that door (teamevent.go). The command itself is left running, as an interrupt -// always leaves it. What starts the conversation again is somebody meaning to: -// the person's own words, or the manager's next hand-off. +// start no turn. The stop is the person's own or a manager's team_stop, whoever +// performs the latter: an interface, through the person's door (teamevent.go), +// or the member's own session, through the manager's ([Agent.interruptTeamTurn]). +// The command itself is left running, as an interrupt always leaves it. What +// starts the conversation again is somebody meaning to: the person's own +// words, or the manager's next hand-off. // // A conversation in no team is untouched: there the ending of a command the // person asked to hear about still starts its turn. @@ -26,9 +27,11 @@ package session // command in the background, asks to be told when it ends, and ends its turn: // measured the same day, a crew's Stop passed over such a member and it // reported the work done when its command ended. So a stop that finds no turn -// but a command or a watch still running begins the hold too, and the manager -// that handed out the work the last turn carried is told it was stopped, in -// the words a stopped turn uses. +// but a command or a watch still running begins the hold too. When the member +// is waiting on one of them ([jobRegistry.awaited]), the manager that handed +// out the work the last turn carried is told it was stopped, in the words a +// stopped turn uses. A command left running for its own sake (a dev server) +// is held the same and said to nobody: the work before it was finished. import ( "strings" @@ -48,7 +51,7 @@ type teamStopHold struct { // seated is whether this conversation has a role in any team, as of the // last time its roles were read. Read without a lock or a disk. seated atomic.Bool - // held is set by a stop through the person's door and cleared when a turn + // held is set by the person's stop or a manager's and cleared when a turn // next begins. held atomic.Bool @@ -60,21 +63,22 @@ type teamStopHold struct { origin turnOrigin } -// teamStopHoldLocked begins the hold when the stop came through the person's -// door and there is something to hold: a turn running, or a command or watch -// whose ending would be news. It reports whether it began with no turn running, -// which is the stop the manager has yet to be told of ([Agent.teamStopHoldSaid]). -// The caller holds a.mu. +// teamStopHoldLocked begins the hold when the stop is the person's or a +// manager's and there is something to hold: a turn running, or a command or +// watch whose ending would be news. It reports whether it began with no turn +// running, which is the stop a manager may have yet to be told of +// ([Agent.teamStopHoldSaid]). The caller holds a.mu. func (a *Agent) teamStopHoldLocked(door StopDoor) bool { hold := &a.team.stopHold - if door != StopByPerson || !hold.seated.Load() { + if (door != StopByPerson && door != StopByManager) || !hold.seated.Load() { return false } if a.running { hold.held.Store(true) return false } - if a.jobs == nil || !a.jobs.newsPending() { + // The manager's own door ends a running turn and nothing else. + if door != StopByPerson || a.jobs == nil || !a.jobs.newsPending() { return false } return !hold.held.Swap(true) @@ -98,9 +102,14 @@ func (a *Agent) teamStopHoldFinished(handed map[string]time.Time, origin turnOri } // teamStopHoldSaid tells the managers whose work the last turn carried that -// it was stopped while it waited on a command. It reads the teams' logs, so it -// runs away from the stop's own path. +// it was stopped while it waited on a command or a watch. A member waiting on +// nothing finished that work, however long ago, and its managers are told +// nothing. It reads the jobs and the teams' logs, so it runs away from the +// stop's own path and outside a.mu. func (a *Agent) teamStopHoldSaid() { + if a.jobs == nil || !a.jobs.awaited() { + return + } hold := &a.team.stopHold hold.mu.Lock() handed, origin := hold.last, hold.origin @@ -134,16 +143,44 @@ func (r *jobRegistry) newsPending() bool { return false } +// awaited reports whether this conversation is waiting on something still +// running: a command whose ending it is owed or asked to be told of, the lanes +// [jobRegistry.settleExit] wakes on whatever the exit code, or a watch that +// has not fired. A command started to be left running is not waited on. +func (r *jobRegistry) awaited() bool { + for _, one := range r.all() { + select { + case <-one.done: + continue + default: + } + if one.kind == jobKindWatch { + return true + } + if one.kind != jobKindBash { + continue + } + one.mu.Lock() + waits := one.owed || one.notify || one.stageOwned + one.mu.Unlock() + if waits { + return true + } + } + return false +} + // teamStopHeldNote keeps one piece of background news as a record when the // hold stands, and reports whether it did. A worker parked on the command is -// released with it, as the waking note would have released it. +// released in the locked step that records it, as the waking note's own append +// releases it ([Agent.enqueueNote]). func (a *Agent) teamStopHeldNote(text string) bool { if !a.team.stopHold.held.Load() { return false } a.mu.Lock() + defer a.mu.Unlock() + a.quietNoteLocked(strings.TrimSpace(text) + "\n" + teamStopHeldRule) a.releaseTaskWaitLocked() - a.mu.Unlock() - a.enqueueJobNoteQuiet(strings.TrimSpace(text) + "\n" + teamStopHeldRule) return true } diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go index 3bd4b3c0e3..7dadda61e4 100644 --- a/internal/session/team_stophold_test.go +++ b/internal/session/team_stophold_test.go @@ -104,6 +104,9 @@ func TestTeamPersonStopOfAMemberWaitingOnACommandHolds(t *testing.T) { waitQuiet(t, web) web.settleTeamEvents() one := settlementJob(t, web.jobs) + one.mu.Lock() + one.notify = true + one.mu.Unlock() web.Interrupt() deadline := time.Now().Add(5 * time.Second) @@ -131,6 +134,87 @@ func TestTeamPersonStopOfAMemberWaitingOnACommandHolds(t *testing.T) { } } +// A COMMAND NOBODY WAITS ON IS HELD AND SAID TO NOBODY. The member finished its +// directive and left a server running; a later stop found only that. Its ending +// starts no turn, and the manager is not told finished work "is not done". +func TestTeamPersonStopOfAMemberWithACommandNobodyWaitsOn(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(8) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + calls := oneAnswer(4) + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + waitRequests(t, calls, 1) + waitQuiet(t, web) + web.settleTeamEvents() + one := settlementJob(t, web.jobs) + + web.Interrupt() + web.jobs.settleExit(one, 7) + quietFor() + web.settleTeamEvents() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times, want only its first turn", got) + } + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 0 { + t.Fatalf("finished work was logged as stopped by the person: %+v", said) + } + for i := 0; i < managerCalls.requests(); i++ { + if strings.Contains(userTextIn(managerCalls.request(i)), teamStoppedByPersonLine) { + t.Fatal("the manager was told finished work was stopped before it finished") + } + } +} + +// A MANAGER'S STOP PERFORMED BY THE MEMBER'S OWN SESSION HOLDS AS THE PERSON'S +// DOES. A headless member stopped by team_stop was woken by the ending of the +// command its turn had started and took the stopped directive up again. The +// manager is not told of its own stop. +func TestTeamManagerStopByTheMembersSessionHolds(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(8) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + streaming := make(chan struct{}) + calls := &scriptedCompleter{steps: []step{thinkingStep(streaming), okStep(), okStep()}} + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + one := settlementJob(t, web.jobs) + if said, failed := callTool(t, manager.teamStopTool, `{"handle":"web"}`); failed { + t.Fatalf("team_stop refused: %s", said) + } + waitQuiet(t, web) + web.settleTeamEvents() + + web.jobs.settleExit(one, 7) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the member the manager stopped was asked %d times, want only the stopped turn", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), "job 1 exited 7") || !strings.Contains(string(journal), teamStopHeldRule) { + t.Fatalf("the command's ending was not kept as a record:\n%s", journal) + } + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 0 { + t.Fatalf("the manager's own stop was logged as the person's: %+v", said) + } + if got := managerCalls.requests(); got != 0 { + t.Fatalf("the manager was woken %d times by its own stop", got) + } + + sendDirective(t, manager, "web") + waitRequests(t, calls, 2) +} + // A STOP WITH NOTHING RUNNING AND NOTHING PENDING HOLDS NOTHING: a command the // member starts in a later turn still wakes it. func TestTeamPersonStopOfAnIdleMemberHoldsNothing(t *testing.T) { diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index cc8878270d..7066f6740e 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -150,21 +150,30 @@ type teamWatch struct { capSaid string // pausedHeld is the teams whose traffic asked for this member's turn while // the person had it paused (team_pause.go). The lines stay undelivered on - // the log, and the turn they asked for starts when the pause is lifted. + // the log, and the turn they asked for starts when the pause is lifted, + // unless a turn the person opened has read them by then. pausedHeld map[string]bool } // personTurns counts turns the person started, for the loop breaker. It is // bumped where every turn begins ([Agent.startTurnLocked]) and read by the // watch, so it is atomic rather than under either lock. -type personTurns struct{ n atomic.Int64 } +type personTurns struct { + n atomic.Int64 + // opened says the person's own words opened the turn now running: one they + // typed, or the turn started to answer a line they typed as the last one + // ended. It is what lets a paused member's turn read what the pause holds. + opened atomic.Bool +} -// notePersonTurn counts a turn that opens on the person's own words. +// notePersonTurn counts a turn that opens on the person's own words, and +// remembers whether this one did. func (a *Agent) notePersonTurn(user userMessage) { - if user.wake || user.authored || user.empty() { - return + typed := personTyped(user) + a.team.person.opened.Store(typed || user.answersPerson) + if typed { + a.team.person.n.Add(1) } - a.team.person.n.Add(1) } // watchTeamTraffic starts the watch, or does nothing for a conversation that @@ -330,6 +339,10 @@ func (a *Agent) teamStopTick(profile string, turnAt time.Time, serial uint64) { // again under the lock the cancel is taken under, and a turn that has ended // is left alone, which is also what keeps a queued follow-up from being dropped // by a stop that arrived after its turn was over. +// +// AND THE STOP HOLDS, as the person's does (team_stophold.go): a command the +// stopped turn left running would otherwise end, wake the member and take the +// stopped directive up again. func (a *Agent) interruptTeamTurn(serial uint64) { live := func() bool { return a.running && a.teamTurnSerial == serial && a.cancel != nil } a.mu.Lock() @@ -346,6 +359,7 @@ func (a *Agent) interruptTeamTurn(serial uint64) { return } cancel := a.cancel + a.teamStopHoldLocked(StopByManager) a.dropFollowUpsLocked() a.stopSteerGraceLocked() a.mu.Unlock() From 648ea9d7611c546c3a4079c7615a8d487c444e89 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:16:37 -0500 Subject: [PATCH 14/37] tasks: final review round 1 repairs for a reference saying so A reference that joined a writing run was told it only reads; a joined task is now told what is true of the run it joined. The receipt's remedy asked for file names that do not work unless given by full path. A reference no longer prints the in-place redirect, and a home-folder ground given as the proposal's ground gets the home sentence. A reference run now lands without calling the engine's landing, which failed on a folder that is not a repository and filed a failure note. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2909-reference-task-says-so.md | 8 +- internal/manual/chat/how-tasks-run.md | 17 +- internal/session/task.go | 57 +++++-- internal/session/task_reference_test.go | 152 +++++++++++++++++- internal/session/task_run_belt.go | 116 +++++++------ internal/session/taskrouting.go | 2 +- internal/session/workspace_ownership.go | 4 +- 7 files changed, 279 insertions(+), 77 deletions(-) diff --git a/docs/changes/unreleased/2909-reference-task-says-so.md b/docs/changes/unreleased/2909-reference-task-says-so.md index 89d630dca3..1173a7bbca 100644 --- a/docs/changes/unreleased/2909-reference-task-says-so.md +++ b/docs/changes/unreleased/2909-reference-task-says-so.md @@ -4,9 +4,11 @@ title: A task that only reads its folder says so when it starts, to its worker, pr: 2909 surface: [engine, chat] invalidates: - - "A task whose stand is a reference (TaskModeReference, a ground it only reads) got the same receipt as any task: \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\" Outside the home folder its receipt now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file to make or change there. If the work is meant to change , stop this task and propose it again naming the files under it makes or changes.\" The home folder's sentence is as it was." - - "A reference worker was told \" is yours to read, not to change. Everything you make goes in , your own folder. In your report, say where in that folder the results are.\" only when its ground held the home folder (taskCopy.readsHome, withHomeReadingNote); over any other ground it was told nothing. Every reference worker whose folder is not its ground is now told \" is yours to read, not to change. Everything you make goes in , your own folder, and stays there: nothing you make reaches . In your report, say where in that folder the results are, and never say the work is in .\" (taskReadsNote; the field is taskCopy.reads)." - - "A run that only read its ground landed with no line of its own (RunLanding.Line empty, no branch), and its page's homecoming note read \"its work is in on \". Its landing line and that note now read \"it changed nothing in : what it made is in \" (referenceLandingLine)." + - "A task whose stand is a reference (TaskModeReference, a ground it only reads) was told so on its receipt only when `where` named a folder holding the home folder (homeTaskRedirect). Where the proposal's `ground` or its brief had chosen the folder, the receipt read \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\", the home folder included; on the other rungs it had no sentence about the folder. On every rung its receipt now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file there by full path. If the work is meant to change , stop this task and propose it again naming the files it makes or changes by their full path under .\" (taskReadsSentence), or over the home folder \"The task reads and keeps what it makes in its own folder; nothing in changes.\" whichever door named the folder." + - "A reference worker was told \" is yours to read, not to change. Everything you make goes in , your own folder. In your report, say where in that folder the results are.\" only when its ground held the home folder (taskCopy.readsHome, withHomeReadingNote); over any other ground it was told nothing. Every reference worker whose folder is not its ground is now told \" is yours to read, not to change. Everything you make goes in , your own folder, and stays there: nothing you make reaches . In your report, say where in that folder the results are, and never say the work is in .\" (taskReadsNote; the field is taskCopy.reads, and the run's helper is withTaskReadsNote)." + - "A run that only read its ground was handed to the engine's landing, which failed in its folder with \"fatal: not a git repository\": a plan note \"the run's landing failed\" was filed, the landing had no line (RunLanding.Line empty, no branch) and the run's page got no homecoming note. Such a run is no longer handed to the engine's landing (landReferenceRun): its landing line and its page's homecoming note both read \"it changed nothing in : what it made is in \" (referenceLandingLine)." + - "A reference whose proposal asked for `where: \"in place\"` inside a repository had the redirect \"in place was asked for, and is a repository — the work goes on a branch cut from it instead\" printed on its receipt. The stand still carries that redirect, and the receipt of a reference no longer prints it (taskStandRedirect)." + - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode)." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." --- diff --git a/internal/manual/chat/how-tasks-run.md b/internal/manual/chat/how-tasks-run.md index 28f4f1fdf3..c086c5338a 100644 --- a/internal/manual/chat/how-tasks-run.md +++ b/internal/manual/chat/how-tasks-run.md @@ -113,16 +113,19 @@ row carry the ground and how the task stood on it. A task whose whole contract names no file to make or change is treated as reading its repository: it gets an empty folder of its own and the repository is left alone. Naming a project in words is not naming a file, so a brief such as "build the app in the MacStats -repo" reads this way. +repo" reads this way. So does a relative path such as `Sources/App/main.swift` when +neither the file nor the folder that would hold it is there yet. Such a task says so three times. Its receipt reads `It reads and writes only in a folder of its own, so nothing in changes`, and says to stop it and propose it again -naming the files under that folder it makes or changes. Its worker is told the folder is to -read, not to change, and never to report the work as being there. Its landing ends `it -changed nothing in : what it made is in `. - -To have the work done in the repository, name a file under it in the brief, in what to -produce or in the done-when, as a path such as `Sources/App/main.swift`, or say "work here". +naming the files it makes or changes by their full path under that folder. Its worker is +told the folder is to read, not to change, and never to report the work as being there. A +task run as a run ends its landing `it changed nothing in : what it made is in `; the older single-task road lands without that line. A task that joins a run +already underway is told what is true of that run instead, since it shares the run's copy. + +To have the work done in the repository, name a file under it by full path in the brief, in +what to produce or in the done-when, such as `~/MacStats/Sources/App/main.swift`. ## Does a task touch my working copy? — where does my task work, what the card calls the task's directory diff --git a/internal/session/task.go b/internal/session/task.go index 731d1918db..bc63405b48 100644 --- a/internal/session/task.go +++ b/internal/session/task.go @@ -1091,14 +1091,18 @@ func (a *Agent) startApprovedHandoff(ctx context.Context, p *stagedProposal, spe ctx = withProgramWish(ctx, programWish{thinking: spec.thinking, carry: a.programCarryOf(prior, via.Name)}) } a.expectRunSource(p.id, spec.source) - joined, err := a.startOrJoinTaskRunVia(context.WithoutCancel(ctx), p.id, spec.title, proposalRunDescription(spec, via, placement), spec.dependsOn, stand, question, via, asked...) + mode, joined, err := a.startOrJoinTaskRunVia(context.WithoutCancel(ctx), p.id, spec.title, proposalRunDescription(spec, via, placement), spec.dependsOn, stand, question, via, asked...) a.rollbackFailedProgramStart(via, p.id, prior, err) + if joined { + stand.mode = mode + } return handoffStart{joined: joined, stand: stand, asked: asked, placed: placement.sentence}, err } // handoffStart is what starting an approved hand-off settled: whether it -// joined a run already underway, the stand it runs on, the programs asked -// for, and the sentence that says which computer it was placed on. +// joined a run already underway, the stand it runs on (in the joined run's +// mode when it joined one), the programs asked for, and the sentence that says +// which computer it was placed on. type handoffStart struct { joined bool stand taskStand @@ -1143,7 +1147,14 @@ func (a *Agent) handoffAnswer(p *stagedProposal, spec taskSpec, elsewhere string return refusal.Error(), true, true } if err == nil { - receipt := taskReceipt(p.id, spec, TaskRunning, p.stand, elsewhere) + said := p.stand + if joined { + // A TASK THAT JOINED A RUN IS SAID AS THAT RUN STANDS. It shares the + // run's copy, so a receipt read off its own stand told a reference + // that joined a worktree that nothing in the ground would change. + said.mode = stand.mode + } + receipt := taskReceipt(p.id, spec, TaskRunning, said, elsewhere) switch { case via != nil: receipt = delegateStartedReceipt(p.id, spec.title, strings.Join(asked, ", "), delegateReceipt(canonicalPath(stand.dir), *via, a.runRowCopy(p.id)), elsewhere) @@ -1211,10 +1222,10 @@ func taskReceipt(id uint64, spec taskSpec, state TaskState, stand taskStand, els } if state == TaskQueued { result := fmt.Sprintf("task %d queued%s: %s\nIt starts when the work it waits on has finished and a slot is free. %s", id, on, spec.title, taskHandoffWakeSentence) - return withElsewhere(withReport(withReport(result, taskStandSentence(stand)), stand.redirect), elsewhere) + return withElsewhere(withReport(withReport(result, taskStandSentence(stand)), taskStandRedirect(stand)), elsewhere) } result := fmt.Sprintf("task %d started%s: %s\nIt works from the brief alone, in a copy of its own. %s", id, on, spec.title, taskHandoffWakeSentence) - return withElsewhere(withReport(withReport(result, taskStandSentence(stand)), stand.redirect), elsewhere) + return withElsewhere(withReport(withReport(result, taskStandSentence(stand)), taskStandRedirect(stand)), elsewhere) } // taskStandSentence says WHERE the task works whenever that was read from the @@ -1227,13 +1238,19 @@ func taskReceipt(id uint64, spec taskSpec, state TaskState, stand taskStand, els // offered is accepted (it is somebody saying where the work is), and this line // is what makes a wrong one visible in the same breath rather than when the // work lands somewhere nobody looked. The rungs that read the conversation -// instead are silent here, as they always were: the work went where the -// conversation already is. +// instead are silent here when the task works in its ground: the work went +// where the conversation already is. A task that only reads its ground speaks +// on every rung, because its work goes somewhere else. func taskStandSentence(stand taskStand) string { switch { case stand.dir == "": return "" - case stand.mode == TaskModeReference && !HoldsHomeFolder(stand.dir): + case stand.mode == TaskModeReference && HoldsHomeFolder(stand.dir): + // The home folder has its own sentence, said here whichever door named + // it: only the `where` doors leave it on the stand as a redirect, and a + // home folder given as `ground` read "It works in ". + return homeTaskRedirect(stand.dir) + case stand.mode == TaskModeReference: // A REFERENCE IS SAID AS ONE, in the same breath as the start. "It // works in " was true of where the task looks and false of // where its work goes, and the proposer told the person the work was @@ -1247,14 +1264,32 @@ func taskStandSentence(stand taskStand) string { return "" } +// taskStandRedirect is the stand's redirect as a receipt prints it. A reference +// has said where its work goes ([taskStandSentence]) and cuts no branch, so the +// redirect a declined `in place` leaves on its stand +// ([groundModeAfterPlacement]) would contradict the sentence before it, and the +// home folder's redirect would say that sentence twice. +func taskStandRedirect(stand taskStand) string { + if stand.mode == TaskModeReference { + return "" + } + return stand.redirect +} + // taskReadsSentence is what a proposer reads when its task only reads the // ground: where the work will be, that the ground does not change, and what to // do when that is not what was meant. The home folder has its own sentence // ([homeTaskRedirect]). +// +// THE REMEDY IS A FULL PATH, because that is the one spelling that always +// counts: a relative path is read as work under the ground only when the file +// or its folder is already there ([groundHolds]), so "create +// Sources/App/main.swift" in a repository with no Sources folder was proposed +// again and was a reference again. func taskReadsSentence(dir string) string { dir = cleanFolder(dir) - return "It reads " + dir + " and writes only in a folder of its own, so nothing in " + dir + " changes: this proposal named no file to make or change there. " + - "If the work is meant to change " + dir + ", stop this task and propose it again naming the files under " + dir + " it makes or changes." + return "It reads " + dir + " and writes only in a folder of its own, so nothing in " + dir + " changes: this proposal named no file there by full path. " + + "If the work is meant to change " + dir + ", stop this task and propose it again naming the files it makes or changes by their full path under " + dir + "." } // taskHandoffWakeSentence is what EVERY handoff receipt ends with, and it is one diff --git a/internal/session/task_reference_test.go b/internal/session/task_reference_test.go index 00990f301f..54ea18e53d 100644 --- a/internal/session/task_reference_test.go +++ b/internal/session/task_reference_test.go @@ -1,7 +1,11 @@ package session import ( + "context" + "encoding/json" + "os" "path/filepath" + "strconv" "strings" "testing" ) @@ -16,7 +20,7 @@ func TestAReferenceTaskSaysItsGroundDoesNotChange(t *testing.T) { ground, own := filepath.Join(root, "MacStats"), filepath.Join(root, "trees", "1") said := taskStandSentence(taskStand{dir: ground, rung: taskGroundSaid, mode: TaskModeReference}) - for _, want := range []string{"It reads " + ground, "nothing in " + ground + " changes", "propose it again naming the files"} { + for _, want := range []string{"It reads " + ground, "nothing in " + ground + " changes", "propose it again naming the files it makes or changes by their full path under " + ground} { if !strings.Contains(said, want) { t.Errorf("the receipt lacks %q:\n%s", want, said) } @@ -45,9 +49,6 @@ func TestAReferenceTaskSaysItsGroundDoesNotChange(t *testing.T) { if line != "it changed nothing in "+ground+": what it made is in "+own { t.Errorf("the landing line is %q", line) } - if got := beltLandingLine(RunLanding{Line: line}); got != line { - t.Errorf("the landing's one line is %q", got) - } for _, tree := range []taskTree{ {dir: own, ground: ground, mode: TaskModeWorktree}, {dir: ground, ground: ground, mode: TaskModeReference}, @@ -58,11 +59,11 @@ func TestAReferenceTaskSaysItsGroundDoesNotChange(t *testing.T) { } } - brief := withHomeReadingNote(Place{}, "Build it.", taskStand{dir: ground, mode: TaskModeReference}) + brief := withTaskReadsNote(Place{}, "Build it.", taskStand{dir: ground, mode: TaskModeReference}) if !strings.Contains(brief, ground+" is yours to read, not to change") || !strings.Contains(brief, "your assigned working directory") { t.Errorf("a run's workers are not told their ground is read-only:\n%s", brief) } - if got := withHomeReadingNote(Place{}, "Build it.", taskStand{dir: ground, mode: TaskModeWorktree}); got != "Build it." { + if got := withTaskReadsNote(Place{}, "Build it.", taskStand{dir: ground, mode: TaskModeWorktree}); got != "Build it." { t.Errorf("a run that works in its ground was told otherwise:\n%s", got) } } @@ -75,3 +76,142 @@ func TestTheManagersLawsSayWhenATaskIsUsed(t *testing.T) { } } } + +// THE RECEIPT OF A REFERENCE SAYS ONE TRUE THING ABOUT WHERE ITS WORK GOES. A +// declined `in place` leaves a redirect naming a branch on the stand, and a +// reference cuts none; the home folder is said in its own sentence whether a +// `where` door or the proposal's `ground` named it. +func TestAReferenceReceiptSaysNoBranchAndTheHomeFolderOnce(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + ground := filepath.Join(t.TempDir(), "MacStats") + spec := taskSpec{title: "the question"} + branch := whereRedirectSentence("in place", ground) + + reads := taskReceipt(7, spec, TaskRunning, taskStand{dir: ground, mode: TaskModeReference, rung: taskGroundSaid, redirect: branch}, "") + if !strings.Contains(reads, "It reads "+ground) || strings.Contains(reads, "branch cut from it") { + t.Errorf("a reference asked for in place is told about a branch:\n%s", reads) + } + if works := taskReceipt(7, spec, TaskRunning, taskStand{dir: ground, mode: TaskModeWorktree, rung: taskGroundSaid, redirect: branch}, ""); !strings.Contains(works, branch) { + t.Errorf("a task on a branch lost its redirect:\n%s", works) + } + + for _, stand := range []taskStand{ + {dir: home, mode: TaskModeReference, rung: taskGroundSaid}, + {dir: home, mode: TaskModeReference, rung: taskGroundNamed, redirect: homeTaskRedirect(home)}, + } { + for _, state := range []TaskState{TaskRunning, TaskQueued} { + receipt := taskReceipt(7, spec, state, stand, "") + if strings.Count(receipt, homeTaskRedirect(home)) != 1 || strings.Contains(receipt, "It works in "+home) { + t.Errorf("rung %q: the home folder's receipt is\n%s", stand.rung, receipt) + } + } + } +} + +// A REFERENCE RUN LANDS WITHOUT THE ENGINE. Its folder is no repository, so the +// engine's landing failed and filed a failure note for every such run; the +// landing is the one line, in the row's report and on the run's page. +// +// AND A TASK THAT JOINS IT IS TOLD THE RUN ONLY READS, whatever its own stand +// asked for: it works in the run's folder, which nothing lands from. +func TestAReferenceRunLandsWithItsLineAndNoEngineLanding(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + double := newBeltRunDouble("the parser reads tokens") + // The engine's real landing, so that calling it would fail the way it did. + double.real = true + registerBeltRunEngine(t, double) + ground := newTestRepo(t) + sessionDir := t.TempDir() + agent, _ := newTestAgent(t, beltRunCompleter{text: "the parser reads tokens"}, func(config *Config) { + config.Workspace = ground + config.Place = Place{Dir: sessionDir} + config.SessionFile = filepath.Join(sessionDir, placeTranscript) + config.AskConsent = false + }) + if err := agent.startKnownTaskRun(context.Background(), 41, "explain the parser", "brief", nil, taskStand{dir: ground, mode: TaskModeReference, rung: taskGroundSaid}, ""); err != nil { + t.Fatalf("start the reference run: %v", err) + } + <-double.entered + double.mu.Lock() + workspace := double.spec.Workspace + double.mu.Unlock() + if err := agent.startKnownTaskRun(context.Background(), 42, "change the parser", "brief", nil, taskStand{dir: ground, mode: TaskModeWorktree, rung: taskGroundSaid}, ""); err != nil { + t.Fatalf("join the reference run: %v", err) + } + if task := beltRunTaskAt(t, sessionDir, "42"); task == nil || task.ParentID != "41" || !strings.Contains(task.Description, "is yours to read, not to change") { + t.Fatalf("a task that joined a run that only reads was not told so: %+v", task) + } + endBeltRun(t, agent, double) + + line := referenceLandingLine(taskTree{dir: workspace, ground: canonicalPath(ground), mode: TaskModeReference}) + if line == "" || !strings.Contains(line, "it changed nothing in "+canonicalPath(ground)) { + t.Fatalf("the run's folder %q and ground %q make no reference landing: %q", workspace, ground, line) + } + if double.lands() != 0 { + t.Errorf("the engine was asked to land a folder that is no repository %d times", double.lands()) + } + rows := agent.graph().runRows(41) + if len(rows) != 1 || !strings.Contains(rows[0].Report, line) { + t.Errorf("the settled row does not carry the landing line %q: %+v", line, rows) + } + if notes := strings.Join(beltRunNotes(t, sessionDir, "41"), "\n"); !strings.Contains(notes, line) || strings.Contains(notes, "its work is in") { + t.Errorf("the run's page does not say the landing line alone:\n%s", notes) + } + if logDir := agent.logDirectory(); logDir == "" { + t.Error("the conversation has no log directory to read plan notes from") + } else if log, _ := os.ReadFile(filepath.Join(logDir, "plandb.log")); strings.Contains(string(log), "landing failed") { + t.Errorf("a landing failure was filed for a run that had nothing to land:\n%s", log) + } +} + +// A REFERENCE THAT JOINS A RUN WORKING IN ITS GROUND IS TOLD WHAT IS TRUE OF +// THAT RUN. It shares the run's copy, which lands into the ground, so neither +// its receipt nor its worker may be told that nothing it makes reaches there. +func TestAReferenceThatJoinsAWritingRunIsNotToldItOnlyReads(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + double := newBeltRunDouble("the run did the work") + registerBeltRunEngine(t, double) + sessionDir := t.TempDir() + ground := newTestRepo(t) + agent, _ := newTestAgent(t, beltRunCompleter{text: "the run did the work"}, func(config *Config) { + config.Workspace = ground + config.Place = Place{Dir: sessionDir} + config.AskConsent = false + config.TaskAutoApproveSeconds = 0 + }) + root, _, _, err := agent.StartTask(context.Background(), "open the run", false) + if err != nil { + t.Fatal(err) + } + <-double.entered + args, _ := json.Marshal(taskArguments{ + Title: "Explain the parser", Summary: "the proposed work", Brief: "say how the parser reads its input", + Deliverable: "a concise answer", Acceptance: "the question is answered", Ground: ground, + }) + proposal, ok := agent.stageTask(context.Background(), args).(*stagedProposal) + if !ok || proposal.stand.mode != TaskModeReference { + t.Fatalf("the proposal did not stage as a reference: %+v", proposal) + } + agent.ResolveTask(proposal.id, TaskAnswer{Approved: true}) + answer, failed, err := proposal.Commit(context.Background()) + if err != nil || failed { + t.Fatalf("propose_task: failed=%v err=%v answer=%q", failed, err, answer) + } + if !strings.Contains(answer, "It joined the work already underway and shares its copy.") { + t.Fatalf("the proposal did not join the live run:\n%s", answer) + } + for _, untrue := range []string{"It reads ", "nothing in " + canonicalPath(ground) + " changes"} { + if strings.Contains(answer, untrue) { + t.Errorf("the receipt of a task that joined a writing run says %q:\n%s", untrue, answer) + } + } + task := beltRunTaskAt(t, sessionDir, strconv.FormatUint(proposal.id, 10)) + if task == nil || task.ParentID != strconv.FormatUint(root, 10) { + t.Fatalf("the proposal is not a child of the live run: %+v", task) + } + if strings.Contains(task.Description, "yours to read") { + t.Errorf("the worker of a task that joined a writing run is told it only reads:\n%s", task.Description) + } + endBeltRun(t, agent, double) +} diff --git a/internal/session/task_run_belt.go b/internal/session/task_run_belt.go index 25515a4f35..a309d07c80 100644 --- a/internal/session/task_run_belt.go +++ b/internal/session/task_run_belt.go @@ -347,9 +347,10 @@ type RunLanding struct { // brought back to its ground ([Agent.landBeltRun]). Empty is an engine's own // landing, which commits on the copy's branch and merges nothing. Home string - // Line is a landing that says itself: a program's run, whose folder's - // ending ([ProgramFolderEnd.Sentence]) is the whole account of where its - // work is ([beltLandingLine]). Empty for every other run. + // Line is a landing that says itself ([beltLandingLine]): a program's run, + // whose folder's ending ([ProgramFolderEnd.Sentence]) is the whole account + // of where its work is, and a run that only read its ground + // ([referenceLandingLine]). Empty for every other run. Line string } @@ -590,7 +591,7 @@ func (e standsElsewhereError) Error() string { // An approved hand-off under the bash belt belongs to the run store and never to the session tree. func (a *Agent) startKnownTaskRun(ctx context.Context, id uint64, title, brief string, dependsOn []uint64, stand taskStand, question string) error { - _, err := a.startOrJoinTaskRunVia(ctx, id, title, brief, dependsOn, stand, question, nil) + _, _, err := a.startOrJoinTaskRunVia(ctx, id, title, brief, dependsOn, stand, question, nil) return err } @@ -606,7 +607,7 @@ func (a *Agent) startKnownTaskRun(ctx context.Context, id uint64, title, brief s // asked is the models the person asked the program to work with, resolved; // none means the conversation's crew ([Agent.delegateCrew]). func (a *Agent) startKnownTaskRunVia(ctx context.Context, id uint64, title, brief string, dependsOn []uint64, stand taskStand, question string, via *delegate.Delegate, asked ...string) error { - _, err := a.startOrJoinTaskRunVia(ctx, id, title, brief, dependsOn, stand, question, via, asked...) + _, _, err := a.startOrJoinTaskRunVia(ctx, id, title, brief, dependsOn, stand, question, via, asked...) return err } @@ -615,34 +616,36 @@ func (a *Agent) startKnownTaskRunVia(ctx context.Context, id uint64, title, brie // this door can know: a batch of hand-offs is one run, and which of them opened // it is decided here, under the start lock, and nowhere before. func (a *Agent) startOrJoinTaskRun(ctx context.Context, id uint64, title, brief string, dependsOn []uint64, stand taskStand, question string) (bool, error) { - return a.startOrJoinTaskRunVia(ctx, id, title, brief, dependsOn, stand, question, nil) + _, joined, err := a.startOrJoinTaskRunVia(ctx, id, title, brief, dependsOn, stand, question, nil) + return joined, err } // startOrJoinTaskRunVia is the one body behind every door above: the start -// lock, the join, the folder or the copy, the store and the first row. -func (a *Agent) startOrJoinTaskRunVia(ctx context.Context, id uint64, title, brief string, dependsOn []uint64, stand taskStand, question string, via *delegate.Delegate, asked ...string) (bool, error) { +// lock, the join, the folder or the copy, the store and the first row. A +// hand-off that joined answers the mode the run it joined stands in, which is +// the mode its own work now has whatever its stand asked for. +func (a *Agent) startOrJoinTaskRunVia(ctx context.Context, id uint64, title, brief string, dependsOn []uint64, stand taskStand, question string, via *delegate.Delegate, asked ...string) (TaskMode, bool, error) { a.taskStarting.Add(1) defer a.taskStarting.Add(-1) epoch, err := a.beltAdmissionEpoch() if err != nil { - return false, err + return "", false, err } engine := chatRunEngine g := a.graph() if engine == nil || g == nil || g.planPath() == "" { - return false, errRunRoadUnavailable + return "", false, errRunRoadUnavailable } if via == nil { stand, err = a.ownedRunPlacement(ctx, stand) if err != nil { - return false, err + return "", false, err } } - brief = withHomeReadingNote(a.config.Place, brief, stand) ctx, engine, err = a.placeTaskRunEngine(ctx, engine, stand, via != nil) if err != nil { - return false, err + return "", false, err } path := g.planPath() storeID := strconv.FormatUint(id, 10) @@ -686,11 +689,11 @@ func (a *Agent) startOrJoinTaskRunVia(ctx context.Context, id uint64, title, bri a.lockBeltStart() defer a.beltStartMu.Unlock() if err := a.checkBeltAdmission(epoch); err != nil { - return false, err + return "", false, err } live, err := a.joinOrWait(ctx, stand, id, title, brief, dependencies, via) if err != nil { - return false, err + return "", false, err } if live != nil { a.publishRunRow(g, TaskNotice{ @@ -708,8 +711,12 @@ func (a *Agent) startOrJoinTaskRunVia(ctx context.Context, id uint64, title, bri PlanTask: planStoreID(storeID), }) a.publishJoinedRunRows(g, live) - return true, nil + return preparedTaskMode(a.config.Place, live.ground, live.stand.mode), true, nil } + // THE READ-ONLY NOTE IS A RUN'S OWN, added once no live run took the work: + // a hand-off that joined was told what is true of the run it joined + // ([Agent.joinOrWait]). + brief = withTaskReadsNote(a.config.Place, brief, stand) // ADMISSION IS CHECKED BEFORE A FOLDER OR COPY IS TOUCHED. A held run seeds // only its plan store so stopping it cannot leave a repository claim behind; @@ -717,10 +724,12 @@ func (a *Agent) startOrJoinTaskRunVia(ctx context.Context, id uint64, title, bri admission := newRunAdmission(a.config.TaskMaxLoad, a.config.TaskMinFreeMB, a.config.ProfileDir, a.graph().lanes) held := admission != nil && !admission.MayStart() if held || taskPlacementOf(ctx).computer != nil { - return a.startDeferredBeltRun(ctx, engine, g, path, storeID, id, title, brief, stand, question, via, asked, admission, held) + joined, err := a.startDeferredBeltRun(ctx, engine, g, path, storeID, id, title, brief, stand, question, via, asked, admission, held) + return "", joined, err } - return a.startAdmittedBeltRun(ctx, engine, g, path, storeID, id, title, brief, stand, question, via, asked, admission) + joined, err := a.startAdmittedBeltRun(ctx, engine, g, path, storeID, id, title, brief, stand, question, via, asked, admission) + return "", joined, err } // startAdmittedBeltRun is the original synchronous road after admission: route @@ -990,8 +999,12 @@ func (a *Agent) joinOrWait(ctx context.Context, stand taskStand, id uint64, titl a.beltMu.Unlock() return nil, refusal } + // THE JOINED WORKER IS TOLD WHAT IS TRUE OF THE RUN IT JOINED. It works + // in that run's copy, so whether the ground is only read is the run's + // stand to say and never the hand-off's own: a reference that joined a + // worktree was told nothing it made reached a ground its work landed in. _, err := addJoinedTasks(ctx, live.store, []plandb.TaskSpec{{ - ID: storeID, ParentID: live.root, Title: title, Description: brief, Dependencies: dependencies, Model: crewWishOf(ctx).worker, + ID: storeID, ParentID: live.root, Title: title, Description: withTaskReadsNote(a.config.Place, brief, live.stand), Dependencies: dependencies, Model: crewWishOf(ctx).worker, }}) if err == nil { live.joined = append(live.joined, id) @@ -2328,32 +2341,12 @@ func (a *Agent) releaseBeltRun(run *beltRun) { // branch the conversation's note names is the ground's, and a merge that would // not go in answers with the sentence that names the kept branch and the files. func (a *Agent) landBeltRun(ctx context.Context, engine RunEngine, run *beltRun) RunLanding { - landing := a.landBeltRunHome(ctx, engine, run) - // A RUN THAT ONLY READ ITS GROUND SAYS WHERE ITS WORK IS. It has no branch - // and nothing to merge, so its landing had no line at all, and the - // conversation was handed the worker's own account of the work with nothing - // saying the ground was untouched (task_brief.go's [copyOnto] has the run). - if line := referenceLandingLine(run.tree); line != "" { - landing.Line = line - } - return landing -} - -// referenceLandingLine is the landing of a tree that only read its ground: -// where what it made is, and that the ground did not change. Empty for every -// other tree. -func referenceLandingLine(tree taskTree) string { - if tree.mode != TaskModeReference || tree.workspaceSet != nil || tree.dir == "" || tree.ground == "" || - canonicalPath(cleanFolder(tree.dir)) == canonicalPath(cleanFolder(tree.ground)) { - return "" - } - return "it changed nothing in " + cleanFolder(tree.ground) + ": what it made is in " + cleanFolder(tree.dir) -} - -func (a *Agent) landBeltRunHome(ctx context.Context, engine RunEngine, run *beltRun) RunLanding { if run.tree.workspaceSet != nil { return a.landWorkspaceSet(ctx, engine, run) } + if line := referenceLandingLine(run.tree); line != "" { + return a.landReferenceRun(run, line) + } landing, err := engine.Land(ctx, run.store, run.workspace, run.tree.checkBase, run.root) if err != nil { if stopped, _ := a.beltRunStopped(run); stopped { @@ -2367,6 +2360,37 @@ func (a *Agent) landBeltRunHome(ctx context.Context, engine RunEngine, run *belt return a.bringBeltRunHome(run, landing) } +// landReferenceRun is the landing of a run that only read its ground, and it +// asks the engine for nothing. Its folder is no repository, so the engine's +// landing failed with git's `fatal: not a git repository`, a failure note was +// filed for every such run, and the conversation was handed the worker's own +// account of the work with nothing saying the ground was untouched +// (task_brief.go's [copyOnto] has the run). There is no branch to merge and no +// copy to give back: the homecoming is the one line, on the run's page and in +// the landing alike. +func (a *Agent) landReferenceRun(run *beltRun, line string) RunLanding { + if !a.beginBeltHomecoming(run) { + return RunLanding{} + } + if _, err := run.store.AddNote(run.root, run.root, line); err != nil { + if g := a.graph(); g != nil { + g.planNote("the run's homecoming note failed: " + err.Error()) + } + } + return RunLanding{Line: line} +} + +// referenceLandingLine is the landing of a tree that only read its ground: +// where what it made is, and that the ground did not change. Empty for every +// other tree. +func referenceLandingLine(tree taskTree) string { + if tree.mode != TaskModeReference || tree.workspaceSet != nil || tree.dir == "" || tree.ground == "" || + canonicalPath(cleanFolder(tree.dir)) == canonicalPath(cleanFolder(tree.ground)) { + return "" + } + return "it changed nothing in " + cleanFolder(tree.ground) + ": what it made is in " + cleanFolder(tree.dir) +} + // bringBeltRunHome is the second half of a run's landing: the copy's branch // merged into the ground it was cut from, the person's unfinished work carried // across or the branch kept and the files named, the copy given back, and the @@ -2401,10 +2425,6 @@ func (a *Agent) bringBeltRunHome(run *beltRun, landing RunLanding) RunLanding { landing.Branch = branch } home := withReport("its work is in "+run.ground+" on "+landing.Branch, said) - if line := referenceLandingLine(run.tree); line != "" { - // A run that only read its ground left nothing in it to point at. - home = line - } if _, err := run.store.AddNote(run.root, run.root, home); err != nil { if g := a.graph(); g != nil { g.planNote("the run's homecoming note failed: " + err.Error()) @@ -2856,7 +2876,9 @@ func beltRunOutcomeNote(store *plandb.Store, rootID string, summary RunSummary, // go back to their own branch and bring the work in. This line is the one // account of a landing the conversation's model is given, and a model told // only `landed on task/x: 2 files` would tell the person a thing about their -// folder that nobody checked. +// folder that nobody checked. A run that only read its ground says itself the +// same way ([referenceLandingLine]): it has no branch, and its ground did not +// change. func beltLandingLine(landing RunLanding) string { if landing.Line != "" { return landing.Line diff --git a/internal/session/taskrouting.go b/internal/session/taskrouting.go index fa43dd32fe..618bb10ac0 100644 --- a/internal/session/taskrouting.go +++ b/internal/session/taskrouting.go @@ -1606,7 +1606,7 @@ func (a *Agent) retryRestoredPark(n uint64, parked *parkedHandoff) error { question := questionAtTaskHandoff(a.owedAsks) a.mu.Unlock() ctx := withCrewWish(context.Background(), a.proposalCrewWish(n, crewWish{effort: rec.Effort, worker: rec.Worker})) - _, err := a.startOrJoinTaskRunVia(ctx, n, parked.title, rec.Brief, rec.DependsOn, taskStand{dir: rec.Dir, mode: rec.StandMode}, question, nil, rec.Asked...) + _, _, err := a.startOrJoinTaskRunVia(ctx, n, parked.title, rec.Brief, rec.DependsOn, taskStand{dir: rec.Dir, mode: rec.StandMode}, question, nil, rec.Asked...) var none *crewroute.NoEligibleError switch { case err == nil: diff --git a/internal/session/workspace_ownership.go b/internal/session/workspace_ownership.go index fe8f9a985f..538e9e729a 100644 --- a/internal/session/workspace_ownership.go +++ b/internal/session/workspace_ownership.go @@ -100,10 +100,10 @@ func homeTaskRedirect(dir string) string { return "The task reads " + dir + " and keeps what it makes in its own folder; nothing in " + dir + " changes." } -// withHomeReadingNote is [taskCopy.ownFolderNote] for a run, whose workers learn +// withTaskReadsNote is [taskCopy.ownFolderNote] for a run, whose workers learn // their folder as the assigned working directory and read the run's words. It // is said over every ground a run only reads, the home folder or not. -func withHomeReadingNote(place Place, brief string, stand taskStand) string { +func withTaskReadsNote(place Place, brief string, stand taskStand) string { ground := canonicalPath(strings.TrimSpace(stand.dir)) if stand.workspaceSet != nil || ground == "" || preparedTaskMode(place, ground, stand.mode) != TaskModeReference { return brief From 0bee31a92d37d802fb45d8d5ac9bb4ec7e5b146d Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:33:28 -0500 Subject: [PATCH 15/37] teams: final review round 2 repairs for the quiet global manager A directive the global manager sends is answered with team_post, and its text, the top-level manager's text and the send answer all say so. A member of the team that holds every team that manages nothing is told what an ordinary member is told, since its ending does wake the global manager. The closed-manager test now covers a failure opening it. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2906-global-manager-quiet.md | 6 +- internal/manual/chat/team-manager.md | 9 ++- internal/session/team.go | 21 +++--- internal/session/team_nest_test.go | 66 +++++++++++++++---- internal/session/team_sendoutcome.go | 6 +- 5 files changed, 80 insertions(+), 28 deletions(-) diff --git a/docs/changes/unreleased/2906-global-manager-quiet.md b/docs/changes/unreleased/2906-global-manager-quiet.md index 4f06f87523..d5fe02a871 100644 --- a/docs/changes/unreleased/2906-global-manager-quiet.md +++ b/docs/changes/unreleased/2906-global-manager-quiet.md @@ -5,9 +5,9 @@ pr: 2906 surface: [engine, chat] invalidates: - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team the finished event of a member that manages a top-level team (teams.File.TopManagers, teamRole.quietEnding) no longer starts the global manager's turn either (teamEventWakesManagerOf): of that manager's events only failed and asking do, and its team_post, a decision packet it raises and a conflict it declares wake the global manager as before. A global manager nobody has open is likewise no longer opened by such a finished event. A member of that team that manages nothing, and every other team, are unchanged, so a stopped-by-the-person event from such a member wakes the global manager where the earlier rule kept every idle event in that team from doing so." - - "team_send answered every manager \"Replies and endings wake you when they arrive, so there is no need to wait or poll.\" In the team that holds every team it now answers \"Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A manager's turn ending on its own does not wake you: team_status says where it stands.\" The answer in every other team is as it was." - - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\", and its scope adds \"A manager's turn ending does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the note every turn of the global manager carries." - - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending does not start its turn: post what it should act on or tell the person, and nothing the person already has from you here.\" The rest of that note is as it was." + - "team_send answered every manager \"Replies and endings wake you when they arrive, so there is no need to wait or poll.\" In the team that holds every team it now answers \"Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn ending alone does not wake you, and team_status says where it stands.\" The answer in every other team is as it was." + - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\" and ends \"A top-level team's manager ending its turn does not start yours.\", and its scope adds \"A manager answers a directive of yours with team_post, since its turn ending tells you nothing; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the note every turn of the global manager carries." + - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending tells it nothing: answer each of its directives with team_post to the manager. Apart from those answers, post only what it should act on or tell the person.\" The rest of that note is as it was. Every member of that team was given that note, \"because you manage a top-level team\" included; a member there that manages nothing is now given the note a member of any team is given." --- The global manager's members are the managers of whole teams, each a conversation diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index aa51147ebd..60f4e283fc 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -540,9 +540,14 @@ A top-level manager's turn ending does not start the global manager's turn. You those managers directly and each answer ends a turn, so the endings stay in `All teams`' traffic, where `team_status` reads them. The global manager is woken by what a manager posts to it with `team_post`, by a manager's question or a permission it is held on, and by a -manager's turn failing. It is told never to send a manager your own request to that manager +manager's turn failing. So a directive the global manager sent is answered with `team_post`: +each manager is told to answer its directives that way, and apart from those answers to post +only what the global manager should act on or tell you. A manager that ends its turn on a +directive without posting has told the global manager nothing, and `team_status` is where it +finds out. The global manager is told never to send a manager your own request to that manager back as a directive. A member of `All teams` that manages no team is an ordinary member -there: its turn ending wakes the global manager as in any team. +there: it is told what a member of any team is told, and its turn ending wakes the global +manager as in any team. ## Conflicts between members and teams diff --git a/internal/session/team.go b/internal/session/team.go index 30e5647781..04ca2c51ad 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -1735,7 +1735,7 @@ func teamManagerScope(role teamRole, file *teams.File) string { if role.root { parts = append(parts, fmt.Sprintf("You are the global manager: %q holds every team, and your members are the managers of the top-level teams, never their members. "+ "Direct those managers and they pass it on. Their questions and conflicts between teams come to you before the person. team_start with kind team starts a new top-level team. "+ - "A manager's turn ending does not start yours; team_status says where each of them stands. "+ + "A manager answers a directive of yours with team_post, since its turn ending tells you nothing; team_status says where each of them stands. "+ "The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.", role.name)) } else if home, ok := file.Home(role.key); ok && home.Team != role.id { boss := "its manager" @@ -1775,13 +1775,14 @@ func teamManagerDelivery(role teamRole) string { if !role.wakes { return "This team's auto-wake is off: what you send, and your members' replies, wait for each conversation's next turn, so an idle member does not start on a directive until it next runs." } - // The global manager's turn is not started by a member's turn ending - // ([teamEventWakesManagerOf]). - back := "Members' replies to you, and their finishing, failing or asking," + // The global manager's turn is not started by a top-level manager's turn + // ending ([teamEventWakesManagerOf]). The root can hold ordinary members + // too, so the sentence names whose ending it is. + back, except := "Members' replies to you, and their finishing, failing or asking,", "" if role.root { - back = "Members' replies to you, and their failing or asking," + back, except = "Members' replies to you, and their failing or asking,", " A top-level team's manager ending its turn does not start yours." } - return "A directive (team_send kind directive) starts an idle member's turn; a note waits for its next turn. team_send's answer says whether each member started: one the person paused does not start until they resume it, and work is under way only where the answer says so. " + back + " come back to you and start your turn when you are idle, so do not wait or poll for them." + return "A directive (team_send kind directive) starts an idle member's turn; a note waits for its next turn. team_send's answer says whether each member started: one the person paused does not start until they resume it, and work is under way only where the answer says so. " + back + " come back to you and start your turn when you are idle, so do not wait or poll for them." + except } // teamRoster names the manager's members by handle, with the start of each @@ -1834,10 +1835,14 @@ func teamMemberRole(role teamRole) string { if role.handle != "" { you = "@" + role.handle } - if role.root { + // Only a top-level team's manager is told its ending is silent: anybody + // else the root holds is an ordinary member there, whose ending wakes the + // global manager ([teamRole.quietEnding]), and reads the text below. + if role.quietEnding(role.key) { return fmt.Sprintf("You are %s in %q because you manage a top-level team: you report to its manager, the global manager. Its directives reach you marked \"◆ from manager\", "+ "your questions go to it before the person, and you report to it with team_post to the manager. "+ - "Your turn ending does not start its turn: post what it should act on or tell the person, and nothing the person already has from you here.", you, role.name) + "Your turn ending tells it nothing: answer each of its directives with team_post to the manager. "+ + "Apart from those answers, post only what it should act on or tell the person.", you, role.name) } if role.boss != "" && role.boss != role.id && !role.shared { said := fmt.Sprintf("You are %s in the team %q, which has no manager of its own, so you answer to the manager of %q: team_post to the manager reaches it, and to the room or a teammate stays in %q.", diff --git a/internal/session/team_nest_test.go b/internal/session/team_nest_test.go index 756161e6a9..82e99d312b 100644 --- a/internal/session/team_nest_test.go +++ b/internal/session/team_nest_test.go @@ -9,12 +9,15 @@ package session // teams.json and real Traffic, through internal/teams. import ( + "context" + "errors" "os" "path/filepath" "strings" "testing" "time" + "github.com/Agent-Field/agentfield/sdk/go/ai" "github.com/Agent-Field/codeaf/internal/teams" ) @@ -524,7 +527,10 @@ func TestAnUnmanagedSubTeamsMemberAnswersToTheManagerAbove(t *testing.T) { // THE GLOBAL MANAGER IS NOT WOKEN BY A TOP-LEVEL MANAGER'S TURN ENDING. The // person talks to that manager directly and each answer ends a turn; what the -// global manager should act on is posted to it, and that still wakes it. +// global manager should act on is posted to it, and that still wakes it. A +// directive of the global manager's is answered the same way, and both sides +// are told so, because the ending that closes the loop in any other team says +// nothing here. func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { fastTeamWake(t) n := newTeamTree(t, "gm", "boss", "web") @@ -541,9 +547,13 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { } gmCalls := oneAnswer(4) gm := teamAgent(t, n.fixture, n.paths["gm"], gmCalls, nil) - boss := teamAgent(t, n.fixture, n.paths["boss"], oneAnswer(4), nil) + bossCalls := oneAnswer(4) + boss := teamAgent(t, n.fixture, n.paths["boss"], bossCalls, nil) submitAndWait(t, boss, "plan the release") + if role := strings.Join(roleNotes(bossCalls.request(0)), "\n"); !strings.Contains(role, "Your turn ending tells it nothing: answer each of its directives with team_post to the manager.") { + t.Fatalf("the top-level manager is not told to answer the global manager's directive with a post:\n%s", role) + } boss.settleTeamEvents() // Past the settle a wake waits out, with room: a wake the ending had armed // would have fired by now. @@ -564,7 +574,7 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { } waitRequests(t, gmCalls, 1) asked := userTextIn(gmCalls.request(0)) - for _, want := range []string{"from @boss: harbor shipped", "A manager's turn ending does not start yours", "and their failing or asking, come back to you"} { + for _, want := range []string{"from @boss: harbor shipped", "A manager answers a directive of yours with team_post", "and their failing or asking, come back to you", "A top-level team's manager ending its turn does not start yours."} { if !strings.Contains(asked, want) { t.Fatalf("the global manager's turn lacks %q:\n%s", want, asked) } @@ -575,8 +585,9 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { if strings.Contains(asked, "finished its turn") || strings.Contains(asked, "What your members in") { t.Fatalf("the ending rode into the global manager's turn as something that woke it:\n%s", asked) } - // Its own send's answer does not promise that an ending wakes it. - if said := sendDirective(t, gm, "boss"); strings.Contains(said, "endings wake you") || !strings.Contains(said, "A manager's turn ending on its own does not wake you") { + // Its own send's answer does not promise that an ending wakes it, and says + // what answers the directive. + if said := sendDirective(t, gm, "boss"); strings.Contains(said, "endings wake you") || !strings.Contains(said, "A top-level team's manager answers a directive with team_post: its turn ending alone does not wake you") { t.Fatalf("the global manager's send says endings wake it: %s", said) } } @@ -584,7 +595,8 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { // A GLOBAL MANAGER NOBODY HAS OPEN IS NOT OPENED BY THE ENDING EITHER, and is // still opened by a top-level manager's failure. A member of the team that // holds every team that manages nothing is an ordinary member there: its -// ending opens the manager as it does in any team. +// ending opens the manager as it does in any team, and its role says nothing +// about managing a team or an ending nobody hears. func TestAClosedGlobalManagerIsNotOpenedByATopLevelManagersTurnEnding(t *testing.T) { fastTeamWake(t) n := newTeamTree(t, "gm", "boss", "web", "guest") @@ -612,7 +624,18 @@ func TestAClosedGlobalManagerIsNotOpenedByATopLevelManagersTurnEnding(t *testing } return count } - boss := teamAgent(t, n.fixture, n.paths["boss"], oneAnswer(2), nil) + waitOpened := func(want int) bool { + deadline := time.Now().Add(5 * time.Second) + for opened() < want && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + return opened() >= want + } + bossCalls := oneAnswer(1) + bossCalls.steps = append(bossCalls.steps, func(context.Context, []ai.Message) (*ai.Response, error) { + return nil, errors.New("insufficient_quota: out of budget") + }) + boss := teamAgent(t, n.fixture, n.paths["boss"], bossCalls, nil) submitAndWait(t, boss, "plan the release") boss.settleTeamEvents() time.Sleep(teamWakeDelay() + 15*teamWatchInterval()) @@ -620,16 +643,33 @@ func TestAClosedGlobalManagerIsNotOpenedByATopLevelManagersTurnEnding(t *testing t.Fatalf("a closed global manager was opened %d times by a top-level manager's turn ending", got) } - guest := teamAgent(t, n.fixture, n.paths["guest"], oneAnswer(2), nil) + submitAndWait(t, boss, "ship it") + boss.settleTeamEvents() + all := teamFixture{profile: n.fixture.profile, teamID: root} + if failed := trafficEvents(t, all, "failed: "); len(failed) != 1 || failed[0].State != teams.StateFailed { + t.Fatalf("the top-level manager's failed turn is not one failed event in the team that holds every team: %+v", failed) + } + if !waitOpened(1) { + t.Fatal("a top-level manager's turn failed and the closed global manager was not opened") + } + + before := opened() + guestCalls := oneAnswer(2) + guest := teamAgent(t, n.fixture, n.paths["guest"], guestCalls, nil) submitAndWait(t, guest, "tidy the notes") guest.settleTeamEvents() - deadline := time.Now().Add(5 * time.Second) - for opened() == 0 && time.Now().Before(deadline) { - time.Sleep(10 * time.Millisecond) - } - if got := opened(); got == 0 { + if !waitOpened(before + 1) { t.Fatal("a member of the team that holds every team that manages nothing ended its turn and its manager was not opened") } + role := strings.Join(roleNotes(guestCalls.request(0)), "\n") + if !strings.Contains(role, `in the team "All teams", which has a manager.`) { + t.Fatalf("a member of the team that holds every team that manages nothing is not told it is a member there:\n%s", role) + } + for _, not := range []string{"you manage a top-level team", "Your turn ending tells it nothing"} { + if strings.Contains(role, not) { + t.Fatalf("a member that manages nothing is told %q, which is true of a top-level team's manager only:\n%s", not, role) + } + } } func TestTeamEventWakesTheGlobalManager(t *testing.T) { diff --git a/internal/session/team_sendoutcome.go b/internal/session/team_sendoutcome.go index 8b643b7ae4..c2c4d7db3c 100644 --- a/internal/session/team_sendoutcome.go +++ b/internal/session/team_sendoutcome.go @@ -206,10 +206,12 @@ func itThey(n int) string { // teamSendWakesSentence is what a send's answer says comes back on its own. // The global manager is not woken by a top-level manager's turn ending -// ([teamEventWakesManagerOf]), so its answer does not promise that. +// ([teamEventWakesManagerOf]), so its answer does not promise that, and says +// what closes a directive instead. The root can hold ordinary members too, so +// the sentence names whose ending it is. func teamSendWakesSentence(root bool) string { if root { - return "Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A manager's turn ending on its own does not wake you: team_status says where it stands." + return "Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn ending alone does not wake you, and team_status says where it stands." } return "Replies and endings wake you when they arrive, so there is no need to wait or poll." } From 82a0c3b6bf9f36320a50a0786550cd61dd995c74 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:40:50 -0500 Subject: [PATCH 16/37] tasks: final review round 2 repairs for a reference saying so A writing task that joined a run which only reads its ground was told it had named no file and to propose again; it now has its own sentence. The read-only note was kept in the brief a rerun re-reads, and the ground's path inside it made the rerun a writing task; the note now goes only to the workers. The manual no longer promises a receipt to a typed /task, and the landing line appears once on the run's page. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2909-reference-task-says-so.md | 7 +- internal/manual/chat/how-tasks-run.md | 20 ++- internal/session/task.go | 27 +++- internal/session/task_reference_test.go | 121 +++++++++++++++++- internal/session/task_run_belt.go | 39 +++--- 5 files changed, 184 insertions(+), 30 deletions(-) diff --git a/docs/changes/unreleased/2909-reference-task-says-so.md b/docs/changes/unreleased/2909-reference-task-says-so.md index 1173a7bbca..9855f1eee1 100644 --- a/docs/changes/unreleased/2909-reference-task-says-so.md +++ b/docs/changes/unreleased/2909-reference-task-says-so.md @@ -4,11 +4,12 @@ title: A task that only reads its folder says so when it starts, to its worker, pr: 2909 surface: [engine, chat] invalidates: - - "A task whose stand is a reference (TaskModeReference, a ground it only reads) was told so on its receipt only when `where` named a folder holding the home folder (homeTaskRedirect). Where the proposal's `ground` or its brief had chosen the folder, the receipt read \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\", the home folder included; on the other rungs it had no sentence about the folder. On every rung its receipt now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file there by full path. If the work is meant to change , stop this task and propose it again naming the files it makes or changes by their full path under .\" (taskReadsSentence), or over the home folder \"The task reads and keeps what it makes in its own folder; nothing in changes.\" whichever door named the folder." + - "A task whose stand is a reference (TaskModeReference, a ground it only reads) was told so on its receipt only when `where` named a folder holding the home folder (homeTaskRedirect). Where the proposal's `ground` or its brief had chosen the folder, the receipt read \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\", the home folder included; on the other rungs it had no sentence about the folder. On every rung the receipt of a task the conversation's model proposes now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file there by full path. If the work is meant to change , stop this task and propose it again naming the files it makes or changes by their full path under .\" (taskReadsSentence), or over the home folder \"The task reads and keeps what it makes in its own folder; nothing in changes.\" whichever door named the folder. A task a person types with `/task` is handed no receipt sentence about its folder on the run road, and on the older single-task road only the stand's redirect, as before." - "A reference worker was told \" is yours to read, not to change. Everything you make goes in , your own folder. In your report, say where in that folder the results are.\" only when its ground held the home folder (taskCopy.readsHome, withHomeReadingNote); over any other ground it was told nothing. Every reference worker whose folder is not its ground is now told \" is yours to read, not to change. Everything you make goes in , your own folder, and stays there: nothing you make reaches . In your report, say where in that folder the results are, and never say the work is in .\" (taskReadsNote; the field is taskCopy.reads, and the run's helper is withTaskReadsNote)." - - "A run that only read its ground was handed to the engine's landing, which failed in its folder with \"fatal: not a git repository\": a plan note \"the run's landing failed\" was filed, the landing had no line (RunLanding.Line empty, no branch) and the run's page got no homecoming note. Such a run is no longer handed to the engine's landing (landReferenceRun): its landing line and its page's homecoming note both read \"it changed nothing in : what it made is in \" (referenceLandingLine)." + - "A run that only read its ground was handed to the engine's landing, which failed in its folder with \"fatal: not a git repository\": a plan note \"the run's landing failed\" was filed, the landing had no line (RunLanding.Line empty, no branch) and the run's page got no homecoming note. Such a run is no longer handed to the engine's landing (landReferenceRun): its landing line reads \"it changed nothing in : what it made is in \" (referenceLandingLine), and its page carries that line once, in the run's outcome note, with no separate homecoming note. A reference run that failed is given the same line; one that was stopped is given none." - "A reference whose proposal asked for `where: \"in place\"` inside a repository had the redirect \"in place was asked for, and is a repository — the work goes on a branch cut from it instead\" printed on its receipt. The stand still carries that redirect, and the receipt of a reference no longer prints it (taskStandRedirect)." - - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode)." + - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode). A hand-off that joined a run which only reads its ground, the home folder apart, is not given the starting task's sentence or \"It joined the work already underway and shares its copy.\": its receipt reads \"It joined the work already underway, which only reads and writes in a folder of its own, so nothing in changes while it is part of that run. To change , propose the work once that run has ended.\" (taskJoinedReadsSentence), whatever files its own proposal named." + - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." --- diff --git a/internal/manual/chat/how-tasks-run.md b/internal/manual/chat/how-tasks-run.md index c086c5338a..223751c352 100644 --- a/internal/manual/chat/how-tasks-run.md +++ b/internal/manual/chat/how-tasks-run.md @@ -116,13 +116,19 @@ project in words is not naming a file, so a brief such as "build the app in the repo" reads this way. So does a relative path such as `Sources/App/main.swift` when neither the file nor the folder that would hold it is there yet. -Such a task says so three times. Its receipt reads `It reads and writes only in a -folder of its own, so nothing in changes`, and says to stop it and propose it again -naming the files it makes or changes by their full path under that folder. Its worker is -told the folder is to read, not to change, and never to report the work as being there. A -task run as a run ends its landing `it changed nothing in : what it made is in `; the older single-task road lands without that line. A task that joins a run -already underway is told what is true of that run instead, since it shares the run's copy. +Such a task says so wherever there is somebody to tell. One the conversation's model +proposes says it in its receipt: `It reads and writes only in a folder of its own, +so nothing in changes`, and to stop it and propose it again naming the files it +makes or changes by their full path under that folder. A task you type with `/task` has no +such receipt. Every such task tells its worker the folder is to read, not to change, and +never to report the work as being there. A task run as a run ends its landing `it changed +nothing in : what it made is in `; the older single-task road lands +without that line. + +A proposed task that joins a run already underway shares that run's copy, so it is told +what is true of that run instead. Joining one that only reads the folder, its receipt says +`nothing in changes while it is part of that run`, whatever files it named, and to +propose the work once that run has ended. To have the work done in the repository, name a file under it by full path in the brief, in what to produce or in the done-when, such as `~/MacStats/Sources/App/main.swift`. diff --git a/internal/session/task.go b/internal/session/task.go index bc63405b48..27e7f1ef1b 100644 --- a/internal/session/task.go +++ b/internal/session/task.go @@ -1147,19 +1147,26 @@ func (a *Agent) handoffAnswer(p *stagedProposal, spec taskSpec, elsewhere string return refusal.Error(), true, true } if err == nil { - said := p.stand + said, shares := p.stand, "It joined the work already underway and shares its copy." if joined { // A TASK THAT JOINED A RUN IS SAID AS THAT RUN STANDS. It shares the // run's copy, so a receipt read off its own stand told a reference // that joined a worktree that nothing in the ground would change. said.mode = stand.mode + // AND A RUN THAT ONLY READS IS SAID AS THE RUN'S DOING, never the + // proposal's: the starting task's sentence told a proposal that had + // named its files by full path that it named none, and to propose + // again, which joins the same run. + if reads := taskJoinedReadsSentence(said); reads != "" { + said, shares = taskStand{}, reads + } } receipt := taskReceipt(p.id, spec, TaskRunning, said, elsewhere) switch { case via != nil: receipt = delegateStartedReceipt(p.id, spec.title, strings.Join(asked, ", "), delegateReceipt(canonicalPath(stand.dir), *via, a.runRowCopy(p.id)), elsewhere) case joined: - receipt = withReport(receipt, "It joined the work already underway and shares its copy.") + receipt = withReport(receipt, shares) } return receipt, false, true } @@ -1292,6 +1299,22 @@ func taskReadsSentence(dir string) string { "If the work is meant to change " + dir + ", stop this task and propose it again naming the files it makes or changes by their full path under " + dir + "." } +// taskJoinedReadsSentence is what a proposer reads when its task joined a run +// already underway that only reads the ground, and nothing for any other +// stand. What the proposal named does not decide it and proposing again +// changes nothing while that run lives, so it says neither +// ([taskReadsSentence]) and names the one thing that does: the run's ending. +// The home folder is only ever read and keeps its own sentence +// ([homeTaskRedirect]). +func taskJoinedReadsSentence(stand taskStand) string { + if stand.mode != TaskModeReference || stand.dir == "" || HoldsHomeFolder(stand.dir) { + return "" + } + dir := cleanFolder(stand.dir) + return "It joined the work already underway, which only reads " + dir + " and writes in a folder of its own, so nothing in " + dir + " changes while it is part of that run. " + + "To change " + dir + ", propose the work once that run has ended." +} + // taskHandoffWakeSentence is what EVERY handoff receipt ends with, and it is one // sentence because it answers one question: what does the model do now? // diff --git a/internal/session/task_reference_test.go b/internal/session/task_reference_test.go index 54ea18e53d..27b7536786 100644 --- a/internal/session/task_reference_test.go +++ b/internal/session/task_reference_test.go @@ -8,6 +8,10 @@ import ( "strconv" "strings" "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/crewroute" ) // A TASK THAT ONLY READS ITS GROUND SAYS SO AT ALL THREE ENDS: the proposer's @@ -155,8 +159,8 @@ func TestAReferenceRunLandsWithItsLineAndNoEngineLanding(t *testing.T) { if len(rows) != 1 || !strings.Contains(rows[0].Report, line) { t.Errorf("the settled row does not carry the landing line %q: %+v", line, rows) } - if notes := strings.Join(beltRunNotes(t, sessionDir, "41"), "\n"); !strings.Contains(notes, line) || strings.Contains(notes, "its work is in") { - t.Errorf("the run's page does not say the landing line alone:\n%s", notes) + if notes := strings.Join(beltRunNotes(t, sessionDir, "41"), "\n"); strings.Count(notes, line) != 1 || strings.Contains(notes, "its work is in") { + t.Errorf("the run's page does not say the landing line alone, once:\n%s", notes) } if logDir := agent.logDirectory(); logDir == "" { t.Error("the conversation has no log directory to read plan notes from") @@ -215,3 +219,116 @@ func TestAReferenceThatJoinsAWritingRunIsNotToldItOnlyReads(t *testing.T) { } endBeltRun(t, agent, double) } + +// A TASK THAT JOINS A RUN THAT ONLY READS IS TOLD SO AS THE RUN'S DOING. Its +// own proposal named a file by full path, so the starting task's reason ("named +// no file") is false of it, and its remedy ("propose it again") joins the same +// run: the receipt says what is true and the one thing that changes it. +func TestAWritingTaskThatJoinsAReferenceRunIsToldTheRunOnlyReads(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + double := newBeltRunDouble("the parser reads tokens") + registerBeltRunEngine(t, double) + sessionDir := t.TempDir() + ground := newTestRepo(t) + agent, _ := newTestAgent(t, beltRunCompleter{text: "the parser reads tokens"}, func(config *Config) { + config.Workspace = ground + config.Place = Place{Dir: sessionDir} + config.AskConsent = false + config.TaskAutoApproveSeconds = 0 + }) + if err := agent.startKnownTaskRun(context.Background(), 41, "explain the parser", "brief", nil, taskStand{dir: ground, mode: TaskModeReference, rung: taskGroundSaid}, ""); err != nil { + t.Fatalf("start the reference run: %v", err) + } + <-double.entered + file := filepath.Join(canonicalPath(ground), "parser_notes.go") + args, _ := json.Marshal(taskArguments{ + Title: "Write the parser notes", Summary: "the proposed work", Brief: "write " + file, + Deliverable: "the file " + file, Acceptance: file + " is there", Ground: ground, + }) + proposal, ok := agent.stageTask(context.Background(), args).(*stagedProposal) + if !ok || proposal.stand.mode != TaskModeWorktree { + t.Fatalf("the proposal did not stage as work in its ground: %+v", proposal) + } + agent.ResolveTask(proposal.id, TaskAnswer{Approved: true}) + answer, failed, err := proposal.Commit(context.Background()) + if err != nil || failed { + t.Fatalf("propose_task: failed=%v err=%v answer=%q", failed, err, answer) + } + dir := canonicalPath(ground) + for _, want := range []string{ + "It joined the work already underway, which only reads " + dir, + "nothing in " + dir + " changes while it is part of that run", + "To change " + dir + ", propose the work once that run has ended.", + } { + if !strings.Contains(answer, want) { + t.Errorf("the receipt of a task that joined a run that only reads lacks %q:\n%s", want, answer) + } + } + for _, untrue := range []string{"named no file", "propose it again", "It works in", "shares its copy"} { + if strings.Contains(answer, untrue) { + t.Errorf("the receipt of a task that joined a run that only reads says %q:\n%s", untrue, answer) + } + } + endBeltRun(t, agent, double) +} + +// A RERUN OF A REFERENCE RUN IS STILL A REFERENCE. The read-only note names the +// ground by full path, and a rerun reads the crew's kept brief again as a +// contract: kept with the note, the rerun stood as a writing task on the +// repository, cut a branch and merged, under words calling it read-only. +func TestARerunOfAReferenceRunIsStillAReference(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + first := newBeltRunDouble("the parser reads tokens") + registerBeltRunEngine(t, first) + ground := canonicalPath(newTestRepo(t)) + sessionDir := t.TempDir() + agent, _ := newTestAgent(t, beltRunCompleter{text: "the parser reads tokens"}, func(c *Config) { + // The conversation stands in a plain folder and is about the repository. + c.Workspace = t.TempDir() + c.Place = Place{Dir: sessionDir} + c.SessionFile = filepath.Join(sessionDir, placeTranscript) + c.AskConsent = false + c.ProfileDir = t.TempDir() + c.RouteCrew = func(config.CrewAsk) (crewroute.Decision, error) { return flashDecision(), nil } + }) + agent.refer(PlaceRef{Path: ground, Arrival: PlaceSaid, Referred: time.Now()}) + liveStand := func() taskStand { + agent.beltMu.Lock() + defer agent.beltMu.Unlock() + if agent.beltRun == nil { + return taskStand{} + } + return agent.beltRun.stand + } + + id, _, _, err := agent.StartTask(context.Background(), "say how the parser reads its input", false) + if err != nil { + t.Fatalf("start the reference run: %v", err) + } + <-first.entered + if stand := liveStand(); stand.dir != ground || stand.mode != TaskModeReference { + t.Fatalf("the run does not only read %s: %+v", ground, stand) + } + first.mu.Lock() + given := first.spec.Brief + first.mu.Unlock() + if !strings.Contains(given, ground+" is yours to read, not to change") { + t.Errorf("the run's workers are not told their ground is read-only:\n%s", given) + } + crew := agent.crews.get(id) + if crew == nil || strings.Contains(crew.brief, "yours to read") || strings.Contains(crew.brief, ground) { + t.Fatalf("the brief a rerun reads again carries the read-only note: %+v", crew) + } + endBeltRun(t, agent, first) + + second := newBeltRunDouble("the parser reads tokens") + registerBeltRunEngine(t, second) + if _, err := agent.rerunWithRouting(context.Background(), TaskNotice{ID: id, Title: crew.title, State: TaskDone}, crew, TaskRoutingAction{Kind: TaskRoutingBest}); err != nil { + t.Fatalf("rerun the reference run: %v", err) + } + <-second.entered + if stand := liveStand(); stand.dir != ground || stand.mode != TaskModeReference { + t.Errorf("the rerun of a run that only read %s stands as %+v", ground, stand) + } + endBeltRun(t, agent, second) +} diff --git a/internal/session/task_run_belt.go b/internal/session/task_run_belt.go index a309d07c80..ee19659570 100644 --- a/internal/session/task_run_belt.go +++ b/internal/session/task_run_belt.go @@ -713,10 +713,6 @@ func (a *Agent) startOrJoinTaskRunVia(ctx context.Context, id uint64, title, bri a.publishJoinedRunRows(g, live) return preparedTaskMode(a.config.Place, live.ground, live.stand.mode), true, nil } - // THE READ-ONLY NOTE IS A RUN'S OWN, added once no live run took the work: - // a hand-off that joined was told what is true of the run it joined - // ([Agent.joinOrWait]). - brief = withTaskReadsNote(a.config.Place, brief, stand) // ADMISSION IS CHECKED BEFORE A FOLDER OR COPY IS TOUCHED. A held run seeds // only its plan store so stopping it cannot leave a repository claim behind; @@ -740,7 +736,15 @@ func (a *Agent) startAdmittedBeltRun(ctx context.Context, engine RunEngine, g *T if err != nil { return false, err } - plan, store, err := a.openBeltRunStore(g, path, storeID, title, brief, false) + // THE READ-ONLY NOTE IS IN WHAT THE WORKERS ARE GIVEN AND NEVER IN THE + // CONTRACT. The crew above keeps the brief it was routed on, and a rerun + // reads that brief again as a contract (taskcrew.go, taskrouting.go): the + // note names the ground by full path, so a rerun that found it there stood + // as a writing task on the folder its own words called read-only. It is a + // run's own, added once no live run took the work: a hand-off that joined + // was told what is true of the run it joined ([Agent.joinOrWait]). + given := withTaskReadsNote(a.config.Place, brief, stand) + plan, store, err := a.openBeltRunStore(g, path, storeID, title, given, false) if err != nil { folder.abandon() return false, err @@ -807,7 +811,7 @@ func (a *Agent) startAdmittedBeltRun(ctx context.Context, engine RunEngine, g *T Crew: run.crewDecision(), CrewState: a.initialCrewRecord(run), Model: run.crewWorker(), }) - spec := a.beltRunSpec(run, brief) + spec := a.beltRunSpec(run, given) a.holdProgramCeilings(run, spec) go a.driveBeltRun(runCtx, engine, run, spec) return false, nil @@ -825,7 +829,10 @@ func (a *Agent) startDeferredBeltRun(ctx context.Context, engine RunEngine, g *T return false, err } } - plan, store, err := a.openBeltRunStore(g, path, storeID, title, brief, false) + // The workers' words, and never the crew's kept brief + // ([Agent.startAdmittedBeltRun] has why). + given := withTaskReadsNote(a.config.Place, brief, stand) + plan, store, err := a.openBeltRunStore(g, path, storeID, title, given, false) if err != nil { return false, err } @@ -848,7 +855,7 @@ func (a *Agent) startDeferredBeltRun(ctx context.Context, engine RunEngine, g *T machineHeld = map[string]bool{planStoreID(storeID): true} } run := &beltRun{ - plan: plan, store: store, root: store.RootID(), row: id, title: title, brief: brief, + plan: plan, store: store, root: store.RootID(), row: id, title: title, brief: given, stand: stand, ground: canonicalPath(stand.dir), pending: true, admission: admission, machineHeld: machineHeld, cut: cut, born: born, over: make(chan struct{}), @@ -864,7 +871,7 @@ func (a *Agent) startDeferredBeltRun(ctx context.Context, engine RunEngine, g *T ID: id, Title: title, State: TaskQueued, Program: programName(via), Remote: cloneTaskRemote(run.remote), Computer: run.taskComputerName(), PlanTask: planStoreID(storeID), Crew: run.crewDecision(), CrewState: a.initialCrewRecord(run), Model: run.crewWorker(), Waiting: waiting, - PendingRun: &PendingRunRecord{WorkspaceSet: stand.workspaceSet, Brief: brief, Ground: stand.dir, Mode: stand.mode, Asked: asked}, + PendingRun: &PendingRunRecord{WorkspaceSet: stand.workspaceSet, Brief: given, Ground: stand.dir, Mode: stand.mode, Asked: asked}, }) go a.driveBeltRun(runCtx, engine, run, RunSpec{}) return false, nil @@ -2366,17 +2373,17 @@ func (a *Agent) landBeltRun(ctx context.Context, engine RunEngine, run *beltRun) // filed for every such run, and the conversation was handed the worker's own // account of the work with nothing saying the ground was untouched // (task_brief.go's [copyOnto] has the run). There is no branch to merge and no -// copy to give back: the homecoming is the one line, on the run's page and in -// the landing alike. +// copy to give back: the homecoming is the one line. It is not written twice: +// the landing carries it and the run's one outcome note is where its page +// reads it ([beltRunOutcomeNote]), as a merge that did not go in is read +// ([Agent.bringBeltRunHome]). +// +// A RUN THAT FAILED IS GIVEN THE SAME LINE, and it is as true of it: the ground +// was not its to change, and whatever it made before it ended is in its folder. func (a *Agent) landReferenceRun(run *beltRun, line string) RunLanding { if !a.beginBeltHomecoming(run) { return RunLanding{} } - if _, err := run.store.AddNote(run.root, run.root, line); err != nil { - if g := a.graph(); g != nil { - g.planNote("the run's homecoming note failed: " + err.Error()) - } - } return RunLanding{Line: line} } From c2f783a1e2e300e072163a879283fe995eed14aa Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:51:00 -0500 Subject: [PATCH 17/37] teams: final review round 2 repairs Handed work now lasts as long as the work does: across a turn that ends while the member waits on a command, and the turn that command starts. A stop of such a later turn, or of the person's own turn while the member waits on handed work, tells the manager once, so a hold never swallows the ending of handed work with nobody told. The manual says a task landing still starts a stopped conversation. The app's pause-kill, its quit door and the pause carry-over have tests. Co-Authored-By: Claude Fable 5.2 --- cmd/codeaf/app.go | 2 +- cmd/codeaf/appcrewstops_test.go | 187 +++++++++++++++ cmd/codeaf/appwakes.go | 13 +- .../unreleased/2897-crew-handoff-outcome.md | 4 +- internal/manual/chat/team-manager.md | 30 +-- internal/session/agent.go | 4 +- internal/session/team.go | 9 +- internal/session/team_pause.go | 14 +- internal/session/team_stophold.go | 111 +++++---- internal/session/team_stophold_test.go | 217 +++++++++++++++--- internal/session/teamevent.go | 15 +- 11 files changed, 494 insertions(+), 112 deletions(-) create mode 100644 cmd/codeaf/appcrewstops_test.go diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 92344af9bf..a82e0e3906 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -5003,7 +5003,7 @@ func (b *appBackend) Close() error { // is only detached from. if live := b.liveOf(a); live != nil && live.conn.Assembled { // The app is leaving; the person did not press stop. - appInterruptFor(live.conn.Conv, session.StopByClosing, "") + appInterruptFor(live.conn.Conv, session.StopByClosing) } b.letGoTimed(a, os.Stderr) }) diff --git a/cmd/codeaf/appcrewstops_test.go b/cmd/codeaf/appcrewstops_test.go new file mode 100644 index 0000000000..b98519874e --- /dev/null +++ b/cmd/codeaf/appcrewstops_test.go @@ -0,0 +1,187 @@ +package main + +import ( + "os" + "path/filepath" + "slices" + "sync" + "testing" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/session" + teamstore "github.com/Agent-Field/codeaf/internal/teams" +) + +// dooredConversation remembers the door each stop came through, as a +// conversation reached across a connection is told it. +type dooredConversation struct { + *fakeConversation + doorMu sync.Mutex + doors []session.StopDoor +} + +func (d *dooredConversation) Interrupt() { d.InterruptFor(session.StopByPerson) } + +func (d *dooredConversation) InterruptFor(door session.StopDoor) { + d.doorMu.Lock() + defer d.doorMu.Unlock() + d.doors = append(d.doors, door) +} + +func (d *dooredConversation) stops() []session.StopDoor { + d.doorMu.Lock() + defer d.doorMu.Unlock() + return slices.Clone(d.doors) +} + +// dooredBackend holds one conversation that records its stops. +func dooredBackend(t *testing.T, assembled bool) (*appBackend, *dooredConversation, appwire.Agent) { + t.Helper() + state, profile := t.TempDir(), t.TempDir() + conv := &dooredConversation{fakeConversation: &fakeConversation{}} + backend := newFakeBackend(newAppRecorder(), func(ask appOpenAsk) (*appConn, error) { + return &appConn{Conv: conv, Workspace: ask.Workspace, Transcript: appFakeTranscript, Assembled: assembled, Release: func() {}}, nil + }) + t.Cleanup(func() { backend.Close() }) + backend.state = &appState{path: filepath.Join(state, appStateName)} + backend.profileDir = profile + agent, err := mustCreate(t, backend, appwire.CreateAsk{Workspace: t.TempDir()}) + if err != nil { + t.Fatal(err) + } + return backend, conv, agent +} + +// wake hands the backend one finished turn it did not start. +func wake(backend *appBackend, id, said string) { + a := backend.agent(id) + events := make(chan session.Event, 1) + events <- session.Event{Kind: session.EventTurnDone} + close(events) + backend.wokenTurn(a, backend.liveOf(a), appTurnElsewhere{said: said, events: events}) +} + +// A PAUSED MEMBER'S STRAY WAKE IS STOPPED AS THE APP'S OWN DOING, and a turn +// the person's words opened is left to run. Through the person's door the stop +// would be told to the member's manager as work the person had stopped. +func TestAppWokenTurnOfAPausedMemberStopsThroughTheAppsDoor(t *testing.T) { + backend, conv, agent := dooredBackend(t, false) + crew := teamstore.NewID() + paused := func(on bool) { + t.Helper() + if err := teamstore.Update(backend.profileDir, func(f *teamstore.File) error { + return f.SetPaused(crew, appFakeTranscript, on) + }); err != nil { + t.Fatal(err) + } + } + if err := teamstore.Update(backend.profileDir, func(f *teamstore.File) error { + f.Teams = append(f.Teams, teamstore.Team{ID: crew, Name: "crew"}) + lead := filepath.Join(t.TempDir(), "lead", "transcript.jsonl") + if err := f.AddMember(crew, teamstore.Member{Key: lead, File: lead, Handle: "lead"}); err != nil { + return err + } + if err := f.AddMember(crew, teamstore.Member{Key: appFakeTranscript, File: appFakeTranscript, Handle: "scout", Started: true}); err != nil { + return err + } + return f.SetManager(crew, lead) + }); err != nil { + t.Fatal(err) + } + + wake(backend, agent.ID, "") + if got := conv.stops(); len(got) != 0 { + t.Fatalf("a wake of a member that is not paused was stopped: %v", got) + } + paused(true) + if !backend.crewPaused(agent.ID) { + t.Fatal("the app does not read the member as paused") + } + wake(backend, agent.ID, "carry on with the header") + if got := conv.stops(); len(got) != 0 { + t.Fatalf("a turn the person's own words opened on a paused member was stopped: %v", got) + } + wake(backend, agent.ID, "") + if got := conv.stops(); len(got) != 1 || got[0] != session.StopByWorkStopped { + t.Fatalf("a paused member's stray wake was stopped through %v, want only %q", got, session.StopByWorkStopped) + } +} + +// QUITTING THE APP IS NOT THE PERSON'S STOP: a conversation the app assembled +// is stopped through the closing door, so a member's manager is not told the +// person stopped its work, and one that is another window's is left alone. +func TestAppCloseStopsThroughTheClosingDoor(t *testing.T) { + backend, conv, _ := dooredBackend(t, true) + backend.Close() + if got := conv.stops(); len(got) != 1 || got[0] != session.StopByClosing { + t.Fatalf("closing the app stopped its conversation through %v, want only %q", got, session.StopByClosing) + } + + backend, conv, _ = dooredBackend(t, false) + backend.Close() + if got := conv.stops(); len(got) != 0 { + t.Fatalf("closing the app stopped a conversation it only joined: %v", got) + } +} + +// AN EARLIER BUILD'S PAUSE IS CLEARED FROM THE APP'S FILE ONLY ONCE THE TEAM'S +// RECORD HAS IT. A store that could not be read keeps the flag for the next +// launch; a pause whose crew is gone has nowhere to go and is dropped. +func TestAppMovePausesToStoreKeepsAPauseItCouldNotCarry(t *testing.T) { + backend, _, agent := dooredBackend(t, false) + crew, gone := teamstore.NewID(), teamstore.NewID() + if err := teamstore.Update(backend.profileDir, func(f *teamstore.File) error { + f.Teams = append(f.Teams, teamstore.Team{ID: crew, Name: "crew"}) + lead := filepath.Join(t.TempDir(), "lead", "transcript.jsonl") + if err := f.AddMember(crew, teamstore.Member{Key: lead, File: lead, Handle: "lead"}); err != nil { + return err + } + if err := f.AddMember(crew, teamstore.Member{Key: appFakeTranscript, File: appFakeTranscript, Handle: "scout", Started: true}); err != nil { + return err + } + return f.SetManager(crew, lead) + }); err != nil { + t.Fatal(err) + } + if err := backend.crewLayer().write(func(f *appCrewLayerFile) error { + f.member(crew, agent.ID).Paused = true + f.member(gone, agent.ID).Paused = true + return nil + }); err != nil { + t.Fatal(err) + } + flag := func(crew string) (paused bool) { + t.Helper() + if err := backend.crewLayer().read(func(f *appCrewLayerFile) { paused = f.member(crew, agent.ID).Paused }); err != nil { + t.Fatal(err) + } + return paused + } + + // The store cannot be read: nothing is carried and nothing is forgotten. + path := teamstore.Path(backend.profileDir) + if err := os.Rename(path, path+".aside"); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(path, 0o700); err != nil { + t.Fatal(err) + } + backend.movePausesToStore() + if !flag(crew) || !flag(gone) { + t.Fatalf("a pause that could not be carried was cleared: crew=%v gone=%v", flag(crew), flag(gone)) + } + + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.Rename(path+".aside", path); err != nil { + t.Fatal(err) + } + backend.movePausesToStore() + if !backend.crewPaused(agent.ID) { + t.Fatal("the earlier build's pause was not carried onto the team's record") + } + if flag(crew) || flag(gone) { + t.Fatalf("a settled pause is still in the app's file: crew=%v gone=%v", flag(crew), flag(gone)) + } +} diff --git a/cmd/codeaf/appwakes.go b/cmd/codeaf/appwakes.go index 360e13c9f3..b1d5f85503 100644 --- a/cmd/codeaf/appwakes.go +++ b/cmd/codeaf/appwakes.go @@ -25,19 +25,10 @@ import ( // before a turn starts; a turn woken some other way while it holds is stopped // here at once. A turn the person's own words opened is not. -// appPausedStop is what a turn ended because its member is paused is told. -const appPausedStop = "this member is paused, so the turn stopped before it did anything; resume it to let it run" - // appInterruptFor ends a conversation's turn through a named door, for a stop // that is the app's own doing and not the person's stop key. A conversation // that cannot name a door is stopped the plain way. -func appInterruptFor(conv appConversation, door session.StopDoor, why string) { - if named, ok := conv.(interface { - InterruptNamed(session.StopDoor, string) - }); ok && why != "" { - named.InterruptNamed(door, why) - return - } +func appInterruptFor(conv appConversation, door session.StopDoor) { if doored, ok := conv.(interface{ InterruptFor(session.StopDoor) }); ok { doored.InterruptFor(door) return @@ -189,7 +180,7 @@ func (b *appBackend) wokenTurn(a *appAgent, live *appLive, elsewhere appTurnElse // any window, is theirs and runs. The stop is the app's and says so: // through the person's door it would be told to the member's manager // as work the person had stopped. - appInterruptFor(live.conn.Conv, session.StopByWorkStopped, appPausedStop) + appInterruptFor(live.conn.Conv, session.StopByWorkStopped) } live.box.Event(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) live.box.Event(appwire.EventTurnStarted, appwire.TurnStarted{Agent: id, Turn: turn}) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 26c78b26c2..80698182c7 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -7,14 +7,14 @@ invalidates: - "team_send answered every directive with \"A member that is idle starts a turn on it now, and a busy one reads it at its next step\" whatever happened. It now waits up to four seconds on the team's traffic and says for each member one of: \"@web started a turn on it.\", \"@web is in a turn and reads it at the next step.\", \"@web did NOT start: .\", \"@web is waiting on the person and reads it once they answer.\", or \"@web has shown no sign of starting yet; team_status says whether it did.\" Where a member did not start, the answer also tells the manager not to tell the person the work is under way." - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A member paused in any of its teams is not opened or woken by any team's traffic (File.PausedAnywhere), shows as paused in each of its crews, and is resumed from any of them (SetPaused false clears every membership); the directive stays undelivered and starts the member's turn when the person resumes it, including after a restart. A turn something else starts in a paused member (a command's ending, a task landing) is handed none of its teams' traffic and moves no cursor; a turn the person's own words open still reads what waited, and Resume then starts no turn on lines already read. The app carries an earlier build's pause onto the team's record once." - "A directive to a paused member wrote \"woke @x\" then \"stopped\" to the traffic. It now writes one line from system, \"held @x: the person paused it; it starts on this when they resume it\", answering the directive, and Resume writes an event from you with the text \"resumed\" to every open crew the member belongs to, whichever one it was pressed in." - - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A turn that was handed its manager's work (a directive, or the brief a started member begins on) and that the person then stops now ends \"stopped by the person\" (teams.StoppedByPerson); it wakes the manager and is delivered as \"@x's turn on what you handed it was stopped by the person before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask.\" A stopped turn that carried only the person's own request, a stop by the manager's team_stop (whichever interface performs it), the desktop app quitting, and the app ending a paused member's stray wake still end \"stopped\" and still wake nobody; the app's two stops now cancel through StopByClosing and StopByWorkStopped, where they used the person's door. The global manager is not woken by either." + - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A stop by the person of a member that is on its manager's work (a directive, or the brief a started member begins on) now ends \"stopped by the person\" (teams.StoppedByPerson), once per hand-off; it wakes the manager and is delivered as \"@x's turn on what you handed it was stopped by the person before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask.\" The work is under way from the hand-off until a turn finishes, or fails, with no background command left that the member waits on (one whose ending it is owed or asked to be notified of, or a watch that has not fired): a turn such a command's ending starts is still on it, and so is a turn the person opened with their own words while the member waits on one. A stop by the person with none of the manager's work under way, a stop by the manager's team_stop (whichever interface performs it), the desktop app quitting, and the app ending a paused member's stray wake still end \"stopped\" and still wake nobody; the app's two stops now cancel through StopByClosing and StopByWorkStopped, where they used the person's door. The global manager is not woken by either." - "team_status and the manager's digest gave a member's state as running, asking, idle or failed only. A member's line may now read \"paused by the person; it starts nothing until they resume it\" or \"on standby; no work handed out yet\", carries the member's role after its handle (\"- @dev, macOS developer\"), and may add \"has not started on #22\" (only for a member that is not in a turn) or \"its last turn was stopped by the person\"." - "Accepting a crew proposal (crews.create from proposal) started every helper at once on its brief. Each helper now joins on standby (teams.Member.Standby, cleared by the member's session once its start line is handed to it): its start line starts no turn, however much later the first directive comes, the traffic says \"opened @x on standby; it starts on its manager's first directive\", and the first directive hands it that line marked \"◆ your standing role from manager (what you are here for, not work to begin; work arrives as a directive)\" in place of \"◆ brief from manager\". team_start and members.start still start a member on its brief at once." - "A proposal's role name was kept only as an app-layer role with no instructions, so it reached neither the member nor the manager. It is now also the team's record (teams.Member.Role, File.SetRole): the member's team note says \"Your role in this team: .\", and the manager's roster shows the role in place of the title (\"@dev (macOS developer)\"). members.role and a role's rename write it too." - "The crew proposal prompt asked for each helper's brief as the \"whole assignment\". It now asks for \"what this helper is responsible for\", and says an accepted crew joins on standby." - "The desktop app stopped every turn it had not started itself on a paused member, including one the person opened by typing to that member from another window. It now leaves a turn the person's own words opened alone, and still stops any other wake (a background process ending, a task landing)." - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\". It also refuses a member that manages another open team (\"@lead manages and is not paused; stop its turn instead\"), and making a conversation a manager lifts its pause." - - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop, whether an interface performs it or the member's own session does) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A stop by the person that finds no turn running but a command or watch still running begins the same hold. Only when the conversation is waiting on one of them (a command whose ending it is owed or asked to be notified of, or a watch that has not fired) does it also write \"stopped by the person\" to the teams whose manager handed out what the conversation's last finished turn carried, which wakes that manager; a command left running for its own sake, such as a dev server, tells no manager anything. The command is still left running by the stop, and a conversation in no team is unchanged." + - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop, whether an interface performs it or the member's own session does) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A stop by the person that finds no turn running but a command or watch still running, or a failed command's ending about to start a turn, begins the same hold; that pending wake is withdrawn and its note is read by the next turn. Only when the conversation is waiting on one of them for work a manager handed it does it also write \"stopped by the person\" to that manager's team, which wakes the manager; a command left running for its own sake, such as a dev server, tells no manager anything. The hold covers a background command's ending and a watch's firing and nothing else: a background task landing, the person's own message and the manager's next hand-off still start the conversation, and that turn ends the hold. The command is still left running by the stop, and a conversation in no team is unchanged." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 2713ab68f8..03ec91c380 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -333,10 +333,10 @@ A deliberate message jump opens the activity and tool-call groups that contain t A member of a team that has a manager tells the manager, through the traffic, three things it would never write in a message: -- `finished` when a turn ends, `stopped by the person` when you stopped a turn that had been - handed its manager's work (a directive, or the brief it was started on), `stopped` for every - other stop (its manager's, codeaf ending it, or your stop of a turn that carried only your own - request), and `failed: ` with the error's first line when a turn ends on one; +- `finished` when a turn ends, `stopped by the person` when you stopped a member that was on + its manager's work (a directive, or the brief it was started on), `stopped` for every + other stop (its manager's, codeaf ending it, or your stop when none of the manager's work + was under way), and `failed: ` with the error's first line when a turn ends on one; - when it starts waiting on you: the permission line for a permission prompt (`needs your ok to run bash`), or `asks: ` and the question for anything else; - `no longer waiting` when the last of those questions comes down. @@ -346,10 +346,13 @@ nothing you type is ever written to the traffic. `team_status` reads them too, s on a permission prompt shows as `asking` rather than `running`, for as long as some process holds that conversation's transcript and the wait is under 30 minutes. -When you stop a member's turn that had been handed the manager's work, its manager is woken -and told the work is not done, that you chose to stop it, and not to hand it out again unless -you ask. Stopping a turn that carried only what you typed to the member tells the manager -nothing, and neither does codeaf quitting or a paused member's stray wake being ended. +When you stop a member that is on the manager's work, its manager is woken once and told +the work is not done, that you chose to stop it, and not to hand it out again unless you ask. +The work is under way from the hand-off until a turn finishes with no background command +left that the member waits on. So a turn such a command's ending starts is still on it, and +so is a turn you opened by typing to the member while it waits on one. Stopping a member +with none of the manager's work under way tells the manager nothing, and neither does codeaf +quitting or a paused member's stray wake being ended. ## A stopped member's command is still running — why it did not start again when the command ended @@ -367,9 +370,10 @@ stopped, as for a stopped turn. That is said only for a command the member asked end of, or a watch that has not fired. A command left running for its own sake, such as a dev server, is held the same way and the manager is told nothing: the work before it was finished. -The conversation starts again when somebody means it to: your own message to it, or the -manager's next hand-off. That turn reads the record, which says it arrived after the stop -and is no reason to take the stopped work up again. +Only a background command's ending and a watch firing are held. Whatever else starts a +conversation still does: your own message to it, the manager's next hand-off, a background +task landing. That turn ends the hold and reads the record, which says it arrived after the +stop and is no reason to take the stopped work up again. To end the command itself, use **Stop all** on the conversation's Processes tab. A conversation in no crew is unchanged: there a command's ending still starts its turn. @@ -590,8 +594,8 @@ working, that is straight away. When it is idle, it depends on the kind of messa start (see **Pausing a crew member**). - A **note** wakes nobody. An idle member reads it when it next runs, for whatever reason. - A member's **reply to the manager** (`team_post` to the manager), and a member finishing - without a reply, failing, starting to wait on you, or having a turn that carried the - manager's work stopped by you, start an idle manager's turn. A reply + without a reply, failing, starting to wait on you, or being stopped by you while on the + manager's work, start an idle manager's turn. A reply and the end of the same turn are one wake, even if the ending arrives after the manager already ran. Replies arriving within a few seconds are gathered into one turn. diff --git a/internal/session/agent.go b/internal/session/agent.go index 1f1173ea0e..79bdfcfbb6 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -2648,7 +2648,7 @@ func (a *Agent) interruptNamed(door StopDoor, name string) { a.interrupt.begin() a.mu.Lock() cancel := a.cancel - waiting := a.teamStopHoldLocked(door) + waiting, withdrew := a.teamStopHoldLocked(door) cutPass := a.cutManualPassLocked() a.dropFollowUpsLocked() // AND THE SECOND LOOK AT A YOUNG COMMAND IS RELEASED BEFORE THIS LOCK IS, @@ -2667,7 +2667,7 @@ func (a *Agent) interruptNamed(door StopDoor, name string) { cancel(stopAs(door, name)) } if waiting { - a.teamStopHoldSaid() + a.teamStopHoldSaid(withdrew) } } diff --git a/internal/session/team.go b/internal/session/team.go index 2b6c4537f4..0e7a39fe8b 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -258,10 +258,11 @@ type teamSeat struct { // thread.go). Memory only: a conversation reopened answers nothing until // the manager next speaks to it, which reads as a thread of its own. answering map[string]string - // handed is, per team, when this conversation was first handed work by - // that team's manager (a directive, or the brief it was started on) since - // its last turn ended. A turn's ending takes it ([Agent.teamHandedTake]): - // it is what makes a stop of that turn the stop of handed-out work. + // handed is, per team, when this conversation was first handed the work + // it is on by that team's manager (a directive, or the brief it was + // started on). It lasts as long as the work does, across the turns a + // command it waits on separates ([Agent.teamHandedCarried]), and is what + // makes the person's stop the stop of handed-out work. handed map[string]time.Time // stopHold is the person's stop of this conversation's turn while it sat // in a team, kept until a turn next begins (team_stophold.go). diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 0439094b24..225d25f024 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -209,8 +209,9 @@ func (a *Agent) teamHandedLocked(role teamRole, entry teams.Entry) { } } -// teamHandedTake is the teams that handed this conversation work since its -// last turn ended, with when, taken: the turn now ending is the one that had it. +// teamHandedTake is the teams whose handed-out work this conversation is on, +// with when it was handed, taken: the work ends here, stopped or finished with +// nothing left to wait for ([Agent.teamHandedCarried]). func (a *Agent) teamHandedTake() map[string]time.Time { a.team.mu.Lock() defer a.team.mu.Unlock() @@ -226,10 +227,11 @@ func (a *Agent) teamHandedTake() map[string]time.Time { // // THREE THINGS MUST HOLD, PER TEAM. The cancel came through the person's door; // the app's own stops (quitting, a paused member's stray wake) name another. -// The turn was handed that manager's work, whoever opened it: a directive read -// at a step of a turn the person had started is as undone by their stop as one -// that woke the member, and a turn that carried only the person's own request -// is theirs alone. And no manager's stop is on that team's log since the work +// The conversation was on that manager's work, whoever opened the turn: a +// directive read at a step of a turn the person had started is as undone by +// their stop as one that woke the member, and so is work that waits on a +// command while the person's own turn is stopped. A turn with no handed work +// alive is theirs alone. And no manager's stop is on that team's log since the work // was handed over: an interface holding the member performs the manager's // `team_stop` through the same door as the person's stop key (the app, the // terminal, a remote window), usually before the member's own session reads diff --git a/internal/session/team_stophold.go b/internal/session/team_stophold.go index 4d0e583bbd..dcb0cbf0a8 100644 --- a/internal/session/team_stophold.go +++ b/internal/session/team_stophold.go @@ -16,9 +16,10 @@ package session // start no turn. The stop is the person's own or a manager's team_stop, whoever // performs the latter: an interface, through the person's door (teamevent.go), // or the member's own session, through the manager's ([Agent.interruptTeamTurn]). -// The command itself is left running, as an interrupt always leaves it. What -// starts the conversation again is somebody meaning to: the person's own -// words, or the manager's next hand-off. +// The command itself is left running, as an interrupt always leaves it. Only +// those two lanes are held: the person's own words, the manager's next +// hand-off and a background task landing still start a turn, which ends the +// hold. // // A conversation in no team is untouched: there the ending of a command the // person asked to hear about still starts its turn. @@ -27,17 +28,22 @@ package session // command in the background, asks to be told when it ends, and ends its turn: // measured the same day, a crew's Stop passed over such a member and it // reported the work done when its command ended. So a stop that finds no turn -// but a command or a watch still running begins the hold too. When the member -// is waiting on one of them ([jobRegistry.awaited]), the manager that handed -// out the work the last turn carried is told it was stopped, in the words a -// stopped turn uses. A command left running for its own sake (a dev server) -// is held the same and said to nobody: the work before it was finished. +// but a command or a watch still running begins the hold too, and withdraws +// the wake a failed command's ending had armed ([Agent.deferJobWakeLocked]). +// A command left running for its own sake (a dev server) is held the same. +// +// No handed-out work stalls unsaid. What a manager handed this conversation +// lasts as long as the work does ([Agent.teamHandedCarried]): through a turn +// that finishes while the member waits on a command ([jobRegistry.awaited]) +// and through the turn that command's ending starts. A stop through the +// person's door that begins the hold while such work is alive tells that +// team's manager once, in the words a stopped turn uses, whether the stopped +// turn carried the work, was the person's own, or there was no turn at all. import ( "strings" "sync" "sync/atomic" - "time" "github.com/Agent-Field/codeaf/internal/guard" "github.com/Agent-Field/codeaf/internal/teams" @@ -56,10 +62,8 @@ type teamStopHold struct { held atomic.Bool mu sync.Mutex - // last is what the turn that last finished had been handed, per team, and - // origin is that turn's. It is what a stop that finds no turn running is - // the stop of. A turn beginning forgets it. - last map[string]time.Time + // origin is the turn that last ended with handed work still alive: what a + // stop that finds no turn running is the stop of. origin turnOrigin } @@ -67,57 +71,86 @@ type teamStopHold struct { // manager's and there is something to hold: a turn running, or a command or // watch whose ending would be news. It reports whether it began with no turn // running, which is the stop a manager may have yet to be told of -// ([Agent.teamStopHoldSaid]). The caller holds a.mu. -func (a *Agent) teamStopHoldLocked(door StopDoor) bool { +// ([Agent.teamStopHoldSaid]), and whether it withdrew a wake already armed. +// The caller holds a.mu. +func (a *Agent) teamStopHoldLocked(door StopDoor) (waiting, withdrew bool) { hold := &a.team.stopHold if (door != StopByPerson && door != StopByManager) || !hold.seated.Load() { - return false + return false, false } if a.running { hold.held.Store(true) - return false + return false, false } // The manager's own door ends a running turn and nothing else. - if door != StopByPerson || a.jobs == nil || !a.jobs.newsPending() { - return false + if door != StopByPerson { + return false, false + } + // A command that failed moments ago has its wake on a clock, and that turn + // would end the hold: the clock is withdrawn and its notes stay queued + // for the next turn. + withdrew = a.jobWake != nil + if !withdrew && (a.jobs == nil || !a.jobs.newsPending()) { + return false, false } - return !hold.held.Swap(true) + a.stopJobWakeLocked() + return !hold.held.Swap(true), withdrew } // teamStopHoldOver ends the hold: a turn has begun. -func (a *Agent) teamStopHoldOver() { +func (a *Agent) teamStopHoldOver() { a.team.stopHold.held.Store(false) } + +// teamHandedCarried is a turn's ending that nobody stopped. The work a manager +// handed this conversation ends with it unless the work goes on: the member +// still waits on a command, or that command's ending has already started the +// next turn or is about to. +func (a *Agent) teamHandedCarried(origin turnOrigin) { + a.team.mu.Lock() + none := len(a.team.handed) == 0 + a.team.mu.Unlock() + if none { + return + } + if !a.teamWorkGoesOn() { + a.teamHandedTake() + return + } hold := &a.team.stopHold - hold.held.Store(false) hold.mu.Lock() - hold.last = nil + hold.origin = origin hold.mu.Unlock() } -// teamStopHoldFinished remembers what a turn that finished had been handed. -func (a *Agent) teamStopHoldFinished(handed map[string]time.Time, origin turnOrigin) { - hold := &a.team.stopHold - hold.mu.Lock() - hold.last, hold.origin = handed, origin - hold.mu.Unlock() +// teamWorkGoesOn reports whether a turn that just ended left its work waiting. +// A turn the person's own words opened is not the work going on: the turn that +// ended had nothing left to wait for. +func (a *Agent) teamWorkGoesOn() bool { + if a.jobs != nil && a.jobs.awaited() { + return true + } + a.mu.Lock() + defer a.mu.Unlock() + return a.jobWake != nil || a.running && a.personWords == "" } -// teamStopHoldSaid tells the managers whose work the last turn carried that -// it was stopped while it waited on a command or a watch. A member waiting on -// nothing finished that work, however long ago, and its managers are told +// teamStopHoldSaid tells the managers whose work this conversation is still on +// that it was stopped while it waited on a command or a watch, or on the wake +// the hold withdrew. It ends that work: the stop is reported. A member waiting +// on nothing finished its work, however long ago, and its managers are told // nothing. It reads the jobs and the teams' logs, so it runs away from the // stop's own path and outside a.mu. -func (a *Agent) teamStopHoldSaid() { - if a.jobs == nil || !a.jobs.awaited() { +func (a *Agent) teamStopHoldSaid(withdrew bool) { + if !withdrew && (a.jobs == nil || !a.jobs.awaited()) { return } - hold := &a.team.stopHold - hold.mu.Lock() - handed, origin := hold.last, hold.origin - hold.last = nil - hold.mu.Unlock() + handed := a.teamHandedTake() if len(handed) == 0 { return } + hold := &a.team.stopHold + hold.mu.Lock() + origin := hold.origin + hold.mu.Unlock() guard.Go("team stop of waiting work", func() { by := a.teamStoppedByPerson(StopByPerson, handed) if len(by) == 0 { diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go index 7dadda61e4..595dee764e 100644 --- a/internal/session/team_stophold_test.go +++ b/internal/session/team_stophold_test.go @@ -16,6 +16,189 @@ func okStep() step { return func(context.Context, []ai.Message) (*ai.Response, error) { return textResponse("ok"), nil } } +// waitedStep starts a command the member asked to be told the ending of, and +// answers: the turn ends with its work waiting on that command. +func waitedStep(agent func() *Agent, started chan<- *job) step { + return func(context.Context, []ai.Message) (*ai.Response, error) { + registry := agent().jobs + one, err := registry.newJob("fixture", jobKindBash) + if err == nil { + err = registry.add(one) + } + if err != nil { + return nil, err + } + one.mu.Lock() + one.notify = true + one.mu.Unlock() + started <- one + return textResponse("ok"), nil + } +} + +// waitTeamEvents waits until the fixture's Traffic holds n events saying want. +func waitTeamEvents(t *testing.T, fixture teamFixture, want string, n int) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for len(trafficEvents(t, fixture, want)) < n { + if time.Now().After(deadline) { + t.Fatalf("the team's log holds %d %q events, want %d", len(trafficEvents(t, fixture, want)), want, n) + } + time.Sleep(10 * time.Millisecond) + } +} + +// waitManagerToldOfStop waits until the manager was woken with the line that +// says the person stopped work it had handed @web. +func waitManagerToldOfStop(t *testing.T, managerCalls *scriptedCompleter) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + for i := 0; i < managerCalls.requests(); i++ { + if strings.Contains(userTextIn(managerCalls.request(i)), "@web"+teamStoppedByPersonLine) { + return + } + } + if time.Now().After(deadline) { + t.Fatal("the manager was not told the work it handed out was stopped") + } + time.Sleep(10 * time.Millisecond) + } +} + +// waitingMember is a member whose first turn, on the manager's directive, +// starts a command it waits on; later turns take the steps after. +func waitingMember(t *testing.T, after ...step) (teamFixture, *scriptedCompleter, *Agent, *scriptedCompleter, *jobWakeClock, chan *job) { + t.Helper() + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(8) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + var web *Agent + started := make(chan *job, 2) + calls := &scriptedCompleter{steps: append([]step{waitedStep(func() *Agent { return web }, started)}, after...)} + web = teamAgent(t, fixture, fixture.web, calls, nil) + clock := &jobWakeClock{} + web.jobWakeAfter = clock.after + sendDirective(t, manager, "web") + waitRequests(t, calls, 1) + waitTeamEvents(t, fixture, "finished", 1) + return fixture, managerCalls, web, calls, clock, started +} + +// A STOP OF THE TURN A COMMAND'S ENDING STARTED IS THE STOP OF HANDED WORK. The +// member's first turn on the directive finished waiting on a command; its +// ending woke a second turn, still on the manager's work, and the person +// stopped that. The manager is told once, as for the turn the directive woke. +func TestTeamPersonStopOfATurnACommandEndingStartedTellsTheManager(t *testing.T) { + streaming := make(chan struct{}) + fixture, managerCalls, web, _, clock, started := waitingMember(t, thinkingStep(streaming), okStep()) + web.jobs.settleExit(<-started, 0) + clock.advance(jobWakeDelay) + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the command's ending did not start the member's next turn") + } + web.Interrupt() + waitQuiet(t, web) + waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) + waitManagerToldOfStop(t, managerCalls) + quietFor() + web.settleTeamEvents() + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 1 { + t.Fatalf("the stop was logged %d times, want once", len(said)) + } +} + +// AND SO IS A STOP WHILE IT WAITS ON A SECOND COMMAND. The turn the first +// command's ending started finished waiting on another; the stop then finds no +// turn, tells the manager, and the second command's ending starts nothing. +func TestTeamPersonStopWhileWaitingOnASecondCommandTellsTheManager(t *testing.T) { + var web *Agent + second := make(chan *job, 1) + fixture, managerCalls, member, calls, clock, started := waitingMember(t, waitedStep(func() *Agent { return web }, second), okStep()) + web = member + web.jobs.settleExit(<-started, 0) + clock.advance(jobWakeDelay) + waitRequests(t, calls, 2) + waitTeamEvents(t, fixture, "finished", 2) + + web.Interrupt() + waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) + waitManagerToldOfStop(t, managerCalls) + web.jobs.settleExit(<-second, 0) + clock.advance(jobWakeDelay) + quietFor() + web.settleTeamEvents() + if got := calls.requests(); got != 2 { + t.Fatalf("the stopped member was asked %d times, want its two turns before the stop", got) + } + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 1 { + t.Fatalf("the stop was logged %d times, want once", len(said)) + } +} + +// A STOP OF THE PERSON'S OWN TURN WHILE HANDED WORK WAITS IS SAID TOO. The +// member waits on a command for its manager's work; the person asked it +// something else and stopped the answer. The hold then keeps the command's +// ending from starting a turn, so the manager is told or the work would stall +// with nobody knowing. +func TestTeamPersonStopOfTheirOwnTurnWhileHandedWorkWaitsTellsTheManager(t *testing.T) { + streaming := make(chan struct{}) + fixture, managerCalls, web, calls, clock, started := waitingMember(t, thinkingStep(streaming), okStep()) + events := mustSubmit(t, web, "status?") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the person's turn did not start") + } + web.Interrupt() + collect(t, events) + waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) + waitManagerToldOfStop(t, managerCalls) + + web.jobs.settleExit(<-started, 0) + clock.advance(jobWakeDelay) + quietFor() + web.settleTeamEvents() + if got := calls.requests(); got != 2 { + t.Fatalf("the stopped member was asked %d times, want the directive's turn and the person's", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), teamStopHeldRule) { + t.Fatalf("the command's ending was not kept as a record:\n%s", journal) + } + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 1 { + t.Fatalf("the stop was logged %d times, want once", len(said)) + } +} + +// THE HOLD WITHDRAWS A WAKE ALREADY ON ITS CLOCK. A command the member waited +// on ended moments before the stop, and its turn was seconds from starting: +// the stop keeps that turn from starting, tells the manager, and the ending is +// read by the turn somebody next means. +func TestTeamPersonStopWithdrawsACommandEndingAboutToStartATurn(t *testing.T) { + fixture, managerCalls, web, calls, clock, started := waitingMember(t, okStep(), okStep()) + web.jobs.settleExit(<-started, 7) + web.Interrupt() + clock.advance(jobWakeDelay) + waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) + waitManagerToldOfStop(t, managerCalls) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times, want only its first turn", got) + } + events := mustSubmit(t, web, "what happened?") + collect(t, events) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, "job 1 exited 7") { + t.Fatalf("the person's next turn did not read the ending the stop held back:\n%s", asked) + } +} + // A STOP OF A MEMBER HOLDS. A command the stopped turn left running // ends later, and its ending is a record that starts no turn: not the lane a // failure takes, not the one a command the work waited on takes, not a watch's @@ -93,30 +276,12 @@ func TestPersonStopOutsideATeamStillHearsACommandEnd(t *testing.T) { // the person's stop then is the stop of that work. Its manager is told so in // the words a stopped turn uses, and the command's ending starts no turn. func TestTeamPersonStopOfAMemberWaitingOnACommandHolds(t *testing.T) { - fastTeamWake(t) - fixture := newWakingTeamFixture(t) - managerCalls := oneAnswer(8) - manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) - calls := oneAnswer(4) - web := teamAgent(t, fixture, fixture.web, calls, nil) - sendDirective(t, manager, "web") - waitRequests(t, calls, 1) - waitQuiet(t, web) - web.settleTeamEvents() - one := settlementJob(t, web.jobs) - one.mu.Lock() - one.notify = true - one.mu.Unlock() + fixture, managerCalls, web, calls, clock, started := waitingMember(t, okStep()) web.Interrupt() - deadline := time.Now().Add(5 * time.Second) - for len(trafficEvents(t, fixture, teams.StoppedByPerson)) == 0 { - if time.Now().After(deadline) { - t.Fatal("the manager's log was not told the person stopped the member's waiting work") - } - time.Sleep(10 * time.Millisecond) - } - web.jobs.settleExit(one, 0) + waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) + web.jobs.settleExit(<-started, 0) + clock.advance(jobWakeDelay) web.enqueueJobNote("job 8 exited 0") quietFor() if got := calls.requests(); got != 1 { @@ -125,13 +290,7 @@ func TestTeamPersonStopOfAMemberWaitingOnACommandHolds(t *testing.T) { if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 1 { t.Fatalf("the stop was logged %d times, want once", len(said)) } - told := false - for i := 0; i < managerCalls.requests(); i++ { - told = told || strings.Contains(userTextIn(managerCalls.request(i)), "@web"+teamStoppedByPersonLine) - } - if !told { - t.Fatal("the manager was not told the work it handed out was stopped") - } + waitManagerToldOfStop(t, managerCalls) } // A COMMAND NOBODY WAITS ON IS HELD AND SAID TO NOBODY. The member finished its diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index 4fd13b6bf3..22d5522191 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -233,16 +233,21 @@ func (a *Agent) teamTurnEnded(ctx context.Context, hub *eventHub) { a.dropOwedResume() origin := turnOriginFrom(ctx) if err := hub.turnError(); err != nil { - a.teamHandedTake() + a.teamHandedCarried(origin) a.teamEventOwed(origin, teams.StateFailed, "failed: "+firstLineTeam(err.Error())) return } - handed := a.teamHandedTake() - if door, stopped := stopCause(ctx); stopped { - a.teamEventOwedFor(origin, teams.StateIdle, "stopped", a.teamStoppedByPerson(door, handed)) + door, stopped := stopCause(ctx) + if stopped && (door == StopByPerson || door == StopByManager) { + // The handed work ends here: its manager is told, or stopped it itself. + a.teamEventOwedFor(origin, teams.StateIdle, "stopped", a.teamStoppedByPerson(door, a.teamHandedTake())) + return + } + a.teamHandedCarried(origin) + if stopped { + a.teamEventOwed(origin, teams.StateIdle, "stopped") return } - a.teamStopHoldFinished(handed, origin) a.teamEventOwed(origin, teams.StateFinished, "finished") } From 9b88b572963584f8894572c620e63d80ffd84adb Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:09:44 -0500 Subject: [PATCH 18/37] teams: final review round 3 repair The time a hand-off is remembered at is now the latest hand-off's. Kept at the first one while work carried across turns, it let a manager's stop that had found the member idle pass for the stop of a turn a later directive started, and the person's stop of that turn told nobody. Co-Authored-By: Claude Fable 5.2 --- internal/session/team_pause.go | 10 ++++++--- internal/session/team_stophold_test.go | 31 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 225d25f024..4780b3f10a 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -204,9 +204,13 @@ func (a *Agent) teamHandedLocked(role teamRole, entry teams.Entry) { if a.team.handed == nil { a.team.handed = map[string]time.Time{} } - if _, already := a.team.handed[role.id]; !already { - a.team.handed[role.id] = time.Now() - } + // THE TIME IS THE LATEST HAND-OFF'S. A manager's stop on the log since + // this time is read as the stop of the turn being stopped + // ([Agent.teamStoppedByPerson]). Kept at the first hand-off while work + // carried from turn to turn, it let a manager's stop that had found the + // member idle, and so stopped nothing, pass for the stop of a turn a later + // directive started, and the person's stop of that turn told nobody. + a.team.handed[role.id] = time.Now() } // teamHandedTake is the teams whose handed-out work this conversation is on, diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go index 595dee764e..8a8a746e96 100644 --- a/internal/session/team_stophold_test.go +++ b/internal/session/team_stophold_test.go @@ -392,3 +392,34 @@ func TestTeamPersonStopOfAnIdleMemberHoldsNothing(t *testing.T) { t.Fatalf("a stop of a member with nothing running was logged as work stopped: %+v", said) } } + +// A MANAGER'S STOP THAT FOUND THE MEMBER IDLE DOES NOT PASS FOR A LATER ONE. +// The member waits on a command for the first directive; the manager's stop +// finds no turn and stops nothing, but its line stays on the log. A second +// directive starts the member and the person stops that turn: the stop is the +// person's, and the manager is told. +func TestTeamAManagersEarlierStopDoesNotHideThePersonsStop(t *testing.T) { + streaming := make(chan struct{}) + fixture, managerCalls, web, calls, _, _ := waitingMember(t, thinkingStep(streaming), okStep()) + said := func(entry teams.Entry) { + t.Helper() + if err := teams.AppendTraffic(fixture.profile, fixture.teamID, entry); err != nil { + t.Fatal(err) + } + } + said(teams.Entry{Kind: teams.KindStop, From: teams.FromManager, To: "web", Member: convKeyOf(t, fixture.web), Text: "hold on"}) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("a manager's stop of an idle member started %d more turns", got-1) + } + said(teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the footer."}) + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the second directive") + } + web.Interrupt() + waitQuiet(t, web) + waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) + waitManagerToldOfStop(t, managerCalls) +} From 57fac548c033353099392275e427cf3416c03e92 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:11:23 -0500 Subject: [PATCH 19/37] teams: final review round 3 repairs for the quiet global manager No member's turn finishing or being stopped in the team that holds every team wakes or opens the global manager: it can see and direct only the current top-level managers, so a member left seated there after losing its team woke it on every answer for nothing. A team it starts is told to answer the brief it was started on with team_post, as a directive. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2906-global-manager-quiet.md | 9 +- internal/manual/chat/team-manager.md | 29 +-- internal/session/team.go | 34 +-- internal/session/team_nest.go | 8 +- internal/session/team_nest_test.go | 199 ++++++++++++++---- internal/session/team_sendoutcome.go | 10 +- internal/session/team_wakewatch.go | 66 +++--- internal/session/teamevent.go | 2 +- 8 files changed, 237 insertions(+), 120 deletions(-) diff --git a/docs/changes/unreleased/2906-global-manager-quiet.md b/docs/changes/unreleased/2906-global-manager-quiet.md index d5fe02a871..6c90bf417f 100644 --- a/docs/changes/unreleased/2906-global-manager-quiet.md +++ b/docs/changes/unreleased/2906-global-manager-quiet.md @@ -4,10 +4,11 @@ title: The global manager is not woken each time a top-level team's manager ends pr: 2906 surface: [engine, chat] invalidates: - - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team the finished event of a member that manages a top-level team (teams.File.TopManagers, teamRole.quietEnding) no longer starts the global manager's turn either (teamEventWakesManagerOf): of that manager's events only failed and asking do, and its team_post, a decision packet it raises and a conflict it declares wake the global manager as before. A global manager nobody has open is likewise no longer opened by such a finished event. A member of that team that manages nothing, and every other team, are unchanged, so a stopped-by-the-person event from such a member wakes the global manager where the earlier rule kept every idle event in that team from doing so." - - "team_send answered every manager \"Replies and endings wake you when they arrive, so there is no need to wait or poll.\" In the team that holds every team it now answers \"Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn ending alone does not wake you, and team_status says where it stands.\" The answer in every other team is as it was." - - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\" and ends \"A top-level team's manager ending its turn does not start yours.\", and its scope adds \"A manager answers a directive of yours with team_post, since its turn ending tells you nothing; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the note every turn of the global manager carries." - - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending tells it nothing: answer each of its directives with team_post to the manager. Apart from those answers, post only what it should act on or tell the person.\" The rest of that note is as it was. Every member of that team was given that note, \"because you manage a top-level team\" included; a member there that manages nothing is now given the note a member of any team is given." + - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team no member's finished event starts the global manager's turn any longer (teamEventWakesManagerOf): of a member's events there only failed and asking do, and a team_post to the manager, a decision packet a member raises and a conflict it declares wake the global manager as before. A global manager nobody has open is likewise no longer opened by a finished event there. The rule is that whole team's: it covers a top-level team's manager, a manager that was replaced or whose team closed and kept its seat there, and a conversation the person put there, since the global manager lists and directs only the current top-level managers (managedView). Every other team is unchanged." + - "team_send answered every manager \"Replies and endings wake you when they arrive, so there is no need to wait or poll.\" In the team that holds every team it now answers \"Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn finishing or being stopped does not wake you, and team_status says where it stands.\" The answer in every other team is as it was." + - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\" and ends \"A member's turn finishing or being stopped does not start yours.\", and its scope adds \"A manager answers a directive of yours, and the brief you started it on, with team_post, since its turn finishing does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the global manager's role note, which it is handed when that note's text changes." + - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending tells it nothing: answer each of its directives, and the brief it started you on if it started you, with team_post to the manager. Apart from those answers, post only what it should act on or tell the person.\" The rest of that note is as it was. Every member of that team was given that note, \"because you manage a top-level team\" included; a member there that manages no top-level team now is given the note a member of any team is given." + - "The first turn of a team's new manager, on the brief team_start of kind team started it with, woke the manager that started it when it finished, and team_start answered every manager that the new conversation \"makes itself the manager of\" the team \"and reports to you.\" A team the global manager starts no longer wakes it that way, and team_start answers the global manager that the new manager \"reports to you with team_post: its turn finishing on your brief does not start yours, and team_status says where it stands.\" The answer to every other manager is as it was." --- The global manager's members are the managers of whole teams, each a conversation diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 076641a83e..97ad954d9c 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -353,7 +353,7 @@ left that the member waits on. So a turn such a command's ending starts is still so is a turn you opened by typing to the member while it waits on one. Stopping a member with none of the manager's work under way tells the manager nothing, and neither does codeaf quitting or a paused member's stray wake being ended. The global -manager is not woken by a top-level team's manager being stopped (see **The global manager**). +manager is not woken by a member of `All teams` being stopped (see **The global manager**). ## A stopped member's command is still running — why it did not start again when the command ended @@ -540,18 +540,19 @@ report to it, so their questions and conflicts between teams come to it before t you. It can start a new top-level team with `team_start` of kind `team`. Without a global manager, nothing here changes: each top-level manager reports to you. -A top-level manager's turn ending does not start the global manager's turn. You talk to -those managers directly and each answer ends a turn, so the endings stay in `All teams`' -traffic, where `team_status` reads them. The global manager is woken by what a manager posts -to it with `team_post`, by a manager's question or a permission it is held on, and by a -manager's turn failing. So a directive the global manager sent is answered with `team_post`: -each manager is told to answer its directives that way, and apart from those answers to post -only what the global manager should act on or tell you. A manager that ends its turn on a -directive without posting has told the global manager nothing, and `team_status` is where it -finds out. The global manager is told never to send a manager your own request to that manager -back as a directive. A member of `All teams` that manages no team is an ordinary member -there: it is told what a member of any team is told, and its turn ending wakes the global -manager as in any team. +No turn in `All teams` that finishes or is stopped starts the global manager's turn. You talk +to the top-level managers directly and each answer ends a turn, so the endings stay in +`All teams`' traffic, where `team_status` reads them. The global manager is woken by what a +member posts to it with `team_post`, by a member's question or a permission it is held on, and +by a member's turn failing. So a directive the global manager sent, and the brief it started +a team on, are answered with `team_post`: each top-level manager is told so, and apart from +those answers to post only what the global manager should act on or tell you. A manager that +finishes a turn without posting has told it nothing, the first turn of a team it started +included: `team_start` says so, and `team_status` is where it finds out. The global manager +is told never to send a manager your own request to that manager back as a directive. +`All teams` can also hold a conversation that manages no team now, such as a manager you +replaced. The global manager neither lists nor directs it, its turn ending is as quiet, and +it is told what a member of any team is told. ## Conflicts between members and teams @@ -612,7 +613,7 @@ working, that is straight away. When it is idle, it depends on the kind of messa manager's work, start an idle manager's turn. A reply and the end of the same turn are one wake, even if the ending arrives after the manager already ran. Replies arriving within a few seconds are gathered into one turn. The global - manager is the exception: a top-level team's manager finishing or being stopped does not + manager is the exception: a member of `All teams` finishing or being stopped does not start its turn (see **The global manager**). A member no window has open is opened by codeaf in the background so it can run, and a window diff --git a/internal/session/team.go b/internal/session/team.go index 8b6e9f1c46..38b620999c 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -124,12 +124,12 @@ type teamRole struct { // manager is the global manager, and its other members are the top-level // teams' managers. root bool - // tops is, for the root, the keys of the members that manage a top-level - // team now ([teams.File.TopManagers]). The root can hold others, a manager - // that stopped being one or a conversation the person put there, and the - // rule that keeps a manager's turn ending from waking the global manager is - // about these members alone ([teamRole.quietEnding]). - tops map[string]bool + // top says this seat in the root is a top-level team's manager's now + // ([teams.File.TopManagers]). The root can hold others, a manager that + // stopped being one or a conversation the person put there, and only a + // manager is told it sits there because it manages a team + // ([teamMemberRole]). + top bool // dissolvable says this conversation manages the team and the team has // never held anyone but it ([teams.File.Dissolvable]), which is when its // manager is given team_dissolve (team_dissolve.go). @@ -461,7 +461,7 @@ func rolesFor(file *teams.File, keys []string, d teams.Defaults) []teamRole { boss: boss, bossName: bossName, root: team.Root, - tops: topManagerKeys(file, team), + top: team.Root && topManager(file, member.Key), key: member.Key, wakes: effective.Wake, questionsUp: effective.QuestionsUp, @@ -1736,7 +1736,7 @@ func teamManagerScope(role teamRole, file *teams.File) string { if role.root { parts = append(parts, fmt.Sprintf("You are the global manager: %q holds every team, and your members are the managers of the top-level teams, never their members. "+ "Direct those managers and they pass it on. Their questions and conflicts between teams come to you before the person. team_start with kind team starts a new top-level team. "+ - "A manager answers a directive of yours with team_post, since its turn ending tells you nothing; team_status says where each of them stands. "+ + "A manager answers a directive of yours, and the brief you started it on, with team_post, since its turn finishing does not start yours; team_status says where each of them stands. "+ "The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.", role.name)) } else if home, ok := file.Home(role.key); ok && home.Team != role.id { boss := "its manager" @@ -1776,12 +1776,11 @@ func teamManagerDelivery(role teamRole) string { if !role.wakes { return "This team's auto-wake is off: what you send, and your members' replies, wait for each conversation's next turn, so an idle member does not start on a directive until it next runs." } - // The global manager's turn is not started by a top-level manager's turn - // ending ([teamEventWakesManagerOf]). The root can hold ordinary members - // too, so the sentence names whose ending it is. + // The global manager's turn is not started by a turn ending in the root, + // finished or stopped ([teamEventWakesManagerOf]). back, except := "Members' replies to you, and their finishing, failing or asking,", "" if role.root { - back, except = "Members' replies to you, and their failing or asking,", " A top-level team's manager ending its turn does not start yours." + back, except = "Members' replies to you, and their failing or asking,", " A member's turn finishing or being stopped does not start yours." } return "A directive (team_send kind directive) starts an idle member's turn; a note waits for its next turn. team_send's answer says whether each member started: one the person paused does not start until they resume it, and work is under way only where the answer says so. " + back + " come back to you and start your turn when you are idle, so do not wait or poll for them." + except } @@ -1836,13 +1835,14 @@ func teamMemberRole(role teamRole) string { if role.handle != "" { you = "@" + role.handle } - // Only a top-level team's manager is told its ending is silent: anybody - // else the root holds is an ordinary member there, whose ending wakes the - // global manager ([teamRole.quietEnding]), and reads the text below. - if role.quietEnding(role.key) { + // Only a top-level team's manager is told why it sits in the root and how + // to answer the global manager. Nobody's ending there wakes that manager + // ([teamEventWakesManagerOf]), but it directs only these, so anybody else + // the root holds reads the member's text below, which promises no wake. + if role.top { return fmt.Sprintf("You are %s in %q because you manage a top-level team: you report to its manager, the global manager. Its directives reach you marked \"◆ from manager\", "+ "your questions go to it before the person, and you report to it with team_post to the manager. "+ - "Your turn ending tells it nothing: answer each of its directives with team_post to the manager. "+ + "Your turn ending tells it nothing: answer each of its directives, and the brief it started you on if it started you, with team_post to the manager. "+ "Apart from those answers, post only what it should act on or tell the person.", you, role.name) } if role.boss != "" && role.boss != role.id && !role.shared { diff --git a/internal/session/team_nest.go b/internal/session/team_nest.go index 28c4cbecd3..867ba660a7 100644 --- a/internal/session/team_nest.go +++ b/internal/session/team_nest.go @@ -265,8 +265,14 @@ func (a *Agent) teamStartSubTeam(ctx context.Context, team teams.Team, role team case pool != "": money = fmt.Sprintf("It has no cap of its own and spends from %q's pool.", pool) } + reports := "reports to you" + if team.Root { + // The new manager's ending does not wake the global manager, its first + // turn on the brief included ([teamEventWakesManagerOf]). + reports = "reports to you with team_post: its turn finishing on your brief does not start yours, and team_status says where it stands" + } said := fmt.Sprintf("Made the team %q under %q and asked for its manager @%s (%s). The conversations view opens @%s in %q's folder as a member of %q; it is handed your brief marked as yours, "+ - "makes itself the manager of %q, and reports to you. %s", name, team.Name, handle, teams.ThreadNumber(startID), handle, team.Name, team.Name, name, money) + "makes itself the manager of %q, and %s. %s", name, team.Name, handle, teams.ThreadNumber(startID), handle, team.Name, team.Name, name, reports, money) if len(moved) > 0 { said += " Moved in: " + strings.Join(moved, ", ") + "; they are its manager's to direct now, not yours." } diff --git a/internal/session/team_nest_test.go b/internal/session/team_nest_test.go index 82e99d312b..2bf1e7e74d 100644 --- a/internal/session/team_nest_test.go +++ b/internal/session/team_nest_test.go @@ -551,7 +551,7 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { boss := teamAgent(t, n.fixture, n.paths["boss"], bossCalls, nil) submitAndWait(t, boss, "plan the release") - if role := strings.Join(roleNotes(bossCalls.request(0)), "\n"); !strings.Contains(role, "Your turn ending tells it nothing: answer each of its directives with team_post to the manager.") { + if role := strings.Join(roleNotes(bossCalls.request(0)), "\n"); !strings.Contains(role, "Your turn ending tells it nothing: answer each of its directives, and the brief it started you on if it started you, with team_post to the manager.") { t.Fatalf("the top-level manager is not told to answer the global manager's directive with a post:\n%s", role) } boss.settleTeamEvents() @@ -574,7 +574,7 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { } waitRequests(t, gmCalls, 1) asked := userTextIn(gmCalls.request(0)) - for _, want := range []string{"from @boss: harbor shipped", "A manager answers a directive of yours with team_post", "and their failing or asking, come back to you", "A top-level team's manager ending its turn does not start yours."} { + for _, want := range []string{"from @boss: harbor shipped", "A manager answers a directive of yours, and the brief you started it on, with team_post", "and their failing or asking, come back to you", "A member's turn finishing or being stopped does not start yours."} { if !strings.Contains(asked, want) { t.Fatalf("the global manager's turn lacks %q:\n%s", want, asked) } @@ -587,20 +587,21 @@ func TestTheGlobalManagerIsNotWokenByATopLevelManagersTurnEnding(t *testing.T) { } // Its own send's answer does not promise that an ending wakes it, and says // what answers the directive. - if said := sendDirective(t, gm, "boss"); strings.Contains(said, "endings wake you") || !strings.Contains(said, "A top-level team's manager answers a directive with team_post: its turn ending alone does not wake you") { + if said := sendDirective(t, gm, "boss"); strings.Contains(said, "endings wake you") || !strings.Contains(said, "A top-level team's manager answers a directive with team_post: its turn finishing or being stopped does not wake you") { t.Fatalf("the global manager's send says endings wake it: %s", said) } } -// A GLOBAL MANAGER NOBODY HAS OPEN IS NOT OPENED BY THE ENDING EITHER, and is -// still opened by a top-level manager's failure. A member of the team that -// holds every team that manages nothing is an ordinary member there: its -// ending opens the manager as it does in any team, and its role says nothing -// about managing a team or an ending nobody hears. -func TestAClosedGlobalManagerIsNotOpenedByATopLevelManagersTurnEnding(t *testing.T) { +// A GLOBAL MANAGER NOBODY HAS OPEN IS NOT OPENED BY AN ENDING IN ITS TEAM +// EITHER, whoever's it is: a top-level manager's, a member's that manages +// nothing, or a manager's that was replaced and kept its seat. It sees and +// directs only the managers of the top-level teams, so none of those endings +// is one it can act on. A failure still opens it. Only a top-level manager is +// told it sits there because it manages a team. +func TestAClosedGlobalManagerIsNotOpenedByATurnEndingInItsTeam(t *testing.T) { fastTeamWake(t) n := newTeamTree(t, "gm", "boss", "web", "guest") - n.team(t, "harbor", "", "boss", n.member(t, "boss", "boss"), n.member(t, "web", "web")) + harbor := n.team(t, "harbor", "", "boss", n.member(t, "boss", "boss"), n.member(t, "web", "web")) root := "" if err := teams.Update(n.fixture.profile, func(f *teams.File) error { root = f.MakeRoot(f.Teams[0].Made) @@ -613,6 +614,7 @@ func TestAClosedGlobalManagerIsNotOpenedByATopLevelManagersTurnEnding(t *testing }); err != nil { t.Fatal(err) } + since := time.Now() recorder := &recordedResume{} withTeamResume(t, recorder.open) opened := func() int { @@ -624,58 +626,169 @@ func TestAClosedGlobalManagerIsNotOpenedByATopLevelManagersTurnEnding(t *testing } return count } - waitOpened := func(want int) bool { - deadline := time.Now().Add(5 * time.Second) - for opened() < want && time.Now().Before(deadline) { - time.Sleep(10 * time.Millisecond) + // due is the desktop app's question of a conversation it has not opened. + due := func() bool { + return TeamOpenPending(n.fixture.profile, n.paths["gm"], n.file(t), teams.DefaultsAt(n.fixture.profile), since) + } + all := teamFixture{profile: n.fixture.profile, teamID: root} + // quiet runs one turn of agent's and says what, if anything, opened the + // closed global manager on its ending. + endings := 0 + quiet := func(who string, agent *Agent) { + t.Helper() + submitAndWait(t, agent, "tidy the notes") + agent.settleTeamEvents() + endings++ + if ended := trafficEvents(t, all, "finished"); len(ended) != endings { + t.Fatalf("%s ended its turn and the team that holds every team has %d finished events, want %d", who, len(ended), endings) + } + time.Sleep(teamWakeDelay() + 15*teamWatchInterval()) + if got := opened(); got != 0 { + t.Fatalf("a closed global manager was opened %d times by the turn ending of %s", got, who) + } + if due() { + t.Fatalf("the turn ending of %s leaves the closed global manager due an opening", who) } - return opened() >= want } - bossCalls := oneAnswer(1) + bossCalls := oneAnswer(2) bossCalls.steps = append(bossCalls.steps, func(context.Context, []ai.Message) (*ai.Response, error) { return nil, errors.New("insufficient_quota: out of budget") }) boss := teamAgent(t, n.fixture, n.paths["boss"], bossCalls, nil) - submitAndWait(t, boss, "plan the release") - boss.settleTeamEvents() - time.Sleep(teamWakeDelay() + 15*teamWatchInterval()) - if got := opened(); got != 0 { - t.Fatalf("a closed global manager was opened %d times by a top-level manager's turn ending", got) + quiet("a top-level manager", boss) + + guestCalls := oneAnswer(1) + guest := teamAgent(t, n.fixture, n.paths["guest"], guestCalls, nil) + quiet("a member that manages nothing", guest) + ordinary := func(who, role string) { + t.Helper() + if !strings.Contains(role, `in the team "All teams", which has a manager.`) { + t.Fatalf("%s is not told it is a member of the team that holds every team:\n%s", who, role) + } + for _, not := range []string{"you manage a top-level team", "Your turn ending tells it nothing"} { + if strings.Contains(role, not) { + t.Fatalf("%s is told %q, which is said to a top-level team's manager only:\n%s", who, not, role) + } + } } + ordinary("a member that manages nothing", strings.Join(roleNotes(guestCalls.request(0)), "\n")) + // The team's manager is replaced. The old one keeps its seat in the team + // that holds every team, where the global manager no longer sees it. + if err := teams.Update(n.fixture.profile, func(f *teams.File) error { + return f.SetManager(harbor, n.key(t, "web")) + }); err != nil { + t.Fatal(err) + } + f := n.file(t) + if r, _ := f.Team(root); !r.Holds(n.key(t, "boss")) { + t.Fatal("the replaced manager lost its seat in the team that holds every team") + } + if tops := f.TopManagers(); len(tops) != 1 || tops[0].Key != n.key(t, "web") { + t.Fatalf("the top-level managers after the replacement: %+v", tops) + } + quiet("a replaced top-level manager", boss) + former := roleNotes(bossCalls.request(1)) + if len(former) == 0 { + t.Fatal("the replaced manager's next turn carries no new role") + } + ordinary("a replaced top-level manager", former[len(former)-1]) + + // A failure there still opens it, a member's it does not direct included. submitAndWait(t, boss, "ship it") boss.settleTeamEvents() - all := teamFixture{profile: n.fixture.profile, teamID: root} if failed := trafficEvents(t, all, "failed: "); len(failed) != 1 || failed[0].State != teams.StateFailed { - t.Fatalf("the top-level manager's failed turn is not one failed event in the team that holds every team: %+v", failed) + t.Fatalf("the failed turn is not one failed event in the team that holds every team: %+v", failed) + } + deadline := time.Now().Add(5 * time.Second) + for opened() == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) } - if !waitOpened(1) { - t.Fatal("a top-level manager's turn failed and the closed global manager was not opened") + if opened() == 0 { + t.Fatal("a turn failed in the team that holds every team and its closed manager was not opened") } + if !due() { + t.Fatal("a failed turn does not leave the closed global manager due an opening") + } +} - before := opened() - guestCalls := oneAnswer(2) - guest := teamAgent(t, n.fixture, n.paths["guest"], guestCalls, nil) - submitAndWait(t, guest, "tidy the notes") - guest.settleTeamEvents() - if !waitOpened(before + 1) { - t.Fatal("a member of the team that holds every team that manages nothing ended its turn and its manager was not opened") - } - role := strings.Join(roleNotes(guestCalls.request(0)), "\n") - if !strings.Contains(role, `in the team "All teams", which has a manager.`) { - t.Fatalf("a member of the team that holds every team that manages nothing is not told it is a member there:\n%s", role) - } - for _, not := range []string{"you manage a top-level team", "Your turn ending tells it nothing"} { - if strings.Contains(role, not) { - t.Fatalf("a member that manages nothing is told %q, which is true of a top-level team's manager only:\n%s", not, role) +// A TEAM THE GLOBAL MANAGER STARTS REPORTS ITS FIRST TURN WITH A POST. The new +// manager's turn on the brief ends like any other there and wakes nobody, so +// team_start's answer and both roles name the brief beside the directives. +func TestATeamTheGlobalManagerStartsAnswersItsBriefWithAPost(t *testing.T) { + fastTeamWake(t) + n := newTeamTree(t, "gm", "boss", "ops") + n.team(t, "harbor", "", "boss", n.member(t, "boss", "boss")) + root := "" + if err := teams.Update(n.fixture.profile, func(f *teams.File) error { + root = f.MakeRoot(f.Teams[0].Made) + if err := f.AddMember(root, n.member(t, "gm", "all")); err != nil { + return err } + return f.SetManager(root, n.key(t, "gm")) + }); err != nil { + t.Fatal(err) + } + gmCalls := oneAnswer(2) + gm := teamAgent(t, n.fixture, n.paths["gm"], gmCalls, nil) + gm.teamBoundary() + said, failed := callTool(t, gm.teamStartTool, `{"handle":"ops","brief":"Run the ops.","kind":"team","name":"ops"}`) + if failed { + t.Fatalf("the global manager could not start a top-level team: %q", said) + } + if want := `makes itself the manager of "ops", and reports to you with team_post: its turn finishing on your brief does not start yours, and team_status says where it stands.`; !strings.Contains(said, want) { + t.Fatalf("team_start's answer for a top-level team lacks %q:\n%s", want, said) + } + gm.mu.Lock() + role := gm.teamRoleText + gm.mu.Unlock() + if want := "A manager answers a directive of yours, and the brief you started it on, with team_post, since its turn finishing does not start yours"; !strings.Contains(role, want) { + t.Fatalf("the global manager's role lacks %q:\n%s", want, role) + } + + // The interface carries out the start, and the new manager runs its first + // turn on the brief without posting. + if err := teams.Update(n.fixture.profile, func(f *teams.File) error { + m := n.member(t, "ops", "ops") + m.Started = true + return f.AddMember(root, m) + }); err != nil { + t.Fatal(err) + } + opsCalls := oneAnswer(1) + ops := teamAgent(t, n.fixture, n.paths["ops"], opsCalls, nil) + submitAndWait(t, ops, "go") + first := opsCalls.request(0) + if asked := userTextIn(first); !strings.Contains(asked, "◆ brief from manager") || !strings.Contains(asked, "Run the ops.") { + t.Fatalf("the new manager's first turn lacks its brief:\n%s", asked) + } + if role := strings.Join(roleNotes(first), "\n"); !strings.Contains(role, "because you manage a top-level team") || + !strings.Contains(role, "answer each of its directives, and the brief it started you on if it started you, with team_post to the manager.") { + t.Fatalf("the new manager is not told to answer its brief with a post:\n%s", role) + } + ops.settleTeamEvents() + time.Sleep(teamWakeDelay() + 15*teamWatchInterval()) + all := teamFixture{profile: n.fixture.profile, teamID: root} + if ended := trafficEvents(t, all, "finished"); len(ended) != 1 { + t.Fatalf("the new manager's first turn was logged %d times in the team that holds every team, want once", len(ended)) + } + if got := gmCalls.requests(); got != 0 { + t.Fatalf("the global manager was woken %d times by the new manager's first turn ending", got) + } + + if said, failed := callTool(t, ops.teamPostTool, `{"to":"manager","text":"ops is set up"}`); failed { + t.Fatalf("the new manager's report was refused: %q", said) + } + waitRequests(t, gmCalls, 1) + if asked := userTextIn(gmCalls.request(0)); !strings.Contains(asked, "from @ops: ops is set up") { + t.Fatalf("the global manager's turn lacks the new manager's report:\n%s", asked) } } func TestTeamEventWakesTheGlobalManager(t *testing.T) { for _, c := range []struct { state, text string - top, want bool + root, want bool }{ {teams.StateFinished, "finished", false, true}, {teams.StateFinished, "finished", true, false}, @@ -685,8 +798,8 @@ func TestTeamEventWakesTheGlobalManager(t *testing.T) { {teams.StateAsking, "asks: which branch?", true, true}, {teams.StateRunning, "no longer waiting", true, false}, } { - if got := teamEventWakesManagerOf(c.top, c.state, c.text); got != c.want { - t.Errorf("top-level manager %v, %s %q wakes the manager: %v, want %v", c.top, c.state, c.text, got, c.want) + if got := teamEventWakesManagerOf(c.root, c.state, c.text); got != c.want { + t.Errorf("in the team that holds every team %v, %s %q wakes the manager: %v, want %v", c.root, c.state, c.text, got, c.want) } } } diff --git a/internal/session/team_sendoutcome.go b/internal/session/team_sendoutcome.go index c2c4d7db3c..23f1cadd60 100644 --- a/internal/session/team_sendoutcome.go +++ b/internal/session/team_sendoutcome.go @@ -205,13 +205,13 @@ func itThey(n int) string { } // teamSendWakesSentence is what a send's answer says comes back on its own. -// The global manager is not woken by a top-level manager's turn ending -// ([teamEventWakesManagerOf]), so its answer does not promise that, and says -// what closes a directive instead. The root can hold ordinary members too, so -// the sentence names whose ending it is. +// The global manager is not woken by a turn ending in the root, finished or +// stopped ([teamEventWakesManagerOf]), so its answer does not promise that, +// and says what closes a directive instead. Its sends reach top-level +// managers only ([managedView]), which is who the sentence names. func teamSendWakesSentence(root bool) string { if root { - return "Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn ending alone does not wake you, and team_status says where it stands." + return "Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn finishing or being stopped does not wake you, and team_status says where it stands." } return "Replies and endings wake you when they arrive, so there is no need to wait or poll." } diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 1996caa2be..3ef7dc983a 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -455,47 +455,43 @@ func teamEventWakesManager(state, text string) bool { return false } -// teamEventWakesManagerOf is [teamEventWakesManager] for one member's event, -// top when that member is a top-level team's manager seated in the team that -// holds every team ([teamRole.quietEnding]). +// teamEventWakesManagerOf is [teamEventWakesManager] for an event in one team, +// root when that is the team that holds every team. // -// The global manager is not woken by a top-level manager's turn ending, -// finished or stopped. Its members are the managers of whole teams, each a -// conversation the person talks to, and every answer one of them gave the -// person ended a turn. Measured 2026-11-24 in the desktop app: one afternoon -// of the person talking to two crew managers woke the global manager 22 times, -// 803,496 input tokens, and it answered "[no change]" to all 22; the day -// before, one such wake had it read a manager's conversation and send the -// person's own request back to that manager as a directive. What a top-level -// manager wants the global manager to act on it posts (a note wakes), and what -// needs somebody still wakes: a failure, and a question or a permission it is -// held on. The ending itself stays in the team's traffic, where team_status -// reads it. -func teamEventWakesManagerOf(top bool, state, text string) bool { - if top { +// The global manager is not woken by a turn ending in the root, finished or +// stopped. Its members are the managers of whole teams, each a conversation +// the person talks to, and every answer one of them gave the person ended a +// turn. Measured 2026-11-24 in the desktop app: one afternoon of the person +// talking to two crew managers woke the global manager 22 times, 803,496 input +// tokens, and it answered "[no change]" to all 22; the day before, one such +// wake had it read a manager's conversation and send the person's own request +// back to that manager as a directive. What a top-level manager wants the +// global manager to act on it posts (a note wakes), and what needs somebody +// still wakes: a failure, and a question or a permission it is held on. The +// ending itself stays in the team's traffic, where team_status reads it. +// +// The rule is the whole root's, not the top-level managers' alone. A seat in +// the root is never taken back, so it also holds a manager that was replaced +// or whose team closed, and whoever the person put there; the global manager +// neither sees nor directs those ([managedView]), so their endings are ones +// it can do nothing with. +func teamEventWakesManagerOf(root bool, state, text string) bool { + if root { return state == teams.StateFailed || state == teams.StateAsking } return teamEventWakesManager(state, text) } -// quietEnding reports whether member is a top-level team's manager seated in -// the root: the one member whose turn ending does not wake the root's manager. -// Anybody else the root holds is an ordinary member there. -func (r teamRole) quietEnding(member string) bool { - return r.root && r.tops[member] -} - -// topManagerKeys is the keys [teamRole.tops] holds, nil for every team but the -// root. -func topManagerKeys(file *teams.File, team teams.Team) map[string]bool { - if file == nil || !team.Root { - return nil - } - tops := map[string]bool{} +// topManager reports whether key manages an open top-level team now +// ([teams.File.TopManagers]), which is what [teamRole.top] says of a seat in +// the root. +func topManager(file *teams.File, key string) bool { for _, m := range file.TopManagers() { - tops[m.Key] = true + if m.Key == key { + return true + } } - return tops + return false } // teamWakes reports whether an entry starts this conversation's turn when it @@ -503,7 +499,7 @@ func topManagerKeys(file *teams.File, team teams.Team) map[string]bool { // member; a member's post to the manager, or a member's finished, failed or // asking event, for the manager. The watch suppresses a finished event when // the same turn already posted a reply, and the global manager is not woken by -// a top-level manager's turn ending ([teamEventWakesManagerOf]). +// a turn ending in the root ([teamEventWakesManagerOf]). func teamWakes(role teamRole, entry teams.Entry) bool { if !role.joinedAt.IsZero() && entry.At.Before(role.joinedAt) { return false @@ -525,7 +521,7 @@ func teamWakes(role teamRole, entry teams.Entry) bool { case teams.KindNote: return entry.To == teams.ToManager && strings.TrimSpace(entry.Text) != "" case teams.KindEvent: - return teamEventWakesManagerOf(role.quietEnding(entry.Member), entry.State, entry.Text) + return teamEventWakesManagerOf(role.root, entry.State, entry.Text) } return false } diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index 12fedb9e56..62c831e1b5 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -184,7 +184,7 @@ func (a *Agent) writeTeamEvent(event teamEvent) { if err != nil || !role.wakes { continue } - if teamEventWakesManagerOf(role.quietEnding(role.key), event.state, text) { + if teamEventWakesManagerOf(role.root, event.state, text) { // These wake the manager, so a manager nobody has open is opened // (team_wakewatch.go). a.rouseManager(profile, role, event.origin.provenance(role.key)) From 3cd3c04350dc1675fc57c5281c0323f791ec2e26 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:23:20 -0500 Subject: [PATCH 20/37] tasks: final review round 3 repairs for a reference saying so A reference run recovered after a crash before its landing no longer takes the git landing, which failed on a folder that is not a repository; it is accepted with the same line. The manual says when a task that names no file reads its repository and when it gets a branch. Tests cover a held run, a failed and a stopped run, a recovered run and a proposal's receipt through the real proposal road. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2909-reference-task-says-so.md | 4 +- internal/manual/chat/how-tasks-run.md | 25 +- internal/manual/chat/worker-harness.md | 5 +- internal/session/task.go | 8 +- internal/session/task_reference_test.go | 288 +++++++++++++++++- internal/session/task_run_belt.go | 4 +- internal/session/task_run_resolve.go | 13 + 7 files changed, 332 insertions(+), 15 deletions(-) diff --git a/docs/changes/unreleased/2909-reference-task-says-so.md b/docs/changes/unreleased/2909-reference-task-says-so.md index 9855f1eee1..05dbd6bd27 100644 --- a/docs/changes/unreleased/2909-reference-task-says-so.md +++ b/docs/changes/unreleased/2909-reference-task-says-so.md @@ -4,9 +4,9 @@ title: A task that only reads its folder says so when it starts, to its worker, pr: 2909 surface: [engine, chat] invalidates: - - "A task whose stand is a reference (TaskModeReference, a ground it only reads) was told so on its receipt only when `where` named a folder holding the home folder (homeTaskRedirect). Where the proposal's `ground` or its brief had chosen the folder, the receipt read \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\", the home folder included; on the other rungs it had no sentence about the folder. On every rung the receipt of a task the conversation's model proposes now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file there by full path. If the work is meant to change , stop this task and propose it again naming the files it makes or changes by their full path under .\" (taskReadsSentence), or over the home folder \"The task reads and keeps what it makes in its own folder; nothing in changes.\" whichever door named the folder. A task a person types with `/task` is handed no receipt sentence about its folder on the run road, and on the older single-task road only the stand's redirect, as before." + - "A task whose stand is a reference (TaskModeReference, a ground it only reads) was told so on its receipt only when `where` named a folder holding the home folder (homeTaskRedirect). Where the proposal's `ground` or its brief had chosen the folder, the receipt read \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\", the home folder included; on the other rungs it had no sentence about the folder. On every rung the receipt of a task the conversation's model proposes now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file there by full path. If the work is meant to change , stop this task and propose it again naming the files it makes or changes by their full path under .\" (taskReadsSentence), or over the home folder \"The task reads and keeps what it makes in its own folder; nothing in changes.\" whichever door named the folder. The started receipt of such a task now opens \"It works from the brief alone, in a folder of its own.\"; every other task's still opens \"It works from the brief alone, in a copy of its own.\" (taskReceipt). A task a person types with `/task` is handed no receipt sentence about its folder on the run road, and on the older single-task road only the stand's redirect, as before." - "A reference worker was told \" is yours to read, not to change. Everything you make goes in , your own folder. In your report, say where in that folder the results are.\" only when its ground held the home folder (taskCopy.readsHome, withHomeReadingNote); over any other ground it was told nothing. Every reference worker whose folder is not its ground is now told \" is yours to read, not to change. Everything you make goes in , your own folder, and stays there: nothing you make reaches . In your report, say where in that folder the results are, and never say the work is in .\" (taskReadsNote; the field is taskCopy.reads, and the run's helper is withTaskReadsNote)." - - "A run that only read its ground was handed to the engine's landing, which failed in its folder with \"fatal: not a git repository\": a plan note \"the run's landing failed\" was filed, the landing had no line (RunLanding.Line empty, no branch) and the run's page got no homecoming note. Such a run is no longer handed to the engine's landing (landReferenceRun): its landing line reads \"it changed nothing in : what it made is in \" (referenceLandingLine), and its page carries that line once, in the run's outcome note, with no separate homecoming note. A reference run that failed is given the same line; one that was stopped is given none." + - "A run that only read its ground was handed to the engine's landing, which failed in its folder with \"fatal: not a git repository\": a plan note \"the run's landing failed\" was filed, the landing had no line (RunLanding.Line empty, no branch) and the run's page got no homecoming note. Such a run is no longer handed to the engine's landing (landReferenceRun): its landing line reads \"it changed nothing in : what it made is in \" (referenceLandingLine), and its page carries that line once, in the run's outcome note, with no separate homecoming note. A reference run that failed is given the same line; one that was stopped is given none. A reference run recovered after the process ended between its plan finishing and its landing still waits for the person to accept it (completedRunReview); accepting it took the git landing in its folder and failed with the same error, and it now takes this landing and line instead (acceptCompletedRun). A recovered run whose plan had already failed is settled with its failure alone, without the line." - "A reference whose proposal asked for `where: \"in place\"` inside a repository had the redirect \"in place was asked for, and is a repository — the work goes on a branch cut from it instead\" printed on its receipt. The stand still carries that redirect, and the receipt of a reference no longer prints it (taskStandRedirect)." - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode). A hand-off that joined a run which only reads its ground, the home folder apart, is not given the starting task's sentence or \"It joined the work already underway and shares its copy.\": its receipt reads \"It joined the work already underway, which only reads and writes in a folder of its own, so nothing in changes while it is part of that run. To change , propose the work once that run has ended.\" (taskJoinedReadsSentence), whatever files its own proposal named." - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." diff --git a/internal/manual/chat/how-tasks-run.md b/internal/manual/chat/how-tasks-run.md index 223751c352..7757c22902 100644 --- a/internal/manual/chat/how-tasks-run.md +++ b/internal/manual/chat/how-tasks-run.md @@ -82,7 +82,9 @@ rung asks, in the two names you already know. An explicit existing `ground` stil every other rung, even when it is a third folder not offered by that question; the receipt says where in words, `It works in , the folder this proposal gave as its ground.`, so a wrong choice is visible immediately. A stand read from the brief is said the same way: -`It works in , the one folder its brief names the work in.` +`It works in , the one folder its brief names the work in.` A task that only reads +its ground is the exception: its receipt says `It reads and writes only in a folder +of its own` instead (see **A task built my project somewhere else**). **How it stands on that ground is not asked either — it follows from the work.** A repository the task writes in gets a working copy of its own, on a branch cut **from that @@ -111,10 +113,15 @@ row carry the ground and how the task stood on it. ## A task built my project somewhere else — it only read my repository, nothing changed in my folder, where is what the task made A task whose whole contract names no file to make or change is treated as reading its -repository: it gets an empty folder of its own and the repository is left alone. Naming a -project in words is not naming a file, so a brief such as "build the app in the MacStats -repo" reads this way. So does a relative path such as `Sources/App/main.swift` when -neither the file nor the folder that would hold it is there yet. +repository when something chose that repository for it: the proposal's `ground`, its brief, +a place the conversation remembered, or the files the conversation has been working with. +It gets an empty folder of its own and the repository is left alone, even when the +conversation was opened there. A task nothing placed, which simply takes the repository +the conversation stands in, gets a working copy on a branch instead. + +Naming a project in words is not naming a file, so "build the app in the MacStats repo" +with `~/MacStats` as its `ground` reads this way. So does a relative path such as +`Sources/App/main.swift` when neither the file nor its folder is there yet. Such a task says so wherever there is somebody to tell. One the conversation's model proposes says it in its receipt: `It reads and writes only in a folder of its own, @@ -125,10 +132,10 @@ never to report the work as being there. A task run as a run ends its landing `i nothing in : what it made is in `; the older single-task road lands without that line. -A proposed task that joins a run already underway shares that run's copy, so it is told -what is true of that run instead. Joining one that only reads the folder, its receipt says -`nothing in changes while it is part of that run`, whatever files it named, and to -propose the work once that run has ended. +A proposed task that joins a run already underway is told what is true of that run +instead. Joining one that only reads the folder, its receipt says `nothing in +changes while it is part of that run`, whatever files it named, and to propose the work +once that run has ended. To have the work done in the repository, name a file under it by full path in the brief, in what to produce or in the done-when, such as `~/MacStats/Sources/App/main.swift`. diff --git a/internal/manual/chat/worker-harness.md b/internal/manual/chat/worker-harness.md index 2c0ca5fc4c..0f6ac0551e 100644 --- a/internal/manual/chat/worker-harness.md +++ b/internal/manual/chat/worker-harness.md @@ -76,7 +76,10 @@ works in that one copy. **A second `/task` joins the run already underway** when it is about the same folder: the new work becomes a child of the run's root, shares the run's copy, and its answer -says `It joined the work already underway and shares its copy.` A proposed task about +says `It joined the work already underway and shares its copy.` The exception is a run that +only reads its folder, the home folder apart: there is no copy to share, and a proposed +task that joins it is told `It joined the work already underway, which only reads +and writes in a folder of its own` instead. A proposed task about ANOTHER folder is refused while that run is underway, with both folders named and `tasks that run together share one copy of one folder. Propose it again when that work has ended`. A task handed off after the run has ended starts a run of its own, in a new diff --git a/internal/session/task.go b/internal/session/task.go index 27e7f1ef1b..2af3c05d68 100644 --- a/internal/session/task.go +++ b/internal/session/task.go @@ -1231,7 +1231,13 @@ func taskReceipt(id uint64, spec taskSpec, state TaskState, stand taskStand, els result := fmt.Sprintf("task %d queued%s: %s\nIt starts when the work it waits on has finished and a slot is free. %s", id, on, spec.title, taskHandoffWakeSentence) return withElsewhere(withReport(withReport(result, taskStandSentence(stand)), taskStandRedirect(stand)), elsewhere) } - result := fmt.Sprintf("task %d started%s: %s\nIt works from the brief alone, in a copy of its own. %s", id, on, spec.title, taskHandoffWakeSentence) + // A reference has no copy: the sentence after this one says it writes only + // in a folder of its own, and the opener may not say otherwise first. + own := "copy" + if stand.mode == TaskModeReference { + own = "folder" + } + result := fmt.Sprintf("task %d started%s: %s\nIt works from the brief alone, in a %s of its own. %s", id, on, spec.title, own, taskHandoffWakeSentence) return withElsewhere(withReport(withReport(result, taskStandSentence(stand)), taskStandRedirect(stand)), elsewhere) } diff --git a/internal/session/task_reference_test.go b/internal/session/task_reference_test.go index 27b7536786..bebd6d252c 100644 --- a/internal/session/task_reference_test.go +++ b/internal/session/task_reference_test.go @@ -12,6 +12,7 @@ import ( "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/crewroute" + "github.com/Agent-Field/codeaf/internal/plandb" ) // A TASK THAT ONLY READS ITS GROUND SAYS SO AT ALL THREE ENDS: the proposer's @@ -96,9 +97,16 @@ func TestAReferenceReceiptSaysNoBranchAndTheHomeFolderOnce(t *testing.T) { if !strings.Contains(reads, "It reads "+ground) || strings.Contains(reads, "branch cut from it") { t.Errorf("a reference asked for in place is told about a branch:\n%s", reads) } - if works := taskReceipt(7, spec, TaskRunning, taskStand{dir: ground, mode: TaskModeWorktree, rung: taskGroundSaid, redirect: branch}, ""); !strings.Contains(works, branch) { + if !strings.Contains(reads, "It works from the brief alone, in a folder of its own. ") || strings.Contains(reads, "in a copy of its own") { + t.Errorf("a reference's receipt opens on a copy it does not have:\n%s", reads) + } + works := taskReceipt(7, spec, TaskRunning, taskStand{dir: ground, mode: TaskModeWorktree, rung: taskGroundSaid, redirect: branch}, "") + if !strings.Contains(works, branch) { t.Errorf("a task on a branch lost its redirect:\n%s", works) } + if !strings.Contains(works, "It works from the brief alone, in a copy of its own. ") { + t.Errorf("a task on a branch lost its opener:\n%s", works) + } for _, stand := range []taskStand{ {dir: home, mode: TaskModeReference, rung: taskGroundSaid}, @@ -332,3 +340,281 @@ func TestARerunOfAReferenceRunIsStillAReference(t *testing.T) { } endBeltRun(t, agent, second) } + +// A PLAIN REFERENCE PROPOSAL IS TOLD SO THROUGH THE PROPOSAL'S OWN ROAD. The +// sentence is tested above as a function; this is the receipt the model that +// proposed the task is handed, with no run underway to join. +func TestAProposedReferenceTaskIsToldItOnlyReads(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + double := newBeltRunDouble("the parser reads tokens") + registerBeltRunEngine(t, double) + sessionDir := t.TempDir() + ground := newTestRepo(t) + agent, _ := newTestAgent(t, beltRunCompleter{text: "the parser reads tokens"}, func(config *Config) { + config.Workspace = ground + config.Place = Place{Dir: sessionDir} + config.AskConsent = false + config.TaskAutoApproveSeconds = 0 + }) + args, _ := json.Marshal(taskArguments{ + Title: "Explain the parser", Summary: "the proposed work", Brief: "say how the parser reads its input", + Deliverable: "a concise answer", Acceptance: "the question is answered", Ground: ground, + }) + proposal, ok := agent.stageTask(context.Background(), args).(*stagedProposal) + if !ok || proposal.stand.mode != TaskModeReference { + t.Fatalf("the proposal did not stage as a reference: %+v", proposal) + } + agent.ResolveTask(proposal.id, TaskAnswer{Approved: true}) + answer, failed, err := proposal.Commit(context.Background()) + if err != nil || failed { + t.Fatalf("propose_task: failed=%v err=%v answer=%q", failed, err, answer) + } + <-double.entered + dir := canonicalPath(ground) + for _, want := range []string{ + "It works from the brief alone, in a folder of its own. ", + "It reads " + dir + " and writes only in a folder of its own, so nothing in " + dir + " changes: this proposal named no file there by full path.", + "stop this task and propose it again naming the files it makes or changes by their full path under " + dir + ".", + } { + if !strings.Contains(answer, want) { + t.Errorf("the receipt of a proposed reference lacks %q:\n%s", want, answer) + } + } + for _, untrue := range []string{"It works in", "in a copy of its own", "It joined the work already underway"} { + if strings.Contains(answer, untrue) { + t.Errorf("the receipt of a proposed reference says %q:\n%s", untrue, answer) + } + } + endBeltRun(t, agent, double) +} + +// A REFERENCE RUN THAT FAILED IS GIVEN THE LANDING LINE AND ONE THAT WAS +// STOPPED IS GIVEN NONE. What a failed run made is still in its folder and its +// ground is still untouched; a stopped run has its own ending and no landing. +func TestAFailedReferenceRunHasItsLandingLineAndAStoppedOneHasNone(t *testing.T) { + for _, tc := range []struct { + name string + stop bool + }{{name: "failed"}, {name: "stopped", stop: true}} { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + double := newBeltRunDouble("the parser was not read") + // The engine's own ending of a run that did not finish: its word for + // it, and the store's root left for the door to end. + double.summary.Outcome, double.leaveOpen = "ran and did not finish", true + double.real, double.honoursStop = true, tc.stop + registerBeltRunEngine(t, double) + ground := newTestRepo(t) + sessionDir := t.TempDir() + agent, _ := newTestAgent(t, beltRunCompleter{text: "the parser was not read"}, func(config *Config) { + config.Workspace = ground + config.Place = Place{Dir: sessionDir} + config.SessionFile = filepath.Join(sessionDir, placeTranscript) + config.AskConsent = false + }) + if err := agent.startKnownTaskRun(context.Background(), 41, "explain the parser", "brief", nil, taskStand{dir: ground, mode: TaskModeReference, rung: taskGroundSaid}, ""); err != nil { + t.Fatalf("start the reference run: %v", err) + } + <-double.entered + if tc.stop { + if _, err := agent.Cancel(CancelTask + ":41"); err != nil { + t.Fatalf("stop the run: %v", err) + } + beltRunWaitFor(t, "the stopped run to end", func() bool { + agent.beltMu.Lock() + defer agent.beltMu.Unlock() + return agent.beltRun == nil + }) + } else { + endBeltRun(t, agent, double) + } + rows := agent.graph().runRows(41) + if len(rows) != 1 || rows[0].State != TaskFailed || rows[0].Stopped != tc.stop { + t.Fatalf("the run did not end %s: %+v", tc.name, rows) + } + said := rows[0].Report + "\n" + strings.Join(beltRunNotes(t, sessionDir, "41"), "\n") + line := "it changed nothing in " + canonicalPath(ground) + ": what it made is in " + if got := strings.Contains(rows[0].Report, line); got == tc.stop { + t.Errorf("a %s reference run's row carries the landing line: %v\n%s", tc.name, got, rows[0].Report) + } + if tc.stop && strings.Contains(said, "it changed nothing in") { + t.Errorf("a stopped reference run was given a landing:\n%s", said) + } + if double.lands() != 0 { + t.Errorf("the engine was asked to land a folder that is no repository %d times", double.lands()) + } + }) + } +} + +// A REFERENCE RUN THAT IS HELD AND ADMITTED LATER STILL TELLS ITS WORKERS. The +// held road keeps the workers' words itself (the store's root, the run's own +// brief and the record a reopened conversation reads the run back from), and +// the crew's kept brief stays the brief as it was handed in. +func TestAHeldReferenceRunStillTellsItsWorkersTheGroundIsReadOnly(t *testing.T) { + littleMemoryHost(t) + t.Setenv("CODEAF_TASK_BELT", "bash") + engine := newBeltRunDouble("the parser reads tokens") + registerBeltRunEngine(t, engine) + ground := canonicalPath(newTestRepo(t)) + // The conversation stands in a plain folder and is about the repository. + sessionDir, workspace, profile := t.TempDir(), t.TempDir(), t.TempDir() + open := func() *Agent { + agent, _ := newTestAgent(t, beltRunCompleter{text: "the parser reads tokens"}, func(c *Config) { + c.Workspace = workspace + c.Place = Place{Dir: sessionDir} + c.SessionFile = filepath.Join(sessionDir, placeTranscript) + c.ProfileDir = profile + c.AskConsent, c.TaskMaxLoad, c.TaskMinFreeMB = false, 0, 1<<40 + c.RouteCrew = func(config.CrewAsk) (crewroute.Decision, error) { return flashDecision(), nil } + }) + return agent + } + note := ground + " is yours to read, not to change" + keptBrief := func(agent *Agent, id uint64) { + t.Helper() + crew := agent.crews.get(id) + if crew == nil || strings.Contains(crew.brief, "yours to read") || strings.Contains(crew.brief, ground) { + t.Fatalf("the brief a rerun reads again carries the read-only note: %+v", crew) + } + } + + first := open() + first.refer(PlaceRef{Path: ground, Arrival: PlaceSaid, Referred: time.Now()}) + id, _, _, err := first.StartTask(context.Background(), "say how the parser reads its input", false) + if err != nil { + t.Fatalf("start the held reference run: %v", err) + } + beltRunWaitFor(t, "the held row", func() bool { + rows := first.graph().runRows(id) + return len(rows) == 1 && rows[0].State == TaskQueued && rows[0].Waiting == waitingMachineBusy + }) + first.beltMu.Lock() + held := first.beltRun + stand, brief := taskStand{}, "" + if held != nil { + stand, brief = held.stand, held.brief + } + first.beltMu.Unlock() + if held == nil || stand.dir != ground || stand.mode != TaskModeReference { + t.Fatalf("the held run does not only read %s: %+v", ground, stand) + } + if !strings.Contains(brief, note) { + t.Errorf("the brief a held run keeps for its workers lacks the read-only note:\n%s", brief) + } + storeID := strconv.FormatUint(id, 10) + if root := beltRunTaskAt(t, sessionDir, storeID); root == nil || !strings.Contains(root.Description, note) { + t.Errorf("the held run's root does not tell its workers the ground is read-only: %+v", root) + } + if row, found := runRowOf(first.graph(), id); !found || row.PendingRun == nil || !strings.Contains(row.PendingRun.Brief, note) { + t.Errorf("the record a reopened conversation reads the run from lacks the read-only note: %+v", row.PendingRun) + } + keptBrief(first, id) + if engine.didRun() { + t.Fatal("a held run reached the engine") + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + select { + case <-held.over: + case <-time.After(5 * time.Second): + t.Fatal("the held driver did not leave") + } + + // The machine has room now, and the reopened conversation admits the run + // it kept: a host that says nothing holds nothing. + little := readHost + readHost = func() (machineReading, bool) { return machineReading{}, false } + t.Cleanup(func() { readHost = little }) + second := open() + select { + case <-engine.entered: + case <-time.After(10 * time.Second): + t.Fatal("the admitted run did not reach its engine") + } + engine.mu.Lock() + given, own := engine.spec.Brief, engine.spec.Workspace + engine.mu.Unlock() + if !strings.Contains(given, note) || !strings.Contains(given, "your assigned working directory") { + t.Errorf("the workers of a run admitted later are not told their ground is read-only:\n%s", given) + } + if own == "" || canonicalPath(own) == ground { + t.Errorf("the admitted run works in %q, not a folder of its own", own) + } + keptBrief(second, id) + endBeltRun(t, second, engine) + if rows := second.graph().runRows(id); len(rows) != 1 || !strings.Contains(rows[0].Report, "it changed nothing in "+ground) { + t.Errorf("the run admitted later did not land as a reference: %+v", rows) + } +} + +// A REFERENCE RUN RECOVERED AFTER ITS PLAN FINISHED IS ACCEPTED WITH THE SAME +// LANDING. The process ended between the root's `done` and the landing, so the +// row waits for the person; accepting it took the git landing in a folder that +// is no repository and failed, and the run never got its line. +func TestARecoveredReferenceRunIsAcceptedWithItsLandingLine(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + engine := newBeltRunDouble("must not run") + registerBeltRunEngine(t, engine) + place, repo := t.TempDir(), newTestRepo(t) + open := func() *Agent { + agent, _ := newTestAgent(t, &scriptedCompleter{}, func(c *Config) { + c.Place, c.Workspace, c.SessionFile = Place{Dir: place}, repo, filepath.Join(place, placeTranscript) + c.AskConsent = false + }) + return agent + } + first := open() + g := first.graph() + id := g.reserve() + tree, err := prepareTaskTreeOn(context.Background(), first.config.Place, repo, "1111dddd1111dddd", id, "explain the parser", + taskStand{dir: repo, mode: TaskModeReference, rung: taskGroundSaid}) + if err != nil { + t.Fatal(err) + } + line := referenceLandingLine(tree) + if line == "" { + t.Fatalf("the prepared tree is no reference: %+v", tree) + } + made := filepath.Join(tree.dir, "parser.md") + if err := os.WriteFile(made, []byte("the parser reads tokens\n"), 0o600); err != nil { + t.Fatal(err) + } + storeID := strconv.FormatUint(id, 10) + store, err := plandb.Open(g.planPath(), "mock", storeID, "explain the parser", "say how the parser reads its input", g.planChat()) + if err != nil { + t.Fatal(err) + } + if err := store.CompleteRoot("the parser reads tokens; see parser.md"); err != nil { + t.Fatal(err) + } + _ = store.Close() + first.publishRunRow(g, TaskNotice{ID: id, Title: "explain the parser", State: TaskRunning, Copy: runCopyOf(tree), CrewState: first.unroutedCrewRecord(), StartedAt: time.Now().Add(-time.Minute), PlanTask: planStoreID(storeID)}) + if err := first.Close(); err != nil { + t.Fatal(err) + } + + second := open() + if kept, found := runRowOf(second.graph(), id); !found || kept.State != TaskUnverified || !kept.RecoveredCompletion { + t.Fatalf("the recovered reference run does not wait for the person: %+v", kept) + } + before := runTreeHead(repo) + if err := second.ResolveUnverified(id, TaskAccept, "read parser.md"); err != nil { + t.Fatalf("accepting a recovered reference run: %v", err) + } + landed, _ := runRowOf(second.graph(), id) + if landed.State != TaskDone || !strings.Contains(landed.Report, line) || !strings.Contains(landed.Report, "the parser reads tokens; see parser.md") { + t.Errorf("the accepted run did not land with its line %q: %+v", line, landed) + } + if landed.Branch != "" || landed.Merge != "" || runTreeHead(repo) != before { + t.Errorf("accepting a run that only read %s touched it: %+v", repo, landed) + } + if _, err := os.Stat(made); err != nil { + t.Errorf("what the run made is gone from its folder: %v", err) + } + if notes := strings.Join(beltRunNotes(t, place, storeID), "\n"); strings.Count(notes, line) != 1 { + t.Errorf("the run's page does not say the landing line once:\n%s", notes) + } + nothingStarted(t, second, engine) +} diff --git a/internal/session/task_run_belt.go b/internal/session/task_run_belt.go index ee19659570..5854b1d062 100644 --- a/internal/session/task_run_belt.go +++ b/internal/session/task_run_belt.go @@ -711,7 +711,9 @@ func (a *Agent) startOrJoinTaskRunVia(ctx context.Context, id uint64, title, bri PlanTask: planStoreID(storeID), }) a.publishJoinedRunRows(g, live) - return preparedTaskMode(a.config.Place, live.ground, live.stand.mode), true, nil + // The stand is fixed when the run is made; the run's ground is written + // again under beltMu once a held run's copy is ready. + return preparedTaskMode(a.config.Place, canonicalPath(strings.TrimSpace(live.stand.dir)), live.stand.mode), true, nil } // ADMISSION IS CHECKED BEFORE A FOLDER OR COPY IS TOUCHED. A held run seeds diff --git a/internal/session/task_run_resolve.go b/internal/session/task_run_resolve.go index eeb2df3ead..6a8ccaf93d 100644 --- a/internal/session/task_run_resolve.go +++ b/internal/session/task_run_resolve.go @@ -99,6 +99,19 @@ func (a *Agent) acceptCompletedRun(ctx context.Context, g *TaskGraph, kept TaskN if err != nil { return "", true, err } + // A RUN THAT ONLY READ ITS GROUND IS ACCEPTED WITH THE LANDING IT WOULD HAVE + // HAD ([Agent.landReferenceRun]). Its folder is no repository, so the git + // landing below failed in it with `fatal: not a git repository` and the + // run could never be accepted; there is no branch to restore, commit or + // merge, and the homecoming is the one line. + if line := referenceLandingLine(tree); line != "" && kept.WorkspaceSet == nil { + if err := a.admitCompletedRunHomecoming(ctx, epoch); err != nil { + return "", true, err + } + kept.State = TaskDone + kept.Report = withReport(acceptedLine(strings.TrimSpace(why), by), withReport(root.Result, line)) + return a.saveCompletedRunOutcome(g, kept, path, root.ID) + } // A refused landing releases Git's registration while retaining its files. // Restore that registration before checking or committing the saved branch. if reopened, back, problem := tree.reopenReleased(); problem != "" { From 51b72c1ef1651209e0cccaaa77e9a62228ba2b9d Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:40:35 -0500 Subject: [PATCH 21/37] tasks: keep the recovered-run accept under the complexity ceiling The reference branch added to acceptCompletedRun put it one decision over the task engine's ceiling of 15. The copy is read and the reference case decided in a small wrapper; the git landing is its own function. Co-Authored-By: Claude Fable 5.2 --- internal/session/task_run_resolve.go | 31 ++++++++++++++++++---------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/internal/session/task_run_resolve.go b/internal/session/task_run_resolve.go index 6a8ccaf93d..dc72d43195 100644 --- a/internal/session/task_run_resolve.go +++ b/internal/session/task_run_resolve.go @@ -94,24 +94,33 @@ func (a *Agent) completedRunPlan(id uint64) (string, *plandb.Task, error) { return "", nil, fmt.Errorf("task %d has no completed plan in this conversation; its saved work has not been changed", id) } +// acceptReferenceRun accepts a recovered run that only read its ground, with +// the landing it would have had ([Agent.landReferenceRun]). Its folder is no +// repository, so the git landing failed in it with `fatal: not a git +// repository` and the run could never be accepted; there is no branch to +// restore, commit or merge, and the homecoming is the one line. +func (a *Agent) acceptReferenceRun(ctx context.Context, g *TaskGraph, kept TaskNotice, path string, root *plandb.Task, epoch uint64, why string, by TaskAskOwner, line string) (string, bool, error) { + if err := a.admitCompletedRunHomecoming(ctx, epoch); err != nil { + return "", true, err + } + kept.State = TaskDone + kept.Report = withReport(acceptedLine(strings.TrimSpace(why), by), withReport(root.Result, line)) + return a.saveCompletedRunOutcome(g, kept, path, root.ID) +} + func (a *Agent) acceptCompletedRun(ctx context.Context, g *TaskGraph, kept TaskNotice, path string, root *plandb.Task, epoch uint64, why string, by TaskAskOwner) (string, bool, error) { tree, err := runCopyTree(kept.Copy, a.config.Place) if err != nil { return "", true, err } - // A RUN THAT ONLY READ ITS GROUND IS ACCEPTED WITH THE LANDING IT WOULD HAVE - // HAD ([Agent.landReferenceRun]). Its folder is no repository, so the git - // landing below failed in it with `fatal: not a git repository` and the - // run could never be accepted; there is no branch to restore, commit or - // merge, and the homecoming is the one line. if line := referenceLandingLine(tree); line != "" && kept.WorkspaceSet == nil { - if err := a.admitCompletedRunHomecoming(ctx, epoch); err != nil { - return "", true, err - } - kept.State = TaskDone - kept.Report = withReport(acceptedLine(strings.TrimSpace(why), by), withReport(root.Result, line)) - return a.saveCompletedRunOutcome(g, kept, path, root.ID) + return a.acceptReferenceRun(ctx, g, kept, path, root, epoch, why, by, line) } + return a.acceptCompletedRunTree(ctx, g, kept, path, root, epoch, why, by, tree) +} + +// acceptCompletedRunTree is the git landing of a recovered run's saved copy. +func (a *Agent) acceptCompletedRunTree(ctx context.Context, g *TaskGraph, kept TaskNotice, path string, root *plandb.Task, epoch uint64, why string, by TaskAskOwner, tree taskTree) (string, bool, error) { // A refused landing releases Git's registration while retaining its files. // Restore that registration before checking or committing the saved branch. if reopened, back, problem := tree.reopenReleased(); problem != "" { From 475dca2f99e5a1b3e26245057945d2a064d3811e Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:08:23 -0500 Subject: [PATCH 22/37] changes: one entry for the crew delegation pull request The global manager and read-only task changes now land in this pull request with the hand-off, pause and standby changes, and the rule is one change entry per pull request. Their two entries are folded into this one, items and reasons unchanged. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2897-crew-handoff-outcome.md | 25 ++++++++++++++++++- .../unreleased/2906-global-manager-quiet.md | 18 ------------- .../unreleased/2909-reference-task-says-so.md | 19 -------------- 3 files changed, 24 insertions(+), 38 deletions(-) delete mode 100644 docs/changes/unreleased/2906-global-manager-quiet.md delete mode 100644 docs/changes/unreleased/2909-reference-task-says-so.md diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 80698182c7..e4fd49adc5 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -1,6 +1,6 @@ --- kind: changed -title: A crew manager is told what became of each hand-off, and a paused member holds its work +title: Crew hand-offs say what happened, pause and stop hold, and a read-only task says so pr: 2897 surface: [engine, app, chat] invalidates: @@ -15,6 +15,18 @@ invalidates: - "The desktop app stopped every turn it had not started itself on a paused member, including one the person opened by typing to that member from another window. It now leaves a turn the person's own words opened alone, and still stops any other wake (a background process ending, a task landing)." - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\". It also refuses a member that manages another open team (\"@lead manages and is not paused; stop its turn instead\"), and making a conversation a manager lifts its pause." - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop, whether an interface performs it or the member's own session does) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A stop by the person that finds no turn running but a command or watch still running, or a failed command's ending about to start a turn, begins the same hold; that pending wake is withdrawn and its note is read by the next turn. Only when the conversation is waiting on one of them for work a manager handed it does it also write \"stopped by the person\" to that manager's team, which wakes the manager; a command left running for its own sake, such as a dev server, tells no manager anything. The hold covers a background command's ending and a watch's firing and nothing else: a background task landing, the person's own message and the manager's next hand-off still start the conversation, and that turn ends the hold. The command is still left running by the stop, and a conversation in no team is unchanged." + - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team no member's finished event starts the global manager's turn any longer (teamEventWakesManagerOf): of a member's events there only failed and asking do, and a team_post to the manager, a decision packet a member raises and a conflict it declares wake the global manager as before. A global manager nobody has open is likewise no longer opened by a finished event there. The rule is that whole team's: it covers a top-level team's manager, a manager that was replaced or whose team closed and kept its seat there, and a conversation the person put there, since the global manager lists and directs only the current top-level managers (managedView). Every other team is unchanged." + - "team_send answered every manager \"Replies and endings wake you when they arrive, so there is no need to wait or poll.\" In the team that holds every team it now answers \"Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn finishing or being stopped does not wake you, and team_status says where it stands.\" The answer in every other team is as it was." + - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\" and ends \"A member's turn finishing or being stopped does not start yours.\", and its scope adds \"A manager answers a directive of yours, and the brief you started it on, with team_post, since its turn finishing does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the global manager's role note, which it is handed when that note's text changes." + - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending tells it nothing: answer each of its directives, and the brief it started you on if it started you, with team_post to the manager. Apart from those answers, post only what it should act on or tell the person.\" The rest of that note is as it was. Every member of that team was given that note, \"because you manage a top-level team\" included; a member there that manages no top-level team now is given the note a member of any team is given." + - "The first turn of a team's new manager, on the brief team_start of kind team started it with, woke the manager that started it when it finished, and team_start answered every manager that the new conversation \"makes itself the manager of\" the team \"and reports to you.\" A team the global manager starts no longer wakes it that way, and team_start answers the global manager that the new manager \"reports to you with team_post: its turn finishing on your brief does not start yours, and team_status says where it stands.\" The answer to every other manager is as it was." + - "A task whose stand is a reference (TaskModeReference, a ground it only reads) was told so on its receipt only when `where` named a folder holding the home folder (homeTaskRedirect). Where the proposal's `ground` or its brief had chosen the folder, the receipt read \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\", the home folder included; on the other rungs it had no sentence about the folder. On every rung the receipt of a task the conversation's model proposes now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file there by full path. If the work is meant to change , stop this task and propose it again naming the files it makes or changes by their full path under .\" (taskReadsSentence), or over the home folder \"The task reads and keeps what it makes in its own folder; nothing in changes.\" whichever door named the folder. The started receipt of such a task now opens \"It works from the brief alone, in a folder of its own.\"; every other task's still opens \"It works from the brief alone, in a copy of its own.\" (taskReceipt). A task a person types with `/task` is handed no receipt sentence about its folder on the run road, and on the older single-task road only the stand's redirect, as before." + - "A reference worker was told \" is yours to read, not to change. Everything you make goes in , your own folder. In your report, say where in that folder the results are.\" only when its ground held the home folder (taskCopy.readsHome, withHomeReadingNote); over any other ground it was told nothing. Every reference worker whose folder is not its ground is now told \" is yours to read, not to change. Everything you make goes in , your own folder, and stays there: nothing you make reaches . In your report, say where in that folder the results are, and never say the work is in .\" (taskReadsNote; the field is taskCopy.reads, and the run's helper is withTaskReadsNote)." + - "A run that only read its ground was handed to the engine's landing, which failed in its folder with \"fatal: not a git repository\": a plan note \"the run's landing failed\" was filed, the landing had no line (RunLanding.Line empty, no branch) and the run's page got no homecoming note. Such a run is no longer handed to the engine's landing (landReferenceRun): its landing line reads \"it changed nothing in : what it made is in \" (referenceLandingLine), and its page carries that line once, in the run's outcome note, with no separate homecoming note. A reference run that failed is given the same line; one that was stopped is given none. A reference run recovered after the process ended between its plan finishing and its landing still waits for the person to accept it (completedRunReview); accepting it took the git landing in its folder and failed with the same error, and it now takes this landing and line instead (acceptCompletedRun). A recovered run whose plan had already failed is settled with its failure alone, without the line." + - "A reference whose proposal asked for `where: \"in place\"` inside a repository had the redirect \"in place was asked for, and is a repository — the work goes on a branch cut from it instead\" printed on its receipt. The stand still carries that redirect, and the receipt of a reference no longer prints it (taskStandRedirect)." + - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode). A hand-off that joined a run which only reads its ground, the home folder apart, is not given the starting task's sentence or \"It joined the work already underway and shares its copy.\": its receipt reads \"It joined the work already underway, which only reads and writes in a folder of its own, so nothing in changes while it is part of that run. To change , propose the work once that run has ended.\" (taskJoinedReadsSentence), whatever files its own proposal named." + - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." + - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." --- A manager model reports what its tools tell it. In the measured run a member the @@ -22,3 +34,14 @@ person had paused was handed two directives, the tool said both had started, and the manager told the person so twice before finding an empty folder. Creating that crew had also started every helper on its line of the proposal, one of which began work nobody had asked for. + +The global manager's members are the managers of whole teams, each a conversation +the person talks to, and every answer one of them gave ended a turn. Measured in +the desktop app, one afternoon of that woke the global manager 22 times for +803,496 input tokens, each answered "[no change]", and one earlier wake had it +send the person's own request back to a manager as a directive. + +A proposal that named a repository as its ground and no file by path was read as +work that only reads it. The worker built the project in its own folder, reported +it integrated, and the conversation told the person to run it from a repository +nothing had been written to. diff --git a/docs/changes/unreleased/2906-global-manager-quiet.md b/docs/changes/unreleased/2906-global-manager-quiet.md deleted file mode 100644 index 6c90bf417f..0000000000 --- a/docs/changes/unreleased/2906-global-manager-quiet.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -kind: changed -title: The global manager is not woken each time a top-level team's manager ends a turn -pr: 2906 -surface: [engine, chat] -invalidates: - - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team no member's finished event starts the global manager's turn any longer (teamEventWakesManagerOf): of a member's events there only failed and asking do, and a team_post to the manager, a decision packet a member raises and a conflict it declares wake the global manager as before. A global manager nobody has open is likewise no longer opened by a finished event there. The rule is that whole team's: it covers a top-level team's manager, a manager that was replaced or whose team closed and kept its seat there, and a conversation the person put there, since the global manager lists and directs only the current top-level managers (managedView). Every other team is unchanged." - - "team_send answered every manager \"Replies and endings wake you when they arrive, so there is no need to wait or poll.\" In the team that holds every team it now answers \"Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn finishing or being stopped does not wake you, and team_status says where it stands.\" The answer in every other team is as it was." - - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\" and ends \"A member's turn finishing or being stopped does not start yours.\", and its scope adds \"A manager answers a directive of yours, and the brief you started it on, with team_post, since its turn finishing does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the global manager's role note, which it is handed when that note's text changes." - - "A top-level manager's note about its seat in the team that holds every team ended \"you report to it with team_post to the manager.\" It now adds \"Your turn ending tells it nothing: answer each of its directives, and the brief it started you on if it started you, with team_post to the manager. Apart from those answers, post only what it should act on or tell the person.\" The rest of that note is as it was. Every member of that team was given that note, \"because you manage a top-level team\" included; a member there that manages no top-level team now is given the note a member of any team is given." - - "The first turn of a team's new manager, on the brief team_start of kind team started it with, woke the manager that started it when it finished, and team_start answered every manager that the new conversation \"makes itself the manager of\" the team \"and reports to you.\" A team the global manager starts no longer wakes it that way, and team_start answers the global manager that the new manager \"reports to you with team_post: its turn finishing on your brief does not start yours, and team_status says where it stands.\" The answer to every other manager is as it was." ---- - -The global manager's members are the managers of whole teams, each a conversation -the person talks to, and every answer one of them gave ended a turn. Measured in -the desktop app, one afternoon of that woke the global manager 22 times for -803,496 input tokens, each answered "[no change]", and one earlier wake had it -send the person's own request back to a manager as a directive. diff --git a/docs/changes/unreleased/2909-reference-task-says-so.md b/docs/changes/unreleased/2909-reference-task-says-so.md deleted file mode 100644 index 05dbd6bd27..0000000000 --- a/docs/changes/unreleased/2909-reference-task-says-so.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -kind: changed -title: A task that only reads its folder says so when it starts, to its worker, and when it lands -pr: 2909 -surface: [engine, chat] -invalidates: - - "A task whose stand is a reference (TaskModeReference, a ground it only reads) was told so on its receipt only when `where` named a folder holding the home folder (homeTaskRedirect). Where the proposal's `ground` or its brief had chosen the folder, the receipt read \"It works in , the folder this proposal gave as its ground.\" or \"It works in , the one folder its brief names the work in.\", the home folder included; on the other rungs it had no sentence about the folder. On every rung the receipt of a task the conversation's model proposes now reads \"It reads and writes only in a folder of its own, so nothing in changes: this proposal named no file there by full path. If the work is meant to change , stop this task and propose it again naming the files it makes or changes by their full path under .\" (taskReadsSentence), or over the home folder \"The task reads and keeps what it makes in its own folder; nothing in changes.\" whichever door named the folder. The started receipt of such a task now opens \"It works from the brief alone, in a folder of its own.\"; every other task's still opens \"It works from the brief alone, in a copy of its own.\" (taskReceipt). A task a person types with `/task` is handed no receipt sentence about its folder on the run road, and on the older single-task road only the stand's redirect, as before." - - "A reference worker was told \" is yours to read, not to change. Everything you make goes in , your own folder. In your report, say where in that folder the results are.\" only when its ground held the home folder (taskCopy.readsHome, withHomeReadingNote); over any other ground it was told nothing. Every reference worker whose folder is not its ground is now told \" is yours to read, not to change. Everything you make goes in , your own folder, and stays there: nothing you make reaches . In your report, say where in that folder the results are, and never say the work is in .\" (taskReadsNote; the field is taskCopy.reads, and the run's helper is withTaskReadsNote)." - - "A run that only read its ground was handed to the engine's landing, which failed in its folder with \"fatal: not a git repository\": a plan note \"the run's landing failed\" was filed, the landing had no line (RunLanding.Line empty, no branch) and the run's page got no homecoming note. Such a run is no longer handed to the engine's landing (landReferenceRun): its landing line reads \"it changed nothing in : what it made is in \" (referenceLandingLine), and its page carries that line once, in the run's outcome note, with no separate homecoming note. A reference run that failed is given the same line; one that was stopped is given none. A reference run recovered after the process ended between its plan finishing and its landing still waits for the person to accept it (completedRunReview); accepting it took the git landing in its folder and failed with the same error, and it now takes this landing and line instead (acceptCompletedRun). A recovered run whose plan had already failed is settled with its failure alone, without the line." - - "A reference whose proposal asked for `where: \"in place\"` inside a repository had the redirect \"in place was asked for, and is a repository — the work goes on a branch cut from it instead\" printed on its receipt. The stand still carries that redirect, and the receipt of a reference no longer prints it (taskStandRedirect)." - - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode). A hand-off that joined a run which only reads its ground, the home folder apart, is not given the starting task's sentence or \"It joined the work already underway and shares its copy.\": its receipt reads \"It joined the work already underway, which only reads and writes in a folder of its own, so nothing in changes while it is part of that run. To change , propose the work once that run has ended.\" (taskJoinedReadsSentence), whatever files its own proposal named." - - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." ---- - -A proposal that named a repository as its ground and no file by path was read as -work that only reads it. The worker built the project in its own folder, reported -it integrated, and the conversation told the person to run it from a repository -nothing had been written to. From 10158547fa2f73767f1b52a4f846abd58df45070 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:27:40 -0500 Subject: [PATCH 23/37] app: a listed model says where it falls short of what the app asks An Ollama model's row in models.list carried no window, so a model the server runs with 4,096 tokens looked like any other and the desktop app had nothing to warn about. A row may now carry limits (appwire.ModelLimit): small_window, with the window the server gives the model, how that is known (loaded, modelfile or default), what the app's prompts need and the most the model can hold; and no_tools, when the server's capability list lacks tools. The engine reports the facts and the app words them. The facts come from the Ollama service's own API (/api/ps and /api/show), asked by internal/ollamalimits on each models.list: 300 ms a question, 600 ms in all, inside the list's three seconds, and silence on any error. No other provider is asked, and the checks that read the list for a person's pick read the rows without the questions (offeredModels). A turn that ends on an Ollama model last listed on the server's default window emits models.changed once, since the server can then say the window it gave. The engine's 128,000 fallback, prompt choice and compaction are untouched. Co-Authored-By: Claude Fable 5.2 --- cmd/codeaf/app.go | 35 +- cmd/codeaf/apperrand.go | 4 +- cmd/codeaf/appfactory_ai_search.go | 2 +- cmd/codeaf/appfactory_job_step_edit.go | 2 +- cmd/codeaf/appmodellimits.go | 106 ++++++ cmd/codeaf/appmodellimits_test.go | 173 +++++++++ cmd/codeaf/appmodelsnotice.go | 1 + cmd/codeaf/apptaskmodels.go | 2 +- .../unreleased/2897-crew-handoff-outcome.md | 1 + docs/design/app-v3/PROTOCOL.md | 29 ++ internal/appwire/model_facts_test.go | 35 ++ internal/appwire/wire.go | 31 ++ internal/ollamalimits/ollamalimits.go | 279 ++++++++++++++ internal/ollamalimits/ollamalimits_test.go | 346 ++++++++++++++++++ internal/session/promptprofile.go | 6 + 15 files changed, 1043 insertions(+), 9 deletions(-) create mode 100644 cmd/codeaf/appmodellimits.go create mode 100644 cmd/codeaf/appmodellimits_test.go create mode 100644 internal/ollamalimits/ollamalimits.go create mode 100644 internal/ollamalimits/ollamalimits_test.go diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index a82e0e3906..463ffc1404 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -681,7 +681,7 @@ type appBackend struct { emit appwire.Emitter open appOpener // listModels answers models.list for checks that must agree with it (a - // factory step's model); nil is [appBackend.ListModels]. Tests set it. + // factory step's model); nil is [appBackend.offeredModels]. Tests set it. listModels func() ([]appwire.Model, error) now func() time.Time // after is the claim-expiry clock, replaceable without sleeping in tests. @@ -796,6 +796,11 @@ type appBackend struct { // stopModelNotices removes the model completion subscription and joins // the initial catalog waiter and cancellable sender when this app closes. stopModelNotices func() + // tellModels says models.changed through that subscription's queue, and + // ollamaUnloaded is the models the last list reported on the server's + // default window ([appBackend.addModelLimits]). + tellModels func() + ollamaUnloaded map[string]bool // state is the app's own file: setup, its settings, budgets and raises. state *appState // dayAuth is the daily limit's one-time hand-over from this file's old cap. @@ -3215,6 +3220,7 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n b.resetCloseAfterReply(id) } live.box.Event(appwire.EventTurnDone, appwire.TurnDone{Agent: id, Turn: turn, OK: ok, Error: failure, ErrorKind: kind, Status: status}) + b.modelLoadedBy(live.conn.Conv.Model()) held := false var view appwire.Agent b.locked(func() { @@ -4494,12 +4500,33 @@ const appModelsWait = 3 * time.Second // Connected is the rule providers.list answers signed_in by // ([appBackend.providerConnected]), so the two never disagree. func (b *appBackend) ListModels() ([]appwire.Model, error) { + // What a local server says about its models is asked inside the list's + // own wait, so a list that spent the wait on a catalog asks nothing. + until := time.Now().Add(appModelsWait) + models, sources, err := b.modelRows() + if err != nil { + return nil, err + } + b.addModelLimits(until, models, sources) + return models, nil +} + +// offeredModels is [appBackend.ListModels] for a check on what a person +// picked: the same rows, without the limits, which no check reads and which +// cost a question to a local server. +func (b *appBackend) offeredModels() ([]appwire.Model, error) { + models, _, err := b.modelRows() + return models, err +} + +// modelRows is the rows of models.list and the services they were read from. +func (b *appBackend) modelRows() ([]appwire.Model, modelsource.Set, error) { if !b.providerConnected() { - return []appwire.Model{}, nil + return []appwire.Model{}, modelsource.Set{}, nil } proc, err := b.process() if err != nil { - return nil, appEngineError(err) + return nil, modelsource.Set{}, appEngineError(err) } // THE DEFAULT SERVICE'S CATALOG IS WAITED FOR EVEN WHEN ANOTHER SERVICE HAS // ANSWERED: a list read before it lands is every other service's models @@ -4605,7 +4632,7 @@ func (b *appBackend) ListModels() ([]appwire.Model, error) { models[i].Provider = id } } - return models, nil + return models, sources, nil } // appDefaultModel is the model a new conversation runs on, by the rule every diff --git a/cmd/codeaf/apperrand.go b/cmd/codeaf/apperrand.go index 948380142c..f25d92632b 100644 --- a/cmd/codeaf/apperrand.go +++ b/cmd/codeaf/apperrand.go @@ -74,7 +74,7 @@ func (b *appBackend) Errand(ctx context.Context, id string, ask session.ErrandAs // errandModelServed refuses a model no connected provider offers, by the // same list models.list answers: the engine's existing model policy. func (b *appBackend) errandModelServed(model string) error { - models, err := b.ListModels() + models, err := b.offeredModels() if err != nil { return err } @@ -88,7 +88,7 @@ func (b *appBackend) errandModelServed(model string) error { // the real configuration: the held agent's own routes when one is named, else // the profile's with the default model as floor. func (b *appBackend) ErrandModels(p appwire.ErrandModelsParams) (appwire.ErrandModels, error) { - listed, err := b.ListModels() + listed, err := b.offeredModels() if err != nil { return appwire.ErrandModels{}, err } diff --git a/cmd/codeaf/appfactory_ai_search.go b/cmd/codeaf/appfactory_ai_search.go index 47bfb6f678..c4afefb964 100644 --- a/cmd/codeaf/appfactory_ai_search.go +++ b/cmd/codeaf/appfactory_ai_search.go @@ -129,7 +129,7 @@ func (r *appAISearchRuns) cache(dir, connection string) *aisearch.Cache { } func (b *appBackend) aiSearchPrice(model string) *aisearch.Price { - models, err := b.ListModels() + models, err := b.offeredModels() if err != nil { return nil } diff --git a/cmd/codeaf/appfactory_job_step_edit.go b/cmd/codeaf/appfactory_job_step_edit.go index edff14707e..c945720969 100644 --- a/cmd/codeaf/appfactory_job_step_edit.go +++ b/cmd/codeaf/appfactory_job_step_edit.go @@ -126,7 +126,7 @@ func (b *appBackend) offeredStepModels(picks map[string]string) (map[string]stri if len(picks) == 0 { return nil, nil } - list := b.ListModels + list := b.offeredModels if b.listModels != nil { list = b.listModels } diff --git a/cmd/codeaf/appmodellimits.go b/cmd/codeaf/appmodellimits.go new file mode 100644 index 0000000000..13c104f448 --- /dev/null +++ b/cmd/codeaf/appmodellimits.go @@ -0,0 +1,106 @@ +package main + +import ( + "context" + "net/http" + "strings" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/modelsource" + "github.com/Agent-Field/codeaf/internal/ollamalimits" + "github.com/Agent-Field/codeaf/internal/roles" + "github.com/Agent-Field/codeaf/internal/session" +) + +// addModelLimits writes onto each row what its own server says it falls short +// in ([appwire.ModelLimit]), asking no later than until. +// +// It also remembers which models were reported on the server's default window, +// the one answer the server could not put a figure to. Such a model's real +// window is known once a turn has loaded it, so the turn's end asks the app to +// list again ([appBackend.modelLoadedBy]). +func (b *appBackend) addModelLimits(until time.Time, models []appwire.Model, sources modelsource.Set) { + ctx, cancel := context.WithDeadline(context.Background(), until) + defer cancel() + unloaded := appOllamaLimits(ctx, models, sources, nil) + b.locked(func() { b.ollamaUnloaded = unloaded }) +} + +// appOllamaLimits fills the limits of the rows an Ollama service serves and +// answers the models, by the name the server knows them by, that it reported +// on the server's default window. client is the test's door; nil is the +// probe's own. +// +// ONLY A CONNECTED OLLAMA IS ASKED, AND ONLY ABOUT ITS OWN MODELS. The +// questions are that server's own API: another provider's address would answer +// them with an error at best, and a model another service serves is not this +// server's to describe even when both happen to list the same name. +func appOllamaLimits(ctx context.Context, models []appwire.Model, sources modelsource.Set, client *http.Client) map[string]bool { + service, connected := sources.ByID(ollamalimits.SourceID) + if !connected || !service.HasCredentials() { + return nil + } + probe, ok := ollamalimits.At(service.Address, service.Key) + if !ok { + return nil + } + probe.Client = client + rows := map[string][]int{} + var names []string + for i, model := range models { + owner, bare := sources.For(model.ID) + if !strings.EqualFold(owner.Source.ID, ollamalimits.SourceID) || bare == "" { + continue + } + if rows[bare] == nil { + names = append(names, bare) + } + rows[bare] = append(rows[bare], i) + } + var unloaded map[string]bool + for name, limits := range probe.Limits(ctx, names, session.LeanWindow()) { + for _, i := range rows[name] { + models[i].Limits = limits + } + if limits[0].Kind == appwire.LimitSmallWindow && limits[0].Source == appwire.WindowDefault { + if unloaded == nil { + unloaded = map[string]bool{} + } + unloaded[name] = true + } + } + return unloaded +} + +// modelLoadedBy is called when a turn on model has ended. A turn on an Ollama +// model the last list could put no window to has loaded it, so the server can +// now say what it gave the model: the app is told the models changed, once, +// and its next list reads the real figure. +func (b *appBackend) modelLoadedBy(model string) { + if proc := openedEngineProcess(); proc != nil { + _, sources := proc.currentAccount() + b.ollamaLoaded(sources, model) + } +} + +// ollamaLoaded is [appBackend.modelLoadedBy] over the services given. It is +// said once for a model and not at every turn's end: the list the notice asks +// for forgets the model unless the server still has no figure for it. +func (b *appBackend) ollamaLoaded(sources modelsource.Set, model string) { + model, _ = roles.SplitEffort(model) + owner, bare := sources.For(model) + if !strings.EqualFold(owner.Source.ID, ollamalimits.SourceID) { + return + } + var tell func() + b.locked(func() { + if b.ollamaUnloaded[bare] { + delete(b.ollamaUnloaded, bare) + tell = b.tellModels + } + }) + if tell != nil { + tell() + } +} diff --git a/cmd/codeaf/appmodellimits_test.go b/cmd/codeaf/appmodellimits_test.go new file mode 100644 index 0000000000..229095bce1 --- /dev/null +++ b/cmd/codeaf/appmodellimits_test.go @@ -0,0 +1,173 @@ +package main + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "sync" + "testing" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/modelsource" + "github.com/Agent-Field/codeaf/internal/session" +) + +// appOllamaStub is an Ollama whose every model takes no tools and sets no +// window, with nothing loaded. It records which models it was asked about. +type appOllamaStub struct { + *httptest.Server + mu sync.Mutex + hits int + asked []string +} + +func newAppOllamaStub(t *testing.T) *appOllamaStub { + t.Helper() + stub := &appOllamaStub{} + stub.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var ask struct { + Model string `json:"model"` + } + _ = json.Unmarshal(body, &ask) + stub.mu.Lock() + stub.hits++ + if ask.Model != "" { + stub.asked = append(stub.asked, ask.Model) + } + stub.mu.Unlock() + if r.URL.Path == "/api/ps" { + io.WriteString(w, `{"models":[]}`) + return + } + io.WriteString(w, `{"capabilities":["completion"],"model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`) + })) + t.Cleanup(stub.Close) + return stub +} + +// appVendoredSource is the source table's row for id. +func appVendoredSource(t *testing.T, id string) modelsource.Source { + t.Helper() + for _, source := range modelsource.Vendored() { + if source.ID == id { + return source + } + } + t.Fatalf("no vendored source %q", id) + return modelsource.Source{} +} + +// A models.list row of an Ollama service carries what that server says, asked +// at the service's own address; the rows of every other service carry nothing +// and are never asked about, a model of the same name included. +func TestAppOllamaLimitsAreAskedOfTheOllamaServiceAlone(t *testing.T) { + stub := newAppOllamaStub(t) + sources := modelsource.NewSet( + modelsource.Connected{Source: modelsource.DefaultSource(""), Key: "sk-or-test"}, + modelsource.Connected{Source: appVendoredSource(t, "ollama"), Address: stub.URL + "/v1"}, + modelsource.Connected{Source: appVendoredSource(t, "deepseek"), Key: "sk-test"}, + ) + models := []appwire.Model{ + {ID: "qwen/qwen3:8b", Provider: "openrouter"}, + {ID: "ollama/qwen3:8b", Provider: "ollama"}, + {ID: "deepseek/deepseek-chat", Provider: "deepseek"}, + {ID: "ollama/library/gemma3", Provider: "ollama"}, + } + unloaded := appOllamaLimits(context.Background(), models, sources, stub.Client()) + + want := []appwire.ModelLimit{ + {Kind: appwire.LimitSmallWindow, Needs: session.LeanWindow(), Most: 40960, Source: appwire.WindowDefault}, + {Kind: appwire.LimitNoTools}, + } + for i, model := range models { + if owned := model.Provider == "ollama"; owned != slices.Equal(model.Limits, want) || (!owned && model.Limits != nil) { + t.Fatalf("row %d %s: limits = %+v", i, model.ID, model.Limits) + } + } + slices.Sort(stub.asked) + if !slices.Equal(stub.asked, []string{"library/gemma3", "qwen3:8b"}) { + t.Fatalf("the server was asked about %q", stub.asked) + } + if len(unloaded) != 2 || !unloaded["qwen3:8b"] || !unloaded["library/gemma3"] { + t.Fatalf("models on the server's default window = %v", unloaded) + } + + data, err := json.Marshal(models[:2]) + wire := `[{"id":"qwen/qwen3:8b","name":"","provider":"openrouter"},{"id":"ollama/qwen3:8b","name":"","provider":"ollama","limits":[{"kind":"small_window","needs":32000,"most":40960,"source":"default"},{"kind":"no_tools"}]}]` + if err != nil || string(data) != wire { + t.Fatalf("wire = %s %v, want %s", data, err, wire) + } +} + +// With no Ollama service connected nothing is asked of anybody: not of a +// custom endpoint that happens to be an Ollama, and not of a vendor's address. +func TestAppOllamaLimitsAskNothingWithoutAnOllamaService(t *testing.T) { + stub := newAppOllamaStub(t) + custom := appVendoredSource(t, modelsource.CustomID) + custom.Written = "local" + vendor := appVendoredSource(t, "deepseek") + sources := modelsource.NewSet( + modelsource.Connected{Source: custom, Key: "none", Address: stub.URL + "/v1"}, + modelsource.Connected{Source: vendor, Key: "sk-test", Address: stub.URL + "/v1"}, + ) + models := []appwire.Model{{ID: "local/qwen3:8b", Provider: "local"}, {ID: "deepseek/deepseek-chat", Provider: "deepseek"}, {ID: "qwen3:8b", Provider: "local"}} + if unloaded := appOllamaLimits(context.Background(), models, sources, stub.Client()); unloaded != nil { + t.Fatalf("models on a default window = %v", unloaded) + } + for _, model := range models { + if model.Limits != nil { + t.Fatalf("%s: limits = %+v", model.ID, model.Limits) + } + } + if stub.hits != 0 { + t.Fatalf("a server that is not an Ollama service was asked %d questions", stub.hits) + } +} + +// An Ollama service with none of the listed models is not asked either, and a +// server that is not there leaves every row as it was. +func TestAppOllamaLimitsLeaveTheListAloneWhenThereIsNothingToAsk(t *testing.T) { + stub := newAppOllamaStub(t) + ollama := modelsource.Connected{Source: appVendoredSource(t, "ollama"), Address: stub.URL + "/v1"} + sources := modelsource.NewSet(modelsource.Connected{Source: modelsource.DefaultSource(""), Key: "sk-or-test"}, ollama) + models := []appwire.Model{{ID: "qwen/qwen3:8b", Provider: "openrouter"}} + if appOllamaLimits(context.Background(), models, sources, stub.Client()); stub.hits != 0 || models[0].Limits != nil { + t.Fatalf("an Ollama with no listed model was asked %d questions", stub.hits) + } + + stub.Close() + models = []appwire.Model{{ID: "ollama/qwen3:8b", Provider: "ollama"}} + if unloaded := appOllamaLimits(context.Background(), models, sources, nil); unloaded != nil || models[0].Limits != nil { + t.Fatalf("an absent server reported %+v, %v", models[0].Limits, unloaded) + } +} + +// A turn on an Ollama model the last list had no window for tells the app to +// list again, once: the server can say the window now that the model is +// loaded. A turn on any other model, or on a model whose window was already +// known, says nothing. +func TestAppTurnOnAnUnloadedOllamaModelAsksForOneNewList(t *testing.T) { + sources := modelsource.NewSet( + modelsource.Connected{Source: modelsource.DefaultSource(""), Key: "sk-or-test"}, + modelsource.Connected{Source: appVendoredSource(t, "ollama")}, + ) + told := 0 + backend := &appBackend{tellModels: func() { told++ }, ollamaUnloaded: map[string]bool{"qwen3:8b": true}} + for _, model := range []string{"qwen/qwen3:8b", "qwen3:8b", "ollama/gemma3:4b", ""} { + if backend.ollamaLoaded(sources, model); told != 0 { + t.Fatalf("a turn on %q asked for a new list", model) + } + } + backend.ollamaLoaded(sources, "ollama/qwen3:8b:high") + backend.ollamaLoaded(sources, "ollama/qwen3:8b") + if told != 1 { + t.Fatalf("told the app %d times, want once", told) + } + // Before the app's model notices are joined there is nobody to tell. + quiet := &appBackend{ollamaUnloaded: map[string]bool{"qwen3:8b": true}} + quiet.ollamaLoaded(sources, "ollama/qwen3:8b") +} diff --git a/cmd/codeaf/appmodelsnotice.go b/cmd/codeaf/appmodelsnotice.go index e45f66f77d..16e1aeca7c 100644 --- a/cmd/codeaf/appmodelsnotice.go +++ b/cmd/codeaf/appmodelsnotice.go @@ -48,6 +48,7 @@ func (b *appBackend) watchModelCompletions(proc *v3Process) { }) } remove := proc.registerServiceNotice(tell) + b.tellModels = func() { tell("", "") } done := make(chan struct{}) b.stopModelNotices = func() { cancel() diff --git a/cmd/codeaf/apptaskmodels.go b/cmd/codeaf/apptaskmodels.go index dc6fb1dce2..f8dbdbf9e2 100644 --- a/cmd/codeaf/apptaskmodels.go +++ b/cmd/codeaf/apptaskmodels.go @@ -315,7 +315,7 @@ func (b *appBackend) servedModel() func(model, provider string) (string, bool) { return nil } listed := sync.OnceValue(func() []appwire.Model { - models, _ := b.ListModels() + models, _ := b.offeredModels() return models }) return func(model, provider string) (string, bool) { diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index e4fd49adc5..3445ab19ed 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -27,6 +27,7 @@ invalidates: - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode). A hand-off that joined a run which only reads its ground, the home folder apart, is not given the starting task's sentence or \"It joined the work already underway and shares its copy.\": its receipt reads \"It joined the work already underway, which only reads and writes in a folder of its own, so nothing in changes while it is part of that run. To change , propose the work once that run has ended.\" (taskJoinedReadsSentence), whatever files its own proposal named." - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." + - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one that is not loaded and whose Modelfile sets a `num_ctx` under it; `source` `default` carries no `window` and is one that is not loaded and sets none, so the server's default will apply. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`. A server that is absent, slow or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine. A turn ending on an Ollama model last listed with `source` `default` emits `models.changed` once. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 1da345b57a..830b4c462d 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -2903,6 +2903,35 @@ per-million figure, so both prices are absent, from a connected service as from any other. Prices are rounded to a billionth of a dollar per million, so $0.10 goes out as `0.1`. +A `Model` may also carry `limits`, a list of `ModelLimit` saying where the model +falls short of what the app asks of one. The engine reports the facts and the +app words the warning. `limits` is absent when nothing is known against the +model, and today only a model of an Ollama service (provider `ollama`) can carry +one: on each `models.list` the engine asks that server's own API, at the +service's address without its `/v1`, what it runs now (`GET /api/ps`) and what +it says about each of its listed models (`POST /api/show`). Each question waits +at most 300 ms, all of them 600 ms, inside the list's three seconds; a server +that is absent, slow or answers in an unknown shape reports no limit. + +| `kind` | sent when | other fields | +|---|---|---| +| `small_window` | the window the server gives the model is under `needs`, or the server has not said what it will give | `needs`, `source`, and `window` and `most` when known | +| `no_tools` | the server lists the model's capabilities and `tools` is not among them | none | + +`needs` is the window the app's prompts ask for, 32000 tokens (the engine's lean +threshold). `source` says how `window` is known: `loaded` (the server is running +the model with this window), `modelfile` (the model is not loaded and its +Modelfile sets `num_ctx`) or `default` (not loaded and nothing sets it, so the +server's default will apply; `window` is then absent, because the server does +not say what its default is). A `loaded` or `modelfile` window of `needs` or +more is no limit. `most` is the most the model itself can hold, when the server +says. A model the server only forwards to another machine has no +`small_window`. A server that sends no capability list has no `no_tools`. + +When a turn ends on an Ollama model the last `models.list` reported with +`source` `default`, the app emits `models.changed` once: the turn loaded the +model, so the next list reads the window the server really gave it. + ## orders methods | method | params | result | diff --git a/internal/appwire/model_facts_test.go b/internal/appwire/model_facts_test.go index 3dd8b12393..8ffa40f108 100644 --- a/internal/appwire/model_facts_test.go +++ b/internal/appwire/model_facts_test.go @@ -39,3 +39,38 @@ func TestModelFactsWireIsOptionalAndUnknownPriceStaysAbsent(t *testing.T) { t.Fatalf("legacy invented facts: %+v %v", legacy, err) } } + +// A model's limits are optional on the wire, under the names the desktop app +// reads: a model nothing is known against sends no limits at all, a window the +// server has not put a figure to sends no window, and a limit that is not about +// the window sends its kind alone. +func TestModelLimitsWireIsAbsentUnlessTheServerSaidSo(t *testing.T) { + data, err := json.Marshal(Model{ID: "plain"}) + if err != nil || strings.Contains(string(data), "limits") { + t.Fatalf("a model with no limits sent some: %s %v", data, err) + } + limited := Model{ID: "ollama/qwen3:8b", Limits: []ModelLimit{ + {Kind: LimitSmallWindow, Window: 4096, Needs: 32000, Most: 40960, Source: WindowLoaded}, + {Kind: LimitSmallWindow, Window: 8192, Needs: 32000, Source: WindowModelfile}, + {Kind: LimitSmallWindow, Needs: 32000, Most: 40960, Source: WindowDefault}, + {Kind: LimitNoTools}, + }} + data, err = json.Marshal(limited) + want := `"limits":[` + + `{"kind":"small_window","window":4096,"needs":32000,"most":40960,"source":"loaded"},` + + `{"kind":"small_window","window":8192,"needs":32000,"source":"modelfile"},` + + `{"kind":"small_window","needs":32000,"most":40960,"source":"default"},` + + `{"kind":"no_tools"}]` + if err != nil || !strings.Contains(string(data), want) { + t.Fatalf("limits wire = %s %v, want %s", data, err, want) + } + var back Model + if err := json.Unmarshal(data, &back); err != nil || len(back.Limits) != 4 || back.Limits[0] != limited.Limits[0] || back.Limits[3] != limited.Limits[3] { + t.Fatalf("limits lost: %s → %+v %v", data, back.Limits, err) + } + // The schema names the words a kind and a source may be. + schema, err := SchemaJSON() + if err != nil || !strings.Contains(string(schema), `"small_window"`) || !strings.Contains(string(schema), `"modelfile"`) { + t.Fatalf("the schema does not describe a model's limits: %v", err) + } +} diff --git a/internal/appwire/wire.go b/internal/appwire/wire.go index a027c44a0c..ee3bc6e70c 100644 --- a/internal/appwire/wire.go +++ b/internal/appwire/wire.go @@ -722,6 +722,37 @@ type Model struct { ProviderName string `json:"provider_name,omitempty"` // Default marks the model a new conversation runs on. Default bool `json:"default,omitempty"` + // Limits says where this model falls short of what the app asks of a model. Absent when nothing is known to. + Limits []ModelLimit `json:"limits,omitempty"` +} + +// The kinds of [ModelLimit], and the ways a small window's size is known. +const ( + LimitSmallWindow = "small_window" + LimitNoTools = "no_tools" + + WindowLoaded = "loaded" + WindowModelfile = "modelfile" + WindowDefault = "default" +) + +// ModelLimit is one way a model falls short, as its server reports it. +// +// IT IS A FACT AND NEVER A SENTENCE. The engine says what the server answered +// and the app words the warning, so a limit carries figures and no text; and a +// limit is sent only where the server said something, because a warning about +// a model nobody asked about is a guess. +type ModelLimit struct { + // Kind is "small_window" or "no_tools". + Kind string `json:"kind" enum:"small_window,no_tools"` + // Window is the tokens the server gives the model now. Absent (0) when Source is "default": the server has not said. + Window int `json:"window,omitempty"` + // Needs is the window the app's prompts ask for (the lean threshold, 32000). Only with small_window. + Needs int `json:"needs,omitempty"` + // Most is the most the model itself can hold, when the server says. Only with small_window. + Most int `json:"most,omitempty"` + // Source says how Window is known: "loaded" (the server is running it with this window), "modelfile" (its Modelfile sets num_ctx), or "default" (not loaded and nothing sets it, so the server's default will apply). Only with small_window. + Source string `json:"source,omitempty" enum:"loaded,modelfile,default"` } // FeatureAgentEffortRungs announces the terminal's full conversation effort dial. diff --git a/internal/ollamalimits/ollamalimits.go b/internal/ollamalimits/ollamalimits.go new file mode 100644 index 0000000000..8781a43e3b --- /dev/null +++ b/internal/ollamalimits/ollamalimits.go @@ -0,0 +1,279 @@ +// Package ollamalimits asks an Ollama server what it will really give a model, +// so the desktop app can say where a model falls short before a turn finds out. +// +// THE OPENAI-SHAPED LISTING CANNOT ANSWER THIS. Ollama's /v1/models names a +// model and nothing else, and the window a local model runs with is decided by +// the server when it loads the model, not by the model: one that can hold +// forty thousand tokens is commonly given four thousand. Only the server's own +// API says which, so this package is the one caller of it, and it reports +// facts only. Nothing here chooses a prompt or a compaction line. +package ollamalimits + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/providerhttp" +) + +// SourceID is the model source this package asks. No other source is asked: +// the questions are Ollama's own and mean nothing to another server. +const SourceID = "ollama" + +const ( + // Each bounds one question and Whole bounds every question of one list. + // The server is nearly always on this computer and answers in a few + // milliseconds; the bounds are for the one that is not there, so that a + // model list never waits on it for longer than a person would notice. + Each = 300 * time.Millisecond + Whole = 600 * time.Millisecond + + // atOnce is how many models are asked about at the same time. A person may + // keep dozens of models, and each answer is read from that model's file. + atOnce = 8 + + // answerLimit bounds one answer. A model's licence, template and Modelfile + // travel in it, so it is far larger than the few fields read here. + answerLimit = 4 << 20 +) + +// Probe asks one Ollama server. Client is the test's door; nil is a client of +// its own that follows no redirect off the server's origin. +type Probe struct { + base string + key string + Client *http.Client +} + +// At is the probe for the server whose OpenAI-shaped address is given, and +// false when that address names no server: the native API sits beside the /v1 +// the chat path uses, on the same origin, so the key that reaches one reaches +// the other and goes nowhere else. +func At(address, key string) (Probe, bool) { + base := strings.TrimSuffix(strings.TrimRight(strings.TrimSpace(address), "/"), "/v1") + parsed, err := url.Parse(base) + if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") { + return Probe{}, false + } + return Probe{base: base, key: strings.TrimSpace(key)}, true +} + +// shown is what the server says about one model, whether or not it is loaded. +type shown struct { + // ok says the server answered. Every other field is nothing without it. + ok bool + // numCtx is the window the model's Modelfile sets, or 0 when it sets none. + numCtx int + // most is the most the model itself can hold, or 0 when the answer has none. + most int + // capabilities is the server's own list, empty from a server too old to + // send one. + capabilities []string + // remote says the server only forwards this model to another machine, so + // no window of this server's applies to it. + remote bool +} + +// Limits answers where each named model falls short, keyed by the name asked +// with; a model nothing is known against is not in the answer. needs is the +// window the app's prompts ask for. +// +// EVERY FAILURE IS SILENCE. A server that is not running, one that answers +// slowly, an answer in a shape this does not know: each reports nothing for +// the models it concerned, because a limit is shown to a person as a warning +// and a warning nobody measured is worse than none. +func (p Probe) Limits(ctx context.Context, names []string, needs int) map[string][]appwire.ModelLimit { + if len(names) == 0 || ctx.Err() != nil { + return nil + } + ctx, cancel := context.WithTimeout(ctx, Whole) + defer cancel() + var ( + running map[string]int + listed bool + wait sync.WaitGroup + ) + shows := make([]shown, len(names)) + gate := make(chan struct{}, atOnce) + wait.Add(1 + len(names)) + guard.Go("ollamalimits/loaded", func() { + defer wait.Done() + running, listed = p.loaded(ctx) + }) + for i, name := range names { + guard.Go("ollamalimits/show", func() { + defer wait.Done() + select { + case gate <- struct{}{}: + defer func() { <-gate }() + shows[i] = p.show(ctx, name) + case <-ctx.Done(): + } + }) + } + wait.Wait() + limits := map[string][]appwire.ModelLimit{} + for i, name := range names { + var found []appwire.ModelLimit + if limit, small := smallWindow(running[tagged(name)], listed, shows[i], needs); small { + found = append(found, limit) + } + // A SERVER THAT SENDS NO LIST HAS NOT SAID THE MODEL LACKS TOOLS. Older + // servers send none at all, and reading that as "no tools" would warn + // about every model they hold. + if len(shows[i].capabilities) > 0 && !slices.Contains(shows[i].capabilities, "tools") { + found = append(found, appwire.ModelLimit{Kind: appwire.LimitNoTools}) + } + if len(found) > 0 { + limits[name] = found + } + } + return limits +} + +// smallWindow is the model's window limit and whether it has one. A window the +// server is running now is believed over the Modelfile's, which only says what +// the next load would ask for; and a model that is not loaded and sets nothing +// is reported with no figure, because the server's default applies and its API +// does not say what that is. +func smallWindow(loaded int, listed bool, model shown, needs int) (appwire.ModelLimit, bool) { + limit := appwire.ModelLimit{Kind: appwire.LimitSmallWindow, Needs: needs, Most: model.most} + switch { + case !listed: + // Whether it is loaded is not known, so neither is which window counts. + return limit, false + case loaded > 0: + limit.Window, limit.Source = loaded, appwire.WindowLoaded + case !model.ok || model.remote: + return limit, false + case model.numCtx > 0: + limit.Window, limit.Source = model.numCtx, appwire.WindowModelfile + default: + limit.Source = appwire.WindowDefault + return limit, true + } + return limit, limit.Window < needs +} + +// loaded is the window of every model the server is running now, by name, and +// whether the server answered at all. +func (p Probe) loaded(ctx context.Context) (map[string]int, bool) { + var answer struct { + Models *[]struct { + Name string `json:"name"` + Model string `json:"model"` + ContextLength int `json:"context_length"` + } `json:"models"` + } + if !p.ask(ctx, http.MethodGet, "/api/ps", nil, &answer) || answer.Models == nil { + return nil, false + } + running := map[string]int{} + for _, model := range *answer.Models { + // A server from before the field was added sends no window; such a + // model is then read by its Modelfile as though it were not loaded. + if model.ContextLength <= 0 { + continue + } + running[tagged(model.Name)] = model.ContextLength + running[tagged(model.Model)] = model.ContextLength + } + return running, true +} + +// show is what the server says about one model. +func (p Probe) show(ctx context.Context, name string) shown { + var answer struct { + Parameters string `json:"parameters"` + ModelInfo map[string]json.RawMessage `json:"model_info"` + Capabilities []string `json:"capabilities"` + RemoteHost string `json:"remote_host"` + RemoteModel string `json:"remote_model"` + } + body, err := json.Marshal(map[string]string{"model": name}) + if err != nil || !p.ask(ctx, http.MethodPost, "/api/show", body, &answer) { + return shown{} + } + return shown{ + ok: true, + numCtx: numCtx(answer.Parameters), + most: mostOf(answer.ModelInfo), + capabilities: answer.Capabilities, + remote: answer.RemoteHost != "" || answer.RemoteModel != "", + } +} + +// ask sends one question and decodes its answer, and says whether both worked. +func (p Probe) ask(ctx context.Context, method, path string, body []byte, into any) bool { + ctx, cancel := context.WithTimeout(ctx, Each) + defer cancel() + request, err := http.NewRequestWithContext(ctx, method, p.base+path, bytes.NewReader(body)) + if err != nil { + return false + } + if body != nil { + request.Header.Set("Content-Type", "application/json") + } + if p.key != "" { + request.Header.Set("Authorization", "Bearer "+p.key) + } + response, err := providerhttp.Clone(p.Client).Do(request) + if err != nil { + return false + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return false + } + return json.NewDecoder(io.LimitReader(response.Body, answerLimit)).Decode(into) == nil +} + +// numCtx reads the window out of a model's parameters, which the server sends +// as lines of a name and a value, and 0 when no line sets one. +func numCtx(parameters string) int { + for _, line := range strings.Split(parameters, "\n") { + fields := strings.Fields(line) + if len(fields) != 2 || fields[0] != "num_ctx" { + continue + } + if n, err := strconv.Atoi(fields[1]); err == nil && n > 0 { + return n + } + } + return 0 +} + +// mostOf is the most the model can hold. The server files it under the model's +// own architecture ("qwen3.context_length"), so the architecture is read first. +func mostOf(info map[string]json.RawMessage) int { + var architecture string + if json.Unmarshal(info["general.architecture"], &architecture) != nil || architecture == "" { + return 0 + } + var most float64 + if json.Unmarshal(info[architecture+".context_length"], &most) != nil || most < 1 || most > 1<<40 { + return 0 + } + return int(most) +} + +// tagged is a model's name with the tag the server assumes when none is +// written, so "llama3" and "llama3:latest" are the one model they are. +func tagged(name string) string { + name = strings.TrimSpace(name) + if name == "" || strings.Contains(name[strings.LastIndex(name, "/")+1:], ":") { + return name + } + return name + ":latest" +} diff --git a/internal/ollamalimits/ollamalimits_test.go b/internal/ollamalimits/ollamalimits_test.go new file mode 100644 index 0000000000..6f18587c02 --- /dev/null +++ b/internal/ollamalimits/ollamalimits_test.go @@ -0,0 +1,346 @@ +package ollamalimits + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "reflect" + "sync" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" +) + +const needs = 32_000 + +// stubServer is an Ollama that answers from two tables: what it is running and +// what it says about each model. A model with no row is one it does not know. +type stubServer struct { + // ps is the body of /api/ps, and psStatus its status when not 200. + ps string + psStatus int + // show is the body of /api/show by model name. + show map[string]string + // slow holds every answer back for this long. + slow time.Duration + + mu sync.Mutex + asked []string + auth []string +} + +func (s *stubServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // The body is read before anything waits: a server notices that its + // caller gave up only once the request has been read to its end. + sent, _ := io.ReadAll(r.Body) + s.mu.Lock() + s.auth = append(s.auth, r.Header.Get("Authorization")) + s.mu.Unlock() + if s.slow > 0 { + select { + case <-time.After(s.slow): + case <-r.Context().Done(): + return + } + } + switch r.Method + " " + r.URL.Path { + case "GET /api/ps": + if s.psStatus != 0 { + w.WriteHeader(s.psStatus) + return + } + _, _ = w.Write([]byte(s.ps)) + case "POST /api/show": + var ask struct { + Model string `json:"model"` + } + _ = json.Unmarshal(sent, &ask) + s.mu.Lock() + s.asked = append(s.asked, ask.Model) + s.mu.Unlock() + body, known := s.show[ask.Model] + if !known { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write([]byte(body)) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +// limitsFrom asks a stub for the named models the way models.list does. +func limitsFrom(t *testing.T, stub *stubServer, names ...string) map[string][]appwire.ModelLimit { + t.Helper() + server := httptest.NewServer(stub) + t.Cleanup(server.Close) + probe, ok := At(server.URL+"/v1", "") + if !ok { + t.Fatalf("no probe for %s", server.URL) + } + probe.Client = server.Client() + return probe.Limits(context.Background(), names, needs) +} + +const ( + nothingRunning = `{"models":[]}` + // plainModel is a model that takes tools, can hold 40960 tokens and whose + // Modelfile sets no window. + plainModel = `{"capabilities":["completion","tools","thinking"],"parameters":"temperature 0.6\nstop \"<|im_end|>\"","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}` +) + +// The window the server is running a model with is the one a turn gets, so it +// is reported over whatever the Modelfile asks for. +func TestALoadedWindowIsBelievedOverTheModelfile(t *testing.T) { + stub := &stubServer{ + ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096}]}`, + show: map[string]string{"qwen3:8b": `{"capabilities":["completion","tools"],"parameters":"num_ctx 65536","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`}, + } + got := limitsFrom(t, stub, "qwen3:8b") + want := map[string][]appwire.ModelLimit{"qwen3:8b": {{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowLoaded}}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("limits = %+v, want %+v", got, want) + } +} + +// A model loaded with room enough has no window limit, however small its +// Modelfile's own figure is. +func TestALoadedWindowLargeEnoughReportsNothing(t *testing.T) { + stub := &stubServer{ + ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":32000}]}`, + show: map[string]string{"qwen3:8b": `{"capabilities":["completion","tools"],"parameters":"num_ctx 2048"}`}, + } + if got := limitsFrom(t, stub, "qwen3:8b"); len(got) != 0 { + t.Fatalf("limits = %+v, want none", got) + } +} + +// The server names a running model with its tag, and a model listed without +// one is the same model. +func TestALoadedModelIsFoundWithoutItsTag(t *testing.T) { + stub := &stubServer{ + ps: `{"models":[{"name":"llama3:latest","model":"llama3:latest","context_length":8192}]}`, + show: map[string]string{"llama3": plainModel}, + } + got := limitsFrom(t, stub, "llama3")["llama3"] + if len(got) != 1 || got[0].Source != appwire.WindowLoaded || got[0].Window != 8192 { + t.Fatalf("limits = %+v, want the loaded window", got) + } +} + +// A model that is not loaded is read by its Modelfile: a small num_ctx is the +// window its next load asks for, and a large one is no limit. +func TestAModelfileWindowIsReportedOnlyWhenSmall(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{ + "small": `{"capabilities":["completion","tools"],"parameters":"temperature 0.6\nnum_ctx 8192\nstop \"x\"","model_info":{"general.architecture":"llama","llama.context_length":131072}}`, + "large": `{"capabilities":["completion","tools"],"parameters":"num_ctx 65536"}`, + }} + got := limitsFrom(t, stub, "small", "large") + want := map[string][]appwire.ModelLimit{"small": {{Kind: appwire.LimitSmallWindow, Window: 8192, Needs: needs, Most: 131072, Source: appwire.WindowModelfile}}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("limits = %+v, want %+v", got, want) + } +} + +// Not loaded and nothing set: the server's default applies and the API does +// not say what it is, so the limit is reported with no window. +func TestAnUnsetWindowIsReportedAsTheServersDefault(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{"qwen3:8b": plainModel}} + got := limitsFrom(t, stub, "qwen3:8b") + want := map[string][]appwire.ModelLimit{"qwen3:8b": {{Kind: appwire.LimitSmallWindow, Needs: needs, Most: 40960, Source: appwire.WindowDefault}}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("limits = %+v, want %+v", got, want) + } +} + +// A server that runs a model from before it reported windows says the model is +// loaded and not with what, so the model is read as though it were not. +func TestALoadedModelWithNoWindowIsReadByItsModelfile(t *testing.T) { + stub := &stubServer{ + ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b"}]}`, + show: map[string]string{"qwen3:8b": `{"parameters":"num_ctx 4096"}`}, + } + got := limitsFrom(t, stub, "qwen3:8b")["qwen3:8b"] + if len(got) != 1 || got[0].Source != appwire.WindowModelfile || got[0].Window != 4096 { + t.Fatalf("limits = %+v, want the Modelfile's window", got) + } +} + +// A model the server only forwards to another machine runs with no window of +// this server's, so the server's default is not reported for it. +func TestAForwardedModelHasNoWindowOfThisServers(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{ + "big:cloud": `{"capabilities":["completion","tools"],"remote_model":"big","remote_host":"https://ollama.com:443"}`, + }} + if got := limitsFrom(t, stub, "big:cloud"); len(got) != 0 { + t.Fatalf("limits = %+v, want none", got) + } +} + +// A capability list without tools is the server saying the model takes none. A +// list with tools, and a server that sends no list, say no such thing. +func TestNoToolsIsReportedOnlyWhenTheServerListsCapabilitiesWithoutIt(t *testing.T) { + loaded := `{"models":[{"name":"chat","context_length":64000},{"name":"tools","context_length":64000},{"name":"old","context_length":64000},{"name":"empty","context_length":64000}]}` + stub := &stubServer{ps: loaded, show: map[string]string{ + "chat": `{"capabilities":["completion","vision"]}`, + "tools": `{"capabilities":["completion","tools"]}`, + "old": `{"parameters":""}`, + "empty": `{"capabilities":[]}`, + }} + got := limitsFrom(t, stub, "chat", "tools", "old", "empty") + want := map[string][]appwire.ModelLimit{"chat": {{Kind: appwire.LimitNoTools}}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("limits = %+v, want %+v", got, want) + } +} + +// Both limits are one model's, the window first. +func TestAModelMayHaveBothLimits(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{"tiny": `{"capabilities":["completion"],"parameters":"num_ctx 2048"}`}} + got := limitsFrom(t, stub, "tiny")["tiny"] + if len(got) != 2 || got[0].Kind != appwire.LimitSmallWindow || got[1].Kind != appwire.LimitNoTools { + t.Fatalf("limits = %+v, want a small window then no tools", got) + } +} + +// Without the list of running models nobody knows which window counts, so no +// window is reported; what the model itself says about tools still is. +func TestAFailedRunningListReportsNoWindow(t *testing.T) { + for _, stub := range []*stubServer{ + {psStatus: http.StatusInternalServerError}, + {ps: `not json`}, + {ps: `{"unrelated":true}`}, + } { + stub.show = map[string]string{"plain": plainModel, "chat": `{"capabilities":["completion"]}`} + got := limitsFrom(t, stub, "plain", "chat") + want := map[string][]appwire.ModelLimit{"chat": {{Kind: appwire.LimitNoTools}}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("ps %q/%d: limits = %+v, want %+v", stub.ps, stub.psStatus, got, want) + } + } +} + +// A model the server will not describe, or describes in a shape nobody knows, +// has no limit: an error is never a warning. +func TestAFailedOrOddAnswerReportsNothingForThatModel(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{ + "garbled": `{"capabilities":`, + "shapes": `{"capabilities":"tools","parameters":7}`, + "plain": plainModel, + }} + got := limitsFrom(t, stub, "unknown", "garbled", "shapes", "plain") + if len(got) != 1 || len(got["plain"]) != 1 { + t.Fatalf("limits = %+v, want only the model that answered", got) + } +} + +// What a model can hold is filed under its architecture; an answer without +// either still reports the window, with no most. +func TestMostIsAbsentWhenTheServerDoesNotSayIt(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{ + "bare": `{"capabilities":["tools"],"model_info":{"general.architecture":"llama"}}`, + "words": `{"capabilities":["tools"],"model_info":{"general.architecture":"llama","llama.context_length":"many"}}`, + }} + for name, limits := range limitsFrom(t, stub, "bare", "words") { + if len(limits) != 1 || limits[0].Most != 0 || limits[0].Source != appwire.WindowDefault { + t.Fatalf("%s: limits = %+v, want the default window with no most", name, limits) + } + } +} + +// A server that does not answer in time costs the list its bound and reports +// nothing, and a list that has no time left asks nothing. +func TestASlowServerReportsNothingWithinTheBound(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{"qwen3:8b": plainModel}, slow: 5 * time.Second} + began := time.Now() + got := limitsFrom(t, stub, "qwen3:8b") + if took := time.Since(began); len(got) != 0 || took > Whole+time.Second { + t.Fatalf("limits = %+v after %s, want none within %s", got, took, Whole) + } + + quick := &stubServer{ps: nothingRunning, show: map[string]string{"qwen3:8b": plainModel}} + server := httptest.NewServer(quick) + defer server.Close() + probe, _ := At(server.URL+"/v1", "") + spent, cancel := context.WithCancel(context.Background()) + cancel() + if got := probe.Limits(spent, []string{"qwen3:8b"}, needs); len(got) != 0 || len(quick.auth) != 0 { + t.Fatalf("a spent list asked %d questions and reported %+v", len(quick.auth), got) + } +} + +// Many models are asked about a few at a time and every one is answered. +func TestEveryModelOfALongListIsAnswered(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{}} + var names []string + for i := range 40 { + name := "model-" + string(rune('a'+i%26)) + string(rune('a'+i/26)) + names = append(names, name) + stub.show[name] = plainModel + } + if got := limitsFrom(t, stub, names...); len(got) != len(names) { + t.Fatalf("%d of %d models answered", len(got), len(names)) + } +} + +// A server that is not there reports nothing. +func TestAnAbsentServerReportsNothing(t *testing.T) { + server := httptest.NewServer(http.NotFoundHandler()) + address := server.URL + "/v1" + server.Close() + probe, ok := At(address, "") + if !ok { + t.Fatal("no probe for a closed server's address") + } + if got := probe.Limits(context.Background(), []string{"qwen3:8b"}, needs); len(got) != 0 { + t.Fatalf("limits = %+v, want none", got) + } +} + +// The native API is beside the /v1 the chat path uses. An address that names +// no server has no probe, and the key travels only when there is one. +func TestTheProbeIsBesideTheChatAddress(t *testing.T) { + for address, base := range map[string]string{ + "http://localhost:11434/v1": "http://localhost:11434", + "http://localhost:11434/v1/": "http://localhost:11434", + "https://box.example/ollama": "https://box.example/ollama", + " http://10.0.0.5:11434/v1 ": "http://10.0.0.5:11434", + } { + if probe, ok := At(address, ""); !ok || probe.base != base { + t.Fatalf("At(%q) = %q %v, want %q", address, probe.base, ok, base) + } + } + for _, address := range []string{"", "localhost:11434", "ftp://localhost/v1", "http:///v1"} { + if _, ok := At(address, ""); ok { + t.Fatalf("At(%q) made a probe", address) + } + } + + stub := &stubServer{ps: nothingRunning, show: map[string]string{"qwen3:8b": plainModel}} + server := httptest.NewServer(stub) + defer server.Close() + probe, _ := At(server.URL+"/v1", " secret ") + probe.Limits(context.Background(), []string{"qwen3:8b"}, needs) + if len(stub.auth) != 2 || stub.auth[0] != "Bearer secret" || stub.auth[1] != "Bearer secret" { + t.Fatalf("authorization sent = %q", stub.auth) + } + stub.auth = nil + probe, _ = At(server.URL+"/v1", "") + probe.Limits(context.Background(), []string{"qwen3:8b"}, needs) + if len(stub.auth) != 2 || stub.auth[0] != "" || stub.auth[1] != "" { + t.Fatalf("a keyless probe sent authorization %q", stub.auth) + } +} + +// The wire's field names are the contract the desktop app reads. +func TestTheLimitsTravelUnderTheirWireNames(t *testing.T) { + stub := &stubServer{ps: nothingRunning, show: map[string]string{"tiny": `{"capabilities":["completion"],"parameters":"num_ctx 2048","model_info":{"general.architecture":"llama","llama.context_length":8192}}`}} + data, err := json.Marshal(limitsFrom(t, stub, "tiny")["tiny"]) + want := `[{"kind":"small_window","window":2048,"needs":32000,"most":8192,"source":"modelfile"},{"kind":"no_tools"}]` + if err != nil || string(data) != want { + t.Fatalf("wire = %s %v, want %s", data, err, want) + } +} diff --git a/internal/session/promptprofile.go b/internal/session/promptprofile.go index 4751b86a0e..06028ef61f 100644 --- a/internal/session/promptprofile.go +++ b/internal/session/promptprofile.go @@ -544,6 +544,12 @@ func (c Config) instructionLimit() int { // than a named file, so a project that has only CLAUDE.md still gets its rules. func (c Config) onlyOneInstructionFile() bool { return c.promptProfile().lean() } +// LeanWindow is [leanWindowThreshold] for a caller outside this package: the +// window under which a model is given the lean prefix, in tokens. The desktop +// app's model list says which models fall under it, and it reads the line here +// so the warning and the prefix cannot come to disagree. +func LeanWindow() int { return leanWindowThreshold } + // takesNoTools says the catalog knows this model and says it takes no tool // calls — the same test internal/provider's toolless.go leaves the tools off // by. Unknown is false: a model nobody has described keeps the working page. From f08017e0d64159e70bc80ea2dbef7f27eff042a2 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:42:30 -0500 Subject: [PATCH 24/37] teams: one decision and one writer for the traffic watch's wakes The team's rules about starting a turn nobody typed were applied once per caller, and each caller wrote its own traffic line. The traffic watch's two wakes now ask one table of rules (team_wakedecide.go) and say the answer through one writer, and the engine's gate and the reason it gives are one function (wakeRefusalLocked) instead of a gate and a ladder that re-guessed it. No behaviour change: every line is written as before. Co-Authored-By: Claude Fable 5.2 --- internal/session/agent.go | 106 +++++++++-- internal/session/team_wakedecide.go | 265 ++++++++++++++++++++++++++++ internal/session/team_wakewatch.go | 223 ++++++----------------- 3 files changed, 408 insertions(+), 186 deletions(-) create mode 100644 internal/session/team_wakedecide.go diff --git a/internal/session/agent.go b/internal/session/agent.go index 79bdfcfbb6..6a9a16e854 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -4785,7 +4785,12 @@ func (a *Agent) wakeLocked() bool { return a.wakeAnsweringLocked(false, "", fals // whether what it just drained was a line THE PERSON TYPED: the woken turn's // opening then says so ([userMessage.answersPerson]). func (a *Agent) wakeAnsweringLocked(answersPerson bool, answersMessage string, answer bool) bool { - if why := a.automaticFactoryRefusal(); !answersPerson && !answer && why != "" { + switch gate, _ := a.wakeRefusalLocked(answersPerson, answer); gate { + case wakeGateOpen: + case wakeGateFactory: + // Automatic work a stopped job refuses is not kept for the person's + // next question to carry: they may still ask its manager something + // without granting it the work (factory_person_stop.go). kept := a.steering[:0] for _, note := range a.steering { if !note.wake { @@ -4794,23 +4799,7 @@ func (a *Agent) wakeAnsweringLocked(answersPerson bool, answersMessage string, a } a.steering = kept return false - } - if !answer { - if err := a.CheckWork(); err != nil { - return false - } - } - // A WALL THAT HAS PASSED BUYS NO TURN NOBODY ASKED FOR. This is arithmetic - // on the Steward's own clock rather than a stopped flag: a stopped flag is a - // different decision in [Steward.Decide], while the wall's budget ending is - // the one stop allowed to win over work still moving. [wallIsUp] reads the - // Steward's own wall and clock without asking its spend closure while this - // function holds a.mu. - wallGone := wallIsUp(a.steward()) - if a.stageSettled || a.running || a.closed || a.workStopped || wallGone || (a.config.InTask && !a.config.roomThread) || !a.opened { - return false - } - if err := a.railBlockLocked(); err != nil { + default: return false } @@ -4861,6 +4850,87 @@ func (a *Agent) wakeAnsweringLocked(answersPerson bool, answersMessage string, a return true } +// wakeGate is which of the engine's own gates refuses a turn nobody typed. +type wakeGate int + +const ( + // wakeGateOpen is no gate refusing: the turn may start. + wakeGateOpen wakeGate = iota + // wakeGateFactory is a factory job refusing automatic work. + wakeGateFactory + // wakeGateSeat is a seat that may not work now ([Agent.CheckWork]). + wakeGateSeat + // wakeGateClosed is a closed session, whose queue nothing drains again. + wakeGateClosed + // wakeGateRunning is a turn in flight: the news is steering, not a second + // turn. + wakeGateRunning + // wakeGateStopped is work the person stopped. + wakeGateStopped + // wakeGateWall is a time limit that has passed. + wakeGateWall + // wakeGateElsewhere is a conversation whose turns are somebody else's to + // start: a task node's runner, a settled stage, one not open yet. + wakeGateElsewhere + // wakeGateRail is the spending limit. + wakeGateRail +) + +// wakeRefusalLocked is the gate a turn nobody typed stops at, and why in the +// words a team's traffic gives its manager; [wakeGateOpen] and "" when it may +// start. A turn in flight has no reason: it is not a refusal, the news rides +// that turn. The caller holds a.mu. +// +// THE GATE AND ITS REASON ARE ONE PIECE OF CODE. They were two: the wake +// refused in one condition, and the team's wake then worked out afterwards +// which part of it must have refused, in an order of its own +// (team_wakewatch.go's ladder). A gate added to one was not added to the +// other, and the traffic named a reason the gate had not used. Now the wake +// asks here and the traffic says what this answered. +// +// ── WHAT REFUSES ── +// +// - a factory job refusing automatic work, unless the turn answers the +// person or a question (factory_person_stop.go). +// - a seat that may not work now, unless the turn answers a question. +// - the session is closed: nothing drains after Close. +// - a turn is already running. +// - the person stopped the work. +// - A WALL THAT HAS PASSED BUYS NO TURN NOBODY ASKED FOR. This is arithmetic +// on the Steward's own clock rather than a stopped flag: a stopped flag is +// a different decision in [Steward.Decide], while the wall's budget ending +// is the one stop allowed to win over work still moving. [wallIsUp] reads +// the Steward's own wall and clock without asking its spend closure while +// this function holds a.mu. +// - the turns are somebody else's to start ([Agent.wakeLocked] says whose). +// - the spend rail, asked last because it is the one gate that reads. +func (a *Agent) wakeRefusalLocked(answersPerson, answer bool) (wakeGate, string) { + if why := a.automaticFactoryRefusal(); !answersPerson && !answer && why != "" { + return wakeGateFactory, why + } + if !answer { + if err := a.CheckWork(); err != nil { + return wakeGateSeat, err.Error() + } + } + switch { + case a.closed: + return wakeGateClosed, "its conversation has closed" + case a.running: + return wakeGateRunning, "" + case a.workStopped: + return wakeGateStopped, "its work was stopped; it reads this at its next turn" + case wallIsUp(a.steward()): + return wakeGateWall, "its time limit has passed; it reads this at its next turn" + case a.stageSettled || (a.config.InTask && !a.config.roomThread) || !a.opened: + return wakeGateElsewhere, "it cannot start a turn on its own here; it reads this at its next turn" + } + if err := a.railBlockLocked(); err != nil { + return wakeGateRail, "its spending limit is reached; it reads this at its next turn" + } + return wakeGateOpen, "" +} + // wokenTurnContext is what a turn nobody submitted starts under: the plain // background, unless a fixture supplied a base ([Agent.wokenTurnBase]). func (a *Agent) wokenTurnContext() context.Context { diff --git a/internal/session/team_wakedecide.go b/internal/session/team_wakedecide.go new file mode 100644 index 0000000000..0c13b06300 --- /dev/null +++ b/internal/session/team_wakedecide.go @@ -0,0 +1,265 @@ +package session + +// ── ONE WAKE PATH: ONE DECISION, ONE LINE ─────────────────────────────────── +// +// A turn nobody typed is started by several things: a manager's directive, a +// team's replies, a member's own start, a command or a watch ending, a task +// landing, news that arrived as a turn ended. Every one of them starts the turn +// through the same door ([Agent.wakeAnsweringLocked]), and the team's rules +// about whether it may were written above that door once per caller. They +// disagreed. The traffic watch read the pause before it started anything and a +// command's ending did not; the watch handed a directive over and then found +// the turn refused; a fresh member held at the cap said nothing where the watch +// said why; and each caller wrote its own line, so `woke` was written for a +// turn that had been running all along. +// +// SO ONE FUNCTION DECIDES AND ONE WRITES. A caller says what is asking for the +// turn (a [wakeCause]); [Agent.decideWake] answers start, queue, hold or +// nothing (a [wakeDecision]) from one table of which rule binds which cause; +// and [Agent.sayWake] is the only place a wake's line is written to a team's +// traffic. A rule added for one cause is a row in the table, read by all. +// +// THE DECISION COMES IN TWO HALVES BECAUSE THE LOCKS DO. The team's rules read +// the teams file, the hour's wakes and the ledger, under the seat's lock and +// off the agent's ([wakeRules]). The engine's gates are the agent's own state +// and are read under a.mu ([Agent.decideWakeLocked]), where the turn is then +// started in the same hold, so the answer is the wake's own. + +import ( + "fmt" + "time" + + "github.com/Agent-Field/codeaf/internal/teams" +) + +// wakeKind is what is asking for a turn nobody typed. +type wakeKind int + +const ( + // wakeDirective is a member's manager: a directive, the answer to its + // question, or the lines a pause held, found again when it is lifted. + wakeDirective wakeKind = iota + 1 + // wakeReplies is a manager's team: its members' posts and events. + wakeReplies +) + +// wakeVerdict is what becomes of the turn that was asked for. +type wakeVerdict int + +const ( + // wakeNothing is no turn and nothing to say: what asked is already read. + wakeNothing wakeVerdict = iota + // wakeStarts is a turn started on it. + wakeStarts + // wakeQueues is a turn already in flight, which takes it at its next step. + wakeQueues + // wakeHolds is no turn, for the reason the decision carries. + wakeHolds +) + +// wakeHolder is the rule that held a wake, which is what chooses its line. +type wakeHolder int + +const ( + heldByNothing wakeHolder = iota + // heldByPause is the person's pause of this member (team_pause.go). + heldByPause + // heldByLimit is the hour's bound on team wakes ([teamWakesPerHour]). + heldByLimit + // heldByCap is a team's daily cap (team_cap.go). + heldByCap + // heldByLoop is the loop breaker ([teamLoopRounds]). + heldByLoop + // heldByGate is one of the engine's own gates ([Agent.wakeRefusalLocked]). + heldByGate +) + +// wakeCause is one request for a turn nobody typed. +type wakeCause struct { + kind wakeKind + // roles are the teams whose traffic asks, as this conversation sits in + // them. A rule that holds some of them and not others takes those out. + roles []teamRole + // batch is, for a manager, the entries that ask in each team. + batch map[string][]teams.Entry +} + +// wakeDecision is the answer, and why when it is not a start. +type wakeDecision struct { + verdict wakeVerdict + by wakeHolder + // gate is the engine's gate, for [heldByGate]. + gate wakeGate + why string +} + +// wakeRule is one team rule a wake may be held by: a hold, or the zero +// decision when it does not bind. It may take roles out of the cause. +type wakeRule func(a *Agent, profile string, c *wakeCause, now time.Time) wakeDecision + +// wakeRules is which team rules bind which cause, in the order they are asked. +// The engine's gates bind every cause and are not listed ([Agent.decideWakeLocked]). +// +// THE PAUSE IS ASKED LAST, AND FRESH. The look that chose a member's roles read +// the teams file through a memo up to a tick old ([sharedTeamsStamp]), so a +// directive sent in the second after the person pressed Pause reached the wake +// as if nothing held it, and the turn it started consumed the directive the +// pause was meant to keep. A manager is never paused, so its row has no pause; +// a member has no loop to break. +var wakeRules map[wakeKind][]wakeRule + +// The table is filled at init because the rules reach, through the turn they +// may start, the watch that reads the table: a literal would be a cycle. +func init() { + wakeRules = map[wakeKind][]wakeRule{ + wakeDirective: {wakeLimitRule, wakeCapRule, wakePauseRule}, + wakeReplies: {wakeLoopRule, wakeLimitRule, wakeCapRule}, + } +} + +// decideTeamWake asks the team's rules for this cause, and answers the first +// hold or a start. It takes no lock of its own and must not be called under +// a.mu: the rules read the teams file and the ledger. +func (a *Agent) decideTeamWake(profile string, c *wakeCause, now time.Time) wakeDecision { + for _, rule := range wakeRules[c.kind] { + if d := rule(a, profile, c, now); d.by != heldByNothing { + return d + } + } + return wakeDecision{verdict: wakeStarts} +} + +// decideWakeLocked is the engine's half of the decision: a start, a turn in +// flight to queue behind, or the gate that refuses and why. The caller holds +// a.mu, and a start decided here is true until that hold is let go. +func (a *Agent) decideWakeLocked() wakeDecision { + switch gate, why := a.wakeRefusalLocked(false, false); gate { + case wakeGateOpen: + return wakeDecision{verdict: wakeStarts} + case wakeGateRunning: + return wakeDecision{verdict: wakeQueues} + default: + return wakeDecision{verdict: wakeHolds, by: heldByGate, gate: gate, why: why} + } +} + +func wakeLimitRule(a *Agent, _ string, _ *wakeCause, now time.Time) wakeDecision { + if why := a.teamWakeLimited(now); why != "" { + return wakeDecision{verdict: wakeHolds, by: heldByLimit, why: why} + } + return wakeDecision{} +} + +func wakeCapRule(a *Agent, profile string, c *wakeCause, _ time.Time) wakeDecision { + if why := a.teamCapHold(profile, c.roles); why != "" { + return wakeDecision{verdict: wakeHolds, by: heldByCap, why: why} + } + return wakeDecision{} +} + +// wakePauseRule keeps the roles the person has not paused, remembering a hold +// for each they have, and holds the wake when none is left. +func wakePauseRule(a *Agent, profile string, c *wakeCause, _ time.Time) wakeDecision { + if c.roles = a.teamPausedSince(profile, c.roles); len(c.roles) == 0 { + return wakeDecision{verdict: wakeHolds, by: heldByPause, why: teamPausedWhy} + } + return wakeDecision{} +} + +// wakeLoopRule is the loop breaker. Its hold carries words only on the wake +// that trips it: the person is asked once, and every wake held after that is +// held unsaid until they speak. +func wakeLoopRule(a *Agent, _ string, _ *wakeCause, _ time.Time) wakeDecision { + held, trip := a.teamLoopHeld() + if !held { + return wakeDecision{} + } + d := wakeDecision{verdict: wakeHolds, by: heldByLoop} + if trip { + d.why = fmt.Sprintf("asks: the team has woken me %d times with no word from you, so I have stopped being woken by it until you say something", teamLoopRounds) + } + return d +} + +// ── the one writer ────────────────────────────────────────────────────────── + +// sayWake writes what became of a wake to the traffic of each team that asked +// for it, and is the only place a wake's line is written. Most decisions have +// a line and some have none: a pause is said by the send that met it +// (team_sendoutcome.go), and a loop already tripped has been said. +// +// THE WORDS ARE READ BACK BY MACHINES. `team_send` answers its manager from +// these lines ([Agent.teamSendOutcome]), the rail and the digest parse `woke `, +// and the desktop app matches the held and stopped lines whole. They are +// written here and nowhere else so that none can drift. +func (a *Agent) sayWake(profile string, c wakeCause, d wakeDecision, now time.Time) { + if !a.wakeSayOnce(d, now) { + return + } + for _, role := range c.roles { + if entry, ok := a.wakeLine(c, role, d); ok { + a.teamSay(profile, role.id, entry) + } + } +} + +// wakeSayOnce reports whether this decision's line is still to be said. A cap +// hold is said once per conversation and reason, because every held wake says +// the same thing and the cap's packet is what asks the person; the hour's limit +// is said once an hour. +func (a *Agent) wakeSayOnce(d wakeDecision, now time.Time) bool { + a.team.mu.Lock() + defer a.team.mu.Unlock() + w := &a.team.watch + switch d.by { + case heldByCap: + said := w.capSaid == d.why + w.capSaid = d.why + return !said + case heldByLimit: + if !w.limitSaid.IsZero() && now.Sub(w.limitSaid) < time.Hour { + return false + } + w.limitSaid = now + } + return true +} + +// wakeLine is the line one team's traffic is given for a decision, and false +// when the decision has none. +func (a *Agent) wakeLine(c wakeCause, role teamRole, d wakeDecision) (teams.Entry, bool) { + who, to := "◆", teams.ToManager + if !role.manager { + who, to = "@"+role.handle, role.handle + } + entry := teams.Entry{Kind: teams.KindEvent, From: teams.FromSystem, To: to, Member: role.key, State: teams.StateIdle} + switch { + case d.verdict == wakeStarts || d.verdict == wakeQueues: + entry.State = teams.StateRunning + if role.manager { + // Under the first waker's name, with the others who replied. + entry.From, entry.Text = teamWakers(c.batch[role.id])[0], teamWokeManagerText(c.batch[role.id]) + break + } + // The wake answers the directive that caused it, the one the boundary + // just handed over, so a reader draws the member as working on that + // thread rather than as a line of its own. + entry.From, entry.Text, entry.Answers = teams.FromManager, teamWokePrefix+who, a.teamAnswering(role.id) + case d.by == heldByCap: + entry.Text = teamHeldPrefix + who + ": " + d.why + case d.by == heldByLimit: + entry.Text = teamCouldNotPrefix + who + ": " + d.why + case d.by == heldByGate && d.why != "": + entry.Text = teamCouldNotPrefix + who + ": " + d.why + if !role.manager { + entry.Answers = a.teamAnswering(role.id) + } + case d.by == heldByLoop && d.why != "": + // The manager asks the room: the rail draws it in the needs-you colour + // and a digest reads it as the manager waiting. + entry.From, entry.To, entry.State, entry.Text = teams.FromManager, teams.ToRoom, teams.StateAsking, d.why + default: + return teams.Entry{}, false + } + return entry, true +} diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 3ef7dc983a..27e2e5f279 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -533,22 +533,12 @@ func teamWakes(role teamRole, entry teams.Entry) bool { // ── the two wakes ─────────────────────────────────────────────────────────── -// teamWakeMember starts a member's turn on the directives it was sent. +// teamWakeMember starts a member's turn on the directives it was sent, when +// the one decision says it may (team_wakedecide.go). func (a *Agent) teamWakeMember(profile string, roles []teamRole, now time.Time) { - if reason := a.teamWakeLimited(now); reason != "" { - a.teamWakeLimitSay(profile, roles, reason, now) - return - } - if reason := a.teamCapHold(profile, roles); reason != "" { - a.teamCapSay(profile, roles, reason) - return - } - // THE PAUSE IS READ AGAIN, FRESH, BEFORE ANYTHING IS HANDED OVER. The look - // that chose these roles read the teams file through a memo up to a tick - // old ([sharedTeamsStamp]), so a directive sent in the second after the - // person pressed Pause reached here as if nothing held it, and the turn it - // started consumed the directive the pause was meant to keep. - if roles = a.teamPausedSince(profile, roles); len(roles) == 0 { + cause := wakeCause{kind: wakeDirective, roles: roles} + if d := a.decideTeamWake(profile, &cause, now); d.verdict != wakeStarts { + a.sayWake(profile, cause, d, now) return } news := a.teamBoundary() @@ -557,30 +547,11 @@ func (a *Agent) teamWakeMember(profile string, roles []teamRole, now time.Time) // handed the directive over already; there is nothing left to wake on. return } - text := teamWakeMemberLead + "\n\n" + news - woke, reason := a.teamWakeWith(text) - if woke { + d := a.wakeWith(teamWakeMemberLead + "\n\n" + news) + if d.verdict != wakeHolds { a.teamWakeCount(now) } - for _, role := range roles { - // The wake answers the directive that caused it, the one the - // boundary above just handed over, so a reader draws the member as - // working on that thread rather than as a line of its own. - answers := a.teamAnswering(role.id) - if woke { - a.teamSay(profile, role.id, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromManager, To: role.handle, Member: role.key, - State: teams.StateRunning, Text: teamWokePrefix + "@" + role.handle, Answers: answers, - }) - continue - } - if reason != "" { - a.teamSay(profile, role.id, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromSystem, To: role.handle, Member: role.key, - State: teams.StateIdle, Text: teamCouldNotPrefix + "@" + role.handle + ": " + reason, Answers: answers, - }) - } - } + a.sayWake(profile, cause, d, now) } // teamWakeManager starts a manager's turn on the batch its members' replies @@ -590,23 +561,14 @@ func (a *Agent) teamWakeManager(profile string, roles []teamRole, batch map[stri for _, role := range roles { byID[role.id] = role } - if a.teamLoopHeld(profile, byID, batch) { - return - } - if reason := a.teamWakeLimited(now); reason != "" { - var said []teamRole - for id := range batch { - said = append(said, byID[id]) - } - a.teamWakeLimitSay(profile, said, reason, now) - return - } - var batchRoles []teamRole + cause := wakeCause{kind: wakeReplies, batch: batch} for id := range batch { - batchRoles = append(batchRoles, byID[id]) + role := byID[id] + role.id = id + cause.roles = append(cause.roles, role) } - if reason := a.teamCapHold(profile, batchRoles); reason != "" { - a.teamCapSay(profile, batchRoles, reason) + if d := a.decideTeamWake(profile, &cause, now); d.verdict != wakeStarts { + a.sayWake(profile, cause, d, now) return } news := a.teamBoundary() @@ -623,67 +585,46 @@ func (a *Agent) teamWakeManager(profile string, roles []teamRole, batch map[stri if len(groups) == 0 { return } - text := teamWakeManagerLead + "\n\n" + teamWakeDeliveryRule + "\n\n" + - strings.Join(groups, "\n\n") - woke, reason := a.teamWakeWith(text) - if woke { + d := a.wakeWith(teamWakeManagerLead + "\n\n" + teamWakeDeliveryRule + "\n\n" + + strings.Join(groups, "\n\n")) + if d.verdict != wakeHolds { a.teamWakeCount(now) a.team.mu.Lock() a.team.watch.rounds++ a.team.mu.Unlock() } - for id, entries := range batch { - role := byID[id] - if woke { - a.teamSay(profile, id, teams.Entry{ - Kind: teams.KindEvent, From: teamWakers(entries)[0], To: teams.ToManager, Member: role.key, - State: teams.StateRunning, Text: teamWokeManagerText(entries), - }) - continue - } - if reason != "" { - a.teamSay(profile, id, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromSystem, To: teams.ToManager, Member: role.key, - State: teams.StateIdle, Text: teamCouldNotPrefix + "◆: " + reason, - }) - } - } + a.sayWake(profile, cause, d, now) } -// teamWakeWith queues text as the session's note and starts a turn on it, -// under one hold of the agent's lock so the answer is the wake's own. It -// reports whether a turn was started (or one was already running, which takes -// the note at its next boundary), and why not when neither. +// teamWakeWith is [Agent.wakeWith] as a yes or no: whether a turn was started +// (or one was already running, which takes the note at its next boundary), and +// why not when neither. func (a *Agent) teamWakeWith(text string) (bool, string) { - if why := a.automaticFactoryRefusal(); why != "" { - return false, why - } - if err := a.CheckWork(); err != nil { - return false, err.Error() - } + d := a.wakeWith(text) + return d.verdict != wakeHolds, d.why +} + +// wakeWith queues text as the session's note and starts a turn on it, under +// one hold of the agent's lock so the decision is the wake's own. +// +// A SEAT THAT MAY NOT WORK AND A JOB THAT REFUSES AUTOMATIC WORK KEEP NOTHING, +// as they keep nothing of any other note ([Agent.enqueueNote], +// [Agent.wakeAnsweringLocked]); nor does a closed session, whose queue nothing +// drains. Every other gate leaves the note queued for the next turn. +func (a *Agent) wakeWith(text string) wakeDecision { note := userMessage{message: textMessage("user", strings.TrimSpace(text)), wake: true, authored: true} a.mu.Lock() defer a.mu.Unlock() - if a.closed { - return false, "its conversation has closed" + d := a.decideWakeLocked() + switch d.gate { + case wakeGateFactory, wakeGateSeat, wakeGateClosed: + return d } a.steering = append(a.steering, note) - if a.running { - return true, "" - } - if a.wakeLocked() { - return true, "" + if d.verdict == wakeStarts { + a.wakeLocked() } - switch { - case a.workStopped: - return false, "its work was stopped; it reads this at its next turn" - case wallIsUp(a.steward()): - return false, "its time limit has passed; it reads this at its next turn" - } - if err := a.railBlockLocked(); err != nil { - return false, "its spending limit is reached; it reads this at its next turn" - } - return false, "it cannot start a turn on its own here; it reads this at its next turn" + return d } // ── the bounds ────────────────────────────────────────────────────────────── @@ -714,60 +655,15 @@ func (a *Agent) teamWakeCount(now time.Time) { a.team.watch.woken = append(a.team.watch.woken, now) } -// teamCapSay tells the Traffic a wake was held at the cap, once per -// conversation and reason: every held wake says the same thing, and the cap -// packet is what asks the person. -func (a *Agent) teamCapSay(profile string, roles []teamRole, reason string) { - a.team.mu.Lock() - say := a.team.watch.capSaid != reason - a.team.watch.capSaid = reason - a.team.mu.Unlock() - if !say { - return - } - for _, role := range roles { - who, to := "◆", teams.ToManager - if !role.manager { - who, to = "@"+role.handle, role.handle - } - a.teamSay(profile, role.id, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromSystem, To: to, Member: role.key, - State: teams.StateIdle, Text: teamHeldPrefix + who + ": " + reason, - }) - } -} - -// teamWakeLimitSay tells the Traffic the limit was reached, once an hour. -func (a *Agent) teamWakeLimitSay(profile string, roles []teamRole, reason string, now time.Time) { - a.team.mu.Lock() - say := a.team.watch.limitSaid.IsZero() || now.Sub(a.team.watch.limitSaid) >= time.Hour - if say { - a.team.watch.limitSaid = now - } - a.team.mu.Unlock() - if !say { - return - } - for _, role := range roles { - who, to := "◆", teams.ToManager - if !role.manager { - who, to = "@"+role.handle, role.handle - } - a.teamSay(profile, role.id, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromSystem, To: to, Member: role.key, - State: teams.StateIdle, Text: teamCouldNotPrefix + who + ": " + reason, - }) - } -} - -// teamLoopHeld is the loop breaker, and true when the manager is not to be -// woken. A turn the person started since the last team wake resets it. +// teamLoopHeld is the loop breaker: held says the manager is not to be woken, +// and trip that this is the wake that tripped it. A turn the person started +// since the last team wake resets it. // -// ON THE TRIP IT ASKS THE PERSON: an asking event from the manager in each -// team's Traffic, which the rail draws in the needs-you colour and a digest -// reads as the manager waiting, and a note queued (not waking) in the -// manager's own conversation, so its next turn knows why nothing woke it. -func (a *Agent) teamLoopHeld(profile string, byID map[string]teamRole, batch map[string][]teams.Entry) bool { +// ON THE TRIP THE PERSON IS ASKED: an asking event from the manager in each +// team's Traffic ([wakeLoopRule], said by [Agent.sayWake]), and a note queued +// (not waking) in the manager's own conversation, so its next turn knows why +// nothing woke it. +func (a *Agent) teamLoopHeld() (held, trip bool) { heard := a.team.person.n.Load() a.team.mu.Lock() w := &a.team.watch @@ -776,26 +672,17 @@ func (a *Agent) teamLoopHeld(profile string, byID map[string]teamRole, batch map } if w.rounds < teamLoopRounds { a.team.mu.Unlock() - return false + return false, false } - trip := !w.held + trip = !w.held w.held = true a.team.mu.Unlock() - if !trip { - return true + if trip { + a.enqueueNote(userMessage{message: textMessage("user", fmt.Sprintf( + "codeaf stopped waking you on your team's replies: they woke you %d times with no word from the person. "+ + "Their lines are still delivered at your next turn. Tell the person where the work stands and ask whether to go on.", teamLoopRounds))}) } - said := fmt.Sprintf("asks: the team has woken me %d times with no word from you, so I have stopped being woken by it until you say something", teamLoopRounds) - for id := range batch { - role := byID[id] - a.teamSay(profile, id, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromManager, To: teams.ToRoom, Member: role.key, - State: teams.StateAsking, Text: said, - }) - } - a.enqueueNote(userMessage{message: textMessage("user", fmt.Sprintf( - "codeaf stopped waking you on your team's replies: they woke you %d times with no word from the person. "+ - "Their lines are still delivered at your next turn. Tell the person where the work stands and ask whether to go on.", teamLoopRounds))}) - return true + return true, trip } // ── what is said ──────────────────────────────────────────────────────────── From 6ecb8d64fa40cd4233a84becd38992b18d6fc8eb Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:50:31 -0500 Subject: [PATCH 25/37] teams: a wake is decided before the directive is read The traffic watch handed a directive over, moving the cursor past it, and only then asked whether a turn could start. A job refusing automatic work, or a seat that may not work, kept nothing of it, so the directive was lost. The decision now comes first: a refused wake says why, moves no cursor, and the next turn's own boundary hands the lines over. A wake that finds a turn already running no longer writes `woke @x`. That turn reads the lines at its next step, the watch looks again when it ends, and team_send answers that the member is in a turn. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2897-crew-handoff-outcome.md | 2 + internal/manual/chat/team-manager.md | 5 + internal/session/team_sendoutcome.go | 19 +++- internal/session/team_wakedecide.go | 26 ++++- internal/session/team_wakewatch.go | 97 ++++++++++++++++--- internal/session/team_wakewatch_test.go | 95 ++++++++++++++++++ 6 files changed, 225 insertions(+), 19 deletions(-) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 3445ab19ed..5e8a694a93 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -28,6 +28,8 @@ invalidates: - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one that is not loaded and whose Modelfile sets a `num_ctx` under it; `source` `default` carries no `window` and is one that is not loaded and sets none, so the server's default will apply. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`. A server that is absent, slow or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine. A turn ending on an Ollama model last listed with `source` `default` emits `models.changed` once. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." + - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." + - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 71f391671b..cd4fe71ec3 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -655,6 +655,11 @@ by its team with nothing from you stops being woken and asks you instead, as a w the traffic. It is woken again after you next say something to it. The ten wakes count ten replies when each member turn replies and then finishes. +A member already in a turn when a directive reaches it was not woken and gets no `woke` line: +it reads the directive at its next step. A wake the member's own limits refuse says why once +(`could not wake @web: its spending limit is reached; it reads this at its next turn`) and +leaves the directive unread in the traffic for that turn. + ## Pausing a crew member — pause, resume, why a directive did not start, held You can pause a member of a crew in the desktop app: **Pause** on its row in the Members tab diff --git a/internal/session/team_sendoutcome.go b/internal/session/team_sendoutcome.go index 23f1cadd60..75aed14c4b 100644 --- a/internal/session/team_sendoutcome.go +++ b/internal/session/team_sendoutcome.go @@ -10,8 +10,8 @@ package session // // SO THE ANSWER WAITS FOR THE EVIDENCE, BRIEFLY. A wake writes a line to the // team's traffic that answers the directive by its id (team_wakewatch.go), a -// refused wake writes why, and a paused member is known from the teams file -// before anything is asked. The send looks at the traffic for a few seconds +// refused wake writes why, a paused member is known from the teams file before +// anything is asked, and a member in a turn is known from its own journal. The send looks at the traffic for a few seconds // and says, per member, one of: started, in a turn already, did not start and // why, or no sign of a start yet. The last is said as plainly as the rest: a // manager told "no sign yet" checks before it reports. @@ -121,9 +121,20 @@ func (a *Agent) teamSendOutcome(ctx context.Context, profile string, team teams. } for _, member := range ready { if _, still := waiting[member.Key]; still { - if _, said := refused[member.Handle]; !said { - unseen = append(unseen, "@"+member.Handle) + if _, said := refused[member.Handle]; said { + continue + } + // A MEMBER WHOSE TURN BEGAN DURING THE WAIT WROTE NO LINE. It was + // idle when the send first looked and in a turn by the time its + // watch reached the directive, and a turn already running is not + // said to have been woken (team_wakedecide.go). Its journal is read + // once more, so the answer is that it is in a turn, not that it has + // shown no sign of starting. + if state, _, ok := a.team.journals.stateOf(member.File, time.Now()); ok && state.State == teams.StateRunning { + busy = append(busy, "@"+member.Handle) + continue } + unseen = append(unseen, "@"+member.Handle) } } var said []string diff --git a/internal/session/team_wakedecide.go b/internal/session/team_wakedecide.go index 0c13b06300..3a1e51cdae 100644 --- a/internal/session/team_wakedecide.go +++ b/internal/session/team_wakedecide.go @@ -129,6 +129,19 @@ func (a *Agent) decideTeamWake(profile string, c *wakeCause, now time.Time) wake return wakeDecision{verdict: wakeStarts} } +// decideWake is the whole decision, made before anything is read or moved: the +// team's rules for this cause, then the engine's gates as they stand. A start +// answered here is a start still to be made, under a later hold of a.mu +// ([Agent.wakeWith]), which asks the gates again. +func (a *Agent) decideWake(profile string, c *wakeCause, now time.Time) wakeDecision { + if d := a.decideTeamWake(profile, c, now); d.verdict != wakeStarts { + return d + } + a.mu.Lock() + defer a.mu.Unlock() + return a.decideWakeLocked() +} + // decideWakeLocked is the engine's half of the decision: a start, a turn in // flight to queue behind, or the gate that refuses and why. The caller holds // a.mu, and a start decided here is true until that hold is let go. @@ -186,7 +199,8 @@ func wakeLoopRule(a *Agent, _ string, _ *wakeCause, _ time.Time) wakeDecision { // sayWake writes what became of a wake to the traffic of each team that asked // for it, and is the only place a wake's line is written. Most decisions have // a line and some have none: a pause is said by the send that met it -// (team_sendoutcome.go), and a loop already tripped has been said. +// (team_sendoutcome.go), a loop already tripped has been said, and a turn that +// was already running was not woken. // // THE WORDS ARE READ BACK BY MACHINES. `team_send` answers its manager from // these lines ([Agent.teamSendOutcome]), the rail and the digest parse `woke `, @@ -234,7 +248,13 @@ func (a *Agent) wakeLine(c wakeCause, role teamRole, d wakeDecision) (teams.Entr } entry := teams.Entry{Kind: teams.KindEvent, From: teams.FromSystem, To: to, Member: role.key, State: teams.StateIdle} switch { - case d.verdict == wakeStarts || d.verdict == wakeQueues: + case d.verdict == wakeQueues: + // A TURN ALREADY RUNNING WAS NOT WOKEN. `woke` was written for it, and a + // manager's send read that back as the member having started on its + // directive. The turn takes the lines at its next step and the traffic + // says nothing: the send reads a running member off its journal. + return teams.Entry{}, false + case d.verdict == wakeStarts: entry.State = teams.StateRunning if role.manager { // Under the first waker's name, with the others who replied. @@ -252,7 +272,7 @@ func (a *Agent) wakeLine(c wakeCause, role teamRole, d wakeDecision) (teams.Entr case d.by == heldByGate && d.why != "": entry.Text = teamCouldNotPrefix + who + ": " + d.why if !role.manager { - entry.Answers = a.teamAnswering(role.id) + entry.Answers = a.teamAsked(role.id) } case d.by == heldByLoop && d.why != "": // The manager asks the room: the rail draws it in the needs-you colour diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 27e2e5f279..5b95942cb4 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -148,6 +148,10 @@ type teamWatch struct { held bool // capSaid is the last cap hold the Traffic was told of. capSaid string + // asked is, per team, the manager's entry that last asked for this member's + // turn. A wake refused before anything is handed over answers it by this, + // because the boundary that would have named it has not been read. + asked map[string]string // pausedHeld is the teams whose traffic asked for this member's turn while // the person had it paused (team_pause.go). The lines stay undelivered on // the log, and the turn they asked for starts when the pause is lifted, @@ -234,6 +238,7 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { // Its own start still owes this member its first turn. if a.teamOwnStartWakes(role, entry) || teamWakes(role, entry) || teamPacketWakes(profile, role, entry) { waking = append(waking, entry) + a.teamAskedLocked(role, entry) } } // A PAUSED MEMBER IS NOT WOKEN, and what would have woken it is not @@ -535,27 +540,90 @@ func teamWakes(role teamRole, entry teams.Entry) bool { // teamWakeMember starts a member's turn on the directives it was sent, when // the one decision says it may (team_wakedecide.go). +// +// THE DECISION COMES BEFORE THE READ. Handing the directive over moves this +// conversation's cursor past it, and a wake refused after that had consumed +// what it then did not start a turn on: a job refusing automatic work, or a +// seat that may not work, kept nothing of it and no later turn was handed it. +// So nothing is read until the team's rules and the engine's gates have both +// said a turn may start. A wake that is held leaves the directive on the log, +// where the next turn's own boundary finds it. func (a *Agent) teamWakeMember(profile string, roles []teamRole, now time.Time) { cause := wakeCause{kind: wakeDirective, roles: roles} - if d := a.decideTeamWake(profile, &cause, now); d.verdict != wakeStarts { - a.sayWake(profile, cause, d, now) + if d := a.decideWake(profile, &cause, now); d.verdict != wakeStarts { + a.teamWakeDeclined(profile, cause, d, now) return } news := a.teamBoundary() if news == "" { // A boundary that ran in the moment between the look and here has - // handed the directive over already; there is nothing left to wake on. + // handed the directive over already; there is nothing left to wake on, + // and nothing to say: the turn that read it was not started by it. return } d := a.wakeWith(teamWakeMemberLead + "\n\n" + news) - if d.verdict != wakeHolds { + if d.verdict == wakeStarts { a.teamWakeCount(now) } a.sayWake(profile, cause, d, now) } +// teamWakeDeclined is a wake that starts no turn, decided before anything was +// read. A hold is said. A turn already in flight is not: it reads its own +// traffic at its next step, so the watch only forgets that it looked. +func (a *Agent) teamWakeDeclined(profile string, cause wakeCause, d wakeDecision, now time.Time) { + if d.verdict == wakeQueues { + a.teamWatchLookAgain(cause.roles) + return + } + a.sayWake(profile, cause, d, now) +} + +// teamWatchLookAgain forgets how far the watch has looked into roles' logs, so +// its next idle look starts again from what has been delivered. +// +// A TURN IN FLIGHT MAY HAVE NO STEP LEFT. The wake that finds a turn running +// leaves the lines for that turn's next boundary, and a turn whose last request +// has already gone out has none: the lines would wait, unread, for a turn +// nothing was going to start, because the watch had already looked past them. +// Looking again costs one read when the turn ends, and finds nothing where the +// turn did read them, since the look never starts behind the delivery +// ([Agent.teamWatchReadLocked]). +func (a *Agent) teamWatchLookAgain(roles []teamRole) { + a.team.mu.Lock() + defer a.team.mu.Unlock() + for _, role := range roles { + delete(a.team.watch.cursors, role.id) + delete(a.team.watch.trafficAt, role.id) + } +} + +// teamAskedLocked remembers entry as what last asked for this member's turn in +// role's team, when it is its manager's. The caller holds a.team.mu. +func (a *Agent) teamAskedLocked(role teamRole, entry teams.Entry) { + if role.manager || entry.From != teams.FromManager { + return + } + if a.team.watch.asked == nil { + a.team.watch.asked = map[string]string{} + } + a.team.watch.asked[role.id] = entry.ID +} + +// teamAsked is the entry a wake refused in team id answers: what the watch +// last saw ask for the turn, or what this conversation was last handed. +func (a *Agent) teamAsked(id string) string { + a.team.mu.Lock() + defer a.team.mu.Unlock() + if asked := a.team.watch.asked[id]; asked != "" { + return asked + } + return a.teamAnsweringLocked(id) +} + // teamWakeManager starts a manager's turn on the batch its members' replies -// made, or, past the loop bound, asks the person instead. +// made, or, past the loop bound, asks the person instead. It decides before it +// reads, as a member's wake does ([Agent.teamWakeMember]). func (a *Agent) teamWakeManager(profile string, roles []teamRole, batch map[string][]teams.Entry, now time.Time) { byID := map[string]teamRole{} for _, role := range roles { @@ -567,8 +635,8 @@ func (a *Agent) teamWakeManager(profile string, roles []teamRole, batch map[stri role.id = id cause.roles = append(cause.roles, role) } - if d := a.decideTeamWake(profile, &cause, now); d.verdict != wakeStarts { - a.sayWake(profile, cause, d, now) + if d := a.decideWake(profile, &cause, now); d.verdict != wakeStarts { + a.teamWakeDeclined(profile, cause, d, now) return } news := a.teamBoundary() @@ -587,7 +655,7 @@ func (a *Agent) teamWakeManager(profile string, roles []teamRole, batch map[stri } d := a.wakeWith(teamWakeManagerLead + "\n\n" + teamWakeDeliveryRule + "\n\n" + strings.Join(groups, "\n\n")) - if d.verdict != wakeHolds { + if d.verdict == wakeStarts { a.teamWakeCount(now) a.team.mu.Lock() a.team.watch.rounds++ @@ -607,10 +675,15 @@ func (a *Agent) teamWakeWith(text string) (bool, string) { // wakeWith queues text as the session's note and starts a turn on it, under // one hold of the agent's lock so the decision is the wake's own. // -// A SEAT THAT MAY NOT WORK AND A JOB THAT REFUSES AUTOMATIC WORK KEEP NOTHING, -// as they keep nothing of any other note ([Agent.enqueueNote], -// [Agent.wakeAnsweringLocked]); nor does a closed session, whose queue nothing -// drains. Every other gate leaves the note queued for the next turn. +// ITS CALLER HAS ALREADY DECIDED, AND THIS DECIDES AGAIN. The text is what a +// boundary just handed over, read after [Agent.decideWake] said a turn could +// start, and the agent's lock was let go in between: a turn may have begun, or +// a gate closed. So the answer here is the one that counts, and what it does +// with text that can no longer start a turn is what every other note gets. A +// turn that began takes it at its next step. A seat that may not work and a +// job that refuses automatic work keep nothing ([Agent.enqueueNote], +// [Agent.wakeAnsweringLocked]), nor does a closed session, whose queue nothing +// drains. Every other gate leaves it queued for the next turn. func (a *Agent) wakeWith(text string) wakeDecision { note := userMessage{message: textMessage("user", strings.TrimSpace(text)), wake: true, authored: true} a.mu.Lock() diff --git a/internal/session/team_wakewatch_test.go b/internal/session/team_wakewatch_test.go index 9c02102fd4..27ee8ef089 100644 --- a/internal/session/team_wakewatch_test.go +++ b/internal/session/team_wakewatch_test.go @@ -7,6 +7,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" @@ -729,3 +730,97 @@ func (c *armedRounds) CompleteWithMessages(ctx context.Context, messages []ai.Me } return c.run(ctx, round) } + +// A REFUSED WAKE LEAVES THE DIRECTIVE WHERE IT WAS. The wake used to hand the +// directive over first and ask the engine's gates afterwards, and a job that +// refuses automatic work, or a seat that may not work, kept nothing of it: the +// traffic said the member could not be woken, the cursor had moved past the +// directive, and no later turn was ever handed it. The decision is made before +// anything is read, so the turn the person next opens still finds it. +func TestTeamWakeARefusedWakeLeavesTheDirectiveUnread(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + completer := oneAnswer(1) + var refusing atomic.Bool + refusing.Store(true) + web := teamAgent(t, fixture, fixture.web, completer, func(config *Config) { + config.FactoryWorkRefusal = func() string { + if refusing.Load() { + return "this job was stopped" + } + return "" + } + }) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header."}) + said := waitEvent(t, fixture, "could not wake @web") + if !strings.HasSuffix(said.Text, ": this job was stopped") || said.Answers == "" { + t.Errorf("the refusal's line is %+v, want the gate's own reason, answering the directive", said) + } + quietFor() + if got := completer.requests(); got != 0 { + t.Fatalf("a refused wake started %d turns", got) + } + if got := trafficEvents(t, fixture, "could not wake @web"); len(got) != 1 { + t.Errorf("the refusal was said %d times, want once", len(got)) + } + refusing.Store(false) + submitAndWait(t, web, "what is waiting for you?") + if asked := userTextIn(completer.request(0)); strings.Count(asked, "Fix the header.") != 1 { + t.Fatalf("the directive a refused wake had read was not there for the next turn:\n%s", asked) + } +} + +// A TURN ALREADY RUNNING WAS NOT WOKEN, AND THE TRAFFIC DOES NOT SAY IT WAS. +// The look found the member idle, a turn began before the wake reached it, and +// the wake wrote `woke @web` for a turn the directive had not started; the +// manager's send then answered that the member had started on it. The turn in +// flight reads the directive at its next step. When it has no step left, the +// watch finds the directive again once the turn has ended, and that wake is +// the one the traffic records. +func TestTeamWakeATurnAlreadyRunningIsNotSaidToHaveWoken(t *testing.T) { + fixture := newWakingTeamFixture(t) + release := make(chan struct{}) + completer := &scriptedCompleter{steps: []step{ + func(ctx context.Context, _ []ai.Message) (*ai.Response, error) { + select { + case <-release: + case <-ctx.Done(): + } + return textResponse("done"), nil + }, + func(context.Context, []ai.Message) (*ai.Response, error) { return textResponse("fixed"), nil }, + }} + web := teamAgent(t, fixture, fixture.web, completer, func(config *Config) { config.teamWatchManual = true }) + events := mustSubmit(t, web, "work on the footer") + waitRequests(t, completer, 1) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header."}) + // The look that found it idle has read the log and moved on, as a tick does + // before it hands the wake over. + var roles []teamRole + web.team.mu.Lock() + for _, role := range web.teamRolesLocked(fixture.profile) { + if !role.manager { + roles = append(roles, role) + web.teamWatchReadLocked(fixture.profile, role) + } + } + web.team.mu.Unlock() + web.teamWakeMember(fixture.profile, roles, time.Now()) + if woke := trafficEvents(t, fixture, "woke @web"); len(woke) != 0 { + t.Fatalf("a turn that was already running is said to have been woken: %+v", woke) + } + close(release) + collect(t, events) + waitQuiet(t, web) + if !web.teamWatchTick(fixture.profile, time.Now()) { + t.Fatal("the member stopped watching its team") + } + waitRequests(t, completer, 2) + if asked := userTextIn(completer.request(1)); strings.Count(asked, "Fix the header.") != 1 { + t.Fatalf("the directive was not handed over once after the turn that was running:\n%s", asked) + } + waitQuiet(t, web) + if woke := trafficEvents(t, fixture, "woke @web"); len(woke) != 1 { + t.Fatalf("the wake that did start a turn was logged %d times, want once", len(woke)) + } +} From f43a0fd72565082bf89fa2083ba330b09f8cf2df Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:00:42 -0500 Subject: [PATCH 26/37] teams: a fresh member's first turn is decided where the watch's wakes are A member its manager started had its own rules for its first turn, and said less than the traffic watch: held at its team's cap or by the person's pause it wrote nothing, and at the cap its brief was read off the log before the cap was asked. Its first turn now goes through the one decision, writes the line the watch writes for the same hold, and leaves the brief on the log until a turn may read it. The watch and TeamOpenPending also ask one predicate, teamEntryWakes, whether an entry starts a turn. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2897-crew-handoff-outcome.md | 1 + internal/manual/chat/team-manager.md | 1 + .../manual/chat/team-questions-and-caps.md | 3 +- internal/session/team_pause.go | 52 ++++----- internal/session/team_pending.go | 19 ++-- internal/session/team_wake.go | 72 ++++++------- internal/session/team_wake_test.go | 93 ++++++++++++++++ internal/session/team_wakedecide.go | 101 ++++++++++++++++-- internal/session/team_wakewatch.go | 33 +++++- 9 files changed, 280 insertions(+), 95 deletions(-) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 5e8a694a93..be13afee41 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -30,6 +30,7 @@ invalidates: - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one that is not loaded and whose Modelfile sets a `num_ctx` under it; `source` `default` carries no `window` and is one that is not loaded and sets none, so the server's default will apply. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`. A server that is absent, slow or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine. A turn ending on an Ollama model last listed with `source` `default` emits `models.changed` once. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." + - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index cd4fe71ec3..46bc680482 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -673,6 +673,7 @@ Resume from any of those crews lifts it: - A directive waits on the crew's log, unread. The traffic says `held @web: the person paused it; it starts on this when they resume it`, once per directive. + A member paused before its first turn says it once for the brief it was started with. - `team_send` tells the manager `@web did NOT start` with the same reason, and that only you can resume it. The manager cannot lift a pause. - `team_status` shows the member as `paused by the person; it starts nothing until they diff --git a/internal/manual/chat/team-questions-and-caps.md b/internal/manual/chat/team-questions-and-caps.md index 88550214f1..999d6108e4 100644 --- a/internal/manual/chat/team-questions-and-caps.md +++ b/internal/manual/chat/team-questions-and-caps.md @@ -65,7 +65,8 @@ two teams can each spend up to the default without sharing one company-wide allo When the pool reaches its cap: - nothing new starts in it: a directive no longer wakes a member, replies no longer wake the - manager, a new member's brief waits, and `team_start` is refused. A turn already running is + manager, a new member's brief waits unread with the same held row, and `team_start` is + refused. A turn already running is never cut off; it finishes, and what was held is delivered at each conversation's next turn; - you are asked once, with a card `harbor reached its $5 cap today`: **Raise to $10** (the team goes on until $10 today) or **Stop for today** (members finish their current turn and diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 4780b3f10a..6eedab955c 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -33,7 +33,9 @@ package session // THE SENDER SAYS SO, ONCE, AT THE SEND. `team_send` reads the same record and // answers that the member is paused, and writes the one traffic line that says // the directive is held ([teamHeldPausedText]). The paused member writes -// nothing, so the log carries one account whether or not anything has it open. +// nothing for a directive, so the log carries one account whether or not +// anything has it open. A start has no send behind it: a member paused before +// its first turn writes that line itself, once ([Agent.teamWakeStart]). // // THE PERSON'S OWN WORDS ARE NOT HELD, as with the daily cap (team_cap.go): a // person typing into a paused member's conversation starts its turn, and that @@ -93,37 +95,34 @@ func (a *Agent) teamPauseReleasedLocked(role teamRole) bool { return true } -// teamOwnStartWakes reports whether entry is the start line that owes this -// member its first turn: its own start, unless the membership was made on -// standby, whose start line is a role to read and not work to begin. -func (a *Agent) teamOwnStartWakes(role teamRole, entry teams.Entry) bool { - return !role.standby && a.teamOwnStart(role, entry) -} - // teamStandbyText is the traffic line a member opened on standby writes, once: // "opened @mac-dev on standby; …". func teamStandbyText(handle string) string { return "opened @" + handle + " on standby; it starts on its manager's first directive" } -// teamStandbySay writes that line unless the team's recent traffic already -// carries it: a conversation with nothing in it yet is fresh every time it is -// opened, and the line is said once. -func (a *Agent) teamStandbySay(profile string, role teamRole) { - text := teamStandbyText(role.handle) - tail, err := teams.ReadTraffic(profile, role.id, "", teamFirstLook) +// teamAutoWakeOffText is the traffic line a member started into a team whose +// auto-wake is off writes: it is open, and nothing started its turn. +func teamAutoWakeOffText(handle string) string { + return "opened @" + handle + "; this team's auto-wake is off, so no turn was started. It reads the brief when it next runs." +} + +// teamSaidAlready reports whether team's recent traffic already carries this +// line about this member, answering the same entry. A conversation with +// nothing in it yet is fresh every time it is opened, and both watches may +// meet the same hold, so a hold is said once for what it holds. A log that +// cannot be read is not written to either. +func teamSaidAlready(profile, team string, line teams.Entry) bool { + tail, err := teams.ReadTraffic(profile, team, "", teamFirstLook) if err != nil { - return + return true } for _, entry := range tail { - if entry.Kind == teams.KindEvent && entry.Member == role.key && entry.Text == text { - return + if entry.Kind == teams.KindEvent && entry.Member == line.Member && entry.Text == line.Text && entry.Answers == line.Answers { + return true } } - a.teamSay(profile, role.id, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromSystem, To: role.handle, Member: role.key, - State: teams.StateIdle, Text: text, - }) + return false } // teamStandbyOver clears a member's standby once its start line is handed to @@ -168,27 +167,28 @@ func teamAt(members []teams.Member) string { // handle, when the person stopped a turn the manager's traffic had started. const teamStoppedByPersonLine = "'s turn on what you handed it was " + teams.StoppedByPerson + " before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask." -// teamPausedSince reads the teams file afresh and returns the roles among -// roles that are still not paused, remembering a hold for each that now is. -func (a *Agent) teamPausedSince(profile string, roles []teamRole) []teamRole { +// teamPausedSplit reads the teams file afresh and divides roles into those +// still not paused and those that now are, remembering a hold for each of the +// latter. A role this conversation no longer has is in neither. +func (a *Agent) teamPausedSplit(profile string, roles []teamRole) (kept, paused []teamRole) { a.team.mu.Lock() defer a.team.mu.Unlock() fresh := map[string]teamRole{} for _, role := range a.teamRolesLocked(profile) { fresh[role.id] = role } - kept := roles[:0:0] for _, role := range roles { now, still := fresh[role.id] if !still { continue } if a.teamPauseHoldLocked(now, true) { + paused = append(paused, now) continue } kept = append(kept, now) } - return kept + return kept, paused } // teamHandedLocked notes that role's manager handed this conversation work: diff --git a/internal/session/team_pending.go b/internal/session/team_pending.go index 7c8ce7dd10..f490644d68 100644 --- a/internal/session/team_pending.go +++ b/internal/session/team_pending.go @@ -46,16 +46,13 @@ func TeamOpenPending(profile, transcript string, file *teams.File, defaults team return false } -// pendingTeamEntry shares the engine's wake rules, including the finished -// event it suppresses after a reply. A member's own start also needs opening. +// pendingTeamEntry reports whether an entry needs the conversation open: it +// would start a turn there by the watch's own rule ([teamEntryWakes]), or it +// carries a line to hand over that the rule has not set aside. func pendingTeamEntry(profile string, role teamRole, entry teams.Entry) bool { - if role.manager && entry.Kind == teams.KindEvent && entry.State == teams.StateFinished && teamFinishedAfterReply(profile, role.id, entry) { - return false - } - if !role.manager && entry.Kind == teams.KindStart && (entry.To == role.handle || (role.startID != "" && entry.ID == role.startID)) { - // A standby start is a role to read at the first turn, not work that - // needs the conversation open. - return !role.standby - } - return teamWakes(role, entry) || teamPacketWakes(profile, role, entry) || teamLine(role, entry) != "" + // A closed conversation has no birth to test a start against, so its own + // start is the one sent to its handle, or the one its membership names. + own := !role.manager && entry.Kind == teams.KindStart && (entry.To == role.handle || (role.startID != "" && entry.ID == role.startID)) + wakes, quiet := teamEntryWakes(profile, role, entry, own) + return wakes || (!quiet && teamLine(role, entry) != "") } diff --git a/internal/session/team_wake.go b/internal/session/team_wake.go index cb813ddde6..17178a2774 100644 --- a/internal/session/team_wake.go +++ b/internal/session/team_wake.go @@ -34,7 +34,9 @@ import ( // A TEAM WHOSE AUTO-WAKE IS OFF IS THE EXCEPTION. The member is still opened, // and the brief is still waiting in the Traffic for its first turn, but no // turn is started for it. The Traffic says so, in the same voice as a wake -// that could not run. +// that could not run. So is a member on standby, one the person paused, and +// one whose team is at its cap: each is a row of the one table that decides +// every wake ([wakeRules]), and each says its own line. // // A conversation that is never started by a manager pays one stat of the teams // file at open and, where a team has a manager, one stat every @@ -104,51 +106,33 @@ func (a *Agent) awaitTeamStart(profile string, base int) { if grown, busy := a.teamWakeState(); busy || grown > base { return } - started := a.teamStarts(profile) - if len(started) == 0 { - continue - } - var waking []teamRole - for _, role := range started { - if role.standby { - // ON STANDBY NOTHING STARTS. The start line is this member's - // role, read at its first turn, and the manager's first - // directive is what begins that turn (team_pause.go). - a.teamStandbySay(profile, role) - continue - } - if role.paused { - // The watch holds it and starts the turn on resume. - a.team.mu.Lock() - a.teamPauseHoldLocked(role, true) - a.team.mu.Unlock() - continue - } - if role.wakes { - waking = append(waking, role) - continue - } - // WAKE OFF HONOURS THE SWITCH. The conversation is already open, - // which is what "opened" means here, and the brief stays unread - // until a turn something else starts. Consuming it now would hand - // it over with nobody to read it. - a.teamSay(profile, role.id, teams.Entry{ - Kind: teams.KindEvent, From: teams.FromSystem, To: role.handle, Member: role.key, - State: teams.StateIdle, - Text: "opened @" + role.handle + "; this team's auto-wake is off, so no turn was started. It reads the brief when it next runs.", - }) - } - if len(waking) == 0 { + if started := a.teamStarts(profile); len(started) > 0 { + a.teamWakeStart(profile, started, time.Now()) return } - if news := a.teamBoundary(); news != "" { - // AT THE CAP THE BRIEF WAITS: it is queued without the wake, and - // the member reads it at its first turn (team_cap.go). - held := a.teamCapHold(profile, a.teamRoles()) != "" - a.enqueueNote(userMessage{message: textMessage("user", news), wake: !held}) - } + } +} + +// teamWakeStart starts a fresh member's first turn on the brief it was started +// with, when the one decision says it may (team_wakedecide.go). +// +// IT IS DECIDED WHERE THE TRAFFIC WATCH'S WAKES ARE. This wake had rules of its +// own, in an order of its own, and said less: a member held at its team's cap +// or by the person's pause wrote nothing, so its manager read a helper it had +// just started as silent, and the brief was read off the log before the cap +// was asked. Now a held first turn writes the line the watch writes for the +// same hold, and the brief stays on the log until a turn may read it. What +// starts the turn is unchanged: the brief as the session's note, with the wake +// bit, and no line in the traffic. +func (a *Agent) teamWakeStart(profile string, started []teamRole, now time.Time) { + cause := wakeCause{kind: wakeStart, roles: started, pools: a.teamRoles()} + if d := a.decideWake(profile, &cause, now); d.verdict != wakeStarts { + a.teamWakeDeclined(profile, cause, d, now) return } + if news := a.teamBoundary(); news != "" { + a.enqueueNote(userMessage{message: textMessage("user", news), wake: true}) + } } // teamStarts is every team this conversation was just started into: a member @@ -167,6 +151,10 @@ func (a *Agent) teamStarts(profile string) []teamRole { for _, entry := range tail { if a.teamOwnStart(role, entry) { started = append(started, role) + // A first turn that is held answers this start. + a.team.mu.Lock() + a.teamAskedLocked(role, entry) + a.team.mu.Unlock() break } } diff --git a/internal/session/team_wake_test.go b/internal/session/team_wake_test.go index d8e238f67b..9af8cb9de9 100644 --- a/internal/session/team_wake_test.go +++ b/internal/session/team_wake_test.go @@ -244,3 +244,96 @@ func TestAFreshMemberWakesWithItsProjectsMemory(t *testing.T) { t.Fatalf("the fresh member's first request did not carry its project's memory:\n%s", system) } } + +// freshMember makes an empty conversation beside the fixture's own, which a +// test then starts into the team under handle. +func freshMember(t *testing.T, fixture teamFixture, handle string) string { + t.Helper() + dir := filepath.Join(filepath.Dir(filepath.Dir(fixture.parser)), handle) + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + transcript := filepath.Join(dir, placeTranscript) + if err := os.WriteFile(transcript, nil, 0o600); err != nil { + t.Fatal(err) + } + return transcript +} + +// A FIRST TURN HELD AT THE CAP SAYS SO, AND ITS BRIEF WAITS ON THE LOG. The +// fresh member's own watch read the brief off the log, found the cap, queued +// the brief with no wake and wrote nothing: the manager that had just started +// a helper saw no sign of it. It now writes the line the traffic watch writes +// for the same hold, once, and the brief is handed over by the first turn +// something else starts. +func TestAStartedMemberHeldAtTheCapSaysSoAndKeepsItsBrief(t *testing.T) { + fixture := newWakingTeamFixture(t) + five := 5.0 + if err := teams.Update(fixture.profile, func(f *teams.File) error { + return f.SetSettings(fixture.teamID, func(s *teams.Settings) { s.CapUSDDay = &five }) + }); err != nil { + t.Fatal(err) + } + stubCapSpend(t, &capSpend{usd: 6, stamp: "s1"}) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindStart, From: teams.FromManager, To: "lexer", Text: "Rewrite the lexer."}) + transcript := freshMember(t, fixture, "lexer") + completer := oneAnswer(1) + // Only the fresh member's own watch looks, so the line is this wake's. + lexer := teamAgent(t, fixture, transcript, completer, func(config *Config) { config.teamWatchManual = true }) + if err := teams.Update(fixture.profile, func(file *teams.File) error { + return file.AddMember(fixture.teamID, teams.Member{Key: convKeyOf(t, transcript), File: transcript, Handle: "lexer"}) + }); err != nil { + t.Fatal(err) + } + held := waitEvent(t, fixture, "held @lexer: harbor reached its $5 cap today") + if held.From != teams.FromSystem || held.To != "lexer" || held.State != teams.StateIdle { + t.Errorf("the cap's line is %+v, want from system to the member, idle", held) + } + time.Sleep(3 * teamWakeEvery) + if got := completer.requests(); got != 0 { + t.Fatalf("a member at its team's cap took %d turns on its brief", got) + } + if got := trafficEvents(t, fixture, "held @lexer"); len(got) != 1 { + t.Errorf("the cap hold was said %d times, want once", len(got)) + } + collect(t, mustSubmit(t, lexer, "go")) + if first := userTextIn(completer.request(0)); !briefIn(first, "Rewrite the lexer.") { + t.Fatalf("the brief a held first turn left on the log was not handed over:\n%s", first) + } +} + +// A MEMBER THE PERSON PAUSED BEFORE ITS FIRST TURN SAYS IT IS HELD. A directive +// to a paused member is said by the send that met the pause; a start has no +// send behind it, and the member held its first turn without a word. It writes +// the same line now, once, answering its start, and Resume starts the turn on +// the brief that waited. +func TestAStartedMemberThePersonPausedSaysItIsHeldAndStartsOnResume(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindStart, From: teams.FromManager, To: "lexer", Text: "Rewrite the lexer."}) + transcript := freshMember(t, fixture, "lexer") + completer := oneAnswer(1) + teamAgent(t, fixture, transcript, completer, nil) + if err := teams.Update(fixture.profile, func(file *teams.File) error { + return file.AddMember(fixture.teamID, teams.Member{Key: convKeyOf(t, transcript), File: transcript, Handle: "lexer", Paused: true}) + }); err != nil { + t.Fatal(err) + } + held := waitEvent(t, fixture, teamHeldPausedText("lexer")) + starts := trafficOf(t, fixture, teams.KindStart) + if len(starts) != 1 || held.From != teams.FromSystem || held.Answers != starts[0].ID { + t.Errorf("the hold's line is %+v, want from system, answering the start %+v", held, starts) + } + time.Sleep(3 * teamWakeEvery) + if got := completer.requests(); got != 0 { + t.Fatalf("a member paused before its first turn took %d turns", got) + } + if got := trafficEvents(t, fixture, teamHeldPausedText("lexer")); len(got) != 1 { + t.Errorf("the hold was said %d times, want once", len(got)) + } + setPaused(t, fixture, transcript, false) + waitRequests(t, completer, 1) + if first := userTextIn(completer.request(0)); !briefIn(first, "Rewrite the lexer.") { + t.Fatalf("the resumed member's first turn did not carry its brief:\n%s", first) + } +} diff --git a/internal/session/team_wakedecide.go b/internal/session/team_wakedecide.go index 3a1e51cdae..def46c68a0 100644 --- a/internal/session/team_wakedecide.go +++ b/internal/session/team_wakedecide.go @@ -41,6 +41,9 @@ const ( wakeDirective wakeKind = iota + 1 // wakeReplies is a manager's team: its members' posts and events. wakeReplies + // wakeStart is a fresh member's own start: the brief its manager started + // it with (team_wake.go). + wakeStart ) // wakeVerdict is what becomes of the turn that was asked for. @@ -72,6 +75,10 @@ const ( heldByLoop // heldByGate is one of the engine's own gates ([Agent.wakeRefusalLocked]). heldByGate + // heldByStandby is a membership made with no work to start on. + heldByStandby + // heldByAutoWakeOff is a team whose traffic starts no turn. + heldByAutoWakeOff ) // wakeCause is one request for a turn nobody typed. @@ -82,6 +89,10 @@ type wakeCause struct { roles []teamRole // batch is, for a manager, the entries that ask in each team. batch map[string][]teams.Entry + // pools are the roles whose caps bind this wake, when they are more than + // the roles that ask: a first turn is held by a cap on any team the + // conversation is in. + pools []teamRole } // wakeDecision is the answer, and why when it is not a start. @@ -105,7 +116,8 @@ type wakeRule func(a *Agent, profile string, c *wakeCause, now time.Time) wakeDe // directive sent in the second after the person pressed Pause reached the wake // as if nothing held it, and the turn it started consumed the directive the // pause was meant to keep. A manager is never paused, so its row has no pause; -// a member has no loop to break. +// a member has no loop to break. A first turn is not counted against the hour: +// it is the one turn its manager asked for by starting the member. var wakeRules map[wakeKind][]wakeRule // The table is filled at init because the rules reach, through the turn they @@ -114,6 +126,7 @@ func init() { wakeRules = map[wakeKind][]wakeRule{ wakeDirective: {wakeLimitRule, wakeCapRule, wakePauseRule}, wakeReplies: {wakeLoopRule, wakeLimitRule, wakeCapRule}, + wakeStart: {wakeStandbyRule, wakePauseRule, wakeAutoWakeOffRule, wakeCapRule}, } } @@ -164,7 +177,11 @@ func wakeLimitRule(a *Agent, _ string, _ *wakeCause, now time.Time) wakeDecision } func wakeCapRule(a *Agent, profile string, c *wakeCause, _ time.Time) wakeDecision { - if why := a.teamCapHold(profile, c.roles); why != "" { + pools := c.pools + if pools == nil { + pools = c.roles + } + if why := a.teamCapHold(profile, pools); why != "" { return wakeDecision{verdict: wakeHolds, by: heldByCap, why: why} } return wakeDecision{} @@ -172,10 +189,52 @@ func wakeCapRule(a *Agent, profile string, c *wakeCause, _ time.Time) wakeDecisi // wakePauseRule keeps the roles the person has not paused, remembering a hold // for each they have, and holds the wake when none is left. -func wakePauseRule(a *Agent, profile string, c *wakeCause, _ time.Time) wakeDecision { - if c.roles = a.teamPausedSince(profile, c.roles); len(c.roles) == 0 { - return wakeDecision{verdict: wakeHolds, by: heldByPause, why: teamPausedWhy} +func wakePauseRule(a *Agent, profile string, c *wakeCause, now time.Time) wakeDecision { + kept, paused := a.teamPausedSplit(profile, c.roles) + return a.wakeSetAside(profile, c, now, wakeDecision{verdict: wakeHolds, by: heldByPause, why: teamPausedWhy}, kept, paused) +} + +// wakeStandbyRule sets aside the memberships made on standby: the start line +// is the member's role, read at its first turn, and the manager's first +// directive is what begins that turn (team_pause.go). +func wakeStandbyRule(a *Agent, profile string, c *wakeCause, now time.Time) wakeDecision { + return a.wakeSetAsideWhere(profile, c, now, heldByStandby, func(role teamRole) bool { return role.standby }) +} + +// wakeAutoWakeOffRule honours the team's switch. The conversation is already +// open, which is what "opened" means in its line, and the brief stays unread +// until a turn something else starts: consuming it now would hand it over with +// nobody to read it. +func wakeAutoWakeOffRule(a *Agent, profile string, c *wakeCause, now time.Time) wakeDecision { + return a.wakeSetAsideWhere(profile, c, now, heldByAutoWakeOff, func(role teamRole) bool { return !role.wakes }) +} + +// wakeSetAsideWhere is [Agent.wakeSetAside] for a rule that reads the role. +func (a *Agent) wakeSetAsideWhere(profile string, c *wakeCause, now time.Time, by wakeHolder, holds func(teamRole) bool) wakeDecision { + var kept, aside []teamRole + for _, role := range c.roles { + if holds(role) { + aside = append(aside, role) + } else { + kept = append(kept, role) + } + } + return a.wakeSetAside(profile, c, now, wakeDecision{verdict: wakeHolds, by: by}, kept, aside) +} + +// wakeSetAside is a rule that holds a wake in some of its teams and not in +// others. The teams it holds are taken out of the cause and told so here; the +// wake goes on for the rest, and is held outright when none is left, which its +// caller then says of the teams that are. +func (a *Agent) wakeSetAside(profile string, c *wakeCause, now time.Time, held wakeDecision, kept, aside []teamRole) wakeDecision { + if len(kept) == 0 { + c.roles = aside + return held } + if len(aside) > 0 { + a.sayWake(profile, wakeCause{kind: c.kind, roles: aside}, held, now) + } + c.roles = kept return wakeDecision{} } @@ -198,9 +257,9 @@ func wakeLoopRule(a *Agent, _ string, _ *wakeCause, _ time.Time) wakeDecision { // sayWake writes what became of a wake to the traffic of each team that asked // for it, and is the only place a wake's line is written. Most decisions have -// a line and some have none: a pause is said by the send that met it -// (team_sendoutcome.go), a loop already tripped has been said, and a turn that -// was already running was not woken. +// a line and some have none: a directive's pause is said by the send that met +// it (team_sendoutcome.go), a loop already tripped has been said, a turn that +// was already running was not woken, and a first turn on a brief says nothing. // // THE WORDS ARE READ BACK BY MACHINES. `team_send` answers its manager from // these lines ([Agent.teamSendOutcome]), the rail and the digest parse `woke `, @@ -211,12 +270,22 @@ func (a *Agent) sayWake(profile string, c wakeCause, d wakeDecision, now time.Ti return } for _, role := range c.roles { - if entry, ok := a.wakeLine(c, role, d); ok { - a.teamSay(profile, role.id, entry) + entry, ok := a.wakeLine(c, role, d) + if !ok || (wakeSaidPerEntry(d) && teamSaidAlready(profile, role.id, entry)) { + continue } + a.teamSay(profile, role.id, entry) } } +// wakeSaidPerEntry reports whether a decision's line is said once for the entry +// it answers, by looking at the log. A member's first turn is looked at by two +// watches (team_wake.go, team_wakewatch.go) and a fresh conversation is fresh +// every time it is opened, so these holds would otherwise be said again. +func wakeSaidPerEntry(d wakeDecision) bool { + return d.by == heldByStandby || d.by == heldByPause || d.by == heldByGate +} + // wakeSayOnce reports whether this decision's line is still to be said. A cap // hold is said once per conversation and reason, because every held wake says // the same thing and the cap's packet is what asks the person; the hour's limit @@ -254,6 +323,10 @@ func (a *Agent) wakeLine(c wakeCause, role teamRole, d wakeDecision) (teams.Entr // directive. The turn takes the lines at its next step and the traffic // says nothing: the send reads a running member off its journal. return teams.Entry{}, false + case d.verdict == wakeStarts && c.kind == wakeStart: + // A first turn on a brief has never had a line: the start above it is + // the manager's own, and the member's turn says the rest. + return teams.Entry{}, false case d.verdict == wakeStarts: entry.State = teams.StateRunning if role.manager { @@ -274,6 +347,14 @@ func (a *Agent) wakeLine(c wakeCause, role teamRole, d wakeDecision) (teams.Entr if !role.manager { entry.Answers = a.teamAsked(role.id) } + case d.by == heldByPause && c.kind == wakeStart: + // A directive's pause is said by the send that met it. A start has no + // send behind it, so the member says the same line, answering its start. + entry.Text, entry.Answers = teamHeldPausedText(role.handle), a.teamAsked(role.id) + case d.by == heldByStandby: + entry.Text = teamStandbyText(role.handle) + case d.by == heldByAutoWakeOff: + entry.Text = teamAutoWakeOffText(role.handle) case d.by == heldByLoop && d.why != "": // The manager asks the room: the rail draws it in the needs-you colour // and a digest reads it as the manager waiting. diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 5b95942cb4..7a6c172991 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -230,13 +230,9 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { arrived := a.teamWatchReadLocked(profile, role) var waking []teams.Entry for _, entry := range arrived { - if role.manager && entry.Kind == teams.KindEvent && entry.State == teams.StateFinished && - teamFinishedAfterReply(profile, role.id, entry) { - continue - } // Membership can arrive after the fresh-session watch expires. // Its own start still owes this member its first turn. - if a.teamOwnStartWakes(role, entry) || teamWakes(role, entry) || teamPacketWakes(profile, role, entry) { + if wakes, _ := teamEntryWakes(profile, role, entry, a.teamOwnStart(role, entry)); wakes { waking = append(waking, entry) a.teamAskedLocked(role, entry) } @@ -499,6 +495,33 @@ func topManager(file *teams.File, key string) bool { return false } +// teamEntryWakes is the one answer to whether an entry on a team's log starts +// role's turn, asked by the watch of an open conversation and by the look that +// decides whether a closed one needs opening ([TeamOpenPending]). They each had +// their own, and differed on a member's own start. +// +// own says the entry is the start that made this membership. Only the caller +// can tell: an open conversation knows when it was born ([Agent.teamOwnStart]), +// and the look at a closed one has only the log. +// +// quiet says the rule has decided the entry is no reason to run at all, which +// is also no reason to open the conversation for the line it carries: +// +// - a manager's member finishing a turn that already replied +// ([teamFinishedAfterReply]): one reply is one wake; +// - a member's own start while it is on standby: the line is its role, read +// at its first turn, and not work to begin (team_pause.go). +func teamEntryWakes(profile string, role teamRole, entry teams.Entry, own bool) (wakes, quiet bool) { + if role.manager && entry.Kind == teams.KindEvent && entry.State == teams.StateFinished && + teamFinishedAfterReply(profile, role.id, entry) { + return false, true + } + if own { + return !role.standby, role.standby + } + return teamWakes(role, entry) || teamPacketWakes(profile, role, entry), false +} + // teamWakes reports whether an entry starts this conversation's turn when it // is idle: a directive from the manager to its handle or to everyone, for a // member; a member's post to the manager, or a member's finished, failed or From 2f2945ffc7e35c2ed796c94492c9dd467dc3a27b Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:07:25 -0500 Subject: [PATCH 27/37] teams: the stop hold is read where a command's ending is queued The hold was read before the agent's lock was taken and the ending queued under a second hold of it, so a command that ended in the instant of a stop found no hold, waited for the stop to let go and woke the stopped conversation. The hold is now a row of the wake table, decided by the note's cause under the lock the note is queued under, in the one function the three endings share. The record and the release of a parked worker stay one locked step, and the traffic is told nothing, as before. Co-Authored-By: Claude Fable 5.2 --- internal/session/agent.go | 31 ++++++++++++------- internal/session/team_stophold.go | 21 +++---------- internal/session/team_stophold_test.go | 41 ++++++++++++++++++++++++++ internal/session/team_wakedecide.go | 35 ++++++++++++++++++++++ 4 files changed, 101 insertions(+), 27 deletions(-) diff --git a/internal/session/agent.go b/internal/session/agent.go index 6a9a16e854..58b96f0432 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -1446,6 +1446,10 @@ func (a *Agent) attachReplayLocked() (entries []DisplayEntry, events <-chan Even // Everything the person types is one of these. A text-only message has no // references and journals exactly as it always did. type userMessage struct { + // cause is what kind of news a session's note carries, for the notes whose + // wake a standing hold may keep as a record instead (team_wakedecide.go's + // [wakeStanding]). Zero is a note no such hold binds. + cause wakeKind // factoryWork marks a runtime manager turn, never the person's chat. factoryWork bool // runner marks words the factory's runner wrote ([runnerNote]): the turn @@ -4238,19 +4242,16 @@ func (a *Agent) enqueueSettleSteering(text string, ceiling int) { // as [jobRegistry.settleExit] composed it. The whole log remains available // through `jobs output` for anything past the tail. func (a *Agent) enqueueJobNote(text string) { - if a.teamStopHeldNote(text) { - return - } - a.enqueueNote(jobNote(text)) + note := jobNote(text) + note.cause = wakeCommand + a.enqueueNote(note) } // enqueueJobNoteUnowed carries the registry's unowed process ending to the // same queue, retaining the one fact the idle wake scheduler needs. func (a *Agent) enqueueJobNoteUnowed(text string) { - if a.teamStopHeldNote(text) { - return - } note := jobNote(text) + note.cause = wakeCommand note.deferJobWake = true a.enqueueNote(note) } @@ -4301,10 +4302,8 @@ func (a *Agent) quietNoteLocked(text string) { // news does not carry one. func (a *Agent) enqueueWatchNote(name, text string, fired bool) { if fired { - if a.teamStopHeldNote(text) { - return - } note := wakeNote(text) + note.cause = wakeWatch note.otherResults = true note.attention = true a.enqueueNote(note) @@ -4431,6 +4430,18 @@ func (a *Agent) enqueueNote(note userMessage) bool { if a.closed || (note.closeKey != "" && a.running) { return false } + if held := a.standingHoldLocked(note.cause); held.verdict == wakeHolds { + // A STANDING HOLD KEEPS THE NEWS AS A RECORD AND STARTS NO TURN + // (team_stophold.go), and it is asked HERE, under the lock the note + // would be queued under. It was asked before the lock was taken, and a + // command that ended in the instant of a stop found no hold, waited + // for the stop to let the lock go and queued its ending as a wake. A + // worker parked on the command is released in the same step, as the + // waking note's own append releases it below. + a.quietNoteLocked(text + "\n" + held.why) + a.releaseTaskWaitLocked() + return true + } a.steering = append(a.steering, note) if note.steered || note.ending { // A NODE'S RUNNER IS WAITING TO BE TOLD, and this is the same release a diff --git a/internal/session/team_stophold.go b/internal/session/team_stophold.go index dcb0cbf0a8..2abdc0a4d3 100644 --- a/internal/session/team_stophold.go +++ b/internal/session/team_stophold.go @@ -13,7 +13,10 @@ package session // // So in a team, from a stop of a running turn until a turn next begins, the // ending of a background command and a watch's firing are kept as a record and -// start no turn. The stop is the person's own or a manager's team_stop, whoever +// start no turn. The hold is one row of the table that decides every wake +// ([wakeStanding]) and is read where the ending would be queued, under the +// lock a stop takes ([Agent.enqueueNote]), so no ending slips between a stop +// and its hold. The stop is the person's own or a manager's team_stop, whoever // performs the latter: an interface, through the person's door (teamevent.go), // or the member's own session, through the manager's ([Agent.interruptTeamTurn]). // The command itself is left running, as an interrupt always leaves it. Only @@ -41,7 +44,6 @@ package session // turn carried the work, was the person's own, or there was no turn at all. import ( - "strings" "sync" "sync/atomic" @@ -202,18 +204,3 @@ func (r *jobRegistry) awaited() bool { } return false } - -// teamStopHeldNote keeps one piece of background news as a record when the -// hold stands, and reports whether it did. A worker parked on the command is -// released in the locked step that records it, as the waking note's own append -// releases it ([Agent.enqueueNote]). -func (a *Agent) teamStopHeldNote(text string) bool { - if !a.team.stopHold.held.Load() { - return false - } - a.mu.Lock() - defer a.mu.Unlock() - a.quietNoteLocked(strings.TrimSpace(text) + "\n" + teamStopHeldRule) - a.releaseTaskWaitLocked() - return true -} diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go index 8a8a746e96..a180f1d105 100644 --- a/internal/session/team_stophold_test.go +++ b/internal/session/team_stophold_test.go @@ -423,3 +423,44 @@ func TestTeamAManagersEarlierStopDoesNotHideThePersonsStop(t *testing.T) { waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) waitManagerToldOfStop(t, managerCalls) } + +// THE HOLD IS READ UNDER THE LOCK THE NOTE IS QUEUED UNDER. It was read first +// and the lock taken afterwards, so a command ending in the instant of a stop +// found no hold, waited for the stop to let go of the lock, and then queued +// its ending as news that started the stopped conversation again. The test +// holds the lock every stop takes, lets a command's ending arrive at it, and +// only then lets the stop's hold land: the ending must find it. +func TestTeamStopHoldIsReadWhereTheEndingIsQueued(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + calls := oneAnswer(1) + web := teamAgent(t, fixture, fixture.web, calls, func(config *Config) { config.teamWatchManual = true }) + if roles := web.teamRoles(); len(roles) == 0 { + t.Fatal("the member has no seat in its team") + } + web.mu.Lock() + arrived := make(chan struct{}) + queued := make(chan struct{}) + go func() { + close(arrived) + web.enqueueJobNote("job 8 exited 0") + close(queued) + }() + <-arrived + // Long enough for the ending to reach the lock it has to wait at. + time.Sleep(100 * time.Millisecond) + web.team.stopHold.held.Store(true) + web.mu.Unlock() + <-queued + quietFor() + if got := calls.requests(); got != 0 { + t.Fatalf("a command ending at the instant of a stop started %d turns", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), "job 8 exited 0") || strings.Count(string(journal), teamStopHeldRule) != 1 { + t.Fatalf("the ending was not kept as one record that says why it started no turn:\n%s", journal) + } +} diff --git a/internal/session/team_wakedecide.go b/internal/session/team_wakedecide.go index def46c68a0..471a27b14e 100644 --- a/internal/session/team_wakedecide.go +++ b/internal/session/team_wakedecide.go @@ -13,6 +13,10 @@ package session // said why; and each caller wrote its own line, so `woke` was written for a // turn that had been running all along. // +// A hold that stands on the conversation itself, a stop until a turn next +// begins, is the same table's second half ([wakeStanding]): it binds the news +// that arrives through the session's own queue, and is read there. +// // SO ONE FUNCTION DECIDES AND ONE WRITES. A caller says what is asking for the // turn (a [wakeCause]); [Agent.decideWake] answers start, queue, hold or // nothing (a [wakeDecision]) from one table of which rule binds which cause; @@ -44,6 +48,10 @@ const ( // wakeStart is a fresh member's own start: the brief its manager started // it with (team_wake.go). wakeStart + // wakeCommand is a background command ending ([Agent.enqueueJobNote]). + wakeCommand + // wakeWatch is a watch firing ([Agent.enqueueWatchNote]). + wakeWatch ) // wakeVerdict is what becomes of the turn that was asked for. @@ -75,6 +83,9 @@ const ( heldByLoop // heldByGate is one of the engine's own gates ([Agent.wakeRefusalLocked]). heldByGate + // heldByStop is a stop of this conversation's turn, standing until a turn + // next begins (team_stophold.go). + heldByStop // heldByStandby is a membership made with no work to start on. heldByStandby // heldByAutoWakeOff is a team whose traffic starts no turn. @@ -130,6 +141,30 @@ func init() { } } +// wakeStanding is which of a conversation's standing holds bind which cause. +// A standing hold is the agent's own state, read under a.mu where the news is +// queued, and what it holds is kept in the conversation as a record that +// starts no turn: the record is its line, and the traffic is told nothing. +// +// Only a command's ending and a watch's firing are held by a stop. The +// person's own words, a manager's next hand-off and a task landing still start +// a turn, which ends that hold (team_stophold.go). +var wakeStanding = map[wakeKind]struct{ stop bool }{ + wakeCommand: {stop: true}, + wakeWatch: {stop: true}, +} + +// standingHoldLocked is the standing hold that keeps news of this kind from +// starting a turn, with the sentence its record is given as why; the zero +// decision when none does. The caller holds a.mu. +func (a *Agent) standingHoldLocked(kind wakeKind) wakeDecision { + binds := wakeStanding[kind] + if binds.stop && a.team.stopHold.held.Load() { + return wakeDecision{verdict: wakeHolds, by: heldByStop, why: teamStopHeldRule} + } + return wakeDecision{} +} + // decideTeamWake asks the team's rules for this cause, and answers the first // hold or a start. It takes no lock of its own and must not be called under // a.mu: the rules read the teams file and the ledger. From e3903ba147c0e7365f5da0309b7c08ef251c97c9 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:26:39 -0500 Subject: [PATCH 28/37] teams: the engine holds a paused member's other wakes too A pause was decided before a turn started for team traffic only. A command ending, a watch firing, a task landing and news recorded as a turn ended each started the paused member's turn, and only the desktop app, where it held the member, ended that turn after it began. The engine now decides them by cause, in the wake table's standing holds: while a conversation is paused in any of its teams and no turn is running, what arrived is kept in the conversation as a record that starts no turn, with a sentence saying why, as the stop hold keeps a command's ending. The next turn reads it. The person's own words are never held, and the app's stop of a stray wake stays as a fallback. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2897-crew-handoff-outcome.md | 1 + internal/manual/chat/team-manager.md | 8 +- internal/session/agent.go | 7 +- internal/session/image.go | 2 +- internal/session/job_wake.go | 7 + internal/session/task_run_belt.go | 9 ++ internal/session/team.go | 5 + internal/session/team_pause.go | 58 +++++++- internal/session/team_pause_test.go | 125 ++++++++++++++++-- internal/session/team_wakedecide.go | 73 ++++++++-- 10 files changed, 260 insertions(+), 35 deletions(-) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index be13afee41..f736aba1a9 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -31,6 +31,7 @@ invalidates: - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." + - "A pause held team traffic only: in a paused member a background command ending, a watch firing, a task landing, and news recorded as a turn ended each started a turn, which the desktop app then stopped where it held the member (appwakes.go) and nothing stopped where it did not. The engine now decides those by cause (wakeStanding and Agent.standingHoldLocked in internal/session/team_wakedecide.go): while a conversation is paused in any of its teams and no turn is running, a command's ending and a watch's firing are written into it as a record ending \"This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened.\" (teamPauseHeldRule), a task landing is recorded as its quiet receipt with that sentence, and news a turn's end recorded starts no further turn and is followed by that sentence. The next turn reads them: one the person's own words open, which is never held, or the turn Resume starts on a directive that waited. A question's answer and a decision the person hands over still start their turn, and the app's stop of a paused member's stray wake is unchanged." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 46bc680482..81678bbb54 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -686,10 +686,10 @@ between. With the team's auto-wake off, a resumed member reads it at its next tu other message. Your own words are not held: typing into a paused member's conversation starts its turn, and -that turn reads what was waiting, so Resume starts nothing more on it. Any other wake, such as -a background process ending, reads none of the crew's lines and is stopped at once in the -desktop app. A pause made by an earlier version of the app is carried onto the team's record -the first time the updated app opens. +that turn reads what was waiting, so Resume starts nothing more on it. Nothing else starts a +paused member: a background command ending, a watch firing or a task landing is written into +its conversation as a record, and its next turn reads it. A pause made by an earlier version +of the app is carried onto the team's record the first time the updated app opens. ## A new crew's members wait on standby — why nobody started after Make the crew diff --git a/internal/session/agent.go b/internal/session/agent.go index 58b96f0432..22fbe51db2 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -2371,7 +2371,7 @@ func (a *Agent) startTurnLocked(ctx context.Context, user userMessage, watcher * // started. Interrupt and Close still reach it — both go through // a.cancel, which this call replaces. a.startTurnLocked(context.Background(), next.message, next.stream) - } else if completed && unanswered && a.wakeAnsweringLocked(drained.heard, drained.only, drained.answer) { + } else if completed && unanswered && !a.turnEndHeldLocked(drained) && a.wakeAnsweringLocked(drained.heard, drained.only, drained.answer) { // SOMETHING LANDED IN THE LAST SECONDS OF THIS TURN. A task's // note, or the person typing while the answer was still // streaming: steering lands at a STEP boundary, and a turn whose @@ -4425,6 +4425,11 @@ func (a *Agent) enqueueNote(note userMessage) bool { if !note.steered { note.authored = true } + if wakeStanding[note.cause].pause { + // The pause this note may be held by is read now, off the lock: it is + // the person's word in a file another process writes (team_pause.go). + a.teamPauseFresh() + } a.mu.Lock() defer a.mu.Unlock() if a.closed || (note.closeKey != "" && a.running) { diff --git a/internal/session/image.go b/internal/session/image.go index c668417ebb..9d3c850b2e 100644 --- a/internal/session/image.go +++ b/internal/session/image.go @@ -514,7 +514,7 @@ func (a *Agent) startVisionTurnLocked(ctx context.Context, kept userMessage, liv // An ordinary turn, on the chat model: the follow-up is words, // and words are what that model can read. a.startTurnLocked(context.Background(), next.message, next.stream) - } else if completed && drained.owed { + } else if completed && drained.owed && !a.turnEndHeldLocked(drained) { // Vision reads only the image message. News recorded at its end // still needs an ordinary turn, even if its wake clock fired. a.wakeAnsweringLocked(drained.heard, drained.only, drained.answer) diff --git a/internal/session/job_wake.go b/internal/session/job_wake.go index 98f3647871..2a60197dad 100644 --- a/internal/session/job_wake.go +++ b/internal/session/job_wake.go @@ -37,6 +37,13 @@ func (a *Agent) deferJobWakeLocked() { return } a.jobWake = nil + // A HOLD THAT BEGAN INSIDE THE WINDOW STILL HOLDS. The endings were + // queued before the person paused the conversation, and the turn this + // clock would start is the one the pause is there to keep from + // starting; they stay queued for the next turn (team_wakedecide.go). + if a.standingHoldLocked(wakeCommand).verdict == wakeHolds { + return + } a.wakeLocked() }) } diff --git a/internal/session/task_run_belt.go b/internal/session/task_run_belt.go index 5854b1d062..48a674cf7e 100644 --- a/internal/session/task_run_belt.go +++ b/internal/session/task_run_belt.go @@ -2489,6 +2489,10 @@ func (a *Agent) deliverBeltRunLanding(run *beltRun, summary RunSummary, landing // admitBeltLanding makes the last quiet check and wake admission one step // against page Stop. Receipt construction and persistence happen outside it. +// +// A CONVERSATION THE PERSON PAUSED IS NOT STARTED BY A LANDING. The result is +// kept as the quiet record a late stop keeps, with the sentence that says why +// it started no turn, and the next turn reads it (team_pause.go). func (a *Agent) admitBeltLanding(run *beltRun, summary RunSummary, line string, landing RunLanding, note userMessage) { run.deliveryMu.Lock() if a.beltRunQuiet(run) { @@ -2496,6 +2500,11 @@ func (a *Agent) admitBeltLanding(run *beltRun, summary RunSummary, line string, a.recordQuietBeltLanding(run, summary, line, landing) return } + if held := a.standingHold(wakeLanding); held.verdict == wakeHolds { + run.deliveryMu.Unlock() + a.recordQuietBeltLanding(run, summary, line+"\n"+held.why, landing) + return + } a.accept(delivery{origin: fromRuntime, kind: msgResult, note: note}) run.deliveryMu.Unlock() } diff --git a/internal/session/team.go b/internal/session/team.go index 293f66af4e..128cef631e 100644 --- a/internal/session/team.go +++ b/internal/session/team.go @@ -273,6 +273,9 @@ type teamSeat struct { // stopHold is the person's stop of this conversation's turn while it sat // in a team, kept until a turn next begins (team_stophold.go). stopHold teamStopHold + // pauseHold is the person's pause of this conversation, as the wakes + // decided under the agent's lock read it (team_pause.go). + pauseHold teamPauseHold } // teamAnsweringLocked is the id this conversation's replies in team id answer @@ -386,6 +389,7 @@ func (a *Agent) teamRolesLocked(profile string) []teamRole { a.team.teamsAt, a.team.roles, a.team.file = now, nil, nil a.team.events.member.Store(false) a.team.stopHold.seated.Store(false) + a.team.pauseHold.paused.Store(false) return nil } file, err := teamView(profile, keys) @@ -400,6 +404,7 @@ func (a *Agent) teamRolesLocked(profile string) []teamRole { a.team.file = file a.team.events.member.Store(eventfulRoles(a.team.roles)) a.team.stopHold.seated.Store(len(a.team.roles) > 0) + a.team.pauseHold.paused.Store(pausedRoles(a.team.roles)) return a.team.roles } diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 6eedab955c..140c7d840c 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -18,12 +18,24 @@ package session // for it to be opened. Something else may still open it (a question's answer, // a wake the retry queue kept); it is then open and held, which costs nothing. // -// AND WHERE THE TRAFFIC IS DELIVERED. A turn something else starts in a paused -// member (a sub-task landing, a command ending) reads none of its teams' lines -// and moves no cursor ([Agent.teamNewsLocked]): its first request used to carry -// the held directive, and the resume then had nothing to start on. A turn that -// does deliver them, the person's own, ends the hold, so the resume starts no -// second turn on lines already read. +// AND WHERE THE TRAFFIC IS DELIVERED. A turn that is not the person's own reads +// none of a paused member's teams' lines and moves no cursor +// ([Agent.teamNewsLocked]): its first request used to carry the held directive, +// and the resume then had nothing to start on. A turn that does deliver them, +// the person's own, ends the hold, so the resume starts no second turn on +// lines already read. +// +// AND NOTHING ELSE STARTS A TURN EITHER. The pause was decided for traffic and +// for nothing else: a background command ending, a watch firing, a task landing +// and news recorded as a turn ended each started the paused member's turn, and +// only an interface that happened to hold the member ended it again +// (cmd/codeaf's appwakes.go), after it had begun and where no interface held +// it, not at all. The engine decides those too now, by the cause of the news +// ([wakeStanding]): what arrived is kept in the conversation as a record that +// starts no turn, with [teamPauseHeldRule] saying why, exactly as a stop keeps +// a command's ending (team_stophold.go). The next turn reads it: the person's +// own words, or the turn Resume starts on a directive that waited. The +// interface's stop stays as it was, for a wake this file does not decide. // // A PAUSE IS THE PERSON'S WORD ABOUT THE CONVERSATION, so it holds in every // team the conversation is a member of ([teams.File.PausedAnywhere]), not only @@ -43,6 +55,7 @@ package session import ( "strings" + "sync/atomic" "time" "github.com/Agent-Field/codeaf/internal/guard" @@ -53,6 +66,39 @@ import ( // and the traffic are both given. const teamPausedWhy = "the person paused it; it starts on this when they resume it" +// teamPauseHeldRule is said with news that started no turn because the person +// had the conversation paused. +const teamPauseHeldRule = "This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened." + +// teamPauseHold is one conversation's pause, for the wakes that are decided +// under the agent's lock and may read neither the teams file nor the seat's +// lock there. +type teamPauseHold struct { + // paused is whether the person has this conversation paused in any of its + // teams, as of the last time its roles were read. Read without a lock or a + // disk. + paused atomic.Bool +} + +// pausedRoles reports whether any of roles is paused. A pause holds the +// conversation in every team it is a member of ([rolesFor]), so one is all. +func pausedRoles(roles []teamRole) bool { + for _, role := range roles { + if role.paused { + return true + } + } + return false +} + +// teamPauseFresh reads this conversation's roles again when the teams store has +// moved, so the pause a wake is about to be decided on is the one on the +// record now and not the one the last boundary read. It costs one look at the +// store's stamp for each piece of news a pause could hold, and nothing for a +// conversation that can be in no team. It takes the seat's lock and must not +// be called under a.mu. +func (a *Agent) teamPauseFresh() { a.teamRoles() } + // teamHeldPausedText is the traffic line for a directive a paused member was // sent: "held @mac-dev: the person paused it; …". func teamHeldPausedText(handle string) string { diff --git a/internal/session/team_pause_test.go b/internal/session/team_pause_test.go index 74f9ead613..6d9930c51e 100644 --- a/internal/session/team_pause_test.go +++ b/internal/session/team_pause_test.go @@ -1,10 +1,15 @@ package session import ( + "context" + "os" "strings" "testing" "time" + "github.com/Agent-Field/agentfield/sdk/go/ai" + + "github.com/Agent-Field/codeaf/internal/plandb" "github.com/Agent-Field/codeaf/internal/teams" ) @@ -600,10 +605,15 @@ func sendTeamNote(t *testing.T, manager *Agent, to string) { } } -// A TURN SOMETHING ELSE STARTS IN A PAUSED MEMBER READS NONE OF ITS TEAM'S -// LINES. A command's ending woke the member, that turn's first request carried -// the held directive, and the resume then started nothing: the manager had been -// told the directive waited for it. +// NOTHING BUT THE PERSON STARTS A PAUSED MEMBER, AND THE ENGINE DECIDES IT. +// A command's ending woke the paused member, and only the desktop app, where +// it held the member, ended that turn after it began; an earlier fault had the +// turn's first request carry the held directive, so the resume started +// nothing. Here no interface is in the loop: a command's ending and a watch's +// firing start no turn, each is kept in the conversation as a record that says +// why, the held directive stays held, and the turn Resume starts reads the +// directive and the records together. After that a command's ending starts a +// turn again. func TestTeamPausedMembersOtherWakeLeavesTheDirectiveHeld(t *testing.T) { fastTeamWake(t) fixture := newWakingTeamFixture(t) @@ -615,22 +625,111 @@ func TestTeamPausedMembersOtherWakeLeavesTheDirectiveHeld(t *testing.T) { quietFor() web.enqueueJobNote("job 8 exited 0") - waitRequests(t, webCalls, 1) - waitQuiet(t, web) - if asked := userTextIn(webCalls.request(0)); strings.Contains(asked, "Fix the header.") { - t.Fatalf("a paused member's turn on a command's ending was handed the held directive:\n%s", asked) - } + web.enqueueWatchNote("checks", "the checks settled", true) quietFor() - if got := webCalls.requests(); got != 1 { - t.Fatalf("the paused member made %d model calls, want only the command's turn", got) + if got := webCalls.requests(); got != 0 { + t.Fatalf("a paused member was started %d times by a command's ending and a watch", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"job 8 exited 0", "the checks settled"} { + if !strings.Contains(string(journal), want) { + t.Fatalf("%q was not kept as a record:\n%s", want, journal) + } + } + if got := strings.Count(string(journal), teamPauseHeldRule); got != 2 { + t.Fatalf("the record said why it started no turn %d times, want 2", got) } setPaused(t, fixture, fixture.web, false) - waitRequests(t, webCalls, 2) - asked := userTextIn(webCalls.request(1)) + waitRequests(t, webCalls, 1) + asked := userTextIn(webCalls.request(0)) if strings.Count(asked, "Fix the header.") != 1 || !strings.Contains(asked, teamWakeMemberLead) { t.Fatalf("the resumed member was not started on the directive that waited, once:\n%s", asked) } + for _, want := range []string{"job 8 exited 0", "the checks settled", teamPauseHeldRule} { + if !strings.Contains(asked, want) { + t.Fatalf("the turn Resume started did not read %q:\n%s", want, asked) + } + } + waitQuiet(t, web) + web.enqueueJobNote("job 9 exited 0") + waitRequests(t, webCalls, 2) +} + +// NEWS A PAUSED MEMBER'S OWN TURN LEFT UNREAD STARTS NO TURN AT ITS END. The +// person typed into a paused member, which is theirs to do, and a command +// ended after that turn's last request had gone out. The turn's end records +// the ending and would start one more turn to answer it, a turn nobody typed +// in a conversation the person paused. It is kept as a record instead. +func TestTeamPausedMembersTurnEndStartsNoTurnOnACommandsEnding(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + var web *Agent + calls := &scriptedCompleter{steps: []step{ + func(context.Context, []ai.Message) (*ai.Response, error) { + web.enqueueJobNote("job 8 exited 0") + return textResponse("started"), nil + }, + okStep(), + }} + web = teamAgent(t, fixture, fixture.web, calls, nil) + collect(t, mustSubmit(t, web, "start the build")) + waitQuiet(t, web) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the paused member made %d model calls, want only the person's turn", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), "job 8 exited 0") || strings.Count(string(journal), teamPauseHeldRule) != 1 { + t.Fatalf("the ending was not kept as one record that says why it started no turn:\n%s", journal) + } +} + +// A TASK LANDING IN A PAUSED MEMBER IS KEPT AS ITS RECEIPT. The landing would +// start the turn that answers it; the person paused the conversation, so the +// result is recorded with its task's identity, as a late stop records it, and +// says why no turn began. +func TestTeamPausedMembersTaskLandingIsKeptAsARecord(t *testing.T) { + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + calls := oneAnswer(1) + web := teamAgent(t, fixture, fixture.web, calls, func(config *Config) { config.teamWatchManual = true }) + store := askStore(t, "repair parser") + defer store.Close() + question := "What did the repair find?" + if _, err := store.Revise(store.RootID(), plandb.TaskPatch{Question: &question}); err != nil { + t.Fatal(err) + } + run := &beltRun{store: store, root: store.RootID(), row: 98, title: "Parser", bringingHome: true} + web.beltMu.Lock() + web.beltRun = run + web.beltMu.Unlock() + t.Cleanup(func() { web.beltMu.Lock(); web.beltRun = nil; web.beltMu.Unlock() }) + web.deliverBeltRunLanding(run, RunSummary{Outcome: beltRunOutcomeDone, Result: "Preserved result."}, RunLanding{}) + web.mu.Lock() + woke := web.running || len(web.steering) != 0 + web.mu.Unlock() + if woke || calls.requests() != 0 { + t.Fatal("a task landing started a paused member's turn") + } + entries := web.Transcript() + if len(entries) != 1 || !entries[0].RoutineCompletion || len(entries[0].CompletionTasks) != 1 || entries[0].CompletionTasks[0].ID != run.row { + t.Fatalf("the held landing lost its task's identity: %+v", entries) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), "Preserved result.") || strings.Count(string(journal), teamPauseHeldRule) != 1 { + t.Fatalf("the landing was not kept with why it started no turn:\n%s", journal) + } } // A HOLD ENDS WHEN ITS LINES ARE READ. The person typed into the paused member diff --git a/internal/session/team_wakedecide.go b/internal/session/team_wakedecide.go index 471a27b14e..b05d7e13a5 100644 --- a/internal/session/team_wakedecide.go +++ b/internal/session/team_wakedecide.go @@ -13,10 +13,6 @@ package session // said why; and each caller wrote its own line, so `woke` was written for a // turn that had been running all along. // -// A hold that stands on the conversation itself, a stop until a turn next -// begins, is the same table's second half ([wakeStanding]): it binds the news -// that arrives through the session's own queue, and is read there. -// // SO ONE FUNCTION DECIDES AND ONE WRITES. A caller says what is asking for the // turn (a [wakeCause]); [Agent.decideWake] answers start, queue, hold or // nothing (a [wakeDecision]) from one table of which rule binds which cause; @@ -28,6 +24,13 @@ package session // off the agent's ([wakeRules]). The engine's gates are the agent's own state // and are read under a.mu ([Agent.decideWakeLocked]), where the turn is then // started in the same hold, so the answer is the wake's own. +// +// AND SOME HOLDS STAND ON THE CONVERSATION ITSELF: a stop, until a turn next +// begins, and the person's pause. They bind the news that arrives through the +// session's own queue (a command's ending, a watch's firing, a task landing, +// what a turn's end recorded), and are read where that news is queued +// ([wakeStanding], [Agent.standingHoldLocked]). What they hold is kept in the +// conversation as a record that starts no turn, and that record is its line. import ( "fmt" @@ -52,6 +55,11 @@ const ( wakeCommand // wakeWatch is a watch firing ([Agent.enqueueWatchNote]). wakeWatch + // wakeLanding is a background task landing ([Agent.admitBeltLanding]). + wakeLanding + // wakeAnswer is news a turn's end recorded with no request left to read it, + // which is owed one more turn ([Agent.turnEndHeldLocked]). + wakeAnswer ) // wakeVerdict is what becomes of the turn that was asked for. @@ -146,25 +154,70 @@ func init() { // queued, and what it holds is kept in the conversation as a record that // starts no turn: the record is its line, and the traffic is told nothing. // -// Only a command's ending and a watch's firing are held by a stop. The -// person's own words, a manager's next hand-off and a task landing still start -// a turn, which ends that hold (team_stophold.go). -var wakeStanding = map[wakeKind]struct{ stop bool }{ - wakeCommand: {stop: true}, - wakeWatch: {stop: true}, +// A STOP HOLDS ONLY A COMMAND'S ENDING AND A WATCH'S FIRING. The person's own +// words, a manager's next hand-off and a task landing still start a turn, +// which ends that hold (team_stophold.go). +// +// A PAUSE HOLDS EVERY TURN NOBODY TYPED, these four and the team's traffic +// ([wakePauseRule]): the person paused the conversation, not one of the ways +// it starts. Their own words are no row here, because they are never held. +var wakeStanding = map[wakeKind]struct{ stop, pause bool }{ + wakeCommand: {stop: true, pause: true}, + wakeWatch: {stop: true, pause: true}, + wakeLanding: {pause: true}, + wakeAnswer: {pause: true}, } // standingHoldLocked is the standing hold that keeps news of this kind from // starting a turn, with the sentence its record is given as why; the zero // decision when none does. The caller holds a.mu. +// +// A PAUSE HOLDS NOTHING FROM A TURN IN FLIGHT. The only turn that runs in a +// paused conversation is one the person's own words opened, and news that +// arrives while it runs is that turn's to read at its next step, as anywhere. +// What it leaves unread at its end is asked about again there +// ([Agent.turnEndHeldLocked]). A stop holds through the turn it stopped, which +// is still winding down when a command it left behind ends. func (a *Agent) standingHoldLocked(kind wakeKind) wakeDecision { binds := wakeStanding[kind] if binds.stop && a.team.stopHold.held.Load() { return wakeDecision{verdict: wakeHolds, by: heldByStop, why: teamStopHeldRule} } + if binds.pause && !a.running && a.team.pauseHold.paused.Load() { + return wakeDecision{verdict: wakeHolds, by: heldByPause, why: teamPauseHeldRule} + } return wakeDecision{} } +// standingHold is [Agent.standingHoldLocked] for a caller that holds no lock +// and records the news itself, with the pause read afresh first. +func (a *Agent) standingHold(kind wakeKind) wakeDecision { + a.teamPauseFresh() + a.mu.Lock() + defer a.mu.Unlock() + return a.standingHoldLocked(kind) +} + +// turnEndHeldLocked reports whether a standing hold keeps the turn that would +// answer what a turn's end just recorded from starting, and says why in the +// conversation when it does. The caller holds a.mu, with the ended turn no +// longer running. +// +// The news is already in the transcript, recorded by the drain, so only the +// sentence is added: the next turn reads both. A line the person typed, and a +// question's answer, are owed their turn whatever is paused. +func (a *Agent) turnEndHeldLocked(drained queueDrain) bool { + if drained.heard || drained.answer { + return false + } + held := a.standingHoldLocked(wakeAnswer) + if held.verdict != wakeHolds { + return false + } + a.quietNoteLocked(held.why) + return true +} + // decideTeamWake asks the team's rules for this cause, and answers the first // hold or a start. It takes no lock of its own and must not be called under // a.mu: the rules read the teams file and the ledger. From 17c5e1e1927d5c7f0213e2b1474e1b45946d90cc Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:46:36 -0500 Subject: [PATCH 29/37] teams: a stop keeps a task landing quiet, and a manager's stop reaches a waiting member Under the stop hold a background task's landing still started the stopped conversation, which took the stopped work up again on the result. It is now kept as the task's quiet receipt with the sentence a held command's ending is given, and the person's next message or the manager's next hand-off reads it. A landing in a conversation nobody stopped, or in no team, is unchanged. A manager's team_stop held only a turn that was running: a member's own session read the stop only while a turn ran, so a member with no window that waited on a command was woken by its ending. Its idle watch now reads the stop and begins the same hold. Nothing is written for it and the manager is not woken by its own stop. Co-Authored-By: Claude Fable 5.2 --- .../unreleased/2897-crew-handoff-outcome.md | 2 + internal/manual/chat/team-manager.md | 12 +- internal/session/task_run_belt.go | 8 +- internal/session/team_pause.go | 4 +- internal/session/team_stophold.go | 66 +++++-- internal/session/team_stophold_test.go | 174 ++++++++++++++++++ internal/session/team_wakedecide.go | 12 +- internal/session/team_wakewatch.go | 40 +++- 8 files changed, 283 insertions(+), 35 deletions(-) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index f736aba1a9..208b55a99b 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -32,6 +32,8 @@ invalidates: - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." - "A pause held team traffic only: in a paused member a background command ending, a watch firing, a task landing, and news recorded as a turn ended each started a turn, which the desktop app then stopped where it held the member (appwakes.go) and nothing stopped where it did not. The engine now decides those by cause (wakeStanding and Agent.standingHoldLocked in internal/session/team_wakedecide.go): while a conversation is paused in any of its teams and no turn is running, a command's ending and a watch's firing are written into it as a record ending \"This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened.\" (teamPauseHeldRule), a task landing is recorded as its quiet receipt with that sentence, and news a turn's end recorded starts no further turn and is followed by that sentence. The next turn reads them: one the person's own words open, which is never held, or the turn Resume starts on a directive that waited. A question's answer and a decision the person hands over still start their turn, and the app's stop of a paused member's stray wake is unchanged." + - "Under the stop hold a background task's landing still started the stopped conversation: only a command's ending and a watch's firing were kept as a record. For a conversation with a role in any team, from a stop of a running turn until a turn next begins, a landing that would start a turn is now recorded as its quiet receipt (Agent.admitBeltLanding, recordQuietBeltLanding) ending \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. The person's own message and the manager's next hand-off still start a turn, which ends the hold and reads the record. A landing in a conversation nobody stopped, and in a conversation in no team, starts its turn as before." + - "A manager's team_stop began the stop hold only for a turn that was running: the member's own session looked for the stop only while a turn ran (teamStopTick), so a member with no window that had started a command, ended its turn and waited was woken by the command's ending and took the stopped work up again. A member's idle watch now reads its manager's stop too and begins the same hold when a command or a watch is still running there (Agent.teamStopWaiting), including in a team whose auto-wake is off, whose log it reads for that only while such a command runs. The command's ending is then kept as a record that starts no turn. Nothing is written to the traffic for it, it is never said as \"stopped by the person\", and the manager is not woken by its own stop." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 81678bbb54..ec29c4e1ac 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -361,8 +361,8 @@ Stopping a turn leaves a command it started in the background running, as it doe conversation. In a crew, that command's ending does not start the conversation again. From a stop of a running turn (yours, or the manager's `team_stop`, with or without a window on the member) until a turn next begins, the -ending of a background command, or a watch firing, is written into the conversation as a -record and starts no turn. This holds for a member and for the manager. +ending of a background command, a watch firing, or a background task landing is written into +the conversation as a record and starts no turn. This holds for a member and for the manager. A member often starts a long command, ends its turn and waits to be told how it ended. It reads idle, and a stop still reaches it: **Stop** on a crew's row stops such a member too, @@ -370,11 +370,11 @@ the command's ending starts no turn, and its manager is told the work it handed stopped, as for a stopped turn. That is said only for a command the member asked to hear the end of, or a watch that has not fired. A command left running for its own sake, such as a dev server, is held the same way and the manager is told nothing: the work before it was finished. +The manager's `team_stop` holds such a member the same way, and the manager is told nothing. -Only a background command's ending and a watch firing are held. Whatever else starts a -conversation still does: your own message to it, the manager's next hand-off, a background -task landing. That turn ends the hold and reads the record, which says it arrived after the -stop and is no reason to take the stopped work up again. +Your own message to the conversation and the manager's next hand-off still start it. That +turn ends the hold and reads the record, which says it arrived after the stop and is no reason +to take the stopped work up again. To end the command itself, use **Stop all** on the conversation's Processes tab. A conversation in no crew is unchanged: there a command's ending still starts its turn. diff --git a/internal/session/task_run_belt.go b/internal/session/task_run_belt.go index 48a674cf7e..20505d1a9e 100644 --- a/internal/session/task_run_belt.go +++ b/internal/session/task_run_belt.go @@ -2490,9 +2490,11 @@ func (a *Agent) deliverBeltRunLanding(run *beltRun, summary RunSummary, landing // admitBeltLanding makes the last quiet check and wake admission one step // against page Stop. Receipt construction and persistence happen outside it. // -// A CONVERSATION THE PERSON PAUSED IS NOT STARTED BY A LANDING. The result is -// kept as the quiet record a late stop keeps, with the sentence that says why -// it started no turn, and the next turn reads it (team_pause.go). +// A CONVERSATION THE PERSON PAUSED IS NOT STARTED BY A LANDING, NOR IS ONE IN A +// TEAM WHOSE TURN WAS STOPPED, until a turn next begins. The result is kept as +// the quiet record a late stop of the task keeps, with the sentence that says +// why it started no turn, and the next turn reads it (team_pause.go, +// team_stophold.go). func (a *Agent) admitBeltLanding(run *beltRun, summary RunSummary, line string, landing RunLanding, note userMessage) { run.deliveryMu.Lock() if a.beltRunQuiet(run) { diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 140c7d840c..e397547249 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -303,9 +303,7 @@ func (a *Agent) teamStoppedByPerson(door StopDoor, handed map[string]time.Time) } managers := false for _, entry := range tail { - if entry.Kind == teams.KindStop && entry.From == teams.FromManager && - (entry.Member == role.key || entry.Member == "" && entry.To == role.handle) && - !entry.At.Before(since) { + if teamManagerStops(role, entry) && !entry.At.Before(since) { managers = true } } diff --git a/internal/session/team_stophold.go b/internal/session/team_stophold.go index 2abdc0a4d3..15fe3d2c95 100644 --- a/internal/session/team_stophold.go +++ b/internal/session/team_stophold.go @@ -12,17 +12,23 @@ package session // that ended such wakes (cmd/codeaf's appwakes.go); it no longer pauses. // // So in a team, from a stop of a running turn until a turn next begins, the -// ending of a background command and a watch's firing are kept as a record and -// start no turn. The hold is one row of the table that decides every wake +// ending of a background command, a watch's firing and a background task's +// landing are kept as a record and start no turn. The hold is one row of the table that decides every wake // ([wakeStanding]) and is read where the ending would be queued, under the // lock a stop takes ([Agent.enqueueNote]), so no ending slips between a stop // and its hold. The stop is the person's own or a manager's team_stop, whoever // performs the latter: an interface, through the person's door (teamevent.go), -// or the member's own session, through the manager's ([Agent.interruptTeamTurn]). +// or the member's own session, through the manager's ([Agent.interruptTeamTurn] +// for a turn, [Agent.teamStopWaiting] for a member with none). // The command itself is left running, as an interrupt always leaves it. Only -// those two lanes are held: the person's own words, the manager's next -// hand-off and a background task landing still start a turn, which ends the -// hold. +// those three lanes are held: the person's own words and the manager's next +// hand-off still start a turn, which ends the hold. +// +// A landing was let through at first, as news of work the stop had not been +// about. It was the same fault one lane over: the stopped member's task came +// back, started its turn, and the turn took the stopped work up again on the +// result. The person's word on it was to keep it quiet, so it is kept as the +// receipt a late stop of the task keeps ([Agent.admitBeltLanding]). // // A conversation in no team is untouched: there the ending of a command the // person asked to hear about still starts its turn. @@ -35,6 +41,13 @@ package session // the wake a failed command's ending had armed ([Agent.deferJobWakeLocked]). // A command left running for its own sake (a dev server) is held the same. // +// A manager's team_stop of such a member holds the same way. The member's own +// session used to look for its manager's stop only while a turn ran, so a +// headless member that waited on a command never read the stop and reported +// the stopped work done when the command ended. Its idle watch reads the stop +// now and begins the hold through the manager's door; the manager is told +// nothing of its own stop, and nothing is written. +// // No handed-out work stalls unsaid. What a manager handed this conversation // lasts as long as the work does ([Agent.teamHandedCarried]): through a turn // that finishes while the member waits on a command ([jobRegistry.awaited]) @@ -72,9 +85,10 @@ type teamStopHold struct { // teamStopHoldLocked begins the hold when the stop is the person's or a // manager's and there is something to hold: a turn running, or a command or // watch whose ending would be news. It reports whether it began with no turn -// running, which is the stop a manager may have yet to be told of -// ([Agent.teamStopHoldSaid]), and whether it withdrew a wake already armed. -// The caller holds a.mu. +// running, and whether it withdrew a wake already armed. Through the person's +// door that is the stop a manager may have yet to be told of +// ([Agent.teamStopHoldSaid]); the manager's own door tells nobody +// ([Agent.teamStopWaiting]). The caller holds a.mu. func (a *Agent) teamStopHoldLocked(door StopDoor) (waiting, withdrew bool) { hold := &a.team.stopHold if (door != StopByPerson && door != StopByManager) || !hold.seated.Load() { @@ -84,10 +98,6 @@ func (a *Agent) teamStopHoldLocked(door StopDoor) (waiting, withdrew bool) { hold.held.Store(true) return false, false } - // The manager's own door ends a running turn and nothing else. - if door != StopByPerson { - return false, false - } // A command that failed moments ago has its wake on a clock, and that turn // would end the hold: the clock is withdrawn and its notes stay queued // for the next turn. @@ -99,6 +109,36 @@ func (a *Agent) teamStopHoldLocked(door StopDoor) (waiting, withdrew bool) { return !hold.held.Swap(true), withdrew } +// teamStopWaiting is a manager's stop that found this member with no turn +// running: the hold begins if a command or a watch is still running here, as +// it does for the person's stop of such a member. A turn that began since the +// look is left alone; a stop written before it began is not addressed to it. +// +// IT SAYS NOTHING. The person's door tells the member's manager that work it +// handed out was stopped ([Agent.teamStopHoldSaid]); this stop is the +// manager's own, which it does not need to be woken to hear of, and +// `stopped by the person` is the person's door's line alone. +func (a *Agent) teamStopWaiting() { + a.mu.Lock() + defer a.mu.Unlock() + if !a.running { + a.teamStopHoldLocked(StopByManager) + } +} + +// teamManagerStops reports whether entry is role's manager stopping this +// membership: a stop line from the manager that names the conversation by its +// key or, carrying none, by its handle. Only a membership that takes this +// team's orders is stopped by it: not the manager's own, and not a shared one, +// whose manager here is a link and whose stops do not reach it. +func teamManagerStops(role teamRole, entry teams.Entry) bool { + if !role.managed || role.manager || role.shared || role.handle == "" { + return false + } + return entry.Kind == teams.KindStop && entry.From == teams.FromManager && + (entry.Member == role.key || entry.Member == "" && entry.To == role.handle) +} + // teamStopHoldOver ends the hold: a turn has begun. func (a *Agent) teamStopHoldOver() { a.team.stopHold.held.Store(false) } diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go index a180f1d105..61f36e2dde 100644 --- a/internal/session/team_stophold_test.go +++ b/internal/session/team_stophold_test.go @@ -9,6 +9,7 @@ import ( "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/plandb" "github.com/Agent-Field/codeaf/internal/teams" ) @@ -464,3 +465,176 @@ func TestTeamStopHoldIsReadWhereTheEndingIsQueued(t *testing.T) { t.Fatalf("the ending was not kept as one record that says why it started no turn:\n%s", journal) } } + +// owedLanding is a background task of agent's whose landing owes the +// conversation an answer, which is the landing that starts a turn. +func owedLanding(t *testing.T, agent *Agent, row uint64) *beltRun { + t.Helper() + store := askStore(t, "repair parser") + t.Cleanup(func() { store.Close() }) + question := "What did the repair find?" + if _, err := store.Revise(store.RootID(), plandb.TaskPatch{Question: &question}); err != nil { + t.Fatal(err) + } + run := &beltRun{store: store, root: store.RootID(), row: row, title: "Parser", bringingHome: true} + agent.beltMu.Lock() + agent.beltRun = run + agent.beltMu.Unlock() + t.Cleanup(func() { agent.beltMu.Lock(); agent.beltRun = nil; agent.beltMu.Unlock() }) + return run +} + +// A STOP KEEPS A TASK LANDING QUIET TOO. The stop held a command's ending and +// a watch's firing and let a background task's landing start the stopped +// conversation, which then took the stopped work up again on the task's +// result. The landing is kept as its receipt, with the sentence that says why +// it started no turn; the person's next message reads it, and from that turn +// on a landing starts its turn again. +func TestTeamStopKeepsATaskLandingFromStartingATurn(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(8), nil) + streaming := make(chan struct{}) + calls := &scriptedCompleter{steps: []step{thinkingStep(streaming), okStep(), okStep(), okStep()}} + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + web.Interrupt() + waitQuiet(t, web) + + web.deliverBeltRunLanding(owedLanding(t, web, 98), RunSummary{Outcome: beltRunOutcomeDone, Result: "Preserved result."}, RunLanding{}) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times, want only the turn the person stopped", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), "Preserved result.") || strings.Count(string(journal), teamStopHeldRule) != 1 { + t.Fatalf("the landing was not kept as one record that says why it started no turn:\n%s", journal) + } + + collect(t, mustSubmit(t, web, "what came back?")) + asked := userTextIn(calls.request(1)) + if !strings.Contains(asked, "Preserved result.") || !strings.Contains(asked, teamStopHeldRule) { + t.Fatalf("the person's next turn did not read the landing and why it was held:\n%s", asked) + } + waitQuiet(t, web) + web.deliverBeltRunLanding(owedLanding(t, web, 99), RunSummary{Outcome: beltRunOutcomeDone, Result: "Second result."}, RunLanding{}) + waitRequests(t, calls, 3) +} + +// A LANDING IN A MEMBER NOBODY STOPPED STILL STARTS ITS TURN. +func TestTeamTaskLandingWithNoStopStillStartsATurn(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + calls := oneAnswer(2) + web := teamAgent(t, fixture, fixture.web, calls, nil) + if roles := web.teamRoles(); len(roles) == 0 { + t.Fatal("the member has no seat in its team") + } + web.deliverBeltRunLanding(owedLanding(t, web, 98), RunSummary{Outcome: beltRunOutcomeDone, Result: "Preserved result."}, RunLanding{}) + waitRequests(t, calls, 1) + if asked := userTextIn(calls.request(0)); !strings.Contains(asked, "Preserved result.") || strings.Contains(asked, teamStopHeldRule) { + t.Fatalf("the landing's own turn does not carry the result as news:\n%s", asked) + } +} + +// AND A CONVERSATION IN NO TEAM IS UNTOUCHED: a landing after the person +// stopped its turn still starts the next one. +func TestPersonStopOutsideATeamStillHearsATaskLanding(t *testing.T) { + a, client, _, wakes, _ := jobWakeFixture(t) + streaming := make(chan struct{}) + client.steps = []step{thinkingStep(streaming), okStep()} + events := mustSubmit(t, a, "think about this for a while") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the turn did not start") + } + a.Interrupt() + collect(t, events) + a.deliverBeltRunLanding(owedLanding(t, a, 98), RunSummary{Outcome: beltRunOutcomeDone, Result: "Preserved result."}, RunLanding{}) + select { + case stream := <-wakes: + collect(t, stream) + case <-time.After(5 * time.Second): + t.Fatal("a task landing started no turn in a conversation that is in no team") + } +} + +// A MANAGER'S STOP OF A MEMBER THAT ONLY WAITS ON A COMMAND HOLDS TOO. The +// member's own session looked for its manager's stop only while a turn ran, so +// one that had started a command, ended its turn and waited never read the +// stop: the command ended, woke it, and it reported the stopped work done. No +// interface holds the member here. The stop begins the hold, the command's +// ending is a record that starts no turn, the stop is not said to be the +// person's, and the manager is not woken to hear of its own stop. +func TestTeamManagerStopOfAMemberWaitingOnACommandHolds(t *testing.T) { + fixture, managerCalls, web, calls, clock, started := waitingMember(t, okStep()) + web.settleTeamEvents() + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindStop, From: teams.FromManager, To: "web", Text: "stop"}) + waitFor(t, "the member to read its manager's stop", func() bool { return web.team.stopHold.held.Load() }) + + web.jobs.settleExit(<-started, 0) + clock.advance(jobWakeDelay) + web.enqueueJobNote("job 8 exited 0") + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the member its manager stopped was asked %d times, want only its first turn", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), "job 8 exited 0") || !strings.Contains(string(journal), teamStopHeldRule) { + t.Fatalf("the command's ending was not kept as a record:\n%s", journal) + } + if said := trafficEvents(t, fixture, "stopped"); len(said) != 0 { + t.Fatalf("the manager's stop of a waiting member wrote to the traffic: %+v", said) + } + for i := 0; i < managerCalls.requests(); i++ { + if strings.Contains(userTextIn(managerCalls.request(i)), teamStoppedByPersonLine) { + t.Fatal("the manager was told its own stop was the person's") + } + } +} + +// AND IN A TEAM WHOSE AUTO-WAKE IS OFF. Such a team's log is not read for +// wakes, so a member there never saw a stop while it sat idle. It reads the +// log for its manager's stop while a command of its own is running, and for +// nothing else: the directive beside the stop still wakes nobody. +func TestTeamManagerStopOfAWaitingMemberHoldsWithAutoWakeOff(t *testing.T) { + fastTeamWake(t) + fixture := newTeamFixture(t, true) + var web *Agent + started := make(chan *job, 1) + calls := &scriptedCompleter{steps: []step{waitedStep(func() *Agent { return web }, started), okStep()}} + web = teamAgent(t, fixture, fixture.web, calls, nil) + clock := &jobWakeClock{} + web.jobWakeAfter = clock.after + collect(t, mustSubmit(t, web, "start the build and wait for it")) + waitQuiet(t, web) + + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindStop, From: teams.FromManager, To: "web", Text: "stop"}) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header."}) + waitFor(t, "the member to read its manager's stop", func() bool { return web.team.stopHold.held.Load() }) + web.jobs.settleExit(<-started, 0) + clock.advance(jobWakeDelay) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the member was asked %d times, want only the person's turn: the stop holds and wake is off", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), teamStopHeldRule) { + t.Fatalf("the command's ending was not kept as a record:\n%s", journal) + } +} diff --git a/internal/session/team_wakedecide.go b/internal/session/team_wakedecide.go index b05d7e13a5..f2a6bf1ea8 100644 --- a/internal/session/team_wakedecide.go +++ b/internal/session/team_wakedecide.go @@ -130,7 +130,7 @@ type wakeRule func(a *Agent, profile string, c *wakeCause, now time.Time) wakeDe // wakeRules is which team rules bind which cause, in the order they are asked. // The engine's gates bind every cause and are not listed ([Agent.decideWakeLocked]). // -// THE PAUSE IS ASKED LAST, AND FRESH. The look that chose a member's roles read +// A DIRECTIVE'S PAUSE IS ASKED LAST, AND FRESH. The look that chose a member's roles read // the teams file through a memo up to a tick old ([sharedTeamsStamp]), so a // directive sent in the second after the person pressed Pause reached the wake // as if nothing held it, and the turn it started consumed the directive the @@ -154,9 +154,11 @@ func init() { // queued, and what it holds is kept in the conversation as a record that // starts no turn: the record is its line, and the traffic is told nothing. // -// A STOP HOLDS ONLY A COMMAND'S ENDING AND A WATCH'S FIRING. The person's own -// words, a manager's next hand-off and a task landing still start a turn, -// which ends that hold (team_stophold.go). +// A STOP HOLDS WHAT THE STOPPED WORK LEFT BEHIND: a command's ending, a watch's +// firing and a background task's landing. The person's own words and a +// manager's next hand-off still start a turn, which ends that hold +// (team_stophold.go). News a turn's end recorded is not held by it: a stopped +// turn starts none, and a turn that completed began after the hold was over. // // A PAUSE HOLDS EVERY TURN NOBODY TYPED, these four and the team's traffic // ([wakePauseRule]): the person paused the conversation, not one of the ways @@ -164,7 +166,7 @@ func init() { var wakeStanding = map[wakeKind]struct{ stop, pause bool }{ wakeCommand: {stop: true, pause: true}, wakeWatch: {stop: true, pause: true}, - wakeLanding: {pause: true}, + wakeLanding: {stop: true, pause: true}, wakeAnswer: {pause: true}, } diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 7a6c172991..4be7f46919 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -52,7 +52,9 @@ import ( // ([sharedTeamsStamp]) while it is idle, which is how a conversation made a // member while it sat idle is noticed; // - one stat of each team's log only while it is idle AND in a managed team -// with wake on, and a page read only when that stat moved. +// with wake on, and a page read only when that stat moved. With wake off +// a member's log is looked at the same way only while it has a command or +// a watch running, for its manager's stop and nothing else. // // A CONVERSATION NOBODY HAS OPEN IS OPENED. A directive to a member no window // and no host holds, and a reply to a manager in the same state, would wake @@ -223,13 +225,29 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { roles = a.teamRolesLocked(profile) } var wakeMembers []teamRole + stopped := false for _, role := range roles { - if !role.managed || !role.wakes || (!role.manager && role.handle == "") { + if !role.managed || (!role.manager && role.handle == "") { + continue + } + // WITH THE TEAM'S AUTO-WAKE OFF THE LOG IS READ ONLY FOR A STOP, and only + // while this member has a command or a watch running whose ending the + // stop would hold (team_stophold.go). Nothing it reads there wakes, and + // a team with wake on never asks what is running. + if !role.wakes && (role.manager || !a.teamWaitsOnNews()) { continue } arrived := a.teamWatchReadLocked(profile, role) var waking []teams.Entry for _, entry := range arrived { + // A MANAGER'S STOP THAT FINDS NO TURN STILL HOLDS what the member + // waits on. One written before this session began is history. + if teamManagerStops(role, entry) && !entry.At.Before(a.startedAt) { + stopped = true + } + if !role.wakes { + continue + } // Membership can arrive after the fresh-session watch expires. // Its own start still owes this member its first turn. if wakes, _ := teamEntryWakes(profile, role, entry, a.teamOwnStart(role, entry)); wakes { @@ -237,6 +255,9 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { a.teamAskedLocked(role, entry) } } + if !role.wakes { + continue + } // A PAUSED MEMBER IS NOT WOKEN, and what would have woken it is not // consumed: the hold is remembered, and the turn starts on the tick // that finds the pause lifted (team_pause.go). @@ -263,6 +284,11 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { batch, w.pending, w.due = w.pending, nil, time.Time{} } a.team.mu.Unlock() + if stopped { + // Before anything is woken: a directive sent after the stop starts a + // turn, and that turn ends the hold as any turn does. + a.teamStopWaiting() + } if len(wakeMembers) > 0 { a.teamWakeMember(profile, wakeMembers, now) } @@ -272,6 +298,12 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { return true } +// teamWaitsOnNews reports whether this conversation has a background command +// or a watch still running: something whose ending a stop would hold. +func (a *Agent) teamWaitsOnNews() bool { + return a.jobs != nil && a.jobs.newsPending() +} + // teamStopTick is a running member performing its manager's stop itself. // // A STOP USED TO BE A WINDOW'S TO PERFORM, and only a window's: team_stop @@ -312,9 +344,7 @@ func (a *Agent) teamStopTick(profile string, turnAt time.Time, serial uint64) { } for _, entry := range entries { w.stopCursors[role.id] = entry.ID - if entry.Kind == teams.KindStop && entry.From == teams.FromManager && - (entry.Member == role.key || entry.Member == "" && entry.To == role.handle) && - !entry.At.Before(turnAt) { + if teamManagerStops(role, entry) && !entry.At.Before(turnAt) { stop = true } } From 48edaf3ccb471c8b30bcc8b9af5a92e0a6a28240 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:20:07 -0500 Subject: [PATCH 30/37] app: a model's window limit is only ever one the server measured A model that was not loaded and set no num_ctx was listed as small_window with source default and no figure. Ollama decides that window when it loads the model, from the machine's memory or OLLAMA_CONTEXT_LENGTH and its settings slider, so on a larger machine or a raised setting the warning was false and its advice did not clear it. The engine now remembers, per Ollama address and model, the context_length last seen in /api/ps (in memory for the life of the process: a restart of the app is often a restart of Ollama or follows a change to its setting, so a figure kept on disk would be one nobody has measured since). A model that is not loaded and sets no num_ctx is reported with that window and source last_loaded, and with no small_window when it has not been seen running. A loaded model always reports its live window and updates the memory. The default source is gone from appwire's enum, PROTOCOL.md and the change entry. The models.changed after a turn now keys on "the server was not running the model at the last list", so it still fires when an unloaded model carries no limit. A list that runs out of time before it can ask about a model (its budget spent, or the 600 ms cap) repeats that model's limits from the last list that could, and keeps whether it was unloaded, so the warning does not blink and the post-turn refresh is not lost. A test drives the whole road through the app's doors against an Ollama stub: ListModels with nothing loaded, a turn's end raising exactly one models.changed, the loaded window on the next list and last_loaded after the server unloads the model. It fails without ListModels' addModelLimits, pump's modelLoadedBy or watchModelCompletions' tellModels. Co-Authored-By: Claude Opus 5.5 --- cmd/codeaf/app.go | 9 +- cmd/codeaf/appmodellimits.go | 68 ++++-- cmd/codeaf/appmodellimits_test.go | 212 ++++++++++++++-- .../unreleased/2897-crew-handoff-outcome.md | 2 +- docs/design/app-v3/PROTOCOL.md | 30 ++- internal/appwire/model_facts_test.go | 10 +- internal/appwire/wire.go | 12 +- internal/ollamalimits/ollamalimits.go | 228 ++++++++++++++---- internal/ollamalimits/ollamalimits_test.go | 158 ++++++++++-- 9 files changed, 597 insertions(+), 132 deletions(-) diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 463ffc1404..2eb22a871f 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -62,6 +62,7 @@ import ( "github.com/Agent-Field/codeaf/internal/home" "github.com/Agent-Field/codeaf/internal/leave" "github.com/Agent-Field/codeaf/internal/modelsource" + "github.com/Agent-Field/codeaf/internal/ollamalimits" "github.com/Agent-Field/codeaf/internal/orchestrate" "github.com/Agent-Field/codeaf/internal/provider" "github.com/Agent-Field/codeaf/internal/redact" @@ -796,11 +797,13 @@ type appBackend struct { // stopModelNotices removes the model completion subscription and joins // the initial catalog waiter and cancellable sender when this app closes. stopModelNotices func() - // tellModels says models.changed through that subscription's queue, and - // ollamaUnloaded is the models the last list reported on the server's - // default window ([appBackend.addModelLimits]). + // tellModels says models.changed through that subscription's queue; + // ollamaUnloaded is the models the Ollama service was not running at the + // last list, and ollamaSeen what this app has seen of that service's + // models, for the lists after ([appBackend.addModelLimits]). tellModels func() ollamaUnloaded map[string]bool + ollamaSeen *ollamalimits.Memory // state is the app's own file: setup, its settings, budgets and raises. state *appState // dayAuth is the daily limit's one-time hand-over from this file's old cap. diff --git a/cmd/codeaf/appmodellimits.go b/cmd/codeaf/appmodellimits.go index 13c104f448..1644c6cd90 100644 --- a/cmd/codeaf/appmodellimits.go +++ b/cmd/codeaf/appmodellimits.go @@ -16,36 +16,56 @@ import ( // addModelLimits writes onto each row what its own server says it falls short // in ([appwire.ModelLimit]), asking no later than until. // -// It also remembers which models were reported on the server's default window, -// the one answer the server could not put a figure to. Such a model's real -// window is known once a turn has loaded it, so the turn's end asks the app to -// list again ([appBackend.modelLoadedBy]). +// It also remembers which models the server said it was not running. Such a +// model is loaded by the next turn on it, and the server can then say the +// window it gave, so the turn's end asks the app to list again +// ([appBackend.modelLoadedBy]). A model this list ran out of time to ask about +// keeps what the last list remembered of it, so a slow answer neither hides a +// warning for one list nor loses that request. func (b *appBackend) addModelLimits(until time.Time, models []appwire.Model, sources modelsource.Set) { ctx, cancel := context.WithDeadline(context.Background(), until) defer cancel() - unloaded := appOllamaLimits(ctx, models, sources, nil) - b.locked(func() { b.ollamaUnloaded = unloaded }) + var seen *ollamalimits.Memory + b.locked(func() { + if b.ollamaSeen == nil { + b.ollamaSeen = &ollamalimits.Memory{} + } + seen = b.ollamaSeen + }) + unloaded, unasked := appOllamaLimits(ctx, models, sources, nil, seen) + b.locked(func() { + for _, name := range unasked { + if b.ollamaUnloaded[name] { + if unloaded == nil { + unloaded = map[string]bool{} + } + unloaded[name] = true + } + } + b.ollamaUnloaded = unloaded + }) } -// appOllamaLimits fills the limits of the rows an Ollama service serves and -// answers the models, by the name the server knows them by, that it reported -// on the server's default window. client is the test's door; nil is the -// probe's own. +// appOllamaLimits fills the limits of the rows an Ollama service serves. It +// answers the models, by the name the server knows them by, that the server +// said it is not running, and the models it ran out of time to ask about, +// whose rows carry what seen kept from the last list that could. client is +// the test's door; nil is the probe's own. // // ONLY A CONNECTED OLLAMA IS ASKED, AND ONLY ABOUT ITS OWN MODELS. The // questions are that server's own API: another provider's address would answer // them with an error at best, and a model another service serves is not this // server's to describe even when both happen to list the same name. -func appOllamaLimits(ctx context.Context, models []appwire.Model, sources modelsource.Set, client *http.Client) map[string]bool { +func appOllamaLimits(ctx context.Context, models []appwire.Model, sources modelsource.Set, client *http.Client, seen *ollamalimits.Memory) (unloaded map[string]bool, unasked []string) { service, connected := sources.ByID(ollamalimits.SourceID) if !connected || !service.HasCredentials() { - return nil + return nil, nil } probe, ok := ollamalimits.At(service.Address, service.Key) if !ok { - return nil + return nil, nil } - probe.Client = client + probe.Client, probe.Memory = client, seen rows := map[string][]int{} var names []string for i, model := range models { @@ -58,25 +78,27 @@ func appOllamaLimits(ctx context.Context, models []appwire.Model, sources models } rows[bare] = append(rows[bare], i) } - var unloaded map[string]bool - for name, limits := range probe.Limits(ctx, names, session.LeanWindow()) { + for name, reading := range probe.Read(ctx, names, session.LeanWindow()) { for _, i := range rows[name] { - models[i].Limits = limits + models[i].Limits = reading.Limits } - if limits[0].Kind == appwire.LimitSmallWindow && limits[0].Source == appwire.WindowDefault { + switch { + case reading.Stale: + unasked = append(unasked, name) + case reading.Unloaded: if unloaded == nil { unloaded = map[string]bool{} } unloaded[name] = true } } - return unloaded + return unloaded, unasked } // modelLoadedBy is called when a turn on model has ended. A turn on an Ollama -// model the last list could put no window to has loaded it, so the server can -// now say what it gave the model: the app is told the models changed, once, -// and its next list reads the real figure. +// model the server was not running at the last list has loaded it, so the +// server can now say what it gave the model: the app is told the models +// changed, once, and its next list reads the window the model really has. func (b *appBackend) modelLoadedBy(model string) { if proc := openedEngineProcess(); proc != nil { _, sources := proc.currentAccount() @@ -86,7 +108,7 @@ func (b *appBackend) modelLoadedBy(model string) { // ollamaLoaded is [appBackend.modelLoadedBy] over the services given. It is // said once for a model and not at every turn's end: the list the notice asks -// for forgets the model unless the server still has no figure for it. +// for forgets the model unless the server is still not running it. func (b *appBackend) ollamaLoaded(sources modelsource.Set, model string) { model, _ = roles.SplitEffort(model) owner, bare := sources.For(model) diff --git a/cmd/codeaf/appmodellimits_test.go b/cmd/codeaf/appmodellimits_test.go index 229095bce1..1ff5a61467 100644 --- a/cmd/codeaf/appmodellimits_test.go +++ b/cmd/codeaf/appmodellimits_test.go @@ -9,9 +9,13 @@ import ( "slices" "sync" "testing" + "time" "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/catalog" + "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/modelsource" + "github.com/Agent-Field/codeaf/internal/ollamalimits" "github.com/Agent-Field/codeaf/internal/session" ) @@ -77,12 +81,11 @@ func TestAppOllamaLimitsAreAskedOfTheOllamaServiceAlone(t *testing.T) { {ID: "deepseek/deepseek-chat", Provider: "deepseek"}, {ID: "ollama/library/gemma3", Provider: "ollama"}, } - unloaded := appOllamaLimits(context.Background(), models, sources, stub.Client()) + unloaded, unasked := appOllamaLimits(context.Background(), models, sources, stub.Client(), &ollamalimits.Memory{}) - want := []appwire.ModelLimit{ - {Kind: appwire.LimitSmallWindow, Needs: session.LeanWindow(), Most: 40960, Source: appwire.WindowDefault}, - {Kind: appwire.LimitNoTools}, - } + // Nothing is loaded and nothing sets a window, so the window is the + // server's to decide when it loads the model: no window limit is reported. + want := []appwire.ModelLimit{{Kind: appwire.LimitNoTools}} for i, model := range models { if owned := model.Provider == "ollama"; owned != slices.Equal(model.Limits, want) || (!owned && model.Limits != nil) { t.Fatalf("row %d %s: limits = %+v", i, model.ID, model.Limits) @@ -92,12 +95,12 @@ func TestAppOllamaLimitsAreAskedOfTheOllamaServiceAlone(t *testing.T) { if !slices.Equal(stub.asked, []string{"library/gemma3", "qwen3:8b"}) { t.Fatalf("the server was asked about %q", stub.asked) } - if len(unloaded) != 2 || !unloaded["qwen3:8b"] || !unloaded["library/gemma3"] { - t.Fatalf("models on the server's default window = %v", unloaded) + if len(unloaded) != 2 || !unloaded["qwen3:8b"] || !unloaded["library/gemma3"] || unasked != nil { + t.Fatalf("models the server is not running = %v, not asked about = %v", unloaded, unasked) } data, err := json.Marshal(models[:2]) - wire := `[{"id":"qwen/qwen3:8b","name":"","provider":"openrouter"},{"id":"ollama/qwen3:8b","name":"","provider":"ollama","limits":[{"kind":"small_window","needs":32000,"most":40960,"source":"default"},{"kind":"no_tools"}]}]` + wire := `[{"id":"qwen/qwen3:8b","name":"","provider":"openrouter"},{"id":"ollama/qwen3:8b","name":"","provider":"ollama","limits":[{"kind":"no_tools"}]}]` if err != nil || string(data) != wire { t.Fatalf("wire = %s %v, want %s", data, err, wire) } @@ -115,8 +118,8 @@ func TestAppOllamaLimitsAskNothingWithoutAnOllamaService(t *testing.T) { modelsource.Connected{Source: vendor, Key: "sk-test", Address: stub.URL + "/v1"}, ) models := []appwire.Model{{ID: "local/qwen3:8b", Provider: "local"}, {ID: "deepseek/deepseek-chat", Provider: "deepseek"}, {ID: "qwen3:8b", Provider: "local"}} - if unloaded := appOllamaLimits(context.Background(), models, sources, stub.Client()); unloaded != nil { - t.Fatalf("models on a default window = %v", unloaded) + if unloaded, unasked := appOllamaLimits(context.Background(), models, sources, stub.Client(), &ollamalimits.Memory{}); unloaded != nil || unasked != nil { + t.Fatalf("models not running = %v, not asked about = %v", unloaded, unasked) } for _, model := range models { if model.Limits != nil { @@ -135,21 +138,21 @@ func TestAppOllamaLimitsLeaveTheListAloneWhenThereIsNothingToAsk(t *testing.T) { ollama := modelsource.Connected{Source: appVendoredSource(t, "ollama"), Address: stub.URL + "/v1"} sources := modelsource.NewSet(modelsource.Connected{Source: modelsource.DefaultSource(""), Key: "sk-or-test"}, ollama) models := []appwire.Model{{ID: "qwen/qwen3:8b", Provider: "openrouter"}} - if appOllamaLimits(context.Background(), models, sources, stub.Client()); stub.hits != 0 || models[0].Limits != nil { + if appOllamaLimits(context.Background(), models, sources, stub.Client(), nil); stub.hits != 0 || models[0].Limits != nil { t.Fatalf("an Ollama with no listed model was asked %d questions", stub.hits) } stub.Close() models = []appwire.Model{{ID: "ollama/qwen3:8b", Provider: "ollama"}} - if unloaded := appOllamaLimits(context.Background(), models, sources, nil); unloaded != nil || models[0].Limits != nil { + if unloaded, _ := appOllamaLimits(context.Background(), models, sources, nil, nil); unloaded != nil || models[0].Limits != nil { t.Fatalf("an absent server reported %+v, %v", models[0].Limits, unloaded) } } -// A turn on an Ollama model the last list had no window for tells the app to -// list again, once: the server can say the window now that the model is -// loaded. A turn on any other model, or on a model whose window was already -// known, says nothing. +// A turn on an Ollama model the server was not running at the last list tells +// the app to list again, once: the server can say the window now that the +// model is loaded. A turn on any other model, or on a model that was already +// loaded, says nothing. func TestAppTurnOnAnUnloadedOllamaModelAsksForOneNewList(t *testing.T) { sources := modelsource.NewSet( modelsource.Connected{Source: modelsource.DefaultSource(""), Key: "sk-or-test"}, @@ -171,3 +174,180 @@ func TestAppTurnOnAnUnloadedOllamaModelAsksForOneNewList(t *testing.T) { quiet := &appBackend{ollamaUnloaded: map[string]bool{"qwen3:8b": true}} quiet.ollamaLoaded(sources, "ollama/qwen3:8b") } + +// A list whose time ran out before the server could be asked keeps what the +// last list found: the row's limits, and that the server was not running the +// model, so the turn after it still asks for a new list. +func TestAppALateListKeepsTheLastListsLimitsAndUnloadedModels(t *testing.T) { + var mu sync.Mutex + ps := `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096}]}` + stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + if r.URL.Path == "/api/ps" { + io.WriteString(w, ps) + return + } + io.WriteString(w, `{"capabilities":["completion","tools"],"model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`) + })) + defer stub.Close() + sources := modelsource.NewSet(modelsource.Connected{Source: appVendoredSource(t, "ollama"), Address: stub.URL + "/v1"}) + backend := &appBackend{} + row := func() []appwire.Model { return []appwire.Model{{ID: "ollama/qwen3:8b", Provider: "ollama"}} } + + loaded := row() + backend.addModelLimits(time.Now().Add(time.Second), loaded, sources) + if len(loaded[0].Limits) != 1 || loaded[0].Limits[0].Source != appwire.WindowLoaded || len(backend.ollamaUnloaded) != 0 { + t.Fatalf("loaded: limits %+v, not running %v", loaded[0].Limits, backend.ollamaUnloaded) + } + mu.Lock() + ps = `{"models":[]}` + mu.Unlock() + unloaded := row() + backend.addModelLimits(time.Now().Add(time.Second), unloaded, sources) + if len(unloaded[0].Limits) != 1 || unloaded[0].Limits[0].Source != appwire.WindowLastLoaded || !backend.ollamaUnloaded["qwen3:8b"] { + t.Fatalf("unloaded: limits %+v, not running %v", unloaded[0].Limits, backend.ollamaUnloaded) + } + + late := row() + backend.addModelLimits(time.Now().Add(-time.Second), late, sources) + if !slices.Equal(late[0].Limits, unloaded[0].Limits) || !backend.ollamaUnloaded["qwen3:8b"] { + t.Fatalf("late: limits %+v, not running %v", late[0].Limits, backend.ollamaUnloaded) + } +} + +// THE WHOLE ROAD, THROUGH THE APP'S OWN DOORS. models.list asks the Ollama +// service while the model is not loaded and reports no window; a turn on that +// model ends and the engine says models.changed once; the next list, with the +// server now running the model at 4,096 tokens, says so; and once the server +// unloads it, the list says the window it had when last loaded. Each step needs +// its wire: the list's limits (ListModels), the turn's end (pump's +// modelLoadedBy) and the notice's door (watchModelCompletions' tellModels). +func TestAppATurnOnAnUnloadedOllamaModelBringsItsWindowToTheList(t *testing.T) { + _, workspace := wakeEnvironment(t, resolvedTempDir(t)) + var mu sync.Mutex + running := false + ollama := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/v1/models": + io.WriteString(w, `{"object":"list","data":[{"id":"qwen3:8b","object":"model","owned_by":"library"}]}`) + case "/api/ps": + mu.Lock() + loaded := running + mu.Unlock() + if loaded { + io.WriteString(w, `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096}]}`) + return + } + io.WriteString(w, `{"models":[]}`) + case "/api/show": + io.WriteString(w, `{"capabilities":["completion","tools"],"model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(ollama.Close) + settings, err := config.LoadKeyless() + if err != nil { + t.Fatal(err) + } + if err := config.WriteSources(settings.ProfileDir, []config.PersistedSource{{ID: "ollama", Written: "ollama", Address: ollama.URL + "/v1"}}); err != nil { + t.Fatal(err) + } + // The default service's list is remembered, so its arrival raises no + // models.changed of its own while this test counts them. + if err := catalog.Remember(catalog.Options{BaseURL: settings.BaseURL, Dir: settings.ProfileDir}, []catalog.Model{{ID: "vendor/alpha", Name: "Alpha", InputModalities: []string{"text"}, OutputModalities: []string{"text"}}}); err != nil { + t.Fatal(err) + } + conv := &fakeConversation{model: "ollama/qwen3:8b", script: []session.Event{{Kind: session.EventTurnDone}}} + var opened sync.Mutex + var opens, releases int + rec := newAppRecorder() + backend := newFakeBackend(rec, fakeOpener(conv, &opens, &releases, &opened)) + defer backend.Close() + + row := func() appwire.Model { + t.Helper() + models, err := backend.ListModels() + if err != nil { + t.Fatal(err) + } + for _, model := range models { + if model.ID == "ollama/qwen3:8b" { + return model + } + } + t.Fatalf("the Ollama model is not listed: %+v", models) + return appwire.Model{} + } + // settled is the count of models.changed once no more arrive. + settled := func() int { + t.Helper() + count, still := appModelsChangedCount(rec), time.Now() + for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { + if now := appModelsChangedCount(rec); now != count { + count, still = now, time.Now() + } else if time.Since(still) > 300*time.Millisecond { + return count + } + } + t.Fatal("models.changed never settled") + return 0 + } + turn := func(agent string) { + t.Helper() + turns := 0 + rec.mu.Lock() + for _, event := range rec.events { + if event == appwire.EventTurnDone { + turns++ + } + } + rec.mu.Unlock() + if _, err := backend.Send(agent, "hello", ""); err != nil { + t.Fatal(err) + } + rec.waitFor(t, 10*time.Second, func(event string, _ any) bool { + if event == appwire.EventTurnDone { + turns-- + } + return turns < 0 + }) + } + + if first := row(); first.Limits != nil { + t.Fatalf("a model never loaded reported %+v", first.Limits) + } + before := settled() + agent, err := mustCreate(t, backend, appwire.CreateAsk{Workspace: workspace, Model: "ollama/qwen3:8b"}) + if err != nil { + t.Fatal(err) + } + mu.Lock() + running = true + mu.Unlock() + turn(agent.ID) + if after := settled(); after != before+1 { + t.Fatalf("a turn on a model that was not loaded raised %d models.changed, want 1", after-before) + } + + want := []appwire.ModelLimit{{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: session.LeanWindow(), Most: 40960, Source: appwire.WindowLoaded}} + if loaded := row(); !slices.Equal(loaded.Limits, want) { + t.Fatalf("the loaded model's limits = %+v, want %+v", loaded.Limits, want) + } + // It was loaded at that list, so the next turn on it asks for nothing. + before = settled() + turn(agent.ID) + if after := settled(); after != before { + t.Fatalf("a turn on a loaded model raised %d models.changed", after-before) + } + + mu.Lock() + running = false + mu.Unlock() + want[0].Source = appwire.WindowLastLoaded + if unloaded := row(); !slices.Equal(unloaded.Limits, want) { + t.Fatalf("the unloaded model's limits = %+v, want %+v", unloaded.Limits, want) + } +} diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 208b55a99b..ccf74269b9 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -27,7 +27,7 @@ invalidates: - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode). A hand-off that joined a run which only reads its ground, the home folder apart, is not given the starting task's sentence or \"It joined the work already underway and shares its copy.\": its receipt reads \"It joined the work already underway, which only reads and writes in a folder of its own, so nothing in changes while it is part of that run. To change , propose the work once that run has ended.\" (taskJoinedReadsSentence), whatever files its own proposal named." - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." - - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one that is not loaded and whose Modelfile sets a `num_ctx` under it; `source` `default` carries no `window` and is one that is not loaded and sets none, so the server's default will apply. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`. A server that is absent, slow or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine. A turn ending on an Ollama model last listed with `source` `default` emits `models.changed` once. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." + - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one that is not loaded and whose Modelfile sets a `num_ctx` under it, which overrides the server's own setting; `source` `last_loaded` is one that is not loaded, sets nothing, and was last seen running in `/api/ps` with that `window` (remembered per service address and model for the life of the engine process, not on disk). A model that is not loaded, sets nothing and has not been seen running carries no `small_window`, because the server's default window depends on the machine and the person's setting and no API reports it; there is no `source` `default`. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`. A server that is absent, refuses or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine; a list that runs out of time repeats each unasked model's limits from the last list that could ask. A turn ending on an Ollama model the server was not running at the last list emits `models.changed` once. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 830b4c462d..88753de4a9 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -2911,25 +2911,33 @@ one: on each `models.list` the engine asks that server's own API, at the service's address without its `/v1`, what it runs now (`GET /api/ps`) and what it says about each of its listed models (`POST /api/show`). Each question waits at most 300 ms, all of them 600 ms, inside the list's three seconds; a server -that is absent, slow or answers in an unknown shape reports no limit. +that is absent, refuses or answers in an unknown shape reports no limit. | `kind` | sent when | other fields | |---|---|---| -| `small_window` | the window the server gives the model is under `needs`, or the server has not said what it will give | `needs`, `source`, and `window` and `most` when known | +| `small_window` | a window the server is known to give the model is under `needs` | `window`, `needs`, `source`, and `most` when known | | `no_tools` | the server lists the model's capabilities and `tools` is not among them | none | `needs` is the window the app's prompts ask for, 32000 tokens (the engine's lean threshold). `source` says how `window` is known: `loaded` (the server is running the model with this window), `modelfile` (the model is not loaded and its -Modelfile sets `num_ctx`) or `default` (not loaded and nothing sets it, so the -server's default will apply; `window` is then absent, because the server does -not say what its default is). A `loaded` or `modelfile` window of `needs` or -more is no limit. `most` is the most the model itself can hold, when the server -says. A model the server only forwards to another machine has no -`small_window`. A server that sends no capability list has no `no_tools`. - -When a turn ends on an Ollama model the last `models.list` reported with -`source` `default`, the app emits `models.changed` once: the turn loaded the +Modelfile sets `num_ctx`, which overrides the server's own setting) or +`last_loaded` (not loaded, nothing sets it, and `window` is what the server gave +the model when this engine last saw it running in `GET /api/ps`). A window of +`needs` or more is no limit. A model that is not loaded, sets no `num_ctx` and +has not been seen running has no `small_window`: the server decides its default +window when it loads a model, from the machine's memory or the person's +setting, and its API does not say what that will be. The engine remembers each +model's last window per service address for as long as it runs, not on disk. +`most` is the most the model itself can hold, when the server says. A model the +server only forwards to another machine has no `small_window`. A server that +sends no capability list has no `no_tools`. A list that runs out of time before +it can ask about a model repeats that model's limits from the last list that +could. Engines before `last_loaded` could send `source` `default` with no +`window`; an app reads it as nothing measured and shows no warning for it. + +When a turn ends on an Ollama model the server was not running at the last +`models.list`, the engine emits `models.changed` once: the turn loaded the model, so the next list reads the window the server really gave it. ## orders methods diff --git a/internal/appwire/model_facts_test.go b/internal/appwire/model_facts_test.go index 8ffa40f108..a73a9e9f5d 100644 --- a/internal/appwire/model_facts_test.go +++ b/internal/appwire/model_facts_test.go @@ -41,8 +41,8 @@ func TestModelFactsWireIsOptionalAndUnknownPriceStaysAbsent(t *testing.T) { } // A model's limits are optional on the wire, under the names the desktop app -// reads: a model nothing is known against sends no limits at all, a window the -// server has not put a figure to sends no window, and a limit that is not about +// reads: a model nothing is known against sends no limits at all, every small +// window carries its figure and how it is known, and a limit that is not about // the window sends its kind alone. func TestModelLimitsWireIsAbsentUnlessTheServerSaidSo(t *testing.T) { data, err := json.Marshal(Model{ID: "plain"}) @@ -52,14 +52,14 @@ func TestModelLimitsWireIsAbsentUnlessTheServerSaidSo(t *testing.T) { limited := Model{ID: "ollama/qwen3:8b", Limits: []ModelLimit{ {Kind: LimitSmallWindow, Window: 4096, Needs: 32000, Most: 40960, Source: WindowLoaded}, {Kind: LimitSmallWindow, Window: 8192, Needs: 32000, Source: WindowModelfile}, - {Kind: LimitSmallWindow, Needs: 32000, Most: 40960, Source: WindowDefault}, + {Kind: LimitSmallWindow, Window: 4096, Needs: 32000, Most: 40960, Source: WindowLastLoaded}, {Kind: LimitNoTools}, }} data, err = json.Marshal(limited) want := `"limits":[` + `{"kind":"small_window","window":4096,"needs":32000,"most":40960,"source":"loaded"},` + `{"kind":"small_window","window":8192,"needs":32000,"source":"modelfile"},` + - `{"kind":"small_window","needs":32000,"most":40960,"source":"default"},` + + `{"kind":"small_window","window":4096,"needs":32000,"most":40960,"source":"last_loaded"},` + `{"kind":"no_tools"}]` if err != nil || !strings.Contains(string(data), want) { t.Fatalf("limits wire = %s %v, want %s", data, err, want) @@ -70,7 +70,7 @@ func TestModelLimitsWireIsAbsentUnlessTheServerSaidSo(t *testing.T) { } // The schema names the words a kind and a source may be. schema, err := SchemaJSON() - if err != nil || !strings.Contains(string(schema), `"small_window"`) || !strings.Contains(string(schema), `"modelfile"`) { + if err != nil || !strings.Contains(string(schema), `"small_window"`) || !strings.Contains(string(schema), `"last_loaded"`) { t.Fatalf("the schema does not describe a model's limits: %v", err) } } diff --git a/internal/appwire/wire.go b/internal/appwire/wire.go index ee3bc6e70c..1d2954b802 100644 --- a/internal/appwire/wire.go +++ b/internal/appwire/wire.go @@ -731,9 +731,9 @@ const ( LimitSmallWindow = "small_window" LimitNoTools = "no_tools" - WindowLoaded = "loaded" - WindowModelfile = "modelfile" - WindowDefault = "default" + WindowLoaded = "loaded" + WindowModelfile = "modelfile" + WindowLastLoaded = "last_loaded" ) // ModelLimit is one way a model falls short, as its server reports it. @@ -745,14 +745,14 @@ const ( type ModelLimit struct { // Kind is "small_window" or "no_tools". Kind string `json:"kind" enum:"small_window,no_tools"` - // Window is the tokens the server gives the model now. Absent (0) when Source is "default": the server has not said. + // Window is the tokens the model has, as Source says it is known. Always sent with small_window: a window nobody measured is no limit. Window int `json:"window,omitempty"` // Needs is the window the app's prompts ask for (the lean threshold, 32000). Only with small_window. Needs int `json:"needs,omitempty"` // Most is the most the model itself can hold, when the server says. Only with small_window. Most int `json:"most,omitempty"` - // Source says how Window is known: "loaded" (the server is running it with this window), "modelfile" (its Modelfile sets num_ctx), or "default" (not loaded and nothing sets it, so the server's default will apply). Only with small_window. - Source string `json:"source,omitempty" enum:"loaded,modelfile,default"` + // Source says how Window is known: "loaded" (the server is running it with this window), "modelfile" (not loaded, and its Modelfile sets num_ctx, which overrides the server's own setting) or "last_loaded" (not loaded, nothing sets it, and this window is what the server gave it when this engine last saw it running). Only with small_window. Engines before last_loaded could send "default", with no window; an app reads that as nothing measured. + Source string `json:"source,omitempty" enum:"loaded,modelfile,last_loaded"` } // FeatureAgentEffortRungs announces the terminal's full conversation effort dial. diff --git a/internal/ollamalimits/ollamalimits.go b/internal/ollamalimits/ollamalimits.go index 8781a43e3b..2848986699 100644 --- a/internal/ollamalimits/ollamalimits.go +++ b/internal/ollamalimits/ollamalimits.go @@ -49,11 +49,13 @@ const ( ) // Probe asks one Ollama server. Client is the test's door; nil is a client of -// its own that follows no redirect off the server's origin. +// its own that follows no redirect off the server's origin. Memory is what +// earlier lists saw ([Memory]); nil remembers nothing. type Probe struct { base string key string Client *http.Client + Memory *Memory } // At is the probe for the server whose OpenAI-shaped address is given, and @@ -69,10 +71,103 @@ func At(address, key string) (Probe, bool) { return Probe{base: base, key: strings.TrimSpace(key)}, true } +// Memory is what this process has seen of its Ollama servers, by server address +// and model: the window each model was last running with in /api/ps, and each +// model's last reading that a list could finish. +// +// IT IS KEPT IN MEMORY ONLY, FOR THE LIFE OF THE PROCESS. A remembered window +// is what the server gave the model when it last loaded it, and a restart of +// the app is commonly a restart of Ollama too, or comes after its setting was +// changed: a figure carried across that from disk would be one nobody has +// measured since. Forgetting costs only the warning until the model next loads. +type Memory struct { + mu sync.Mutex + windows map[string]int + readings map[string]Reading +} + +// remembered is the key of one model of one server. +func remembered(base, name string) string { return base + "\x00" + tagged(name) } + +// sawRunning remembers the window of every model the server is running now. +func (m *Memory) sawRunning(base string, running map[string]int) { + if m == nil || len(running) == 0 { + return + } + m.mu.Lock() + defer m.mu.Unlock() + if m.windows == nil { + m.windows = map[string]int{} + } + for name, window := range running { + m.windows[remembered(base, name)] = window + } +} + +// lastWindow is the window the model was last seen running with, or 0. +func (m *Memory) lastWindow(base, name string) int { + if m == nil { + return 0 + } + m.mu.Lock() + defer m.mu.Unlock() + return m.windows[remembered(base, name)] +} + +// keep remembers a reading a list finished, and recall answers it again for a +// list that could not ask, marked stale. +func (m *Memory) keep(base, name string, reading Reading) { + if m == nil { + return + } + m.mu.Lock() + defer m.mu.Unlock() + if m.readings == nil { + m.readings = map[string]Reading{} + } + m.readings[remembered(base, name)] = reading +} + +func (m *Memory) recall(base, name string) Reading { + if m == nil { + return Reading{Stale: true} + } + m.mu.Lock() + defer m.mu.Unlock() + reading := m.readings[remembered(base, name)] + reading.Stale = true + return reading +} + +// Reading is what one list learnt about one model. +type Reading struct { + // Limits is where the model falls short, empty when nothing is known + // against it. + Limits []appwire.ModelLimit + // Unloaded says the server answered that it is not running the model. + Unloaded bool + // Stale says this list ran out of time before the server could answer + // about the model, so Limits and Unloaded are those of the last list that + // could (nothing, when none could). + Stale bool +} + +// outcome is how one question went. Late is the list's time running out +// before the answer came, which says nothing about the model; refused is an +// answer, however unusable. +type outcome int + +const ( + answered outcome = iota + refused + late +) + // shown is what the server says about one model, whether or not it is loaded. type shown struct { - // ok says the server answered. Every other field is nothing without it. - ok bool + // asked is how the question went. Every other field is nothing unless it + // was answered. + asked outcome // numCtx is the window the model's Modelfile sets, or 0 when it sets none. numCtx int // most is the most the model itself can hold, or 0 when the answer has none. @@ -85,23 +180,32 @@ type shown struct { remote bool } -// Limits answers where each named model falls short, keyed by the name asked -// with; a model nothing is known against is not in the answer. needs is the -// window the app's prompts ask for. +// Read answers, for each named model by the name asked with, where it falls +// short and whether the server is running it. needs is the window the app's +// prompts ask for. // -// EVERY FAILURE IS SILENCE. A server that is not running, one that answers -// slowly, an answer in a shape this does not know: each reports nothing for -// the models it concerned, because a limit is shown to a person as a warning -// and a warning nobody measured is worse than none. -func (p Probe) Limits(ctx context.Context, names []string, needs int) map[string][]appwire.ModelLimit { - if len(names) == 0 || ctx.Err() != nil { +// EVERY FAILURE IS SILENCE. A server that is not running, one that refuses, an +// answer in a shape this does not know: each reports nothing for the models it +// concerned, because a limit is shown to a person as a warning and a warning +// nobody measured is worse than none. A list that runs out of time is the one +// exception: it has learnt nothing, so it answers what the last list that +// finished learnt (Reading.Stale) rather than take a warning away for a moment. +func (p Probe) Read(ctx context.Context, names []string, needs int) map[string]Reading { + if len(names) == 0 { return nil } + readings := make(map[string]Reading, len(names)) + if ctx.Err() != nil { + for _, name := range names { + readings[name] = p.Memory.recall(p.base, name) + } + return readings + } ctx, cancel := context.WithTimeout(ctx, Whole) defer cancel() var ( running map[string]int - listed bool + listed outcome wait sync.WaitGroup ) shows := make([]shown, len(names)) @@ -119,56 +223,68 @@ func (p Probe) Limits(ctx context.Context, names []string, needs int) map[string defer func() { <-gate }() shows[i] = p.show(ctx, name) case <-ctx.Done(): + shows[i] = shown{asked: late} } }) } wait.Wait() - limits := map[string][]appwire.ModelLimit{} + p.Memory.sawRunning(p.base, running) for i, name := range names { - var found []appwire.ModelLimit - if limit, small := smallWindow(running[tagged(name)], listed, shows[i], needs); small { - found = append(found, limit) + if listed == late || shows[i].asked == late { + readings[name] = p.Memory.recall(p.base, name) + continue + } + var reading Reading + if listed == answered { + loaded := running[tagged(name)] + reading.Unloaded = loaded == 0 + if limit, small := smallWindow(loaded, p.Memory.lastWindow(p.base, name), shows[i], needs); small { + reading.Limits = append(reading.Limits, limit) + } } // A SERVER THAT SENDS NO LIST HAS NOT SAID THE MODEL LACKS TOOLS. Older // servers send none at all, and reading that as "no tools" would warn // about every model they hold. if len(shows[i].capabilities) > 0 && !slices.Contains(shows[i].capabilities, "tools") { - found = append(found, appwire.ModelLimit{Kind: appwire.LimitNoTools}) - } - if len(found) > 0 { - limits[name] = found + reading.Limits = append(reading.Limits, appwire.ModelLimit{Kind: appwire.LimitNoTools}) } + p.Memory.keep(p.base, name, reading) + readings[name] = reading } - return limits + return readings } -// smallWindow is the model's window limit and whether it has one. A window the -// server is running now is believed over the Modelfile's, which only says what -// the next load would ask for; and a model that is not loaded and sets nothing -// is reported with no figure, because the server's default applies and its API -// does not say what that is. -func smallWindow(loaded int, listed bool, model shown, needs int) (appwire.ModelLimit, bool) { +// smallWindow is the model's window limit and whether it has one, from the +// window the server runs it with now (loaded) and the one it last ran it with +// (last), either 0 when there is none. Whether the server answered /api/ps at +// all is the caller's: without that nobody knows which window counts. +// +// A window running now is believed over the Modelfile's, which only says what +// the next load would ask for; the Modelfile's over the last load's, because +// it overrides the server's own setting; and a model with none of the three +// has no window limit. The server decides its default when it loads a model, +// from the machine's memory or a setting the person may have raised, and no +// API says what it is, so a warning without a figure would be a guess. +func smallWindow(loaded, last int, model shown, needs int) (appwire.ModelLimit, bool) { limit := appwire.ModelLimit{Kind: appwire.LimitSmallWindow, Needs: needs, Most: model.most} switch { - case !listed: - // Whether it is loaded is not known, so neither is which window counts. - return limit, false case loaded > 0: limit.Window, limit.Source = loaded, appwire.WindowLoaded - case !model.ok || model.remote: + case model.asked != answered || model.remote: return limit, false case model.numCtx > 0: limit.Window, limit.Source = model.numCtx, appwire.WindowModelfile + case last > 0: + limit.Window, limit.Source = last, appwire.WindowLastLoaded default: - limit.Source = appwire.WindowDefault - return limit, true + return limit, false } return limit, limit.Window < needs } // loaded is the window of every model the server is running now, by name, and -// whether the server answered at all. -func (p Probe) loaded(ctx context.Context) (map[string]int, bool) { +// how the question went. +func (p Probe) loaded(ctx context.Context) (map[string]int, outcome) { var answer struct { Models *[]struct { Name string `json:"name"` @@ -176,8 +292,11 @@ func (p Probe) loaded(ctx context.Context) (map[string]int, bool) { ContextLength int `json:"context_length"` } `json:"models"` } - if !p.ask(ctx, http.MethodGet, "/api/ps", nil, &answer) || answer.Models == nil { - return nil, false + if asked := p.ask(ctx, http.MethodGet, "/api/ps", nil, &answer); asked != answered { + return nil, asked + } + if answer.Models == nil { + return nil, refused } running := map[string]int{} for _, model := range *answer.Models { @@ -189,7 +308,7 @@ func (p Probe) loaded(ctx context.Context) (map[string]int, bool) { running[tagged(model.Name)] = model.ContextLength running[tagged(model.Model)] = model.ContextLength } - return running, true + return running, answered } // show is what the server says about one model. @@ -202,11 +321,14 @@ func (p Probe) show(ctx context.Context, name string) shown { RemoteModel string `json:"remote_model"` } body, err := json.Marshal(map[string]string{"model": name}) - if err != nil || !p.ask(ctx, http.MethodPost, "/api/show", body, &answer) { - return shown{} + if err != nil { + return shown{asked: refused} + } + if asked := p.ask(ctx, http.MethodPost, "/api/show", body, &answer); asked != answered { + return shown{asked: asked} } return shown{ - ok: true, + asked: answered, numCtx: numCtx(answer.Parameters), most: mostOf(answer.ModelInfo), capabilities: answer.Capabilities, @@ -214,13 +336,20 @@ func (p Probe) show(ctx context.Context, name string) shown { } } -// ask sends one question and decodes its answer, and says whether both worked. -func (p Probe) ask(ctx context.Context, method, path string, body []byte, into any) bool { +// ask sends one question and decodes its answer, and says how that went: any +// failure once this question's time or the list's has run out is late. +func (p Probe) ask(ctx context.Context, method, path string, body []byte, into any) outcome { ctx, cancel := context.WithTimeout(ctx, Each) defer cancel() + failed := func() outcome { + if ctx.Err() != nil { + return late + } + return refused + } request, err := http.NewRequestWithContext(ctx, method, p.base+path, bytes.NewReader(body)) if err != nil { - return false + return refused } if body != nil { request.Header.Set("Content-Type", "application/json") @@ -230,13 +359,16 @@ func (p Probe) ask(ctx context.Context, method, path string, body []byte, into a } response, err := providerhttp.Clone(p.Client).Do(request) if err != nil { - return false + return failed() } defer response.Body.Close() if response.StatusCode != http.StatusOK { - return false + return refused + } + if json.NewDecoder(io.LimitReader(response.Body, answerLimit)).Decode(into) != nil { + return failed() } - return json.NewDecoder(io.LimitReader(response.Body, answerLimit)).Decode(into) == nil + return answered } // numCtx reads the window out of a model's parameters, which the server sends diff --git a/internal/ollamalimits/ollamalimits_test.go b/internal/ollamalimits/ollamalimits_test.go index 6f18587c02..3eaed2013d 100644 --- a/internal/ollamalimits/ollamalimits_test.go +++ b/internal/ollamalimits/ollamalimits_test.go @@ -72,7 +72,8 @@ func (s *stubServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -// limitsFrom asks a stub for the named models the way models.list does. +// limitsFrom asks a stub for the named models the way models.list does, and +// answers the limits of the models that have some. func limitsFrom(t *testing.T, stub *stubServer, names ...string) map[string][]appwire.ModelLimit { t.Helper() server := httptest.NewServer(stub) @@ -82,7 +83,18 @@ func limitsFrom(t *testing.T, stub *stubServer, names ...string) map[string][]ap t.Fatalf("no probe for %s", server.URL) } probe.Client = server.Client() - return probe.Limits(context.Background(), names, needs) + return limitsOf(probe.Read(context.Background(), names, needs)) +} + +// limitsOf is the limits of the readings that have some. +func limitsOf(readings map[string]Reading) map[string][]appwire.ModelLimit { + limits := map[string][]appwire.ModelLimit{} + for name, reading := range readings { + if len(reading.Limits) > 0 { + limits[name] = reading.Limits + } + } + return limits } const ( @@ -145,15 +157,112 @@ func TestAModelfileWindowIsReportedOnlyWhenSmall(t *testing.T) { } } -// Not loaded and nothing set: the server's default applies and the API does -// not say what it is, so the limit is reported with no window. -func TestAnUnsetWindowIsReportedAsTheServersDefault(t *testing.T) { +// Not loaded and nothing set: the server decides the window when it loads the +// model, from the machine's memory or a setting the person may have raised, and +// its API does not say what that will be. A model never seen running has no +// window limit, and its reading says the server is not running it. +func TestAnUnsetWindowNeverSeenRunningIsNoLimit(t *testing.T) { stub := &stubServer{ps: nothingRunning, show: map[string]string{"qwen3:8b": plainModel}} - got := limitsFrom(t, stub, "qwen3:8b") - want := map[string][]appwire.ModelLimit{"qwen3:8b": {{Kind: appwire.LimitSmallWindow, Needs: needs, Most: 40960, Source: appwire.WindowDefault}}} + server := httptest.NewServer(stub) + defer server.Close() + probe, _ := At(server.URL+"/v1", "") + probe.Memory = &Memory{} + got := probe.Read(context.Background(), []string{"qwen3:8b"}, needs) + if want := map[string]Reading{"qwen3:8b": {Unloaded: true}}; !reflect.DeepEqual(got, want) { + t.Fatalf("readings = %+v, want %+v", got, want) + } +} + +// The window a model was last running with is remembered per server, and once +// the server unloads it the model is reported with that window, said to be the +// last load's. A Modelfile's num_ctx still wins, as it does in the server: it +// overrides the server's own setting. Another server's memory is its own. +func TestALastLoadedWindowIsRememberedPerServer(t *testing.T) { + stub := &stubServer{ + ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096},{"name":"pinned:latest","model":"pinned:latest","context_length":4096}]}`, + show: map[string]string{ + "qwen3:8b": plainModel, + "pinned": `{"capabilities":["tools"],"parameters":"num_ctx 8192"}`, + }, + } + server := httptest.NewServer(stub) + defer server.Close() + seen := &Memory{} + probe, _ := At(server.URL+"/v1", "") + probe.Memory = seen + loaded := probe.Read(context.Background(), []string{"qwen3:8b", "pinned"}, needs) + if r := loaded["qwen3:8b"]; r.Unloaded || len(r.Limits) != 1 || r.Limits[0].Source != appwire.WindowLoaded || r.Limits[0].Window != 4096 { + t.Fatalf("loaded reading = %+v", r) + } + + stub.ps = nothingRunning + got := limitsOf(probe.Read(context.Background(), []string{"qwen3:8b", "pinned"}, needs)) + want := map[string][]appwire.ModelLimit{ + "qwen3:8b": {{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowLastLoaded}}, + "pinned": {{Kind: appwire.LimitSmallWindow, Window: 8192, Needs: needs, Source: appwire.WindowModelfile}}, + } if !reflect.DeepEqual(got, want) { t.Fatalf("limits = %+v, want %+v", got, want) } + + // A larger window seen later replaces the remembered one, and a window + // large enough is no limit once unloaded either. + stub.ps = `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":32768}]}` + probe.Read(context.Background(), []string{"qwen3:8b"}, needs) + stub.ps = nothingRunning + if got := limitsOf(probe.Read(context.Background(), []string{"qwen3:8b"}, needs)); len(got) != 0 { + t.Fatalf("limits after a large load = %+v, want none", got) + } + + other := httptest.NewServer(&stubServer{ps: nothingRunning, show: map[string]string{"qwen3:8b": plainModel}}) + defer other.Close() + elsewhere, _ := At(other.URL+"/v1", "") + elsewhere.Memory = seen + stub.ps = `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096}]}` + probe.Read(context.Background(), []string{"qwen3:8b"}, needs) + if got := limitsOf(elsewhere.Read(context.Background(), []string{"qwen3:8b"}, needs)); len(got) != 0 { + t.Fatalf("another server reported this one's window: %+v", got) + } +} + +// A list that runs out of time has learnt nothing about the models it could not +// ask about, so it answers the last finished list's reading, marked stale: the +// warning does not blink away, and whether the server was running the model is +// not forgotten. Without such a list, a late model has nothing. +func TestALateListAnswersTheLastFinishedReading(t *testing.T) { + stub := &stubServer{ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096}]}`, show: map[string]string{"qwen3:8b": plainModel, "chat": `{"capabilities":["completion"]}`}} + server := httptest.NewServer(stub) + defer server.Close() + probe, _ := At(server.URL+"/v1", "") + probe.Memory = &Memory{} + first := probe.Read(context.Background(), []string{"qwen3:8b", "chat"}, needs) + if first["qwen3:8b"].Stale || first["chat"].Stale || !first["chat"].Unloaded { + t.Fatalf("first readings = %+v", first) + } + + spent, cancel := context.WithCancel(context.Background()) + cancel() + asked := len(stub.auth) + again := probe.Read(spent, []string{"qwen3:8b", "chat", "new"}, needs) + if len(stub.auth) != asked { + t.Fatal("a spent list asked the server") + } + for _, name := range []string{"qwen3:8b", "chat"} { + want := first[name] + want.Stale = true + if !reflect.DeepEqual(again[name], want) { + t.Fatalf("%s spent reading = %+v, want %+v", name, again[name], want) + } + } + if r := again["new"]; !r.Stale || r.Limits != nil || r.Unloaded { + t.Fatalf("a model no list finished = %+v", r) + } + + stub.slow = 5 * time.Second + slow := probe.Read(context.Background(), []string{"qwen3:8b"}, needs) + if r := slow["qwen3:8b"]; !r.Stale || !reflect.DeepEqual(r.Limits, first["qwen3:8b"].Limits) { + t.Fatalf("a slow server's reading = %+v", r) + } } // A server that runs a model from before it reported windows says the model is @@ -226,7 +335,7 @@ func TestAFailedRunningListReportsNoWindow(t *testing.T) { // A model the server will not describe, or describes in a shape nobody knows, // has no limit: an error is never a warning. func TestAFailedOrOddAnswerReportsNothingForThatModel(t *testing.T) { - stub := &stubServer{ps: nothingRunning, show: map[string]string{ + stub := &stubServer{ps: `{"models":[{"name":"plain:latest","context_length":4096}]}`, show: map[string]string{ "garbled": `{"capabilities":`, "shapes": `{"capabilities":"tools","parameters":7}`, "plain": plainModel, @@ -241,12 +350,13 @@ func TestAFailedOrOddAnswerReportsNothingForThatModel(t *testing.T) { // either still reports the window, with no most. func TestMostIsAbsentWhenTheServerDoesNotSayIt(t *testing.T) { stub := &stubServer{ps: nothingRunning, show: map[string]string{ - "bare": `{"capabilities":["tools"],"model_info":{"general.architecture":"llama"}}`, - "words": `{"capabilities":["tools"],"model_info":{"general.architecture":"llama","llama.context_length":"many"}}`, + "bare": `{"capabilities":["tools"],"parameters":"num_ctx 4096","model_info":{"general.architecture":"llama"}}`, + "words": `{"capabilities":["tools"],"parameters":"num_ctx 4096","model_info":{"general.architecture":"llama","llama.context_length":"many"}}`, }} - for name, limits := range limitsFrom(t, stub, "bare", "words") { - if len(limits) != 1 || limits[0].Most != 0 || limits[0].Source != appwire.WindowDefault { - t.Fatalf("%s: limits = %+v, want the default window with no most", name, limits) + got := limitsFrom(t, stub, "bare", "words") + for _, name := range []string{"bare", "words"} { + if limits := got[name]; len(limits) != 1 || limits[0].Most != 0 || limits[0].Window != 4096 { + t.Fatalf("%s: limits = %+v, want the window with no most", name, limits) } } } @@ -267,7 +377,7 @@ func TestASlowServerReportsNothingWithinTheBound(t *testing.T) { probe, _ := At(server.URL+"/v1", "") spent, cancel := context.WithCancel(context.Background()) cancel() - if got := probe.Limits(spent, []string{"qwen3:8b"}, needs); len(got) != 0 || len(quick.auth) != 0 { + if got := limitsOf(probe.Read(spent, []string{"qwen3:8b"}, needs)); len(got) != 0 || len(quick.auth) != 0 { t.Fatalf("a spent list asked %d questions and reported %+v", len(quick.auth), got) } } @@ -281,8 +391,18 @@ func TestEveryModelOfALongListIsAnswered(t *testing.T) { names = append(names, name) stub.show[name] = plainModel } - if got := limitsFrom(t, stub, names...); len(got) != len(names) { - t.Fatalf("%d of %d models answered", len(got), len(names)) + server := httptest.NewServer(stub) + defer server.Close() + probe, _ := At(server.URL+"/v1", "") + got := probe.Read(context.Background(), names, needs) + answered := 0 + for _, reading := range got { + if !reading.Stale && reading.Unloaded { + answered++ + } + } + if len(got) != len(names) || answered != len(names) { + t.Fatalf("%d of %d models answered", answered, len(names)) } } @@ -295,7 +415,7 @@ func TestAnAbsentServerReportsNothing(t *testing.T) { if !ok { t.Fatal("no probe for a closed server's address") } - if got := probe.Limits(context.Background(), []string{"qwen3:8b"}, needs); len(got) != 0 { + if got := limitsOf(probe.Read(context.Background(), []string{"qwen3:8b"}, needs)); len(got) != 0 { t.Fatalf("limits = %+v, want none", got) } } @@ -323,13 +443,13 @@ func TestTheProbeIsBesideTheChatAddress(t *testing.T) { server := httptest.NewServer(stub) defer server.Close() probe, _ := At(server.URL+"/v1", " secret ") - probe.Limits(context.Background(), []string{"qwen3:8b"}, needs) + probe.Read(context.Background(), []string{"qwen3:8b"}, needs) if len(stub.auth) != 2 || stub.auth[0] != "Bearer secret" || stub.auth[1] != "Bearer secret" { t.Fatalf("authorization sent = %q", stub.auth) } stub.auth = nil probe, _ = At(server.URL+"/v1", "") - probe.Limits(context.Background(), []string{"qwen3:8b"}, needs) + probe.Read(context.Background(), []string{"qwen3:8b"}, needs) if len(stub.auth) != 2 || stub.auth[0] != "" || stub.auth[1] != "" { t.Fatalf("a keyless probe sent authorization %q", stub.auth) } From a5e7c878bb2ec31eace64a3f3dd6bc160df64a0a Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:40:19 -0500 Subject: [PATCH 31/37] teams: a task result, the pause's owed turn and the stop look follow the holds A task graph's result reached the conversation through the mailbox with no cause, so neither the pause nor the stop held it: a paused or stopped member was started on it. It now carries the landing cause and is kept as its task's receipt, keeping its task's identity and what settles its delivery. A background task's landing decided its hold, let the agent's lock go and queued its wake under a second hold, so a stop in between let it wake a stopped conversation. It is now decided and queued in one locked step through enqueueNote, and its own receipt is written once the lock is let go. A pause is temporary. News it held (a command's ending, a watch firing, a landing, a turn-end re-wake) is now owed a turn, and Resume starts one that reads it even when no directive waited; what a stop holds still starts nothing. The pause is read afresh where a turn ends and where a command's wake clock fires. With auto-wake off, the look for a manager's stop moved the watch's own cursor past a directive, which then woke nobody once auto-wake was turned on. It has a cursor of its own. A refusal by one of the engine's gates is said for every wake it refuses again, as before this branch; only a first turn's is said once per entry. Co-Authored-By: Claude Opus 5.5 --- .../unreleased/2897-crew-handoff-outcome.md | 8 +- internal/manual/chat/team-manager.md | 13 ++- internal/session/agent.go | 64 +++++++++++-- internal/session/image.go | 4 + internal/session/job_wake.go | 2 + internal/session/task_run.go | 4 + internal/session/task_run_belt.go | 13 +-- internal/session/team_pause.go | 47 ++++++++- internal/session/team_pause_test.go | 96 +++++++++++++++++++ internal/session/team_stophold_test.go | 68 +++++++++++++ internal/session/team_wakedecide.go | 39 ++++---- internal/session/team_wakewatch.go | 49 ++++++++-- internal/session/team_wakewatch_test.go | 65 +++++++++++++ internal/teams/digest_test.go | 16 ++++ 14 files changed, 441 insertions(+), 47 deletions(-) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index ccf74269b9..673afc05d1 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -14,7 +14,7 @@ invalidates: - "The crew proposal prompt asked for each helper's brief as the \"whole assignment\". It now asks for \"what this helper is responsible for\", and says an accepted crew joins on standby." - "The desktop app stopped every turn it had not started itself on a paused member, including one the person opened by typing to that member from another window. It now leaves a turn the person's own words opened alone, and still stops any other wake (a background process ending, a task landing)." - "The manager of a crew could be paused from the app like any member. SetPaused now refuses it: \"the manager of is not paused; stop its turn instead\". It also refuses a member that manages another open team (\"@lead manages and is not paused; stop its turn instead\"), and making a conversation a manager lifts its pause." - - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop, whether an interface performs it or the member's own session does) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A stop by the person that finds no turn running but a command or watch still running, or a failed command's ending about to start a turn, begins the same hold; that pending wake is withdrawn and its note is read by the next turn. Only when the conversation is waiting on one of them for work a manager handed it does it also write \"stopped by the person\" to that manager's team, which wakes the manager; a command left running for its own sake, such as a dev server, tells no manager anything. The hold covers a background command's ending and a watch's firing and nothing else: a background task landing, the person's own message and the manager's next hand-off still start the conversation, and that turn ends the hold. The command is still left running by the stop, and a conversation in no team is unchanged." + - "After the person stopped a turn, the ending of a background command that turn had left running (and a watch's firing) started the conversation's next turn, in a team as anywhere else: a stopped member whose command later exited was woken and reported the stopped work done. For a conversation with a role in any team, from a stop of a running turn (the person's, or a manager's team_stop, whether an interface performs it or the member's own session does) until a turn next begins, such an ending is written into the conversation as a record with \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A stop by the person that finds no turn running but a command or watch still running, or a failed command's ending about to start a turn, begins the same hold; that pending wake is withdrawn and its note is read by the next turn. Only when the conversation is waiting on one of them for work a manager handed it does it also write \"stopped by the person\" to that manager's team, which wakes the manager; a command left running for its own sake, such as a dev server, tells no manager anything. The person's own message and the manager's next hand-off still start the conversation, and that turn ends the hold. The command is still left running by the stop, and a conversation in no team is unchanged." - "A member's finished, failed or asking event started its manager's turn in every team, the team that holds every team included, where only an idle (stopped) event did not. In that team no member's finished event starts the global manager's turn any longer (teamEventWakesManagerOf): of a member's events there only failed and asking do, and a team_post to the manager, a decision packet a member raises and a conflict it declares wake the global manager as before. A global manager nobody has open is likewise no longer opened by a finished event there. The rule is that whole team's: it covers a top-level team's manager, a manager that was replaced or whose team closed and kept its seat there, and a conversation the person put there, since the global manager lists and directs only the current top-level managers (managedView). Every other team is unchanged." - "team_send answered every manager \"Replies and endings wake you when they arrive, so there is no need to wait or poll.\" In the team that holds every team it now answers \"Their replies, questions and failures wake you when they arrive, so there is no need to wait or poll. A top-level team's manager answers a directive with team_post: its turn finishing or being stopped does not wake you, and team_status says where it stands.\" The answer in every other team is as it was." - "The global manager's team note said \"Members' replies to you, and their finishing, failing or asking, come back to you and start your turn when you are idle\". For the global manager it now says \"Members' replies to you, and their failing or asking, come back to you\" and ends \"A member's turn finishing or being stopped does not start yours.\", and its scope adds \"A manager answers a directive of yours, and the brief you started it on, with team_post, since its turn finishing does not start yours; team_status says where each of them stands. The person talks to those managers directly, and what the person asked one of them is that manager's work already: never send a manager the person's own request to it as a directive of yours.\" Both are in the global manager's role note, which it is handed when that note's text changes." @@ -31,9 +31,9 @@ invalidates: - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." - - "A pause held team traffic only: in a paused member a background command ending, a watch firing, a task landing, and news recorded as a turn ended each started a turn, which the desktop app then stopped where it held the member (appwakes.go) and nothing stopped where it did not. The engine now decides those by cause (wakeStanding and Agent.standingHoldLocked in internal/session/team_wakedecide.go): while a conversation is paused in any of its teams and no turn is running, a command's ending and a watch's firing are written into it as a record ending \"This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened.\" (teamPauseHeldRule), a task landing is recorded as its quiet receipt with that sentence, and news a turn's end recorded starts no further turn and is followed by that sentence. The next turn reads them: one the person's own words open, which is never held, or the turn Resume starts on a directive that waited. A question's answer and a decision the person hands over still start their turn, and the app's stop of a paused member's stray wake is unchanged." - - "Under the stop hold a background task's landing still started the stopped conversation: only a command's ending and a watch's firing were kept as a record. For a conversation with a role in any team, from a stop of a running turn until a turn next begins, a landing that would start a turn is now recorded as its quiet receipt (Agent.admitBeltLanding, recordQuietBeltLanding) ending \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. The person's own message and the manager's next hand-off still start a turn, which ends the hold and reads the record. A landing in a conversation nobody stopped, and in a conversation in no team, starts its turn as before." - - "A manager's team_stop began the stop hold only for a turn that was running: the member's own session looked for the stop only while a turn ran (teamStopTick), so a member with no window that had started a command, ended its turn and waited was woken by the command's ending and took the stopped work up again. A member's idle watch now reads its manager's stop too and begins the same hold when a command or a watch is still running there (Agent.teamStopWaiting), including in a team whose auto-wake is off, whose log it reads for that only while such a command runs. The command's ending is then kept as a record that starts no turn. Nothing is written to the traffic for it, it is never said as \"stopped by the person\", and the manager is not woken by its own stop." + - "A pause held team traffic only: in a paused member a background command ending, a watch firing, a task landing, and news recorded as a turn ended each started a turn, which the desktop app then stopped where it held the member (appwakes.go) and nothing stopped where it did not. The engine now decides those by cause (wakeStanding and Agent.standingHoldLocked in internal/session/team_wakedecide.go): while a conversation is paused in any of its teams and no turn is running, a command's ending and a watch's firing are written into it as a record ending \"This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened.\" (teamPauseHeldRule), a task landing (a background task's, or the result of a task the conversation divided, Agent.postTaskMessage) is recorded as its quiet receipt with that sentence, keeping its task's identity, and news a turn's end recorded starts no further turn and is followed by that sentence. The next turn reads them: one the person's own words open, which is never held, or the one turn Resume starts (Agent.teamPauseOwedWake), on a directive that waited or, with none, on what the pause held alone, unless a stop since holds it. The person's own words, a question's answer, a decision the person hands over and codeaf continuing a reply it was closed in the middle of still start their turn, and the app's stop of a paused member's stray wake is unchanged." + - "Under the stop hold a background task's landing still started the stopped conversation: only a command's ending and a watch's firing were kept as a record. For a conversation with a role in any team, from a stop of a running turn until a turn next begins, a landing that would start a turn, a background task's (Agent.admitBeltLanding, recordQuietBeltLanding) or the result of a task the conversation divided (Agent.postTaskMessage), is now recorded as its quiet receipt ending \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. The person's own message and the manager's next hand-off still start a turn, which ends the hold and reads the record. A landing in a conversation nobody stopped, and in a conversation in no team, starts its turn as before." + - "A manager's team_stop began the stop hold only for a turn that was running: the member's own session looked for the stop only while a turn ran (teamStopTick), so a member with no window that had started a command, ended its turn and waited was woken by the command's ending and took the stopped work up again. A member's idle watch now reads its manager's stop too and begins the same hold when a command or a watch is still running there (Agent.teamStopWaiting), including in a team whose auto-wake is off, whose log it reads for that only while such a command runs, from a place of its own, so a directive sent meanwhile still wakes the member once the person turns auto-wake on. The command's ending is then kept as a record that starts no turn. Nothing is written to the traffic for it, it is never said as \"stopped by the person\", and the manager is not woken by its own stop." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index ec29c4e1ac..8a723d43b1 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -685,11 +685,14 @@ waited starts the member's turn within a second or two, including after codeaf w between. With the team's auto-wake off, a resumed member reads it at its next turn like any other message. -Your own words are not held: typing into a paused member's conversation starts its turn, and -that turn reads what was waiting, so Resume starts nothing more on it. Nothing else starts a -paused member: a background command ending, a watch firing or a task landing is written into -its conversation as a record, and its next turn reads it. A pause made by an earlier version -of the app is carried onto the team's record the first time the updated app opens. +A command ending, a watch firing, a task landing and news at its last turn's end start no +turn either: each is written into the conversation as a record. Resume starts one turn that +reads them (with a waiting directive), unless a stop since holds them. + +Not held: your own words (that turn reads what was waiting, so Resume starts nothing more), +your answer to its question, a decision you hand it, and codeaf continuing a reply it was +closed in the middle of. An earlier app's pause moves onto the team's record when the +updated app first opens. ## A new crew's members wait on standby — why nobody started after Make the crew diff --git a/internal/session/agent.go b/internal/session/agent.go index 22fbe51db2..f4f4366782 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -1450,6 +1450,11 @@ type userMessage struct { // wake a standing hold may keep as a record instead (team_wakedecide.go's // [wakeStanding]). Zero is a note no such hold binds. cause wakeKind + // heldReceipt is the record its sender keeps in place of this note when a + // standing hold keeps it from starting a turn, given the sentence that says + // why. It is called once the queue's lock is let go, having been decided + // under it ([Agent.enqueueNote]). Nil keeps the note itself as the record. + heldReceipt func(why string) // factoryWork marks a runtime manager turn, never the person's chat. factoryWork bool // runner marks words the factory's runner wrote ([runnerNote]): the turn @@ -2109,6 +2114,7 @@ func (a *Agent) startTurnLocked(ctx context.Context, user userMessage, watcher * a.stopJobWakeLocked() a.running = true a.teamStopHoldOver() + a.teamPauseOwedOver() a.takeHeldNotesLocked() a.factoryAutomaticTurn = user.factoryWork || user.wake && !user.answersPerson && !user.answer a.runnerTurn = user.runner @@ -2286,6 +2292,9 @@ func (a *Agent) startTurnLocked(ctx context.Context, user userMessage, watcher * // A process the person declined to keep running ends with the turn // that started it (keep_running.go). a.endTurnJobs(seq) + // The pause the turn's end may hold news by is read now, off the + // lock ([Agent.turnEndHeldLocked]). + a.teamPauseFreshSeated() a.mu.Lock() // A DISOWNED TURN CLEANS UP NOTHING. [Agent.Abandon] has already done // every act below — drained the queues, cleared running, closed the @@ -4266,11 +4275,33 @@ func (a *Agent) enqueueJobNoteQuiet(text string) { // quietNoteLocked is [Agent.enqueueJobNoteQuiet] for a caller holding a.mu. func (a *Agent) quietNoteLocked(text string) { - text = strings.TrimSpace(text) - if text == "" || a.closed { + a.keepNoteLocked(userMessage{message: textMessage("user", strings.TrimSpace(text)), batch: true, authored: true}) +} + +// heldNoteLocked keeps a note a standing hold kept from starting a turn as the +// record it becomes, its text followed by why. The caller holds a.mu. +// +// IT KEEPS WHAT MAKES IT THE SAME NEWS. A task's result keeps its task's +// identity and that it is a completion, so it is drawn and read as that task's +// receipt, and every note keeps what settles its durable delivery, so a landing +// held as a record is written down as announced when the record holds it. +func (a *Agent) heldNoteLocked(note userMessage, text, why string) { + record := userMessage{ + message: textMessage("user", strings.TrimSpace(text+"\n"+why)), batch: true, authored: true, + replyTags: note.replyTags, delivered: note.delivered, + } + if note.cause == wakeLanding { + record.completionOnly = note.completionOnly + } + a.keepNoteLocked(record) +} + +// keepNoteLocked records a note that starts no turn: now in an idle open +// conversation, and at the next turn's boundary otherwise. The caller holds a.mu. +func (a *Agent) keepNoteLocked(note userMessage) { + if strings.TrimSpace(note.text()) == "" || a.closed { return } - note := userMessage{message: textMessage("user", text), batch: true, authored: true} if a.running || !a.opened { a.ambient = append(a.ambient, note) return @@ -4430,10 +4461,21 @@ func (a *Agent) enqueueNote(note userMessage) bool { // the person's word in a file another process writes (team_pause.go). a.teamPauseFresh() } + taken, receipt, why := a.enqueueNoteLocked(note, text) + if receipt != nil { + receipt(why) + } + return taken +} + +// enqueueNoteLocked is [Agent.enqueueNote] under the agent's lock, which it +// takes and lets go. A note a standing hold keeps whose sender records its own +// receipt answers that receipt, to be called once the lock is let go. +func (a *Agent) enqueueNoteLocked(note userMessage, text string) (taken bool, receipt func(string), why string) { a.mu.Lock() defer a.mu.Unlock() if a.closed || (note.closeKey != "" && a.running) { - return false + return false, nil, "" } if held := a.standingHoldLocked(note.cause); held.verdict == wakeHolds { // A STANDING HOLD KEEPS THE NEWS AS A RECORD AND STARTS NO TURN @@ -4443,9 +4485,17 @@ func (a *Agent) enqueueNote(note userMessage) bool { // for the stop to let the lock go and queued its ending as a wake. A // worker parked on the command is released in the same step, as the // waking note's own append releases it below. - a.quietNoteLocked(text + "\n" + held.why) + // + // A SENDER THAT KEEPS ITS OWN RECEIPT WRITES IT once the lock is let + // go, because composing it takes this lock: a background task's landing + // ([Agent.admitBeltLanding]). Decided here, it is a record whenever it is + // written, and no stop can land between the decision and a wake. a.releaseTaskWaitLocked() - return true + if note.heldReceipt != nil { + return true, note.heldReceipt, held.why + } + a.heldNoteLocked(note, text, held.why) + return true, nil, "" } a.steering = append(a.steering, note) if note.steered || note.ending { @@ -4474,7 +4524,7 @@ func (a *Agent) enqueueNote(note userMessage) bool { a.wakeAnsweringLocked(false, "", note.answer) } } - return true + return true, nil, "" } // holdSettledLocked keeps the acknowledgements this message earned until they diff --git a/internal/session/image.go b/internal/session/image.go index 9d3c850b2e..3e9105289e 100644 --- a/internal/session/image.go +++ b/internal/session/image.go @@ -450,6 +450,7 @@ func (a *Agent) startVisionTurnLocked(ctx context.Context, kept userMessage, liv } a.running = true a.teamStopHoldOver() + a.teamPauseOwedOver() a.runnerTurn = false hub := a.newReplayHubLocked() a.hub = hub @@ -482,6 +483,9 @@ func (a *Agent) startVisionTurnLocked(ctx context.Context, kept userMessage, liv defer cancel(nil) defer hub.close() defer func() { + // The pause the turn's end may hold news by is read now, off the + // lock ([Agent.turnEndHeldLocked]). + a.teamPauseFreshSeated() a.mu.Lock() // A DISOWNED TURN CLEANS UP NOTHING, by the same law and for the same // reason as an ordinary turn's cleanup (agent.go's startTurnLocked): diff --git a/internal/session/job_wake.go b/internal/session/job_wake.go index 2a60197dad..a5b0afe246 100644 --- a/internal/session/job_wake.go +++ b/internal/session/job_wake.go @@ -29,6 +29,8 @@ func (a *Agent) deferJobWakeLocked() { window := &jobWakeWindow{} a.jobWake = window window.stop = after(jobWakeDelay, func() { + // The pause this clock's turn may be held by is read now, off the lock. + a.teamPauseFreshSeated() a.mu.Lock() defer a.mu.Unlock() // A TURN OR CLOSE MAY HAVE WON THE LOCK FIRST. Even a callback already diff --git a/internal/session/task_run.go b/internal/session/task_run.go index 97401b6afa..acec42ad3e 100644 --- a/internal/session/task_run.go +++ b/internal/session/task_run.go @@ -4336,6 +4336,10 @@ func (n *TaskNode) settlesNote(claim noteClaim) durableDelivery { func (a *Agent) postTaskMessage(node *TaskNode, tag TaskReplyTag, note, record string, durable []durableDelivery, settle settleMark, mark func()) deliveryReceipt { message := wakeNote(note) message.completionOnly = true + // A RESULT IS A LANDING, and a conversation the person paused, or one in a + // team whose turn was stopped, keeps it as a record that starts no turn + // ([wakeStanding]). A node's own worker is in no team and holds nothing. + message.cause = wakeLanding // AND A LANDING THAT HANDS THE MODEL THE DECISION MARKS ITS WAKE A SETTLE ONE, // so the turn it starts runs under the checker's own bound rather than the // run's wall ([settleWake], agent.go's [Agent.wakeLocked]). diff --git a/internal/session/task_run_belt.go b/internal/session/task_run_belt.go index 20505d1a9e..95c7e4c46d 100644 --- a/internal/session/task_run_belt.go +++ b/internal/session/task_run_belt.go @@ -2494,7 +2494,9 @@ func (a *Agent) deliverBeltRunLanding(run *beltRun, summary RunSummary, landing // TEAM WHOSE TURN WAS STOPPED, until a turn next begins. The result is kept as // the quiet record a late stop of the task keeps, with the sentence that says // why it started no turn, and the next turn reads it (team_pause.go, -// team_stophold.go). +// team_stophold.go). The hold is decided under the lock the landing would be +// queued under ([Agent.enqueueNote]), so a stop that lands in the same instant +// either holds it or comes after its turn began. func (a *Agent) admitBeltLanding(run *beltRun, summary RunSummary, line string, landing RunLanding, note userMessage) { run.deliveryMu.Lock() if a.beltRunQuiet(run) { @@ -2502,11 +2504,10 @@ func (a *Agent) admitBeltLanding(run *beltRun, summary RunSummary, line string, a.recordQuietBeltLanding(run, summary, line, landing) return } - if held := a.standingHold(wakeLanding); held.verdict == wakeHolds { - run.deliveryMu.Unlock() - a.recordQuietBeltLanding(run, summary, line+"\n"+held.why, landing) - return - } + // The receipt is written under deliveryMu, which is the order page Stop + // takes its locks in (stoprun.go): deliveryMu, then beltMu and a.mu. + note.cause = wakeLanding + note.heldReceipt = func(why string) { a.recordQuietBeltLanding(run, summary, line+"\n"+why, landing) } a.accept(delivery{origin: fromRuntime, kind: msgResult, note: note}) run.deliveryMu.Unlock() } diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index e397547249..c0dfd2cee1 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -34,8 +34,9 @@ package session // ([wakeStanding]): what arrived is kept in the conversation as a record that // starts no turn, with [teamPauseHeldRule] saying why, exactly as a stop keeps // a command's ending (team_stophold.go). The next turn reads it: the person's -// own words, or the turn Resume starts on a directive that waited. The -// interface's stop stays as it was, for a wake this file does not decide. +// own words, or the turn Resume starts, which it starts on a directive that +// waited or on the news alone ([Agent.teamPauseOwedWake]). The interface's +// stop stays as it was, for a wake this file does not decide. // // A PAUSE IS THE PERSON'S WORD ABOUT THE CONVERSATION, so it holds in every // team the conversation is a member of ([teams.File.PausedAnywhere]), not only @@ -78,6 +79,48 @@ type teamPauseHold struct { // teams, as of the last time its roles were read. Read without a lock or a // disk. paused atomic.Bool + // owed is set when the pause kept news from starting a turn (a command's + // ending, a watch's firing, a task landing, what a turn's end recorded), + // and cleared when a turn next begins, which reads it. Resume starts that + // turn ([Agent.teamPauseOwedWake]). + owed atomic.Bool +} + +// teamPauseFreshSeated is [Agent.teamPauseFresh] for a conversation that has a +// role in a team, and nothing for one that has none: it is asked where every +// turn ends and every command's wake clock fires, and only a member can be +// paused. It must not be called under a.mu. +func (a *Agent) teamPauseFreshSeated() { + if a.team.stopHold.seated.Load() { + a.teamPauseFresh() + } +} + +// teamPauseOwedOver forgets that a pause owes a turn: one has begun, and it +// reads what the pause kept. +func (a *Agent) teamPauseOwedOver() { a.team.pauseHold.owed.Store(false) } + +// teamPauseOwedWake starts the turn a lifted pause owes the news it held. +// +// A PAUSE IS TEMPORARY. What the pause kept from starting a turn is in the +// conversation as a record, or still queued, and the person resuming the +// member is their word that it goes on: a member paused while it waited on a +// command used to stay idle after Resume with the command's ending unread, +// unless a directive had also waited. A stop is different: what its hold +// keeps starts nothing even later ([teamStopHeldRule]), so a stop since the +// pause leaves the records where they are. The traffic is told nothing: this +// turn is the member's own news, not its team's. +func (a *Agent) teamPauseOwedWake() { + hold := &a.team.pauseHold + if !hold.owed.Load() { + return + } + a.mu.Lock() + defer a.mu.Unlock() + if a.running || hold.paused.Load() || !hold.owed.Swap(false) || a.team.stopHold.held.Load() { + return + } + a.wakeLocked() } // pausedRoles reports whether any of roles is paused. A pause holds the diff --git a/internal/session/team_pause_test.go b/internal/session/team_pause_test.go index 6d9930c51e..83bbe6ba38 100644 --- a/internal/session/team_pause_test.go +++ b/internal/session/team_pause_test.go @@ -759,3 +759,99 @@ func TestTeamHeldDirectiveThePersonsTurnReadStartsNothingOnResume(t *testing.T) t.Fatalf("the resumed member made %d model calls, want only the person's turn: a note wakes nobody", got) } } + +// graphResult delivers a task graph's result to agent: a node with no parent, +// whose one reader is the conversation itself. +func graphResult(agent *Agent, id uint64, text string) { + node := &TaskNode{graph: newTaskGraph(), id: id, spec: taskSpec{title: "Parser", request: "repair the parser"}} + agent.deliverTaskNote(node, node.attemptNow(), node.resultTag(), text, "") +} + +// heldGraphResult checks that a task graph's result was kept in agent's +// conversation as one record of its task, followed by why, starting no turn. +func heldGraphResult(t *testing.T, agent *Agent, journalPath string, id uint64, want, why string) { + t.Helper() + agent.mu.Lock() + woke := agent.running || len(agent.steering) != 0 + agent.mu.Unlock() + if woke { + t.Fatal("a task graph's result started a turn, or waits on the queue for one") + } + held := false + for _, entry := range agent.Transcript() { + if strings.Contains(entry.Text, want) { + held = entry.RoutineCompletion && len(entry.CompletionTasks) == 1 && entry.CompletionTasks[0].ID == id + } + } + if !held { + t.Fatalf("the held result lost its task's identity: %+v", agent.Transcript()) + } + journal, err := os.ReadFile(journalPath) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), want) || strings.Count(string(journal), why) != 1 { + t.Fatalf("the result was not kept as one record that says why it started no turn:\n%s", journal) + } +} + +// A TASK GRAPH'S RESULT DOES NOT START A PAUSED MEMBER EITHER. A belt task's +// landing was held and a task the conversation divided, whose result reaches +// it through the mailbox, was not: it carried no cause, and the paused member +// was started on it. It is kept as its task's receipt with the pause's +// sentence, and the person's next turn reads it. +func TestTeamPausedMemberKeepsATaskGraphResultAsARecord(t *testing.T) { + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + calls := oneAnswer(1) + web := teamAgent(t, fixture, fixture.web, calls, func(config *Config) { config.teamWatchManual = true }) + graphResult(web, 12, "task 12 finished: Preserved result.") + quietFor() + if got := calls.requests(); got != 0 { + t.Fatalf("a task graph's result started the paused member %d times", got) + } + heldGraphResult(t, web, fixture.web, 12, "Preserved result.", teamPauseHeldRule) + + collect(t, mustSubmit(t, web, "what came back?")) + if asked := userTextIn(calls.request(0)); !strings.Contains(asked, "Preserved result.") || !strings.Contains(asked, teamPauseHeldRule) { + t.Fatalf("the person's next turn did not read the result and why it was held:\n%s", asked) + } +} + +// A PAUSE IS TEMPORARY: RESUME STARTS THE TURN WHAT IT HELD IS OWED. The member +// waited on a command, the person paused it, and the command ended: no turn, +// the ending kept as a record. Resume used to start nothing unless a directive +// had also waited, and the ending stayed unread. It now starts one turn, which +// reads the record. +func TestTeamResumeStartsATurnOnNewsThePauseHeld(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + var web *Agent + started := make(chan *job, 1) + calls := &scriptedCompleter{steps: []step{waitedStep(func() *Agent { return web }, started), okStep(), okStep()}} + web = teamAgent(t, fixture, fixture.web, calls, nil) + clock := &jobWakeClock{} + web.jobWakeAfter = clock.after + collect(t, mustSubmit(t, web, "start the build and wait for it")) + waitQuiet(t, web) + + setPaused(t, fixture, fixture.web, true) + web.jobs.settleExit(<-started, 0) + clock.advance(jobWakeDelay) + web.enqueueJobNote("job 8 exited 0") + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the paused member was asked %d times, want only the person's turn", got) + } + + setPaused(t, fixture, fixture.web, false) + waitRequests(t, calls, 2) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, "job 8 exited 0") || !strings.Contains(asked, teamPauseHeldRule) { + t.Fatalf("the turn Resume started did not read what the pause held:\n%s", asked) + } + waitQuiet(t, web) + quietFor() + if got := calls.requests(); got != 2 { + t.Fatalf("Resume started %d turns, want one", got-1) + } +} diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go index 61f36e2dde..15332a405a 100644 --- a/internal/session/team_stophold_test.go +++ b/internal/session/team_stophold_test.go @@ -638,3 +638,71 @@ func TestTeamManagerStopOfAWaitingMemberHoldsWithAutoWakeOff(t *testing.T) { t.Fatalf("the command's ending was not kept as a record:\n%s", journal) } } + +// A STOP KEEPS A TASK GRAPH'S RESULT QUIET TOO. The result of a task the +// conversation divided reaches it through the mailbox, and carried no cause: +// it started the stopped member, which took the stopped work up again. It is +// kept as its task's receipt with the stop's sentence, and the person's next +// message reads it. +func TestTeamStopKeepsATaskGraphResultFromStartingATurn(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + manager := teamAgent(t, fixture, fixture.manager, oneAnswer(8), nil) + streaming := make(chan struct{}) + calls := &scriptedCompleter{steps: []step{thinkingStep(streaming), okStep(), okStep()}} + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + web.Interrupt() + waitQuiet(t, web) + + graphResult(web, 12, "task 12 finished: Preserved result.") + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times, want only the turn the person stopped", got) + } + heldGraphResult(t, web, fixture.web, 12, "Preserved result.", teamStopHeldRule) + + collect(t, mustSubmit(t, web, "what came back?")) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, "Preserved result.") || !strings.Contains(asked, teamStopHeldRule) { + t.Fatalf("the person's next turn did not read the result and why it was held:\n%s", asked) + } +} + +// WHAT A STOP HOLDS IS NOT OWED A TURN, unlike what a pause holds. The person +// stopped a member that waited on a command, paused it and resumed it, and the +// command ended in between: Resume starts no turn on the stop's record. +func TestTeamResumeDoesNotTakeUpWhatAStopHeld(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + var web *Agent + started := make(chan *job, 1) + calls := &scriptedCompleter{steps: []step{waitedStep(func() *Agent { return web }, started), okStep()}} + web = teamAgent(t, fixture, fixture.web, calls, nil) + collect(t, mustSubmit(t, web, "start the build and wait for it")) + waitQuiet(t, web) + <-started + web.Interrupt() + if !web.team.stopHold.held.Load() { + t.Fatal("the stop of a member waiting on a command began no hold") + } + + setPaused(t, fixture, fixture.web, true) + web.enqueueJobNote("job 8 exited 0") + setPaused(t, fixture, fixture.web, false) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times, want only the person's turn", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), "job 8 exited 0") || !strings.Contains(string(journal), teamStopHeldRule) { + t.Fatalf("the command's ending was not kept as the stop's record:\n%s", journal) + } +} diff --git a/internal/session/team_wakedecide.go b/internal/session/team_wakedecide.go index f2a6bf1ea8..6e4f5a8422 100644 --- a/internal/session/team_wakedecide.go +++ b/internal/session/team_wakedecide.go @@ -55,7 +55,9 @@ const ( wakeCommand // wakeWatch is a watch firing ([Agent.enqueueWatchNote]). wakeWatch - // wakeLanding is a background task landing ([Agent.admitBeltLanding]). + // wakeLanding is a task landing: a background task's result + // ([Agent.admitBeltLanding]) or a task graph's result delivered to the + // conversation ([Agent.postTaskMessage]). wakeLanding // wakeAnswer is news a turn's end recorded with no request left to read it, // which is owed one more turn ([Agent.turnEndHeldLocked]). @@ -160,9 +162,13 @@ func init() { // (team_stophold.go). News a turn's end recorded is not held by it: a stopped // turn starts none, and a turn that completed began after the hold was over. // -// A PAUSE HOLDS EVERY TURN NOBODY TYPED, these four and the team's traffic -// ([wakePauseRule]): the person paused the conversation, not one of the ways -// it starts. Their own words are no row here, because they are never held. +// A PAUSE HOLDS THESE FOUR AND THE TEAM'S TRAFFIC ([wakePauseRule]): the +// person paused the conversation, not one of the ways it starts. Unlike a +// stop's, what it holds is owed a turn, which Resume starts +// ([Agent.teamPauseOwedWake]). The person's own words (a line they typed, a +// question's answer, a decision they hand over) are no row here, because they +// are never held, and nor are a task worker's relays, since a worker is in no +// team. var wakeStanding = map[wakeKind]struct{ stop, pause bool }{ wakeCommand: {stop: true, pause: true}, wakeWatch: {stop: true, pause: true}, @@ -186,20 +192,16 @@ func (a *Agent) standingHoldLocked(kind wakeKind) wakeDecision { return wakeDecision{verdict: wakeHolds, by: heldByStop, why: teamStopHeldRule} } if binds.pause && !a.running && a.team.pauseHold.paused.Load() { + // AND THE TURN IT WOULD HAVE STARTED IS OWED. A pause is the person's + // word that the member waits, not that the news is spent: Resume starts + // the turn that reads it ([Agent.teamPauseOwedWake]). Every caller acts + // on the hold it is answered, so it is marked here, once. + a.team.pauseHold.owed.Store(true) return wakeDecision{verdict: wakeHolds, by: heldByPause, why: teamPauseHeldRule} } return wakeDecision{} } -// standingHold is [Agent.standingHoldLocked] for a caller that holds no lock -// and records the news itself, with the pause read afresh first. -func (a *Agent) standingHold(kind wakeKind) wakeDecision { - a.teamPauseFresh() - a.mu.Lock() - defer a.mu.Unlock() - return a.standingHoldLocked(kind) -} - // turnEndHeldLocked reports whether a standing hold keeps the turn that would // answer what a turn's end just recorded from starting, and says why in the // conversation when it does. The caller holds a.mu, with the ended turn no @@ -361,7 +363,7 @@ func (a *Agent) sayWake(profile string, c wakeCause, d wakeDecision, now time.Ti } for _, role := range c.roles { entry, ok := a.wakeLine(c, role, d) - if !ok || (wakeSaidPerEntry(d) && teamSaidAlready(profile, role.id, entry)) { + if !ok || (wakeSaidPerEntry(c, d) && teamSaidAlready(profile, role.id, entry)) { continue } a.teamSay(profile, role.id, entry) @@ -372,8 +374,13 @@ func (a *Agent) sayWake(profile string, c wakeCause, d wakeDecision, now time.Ti // it answers, by looking at the log. A member's first turn is looked at by two // watches (team_wake.go, team_wakewatch.go) and a fresh conversation is fresh // every time it is opened, so these holds would otherwise be said again. -func wakeSaidPerEntry(d wakeDecision) bool { - return d.by == heldByStandby || d.by == heldByPause || d.by == heldByGate +// +// ONLY A FIRST TURN'S GATE IS SAID ONCE. A refusal by one of the engine's own +// gates is said for every wake it refuses: a manager's line answers no entry, +// so looked up on the log, a second batch of replies refused for the same +// reason wrote nothing where it had always written its own line. +func wakeSaidPerEntry(c wakeCause, d wakeDecision) bool { + return d.by == heldByStandby || d.by == heldByPause || d.by == heldByGate && c.kind == wakeStart } // wakeSayOnce reports whether this decision's line is still to be said. A cap diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 4be7f46919..9eebd983de 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -134,6 +134,12 @@ type teamWatch struct { stopCursors map[string]string stopAt map[string]fileStamp stopTurn uint64 + // stopLook and stopLookAt are how far an IDLE member has looked for its + // manager's stop in a team whose auto-wake is off ([Agent.teamStopLookLocked]). + // They are kept apart from the watch's cursors, so the wake reads on from + // where it was once the person turns auto-wake on. + stopLook map[string]string + stopLookAt map[string]fileStamp // pending is what has arrived for a manager since the first line that asks // for a wake, per team, and due is when the batch is handed over. pending map[string][]teams.Entry @@ -237,7 +243,16 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { if !role.wakes && (role.manager || !a.teamWaitsOnNews()) { continue } - arrived := a.teamWatchReadLocked(profile, role) + // THE STOP IS LOOKED FOR WITH A CURSOR OF ITS OWN while wake is off. + // The watch's cursor is where a wake reads from once the person turns + // auto-wake on, and a look for a stop that moved it carried it past a + // directive sent meanwhile, which then woke nobody. + var arrived []teams.Entry + if role.wakes { + arrived = a.teamWatchReadLocked(profile, role) + } else { + arrived = a.teamStopLookLocked(profile, role) + } var waking []teams.Entry for _, entry := range arrived { // A MANAGER'S STOP THAT FINDS NO TURN STILL HOLDS what the member @@ -295,6 +310,9 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { if len(batch) > 0 { a.teamWakeManager(profile, roles, batch, now) } + // Last, so a directive that waited is what a resumed member starts on, and + // news its pause kept is read in that same turn. + a.teamPauseOwedWake() return true } @@ -443,8 +461,25 @@ func (a *Agent) teamWatchReadLocked(profile string, role teamRole) []teams.Entry if w.cursors == nil { w.cursors, w.trafficAt = map[string]string{}, map[string]fileStamp{} } + return a.teamLookLocked(profile, role, w.cursors, w.trafficAt) +} + +// teamStopLookLocked is [Agent.teamWatchReadLocked] for the look a team whose +// auto-wake is off is given, for its manager's stop only, with a cursor of its +// own. The caller holds a.team.mu. +func (a *Agent) teamStopLookLocked(profile string, role teamRole) []teams.Entry { + w := &a.team.watch + if w.stopLook == nil { + w.stopLook, w.stopLookAt = map[string]string{}, map[string]fileStamp{} + } + return a.teamLookLocked(profile, role, w.stopLook, w.stopLookAt) +} + +// teamLookLocked reads one team's log on from cursors, never behind the +// delivery, and moves cursors on. The caller holds a.team.mu. +func (a *Agent) teamLookLocked(profile string, role teamRole, cursors map[string]string, trafficAt map[string]fileStamp) []teams.Entry { a.readTeamCursorsLocked() - cursor, known := w.cursors[role.id] + cursor, known := cursors[role.id] if delivered, ok := a.team.cursors[role.id]; ok && (!known || delivered > cursor) { cursor, known = delivered, true } @@ -452,22 +487,22 @@ func (a *Agent) teamWatchReadLocked(profile string, role teamRole) []teams.Entry cursor = a.firstTeamCursor(profile, role) } stamp := stampOf(teams.TrafficPath(profile, role.id)) - if known && stamp == w.trafficAt[role.id] && cursor == w.cursors[role.id] { + if known && stamp == trafficAt[role.id] && cursor == cursors[role.id] { return nil } entries, err := teams.ReadTraffic(profile, role.id, cursor, teamPageLimit) if err != nil { - w.cursors[role.id] = cursor + cursors[role.id] = cursor return nil } for _, entry := range entries { cursor = entry.ID } - w.cursors[role.id] = cursor + cursors[role.id] = cursor if len(entries) < teamPageLimit { - w.trafficAt[role.id] = stamp + trafficAt[role.id] = stamp } else { - w.trafficAt[role.id] = fileStamp{} + trafficAt[role.id] = fileStamp{} } return entries } diff --git a/internal/session/team_wakewatch_test.go b/internal/session/team_wakewatch_test.go index 27ee8ef089..4dee0bd05d 100644 --- a/internal/session/team_wakewatch_test.go +++ b/internal/session/team_wakewatch_test.go @@ -824,3 +824,68 @@ func TestTeamWakeATurnAlreadyRunningIsNotSaidToHaveWoken(t *testing.T) { t.Fatalf("the wake that did start a turn was logged %d times, want once", len(woke)) } } + +// A LOOK FOR A STOP DOES NOT CARRY THE WAKE PAST A DIRECTIVE. With the team's +// auto-wake off, a member waiting on a command reads its team's log for its +// manager's stop. That look moved the watch's own cursor, so a directive sent +// meanwhile was behind it when the person turned auto-wake on, and woke +// nobody. The look has a cursor of its own, and the directive wakes the member. +func TestTeamAutoWakeTurnedOnWakesOnADirectiveTheStopLookPassed(t *testing.T) { + fastTeamWake(t) + fixture := newTeamFixture(t, true) + var web *Agent + started := make(chan *job, 1) + calls := &scriptedCompleter{steps: []step{waitedStep(func() *Agent { return web }, started), okStep()}} + web = teamAgent(t, fixture, fixture.web, calls, nil) + collect(t, mustSubmit(t, web, "start the build and wait for it")) + waitQuiet(t, web) + <-started + + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header."}) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("a directive woke the member %d times with the team's auto-wake off", got-1) + } + err := teams.Update(fixture.profile, func(file *teams.File) error { + for i := range file.Teams { + if file.Teams[i].ID == fixture.teamID { + on := true + file.Teams[i].Settings.Wake = &on + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + waitRequests(t, calls, 2) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, "Fix the header.") { + t.Fatalf("the member woke with auto-wake on was not handed the directive:\n%s", asked) + } +} + +// EVERY WAKE A GATE REFUSES IS SAID. A manager's refused wake answers no entry, +// so saying it once per entry wrote one line for its first refused batch of +// replies and nothing for every later one. +func TestTeamWakeEachRefusedManagerWakeIsSaid(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + completer := oneAnswer(1) + teamAgent(t, fixture, fixture.manager, completer, func(config *Config) { + config.FactoryWorkRefusal = func() string { return "this job was stopped" } + }) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindNote, From: "web", To: teams.ToManager, Text: "The header is fixed."}) + waitEvent(t, fixture, "could not wake ◆") + quietFor() + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindNote, From: "web", To: teams.ToManager, Text: "And the footer."}) + deadline := time.Now().Add(5 * time.Second) + for len(trafficEvents(t, fixture, "could not wake ◆")) < 2 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if got := trafficEvents(t, fixture, "could not wake ◆"); len(got) != 2 { + t.Fatalf("two refused wakes were said %d times, want once each", len(got)) + } + if got := completer.requests(); got != 0 { + t.Fatalf("a refused manager was started %d times", got) + } +} diff --git a/internal/teams/digest_test.go b/internal/teams/digest_test.go index 1504d48b28..9aaa445797 100644 --- a/internal/teams/digest_test.go +++ b/internal/teams/digest_test.go @@ -225,3 +225,19 @@ func TestPauseAcrossTeams(t *testing.T) { t.Fatal("a conversation made a manager is still paused") } } + +// A crew's manager seated in the root team, the one that holds every crew, is +// not paused there: it manages its crew, and the engine's wake rules take a +// manager to be never paused. +func TestPauseRefusesACrewManagerInTheRootTeam(t *testing.T) { + file := &File{Teams: []Team{ + {ID: "all", Name: "All teams", Root: true, Manager: "g", Members: []Member{{Key: "g", Handle: "global"}, {Key: "lead", Handle: "lead"}}}, + {ID: "crew", Name: "dock", Parent: "all", Manager: "lead", Members: []Member{{Key: "lead", Handle: "lead"}, {Key: "a", Handle: "dev"}}}, + }} + if err := file.SetPaused("all", "lead", true); err == nil || !strings.Contains(err.Error(), "manages dock") { + t.Fatalf("pausing a crew's manager in the root team answered %v", err) + } + if _, paused := file.PausedAnywhere("lead"); paused { + t.Fatal("a refused pause left the crew's manager paused") + } +} From 1b851a65c26f16b89abbef7dd7affe027f22e524 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:56:54 -0500 Subject: [PATCH 32/37] app: a model's limit says where its window comes from, and a raised setting reaches the list A loaded model whose Modelfile sets num_ctx was listed with source loaded, so the app advised raising Ollama's setting, which the Modelfile overrides; once unloaded the same model read modelfile and the advice changed. Such a model now reads modelfile whether or not it is loaded, with the running window as the figure when it is loaded. A turn's end asked for a new list only for a model unloaded at the last list, so a model loaded at 4,096 tokens kept its warning after the person raised Ollama's setting and the next turn reloaded it larger. A turn on a model last listed with a small window now asks for one new list too; a turn asks at most once. A server too old to say a running model's window, or one that unloads at once (keep_alive 0), made every Ollama turn ask for a list. A model listed as running without a window is no longer read as unloaded, and one the asked-for list still finds unloaded is not asked about again until a list sees it running. A model whose capability list lacks completion (an embedding model, which Ollama lists beside its chat models and the picker does not filter by name) now carries no limits, rather than no_tools as if it were a weak chat model. Co-Authored-By: Claude Opus 5.5 --- cmd/codeaf/app.go | 13 +- cmd/codeaf/appmodellimits.go | 109 ++++++---- cmd/codeaf/appmodellimits_test.go | 191 +++++++++++++++--- .../unreleased/2897-crew-handoff-outcome.md | 2 +- docs/design/app-v3/PROTOCOL.md | 17 +- internal/appwire/wire.go | 2 +- internal/ollamalimits/ollamalimits.go | 71 +++++-- internal/ollamalimits/ollamalimits_test.go | 86 ++++++-- 8 files changed, 374 insertions(+), 117 deletions(-) diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 2eb22a871f..2aa339d72c 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -798,11 +798,16 @@ type appBackend struct { // the initial catalog waiter and cancellable sender when this app closes. stopModelNotices func() // tellModels says models.changed through that subscription's queue; - // ollamaUnloaded is the models the Ollama service was not running at the - // last list, and ollamaSeen what this app has seen of that service's - // models, for the lists after ([appBackend.addModelLimits]). + // ollamaRelist is the models of the Ollama service a turn's end should ask + // the app to list again (not running, or a small window, at the last list), + // ollamaRelisted those a turn has asked that for since, ollamaQuiet those + // whose asked-for list still found them unloaded, and ollamaSeen what this + // app has seen of that service's models, for the lists after + // ([appBackend.addModelLimits]). tellModels func() - ollamaUnloaded map[string]bool + ollamaRelist map[string]bool + ollamaRelisted map[string]bool + ollamaQuiet map[string]bool ollamaSeen *ollamalimits.Memory // state is the app's own file: setup, its settings, budgets and raises. state *appState diff --git a/cmd/codeaf/appmodellimits.go b/cmd/codeaf/appmodellimits.go index 1644c6cd90..6ffcf91e3f 100644 --- a/cmd/codeaf/appmodellimits.go +++ b/cmd/codeaf/appmodellimits.go @@ -16,12 +16,20 @@ import ( // addModelLimits writes onto each row what its own server says it falls short // in ([appwire.ModelLimit]), asking no later than until. // -// It also remembers which models the server said it was not running. Such a -// model is loaded by the next turn on it, and the server can then say the -// window it gave, so the turn's end asks the app to list again -// ([appBackend.modelLoadedBy]). A model this list ran out of time to ask about -// keeps what the last list remembered of it, so a slow answer neither hides a -// warning for one list nor loses that request. +// It also remembers which models a turn's end should ask the app to list again +// ([appBackend.modelLoadedBy]): one the server said it was not running, which +// the next turn on it loads, so the server can then say the window it gave; +// and one whose row says its window is small, which the next turn on it may +// reload with a larger one after the person raised Ollama's setting and +// restarted it. A model this list ran out of time to ask about keeps what the +// last list remembered of it, so a slow answer neither hides a warning for one +// list nor loses that request. +// +// A MODEL THE SERVER NEVER KEEPS LOADED IS ASKED ABOUT ONCE. When the list a +// turn asked for still finds the model unloaded (a server that unloads it at +// once, keep_alive 0), another turn would find the same, and every list costs +// questions to the server: so no turn asks again for it while it stays +// unloaded, until a list sees it running. func (b *appBackend) addModelLimits(until time.Time, models []appwire.Model, sources modelsource.Set) { ctx, cancel := context.WithDeadline(context.Background(), until) defer cancel() @@ -32,38 +40,63 @@ func (b *appBackend) addModelLimits(until time.Time, models []appwire.Model, sou } seen = b.ollamaSeen }) - unloaded, unasked := appOllamaLimits(ctx, models, sources, nil, seen) + readings := appOllamaLimits(ctx, models, sources, nil, seen) b.locked(func() { - for _, name := range unasked { - if b.ollamaUnloaded[name] { - if unloaded == nil { - unloaded = map[string]bool{} + relist := map[string]bool{} + for name, reading := range readings { + if reading.Stale { + if b.ollamaRelist[name] { + relist[name] = true + } + continue + } + switch { + case reading.Loaded: + delete(b.ollamaRelisted, name) + delete(b.ollamaQuiet, name) + case reading.Unloaded && b.ollamaRelisted[name]: + delete(b.ollamaRelisted, name) + if b.ollamaQuiet == nil { + b.ollamaQuiet = map[string]bool{} } - unloaded[name] = true + b.ollamaQuiet[name] = true + } + if (reading.Unloaded && !b.ollamaQuiet[name]) || appSmallWindow(reading.Limits) { + relist[name] = true } } - b.ollamaUnloaded = unloaded + b.ollamaRelist = relist }) } -// appOllamaLimits fills the limits of the rows an Ollama service serves. It -// answers the models, by the name the server knows them by, that the server -// said it is not running, and the models it ran out of time to ask about, -// whose rows carry what seen kept from the last list that could. client is -// the test's door; nil is the probe's own. +// appSmallWindow says whether limits carry a small window. +func appSmallWindow(limits []appwire.ModelLimit) bool { + for _, limit := range limits { + if limit.Kind == appwire.LimitSmallWindow { + return true + } + } + return false +} + +// appOllamaLimits fills the limits of the rows an Ollama service serves, and +// answers what the server said of each of its models, by the name the server +// knows them by: a model it ran out of time to ask about has the reading seen +// kept from the last list that could, marked stale. client is the test's door; +// nil is the probe's own. // // ONLY A CONNECTED OLLAMA IS ASKED, AND ONLY ABOUT ITS OWN MODELS. The // questions are that server's own API: another provider's address would answer // them with an error at best, and a model another service serves is not this // server's to describe even when both happen to list the same name. -func appOllamaLimits(ctx context.Context, models []appwire.Model, sources modelsource.Set, client *http.Client, seen *ollamalimits.Memory) (unloaded map[string]bool, unasked []string) { +func appOllamaLimits(ctx context.Context, models []appwire.Model, sources modelsource.Set, client *http.Client, seen *ollamalimits.Memory) map[string]ollamalimits.Reading { service, connected := sources.ByID(ollamalimits.SourceID) if !connected || !service.HasCredentials() { - return nil, nil + return nil } probe, ok := ollamalimits.At(service.Address, service.Key) if !ok { - return nil, nil + return nil } probe.Client, probe.Memory = client, seen rows := map[string][]int{} @@ -78,26 +111,19 @@ func appOllamaLimits(ctx context.Context, models []appwire.Model, sources models } rows[bare] = append(rows[bare], i) } - for name, reading := range probe.Read(ctx, names, session.LeanWindow()) { + readings := probe.Read(ctx, names, session.LeanWindow()) + for name, reading := range readings { for _, i := range rows[name] { models[i].Limits = reading.Limits } - switch { - case reading.Stale: - unasked = append(unasked, name) - case reading.Unloaded: - if unloaded == nil { - unloaded = map[string]bool{} - } - unloaded[name] = true - } } - return unloaded, unasked + return readings } // modelLoadedBy is called when a turn on model has ended. A turn on an Ollama -// model the server was not running at the last list has loaded it, so the -// server can now say what it gave the model: the app is told the models +// model the server was not running at the last list has loaded it, and one on a +// model listed with a small window may have reloaded it with a larger one, so +// the server can now say what it gave the model: the app is told the models // changed, once, and its next list reads the window the model really has. func (b *appBackend) modelLoadedBy(model string) { if proc := openedEngineProcess(); proc != nil { @@ -106,9 +132,10 @@ func (b *appBackend) modelLoadedBy(model string) { } } -// ollamaLoaded is [appBackend.modelLoadedBy] over the services given. It is -// said once for a model and not at every turn's end: the list the notice asks -// for forgets the model unless the server is still not running it. +// ollamaLoaded is [appBackend.modelLoadedBy] over the services given. A turn +// says it at most once, and only for a model the last list marked: the list +// the notice asks for marks the model again only if it is still worth asking +// about ([appBackend.addModelLimits]). func (b *appBackend) ollamaLoaded(sources modelsource.Set, model string) { model, _ = roles.SplitEffort(model) owner, bare := sources.For(model) @@ -117,8 +144,12 @@ func (b *appBackend) ollamaLoaded(sources modelsource.Set, model string) { } var tell func() b.locked(func() { - if b.ollamaUnloaded[bare] { - delete(b.ollamaUnloaded, bare) + if b.ollamaRelist[bare] { + delete(b.ollamaRelist, bare) + if b.ollamaRelisted == nil { + b.ollamaRelisted = map[string]bool{} + } + b.ollamaRelisted[bare] = true tell = b.tellModels } }) diff --git a/cmd/codeaf/appmodellimits_test.go b/cmd/codeaf/appmodellimits_test.go index 1ff5a61467..62351424fa 100644 --- a/cmd/codeaf/appmodellimits_test.go +++ b/cmd/codeaf/appmodellimits_test.go @@ -3,6 +3,7 @@ package main import ( "context" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -81,7 +82,7 @@ func TestAppOllamaLimitsAreAskedOfTheOllamaServiceAlone(t *testing.T) { {ID: "deepseek/deepseek-chat", Provider: "deepseek"}, {ID: "ollama/library/gemma3", Provider: "ollama"}, } - unloaded, unasked := appOllamaLimits(context.Background(), models, sources, stub.Client(), &ollamalimits.Memory{}) + readings := appOllamaLimits(context.Background(), models, sources, stub.Client(), &ollamalimits.Memory{}) // Nothing is loaded and nothing sets a window, so the window is the // server's to decide when it loads the model: no window limit is reported. @@ -95,8 +96,8 @@ func TestAppOllamaLimitsAreAskedOfTheOllamaServiceAlone(t *testing.T) { if !slices.Equal(stub.asked, []string{"library/gemma3", "qwen3:8b"}) { t.Fatalf("the server was asked about %q", stub.asked) } - if len(unloaded) != 2 || !unloaded["qwen3:8b"] || !unloaded["library/gemma3"] || unasked != nil { - t.Fatalf("models the server is not running = %v, not asked about = %v", unloaded, unasked) + if len(readings) != 2 || !readings["qwen3:8b"].Unloaded || !readings["library/gemma3"].Unloaded || readings["qwen3:8b"].Stale { + t.Fatalf("readings = %+v, want both models answered and not running", readings) } data, err := json.Marshal(models[:2]) @@ -118,8 +119,8 @@ func TestAppOllamaLimitsAskNothingWithoutAnOllamaService(t *testing.T) { modelsource.Connected{Source: vendor, Key: "sk-test", Address: stub.URL + "/v1"}, ) models := []appwire.Model{{ID: "local/qwen3:8b", Provider: "local"}, {ID: "deepseek/deepseek-chat", Provider: "deepseek"}, {ID: "qwen3:8b", Provider: "local"}} - if unloaded, unasked := appOllamaLimits(context.Background(), models, sources, stub.Client(), &ollamalimits.Memory{}); unloaded != nil || unasked != nil { - t.Fatalf("models not running = %v, not asked about = %v", unloaded, unasked) + if readings := appOllamaLimits(context.Background(), models, sources, stub.Client(), &ollamalimits.Memory{}); readings != nil { + t.Fatalf("readings = %+v", readings) } for _, model := range models { if model.Limits != nil { @@ -144,22 +145,21 @@ func TestAppOllamaLimitsLeaveTheListAloneWhenThereIsNothingToAsk(t *testing.T) { stub.Close() models = []appwire.Model{{ID: "ollama/qwen3:8b", Provider: "ollama"}} - if unloaded, _ := appOllamaLimits(context.Background(), models, sources, nil, nil); unloaded != nil || models[0].Limits != nil { - t.Fatalf("an absent server reported %+v, %v", models[0].Limits, unloaded) + if readings := appOllamaLimits(context.Background(), models, sources, nil, nil); readings["qwen3:8b"].Unloaded || models[0].Limits != nil { + t.Fatalf("an absent server reported %+v, %+v", models[0].Limits, readings) } } -// A turn on an Ollama model the server was not running at the last list tells -// the app to list again, once: the server can say the window now that the -// model is loaded. A turn on any other model, or on a model that was already -// loaded, says nothing. +// A turn on an Ollama model the last list marked tells the app to list again, +// once: the server can say the window now that the model is loaded. A turn on +// any other model, or on a model the list did not mark, says nothing. func TestAppTurnOnAnUnloadedOllamaModelAsksForOneNewList(t *testing.T) { sources := modelsource.NewSet( modelsource.Connected{Source: modelsource.DefaultSource(""), Key: "sk-or-test"}, modelsource.Connected{Source: appVendoredSource(t, "ollama")}, ) told := 0 - backend := &appBackend{tellModels: func() { told++ }, ollamaUnloaded: map[string]bool{"qwen3:8b": true}} + backend := &appBackend{tellModels: func() { told++ }, ollamaRelist: map[string]bool{"qwen3:8b": true}} for _, model := range []string{"qwen/qwen3:8b", "qwen3:8b", "ollama/gemma3:4b", ""} { if backend.ollamaLoaded(sources, model); told != 0 { t.Fatalf("a turn on %q asked for a new list", model) @@ -171,13 +171,13 @@ func TestAppTurnOnAnUnloadedOllamaModelAsksForOneNewList(t *testing.T) { t.Fatalf("told the app %d times, want once", told) } // Before the app's model notices are joined there is nobody to tell. - quiet := &appBackend{ollamaUnloaded: map[string]bool{"qwen3:8b": true}} + quiet := &appBackend{ollamaRelist: map[string]bool{"qwen3:8b": true}} quiet.ollamaLoaded(sources, "ollama/qwen3:8b") } // A list whose time ran out before the server could be asked keeps what the -// last list found: the row's limits, and that the server was not running the -// model, so the turn after it still asks for a new list. +// last list found: the row's limits, and that the model is worth a new list +// after a turn, so the turn after it still asks for one. func TestAppALateListKeepsTheLastListsLimitsAndUnloadedModels(t *testing.T) { var mu sync.Mutex ps := `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096}]}` @@ -197,22 +197,22 @@ func TestAppALateListKeepsTheLastListsLimitsAndUnloadedModels(t *testing.T) { loaded := row() backend.addModelLimits(time.Now().Add(time.Second), loaded, sources) - if len(loaded[0].Limits) != 1 || loaded[0].Limits[0].Source != appwire.WindowLoaded || len(backend.ollamaUnloaded) != 0 { - t.Fatalf("loaded: limits %+v, not running %v", loaded[0].Limits, backend.ollamaUnloaded) + if len(loaded[0].Limits) != 1 || loaded[0].Limits[0].Source != appwire.WindowLoaded || !backend.ollamaRelist["qwen3:8b"] { + t.Fatalf("loaded: limits %+v, to list again %v", loaded[0].Limits, backend.ollamaRelist) } mu.Lock() ps = `{"models":[]}` mu.Unlock() unloaded := row() backend.addModelLimits(time.Now().Add(time.Second), unloaded, sources) - if len(unloaded[0].Limits) != 1 || unloaded[0].Limits[0].Source != appwire.WindowLastLoaded || !backend.ollamaUnloaded["qwen3:8b"] { - t.Fatalf("unloaded: limits %+v, not running %v", unloaded[0].Limits, backend.ollamaUnloaded) + if len(unloaded[0].Limits) != 1 || unloaded[0].Limits[0].Source != appwire.WindowLastLoaded || !backend.ollamaRelist["qwen3:8b"] { + t.Fatalf("unloaded: limits %+v, to list again %v", unloaded[0].Limits, backend.ollamaRelist) } late := row() backend.addModelLimits(time.Now().Add(-time.Second), late, sources) - if !slices.Equal(late[0].Limits, unloaded[0].Limits) || !backend.ollamaUnloaded["qwen3:8b"] { - t.Fatalf("late: limits %+v, not running %v", late[0].Limits, backend.ollamaUnloaded) + if !slices.Equal(late[0].Limits, unloaded[0].Limits) || !backend.ollamaRelist["qwen3:8b"] { + t.Fatalf("late: limits %+v, to list again %v", late[0].Limits, backend.ollamaRelist) } } @@ -226,7 +226,7 @@ func TestAppALateListKeepsTheLastListsLimitsAndUnloadedModels(t *testing.T) { func TestAppATurnOnAnUnloadedOllamaModelBringsItsWindowToTheList(t *testing.T) { _, workspace := wakeEnvironment(t, resolvedTempDir(t)) var mu sync.Mutex - running := false + running, window := false, 4096 ollama := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { @@ -234,10 +234,10 @@ func TestAppATurnOnAnUnloadedOllamaModelBringsItsWindowToTheList(t *testing.T) { io.WriteString(w, `{"object":"list","data":[{"id":"qwen3:8b","object":"model","owned_by":"library"}]}`) case "/api/ps": mu.Lock() - loaded := running + loaded, size := running, window mu.Unlock() if loaded { - io.WriteString(w, `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096}]}`) + fmt.Fprintf(w, `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":%d}]}`, size) return } io.WriteString(w, `{"models":[]}`) @@ -336,12 +336,6 @@ func TestAppATurnOnAnUnloadedOllamaModelBringsItsWindowToTheList(t *testing.T) { if loaded := row(); !slices.Equal(loaded.Limits, want) { t.Fatalf("the loaded model's limits = %+v, want %+v", loaded.Limits, want) } - // It was loaded at that list, so the next turn on it asks for nothing. - before = settled() - turn(agent.ID) - if after := settled(); after != before { - t.Fatalf("a turn on a loaded model raised %d models.changed", after-before) - } mu.Lock() running = false @@ -350,4 +344,141 @@ func TestAppATurnOnAnUnloadedOllamaModelBringsItsWindowToTheList(t *testing.T) { if unloaded := row(); !slices.Equal(unloaded.Limits, want) { t.Fatalf("the unloaded model's limits = %+v, want %+v", unloaded.Limits, want) } + + // The person raises Ollama's setting and restarts it, and the next turn + // loads the model with the larger window. The row last said the window was + // small, so that turn asks for one new list, which drops the warning; the + // turn after, on a model loaded with room enough, asks for nothing. + mu.Lock() + running, window = true, 32768 + mu.Unlock() + before = settled() + turn(agent.ID) + if after := settled(); after != before+1 { + t.Fatalf("a turn on a model listed with a small window raised %d models.changed, want 1", after-before) + } + if raised := row(); raised.Limits != nil { + t.Fatalf("the model loaded with a larger window reported %+v", raised.Limits) + } + before = settled() + turn(agent.ID) + if after := settled(); after != before { + t.Fatalf("a turn on a model loaded with room enough raised %d models.changed", after-before) + } +} + +// A turn on a model listed with a small window asks for one new list, whether +// the model was loaded at that list or not: the person may have raised Ollama's +// setting and restarted it, and only a new list reads the window the turn's +// reload gave. One turn asks once, however the model is marked. +func TestAppTurnOnASmallWindowModelAsksForOneNewList(t *testing.T) { + var mu sync.Mutex + window := 4096 + stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + if r.URL.Path == "/api/ps" { + fmt.Fprintf(w, `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":%d}]}`, window) + return + } + io.WriteString(w, `{"capabilities":["completion","tools"],"model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`) + })) + defer stub.Close() + sources := modelsource.NewSet(modelsource.Connected{Source: appVendoredSource(t, "ollama"), Address: stub.URL + "/v1"}) + told := 0 + backend := &appBackend{tellModels: func() { told++ }} + list := func() []appwire.Model { + models := []appwire.Model{{ID: "ollama/qwen3:8b", Provider: "ollama"}} + backend.addModelLimits(time.Now().Add(time.Second), models, sources) + return models + } + + if small := list(); len(small[0].Limits) != 1 || small[0].Limits[0].Source != appwire.WindowLoaded { + t.Fatalf("limits = %+v, want the loaded small window", small[0].Limits) + } + backend.ollamaLoaded(sources, "ollama/qwen3:8b") + backend.ollamaLoaded(sources, "ollama/qwen3:8b") + if told != 1 { + t.Fatalf("turns on a loaded small-window model told the app %d times, want once before a new list", told) + } + + mu.Lock() + window = 32768 + mu.Unlock() + if raised := list(); raised[0].Limits != nil { + t.Fatalf("limits after the raise = %+v, want none", raised[0].Limits) + } + backend.ollamaLoaded(sources, "ollama/qwen3:8b") + if told != 1 { + t.Fatalf("a turn on a model loaded with room enough told the app again (%d)", told) + } +} + +// A server that never keeps a model loaded (keep_alive 0), or one too old to +// say a running model's window, would otherwise make every turn on the model +// ask for a new list, each a round of questions to the server. A model the +// server lists as running without a window is not marked at all; one the +// asked-for list still finds unloaded is not asked about again until a list +// sees it running. +func TestAppAModelTheServerNeverKeepsLoadedIsAskedAboutOnce(t *testing.T) { + var mu sync.Mutex + ps := `{"models":[]}` + stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + if r.URL.Path == "/api/ps" { + io.WriteString(w, ps) + return + } + io.WriteString(w, `{"capabilities":["completion","tools"],"model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`) + })) + defer stub.Close() + setPS := func(body string) { + mu.Lock() + ps = body + mu.Unlock() + } + sources := modelsource.NewSet(modelsource.Connected{Source: appVendoredSource(t, "ollama"), Address: stub.URL + "/v1"}) + told := 0 + backend := &appBackend{tellModels: func() { told++ }} + list := func() { + backend.addModelLimits(time.Now().Add(time.Second), []appwire.Model{{ID: "ollama/qwen3:8b", Provider: "ollama"}}, sources) + } + turn := func() { backend.ollamaLoaded(sources, "ollama/qwen3:8b") } + + list() + turn() + if told != 1 { + t.Fatalf("the first turn on an unloaded model told the app %d times, want 1", told) + } + // keep_alive 0: the asked-for list still finds the model unloaded. + for range 3 { + list() + turn() + } + if told != 1 { + t.Fatalf("turns on a model the server never keeps loaded told the app %d times, want 1", told) + } + // Seen running once, it is worth asking about again when it next unloads. + setPS(`{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":65536}]}`) + list() + setPS(`{"models":[]}`) + list() + turn() + if told != 2 { + t.Fatalf("after the model was seen running, told the app %d times, want 2", told) + } + + // An old server lists the running model without its window: it is not + // unloaded, and a turn on it asks for nothing. + old := &appBackend{tellModels: func() { told++ }} + setPS(`{"models":[{"name":"qwen3:8b","model":"qwen3:8b"}]}`) + told = 0 + for range 3 { + old.addModelLimits(time.Now().Add(time.Second), []appwire.Model{{ID: "ollama/qwen3:8b", Provider: "ollama"}}, sources) + old.ollamaLoaded(sources, "ollama/qwen3:8b") + } + if told != 0 { + t.Fatalf("turns on a model running without a reported window told the app %d times", told) + } } diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 673afc05d1..fcb419dd3b 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -27,7 +27,7 @@ invalidates: - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode). A hand-off that joined a run which only reads its ground, the home folder apart, is not given the starting task's sentence or \"It joined the work already underway and shares its copy.\": its receipt reads \"It joined the work already underway, which only reads and writes in a folder of its own, so nothing in changes while it is part of that run. To change , propose the work once that run has ended.\" (taskJoinedReadsSentence), whatever files its own proposal named." - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." - - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one that is not loaded and whose Modelfile sets a `num_ctx` under it, which overrides the server's own setting; `source` `last_loaded` is one that is not loaded, sets nothing, and was last seen running in `/api/ps` with that `window` (remembered per service address and model for the life of the engine process, not on disk). A model that is not loaded, sets nothing and has not been seen running carries no `small_window`, because the server's default window depends on the machine and the person's setting and no API reports it; there is no `source` `default`. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`. A server that is absent, refuses or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine; a list that runs out of time repeats each unasked model's limits from the last list that could ask. A turn ending on an Ollama model the server was not running at the last list emits `models.changed` once. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." + - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one whose Modelfile sets `num_ctx`, which overrides the server's own setting, so raising that setting cannot help (its `window` is the running window when loaded, else the Modelfile's, and `loaded` is only for a model whose Modelfile sets none); `source` `last_loaded` is one that is not loaded, sets nothing, and was last seen running in `/api/ps` with that `window` (remembered per service address and model for the life of the engine process, not on disk). A model that is not loaded, sets nothing and has not been seen running carries no `small_window`, because the server's default window depends on the machine and the person's setting and no API reports it; there is no `source` `default`. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`; a model whose list lacks `completion` (an embedding model) carries no limits. A server that is absent, refuses or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine; a list that runs out of time repeats each unasked model's limits from the last list that could ask. A turn ending on an Ollama model the server was not running at the last list, or one that list gave a `small_window`, emits `models.changed` once for that turn; a model the server lists as running without a window is not counted as not running, and one still not running at the list after such a notice raises no further notice for that until a list sees it running. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 88753de4a9..5647707637 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -2920,8 +2920,9 @@ that is absent, refuses or answers in an unknown shape reports no limit. `needs` is the window the app's prompts ask for, 32000 tokens (the engine's lean threshold). `source` says how `window` is known: `loaded` (the server is running -the model with this window), `modelfile` (the model is not loaded and its -Modelfile sets `num_ctx`, which overrides the server's own setting) or +the model with this window and its Modelfile sets no `num_ctx`), `modelfile` +(its Modelfile sets `num_ctx`, which overrides the server's own setting; +`window` is the window it runs with when it is loaded, else the Modelfile's) or `last_loaded` (not loaded, nothing sets it, and `window` is what the server gave the model when this engine last saw it running in `GET /api/ps`). A window of `needs` or more is no limit. A model that is not loaded, sets no `num_ctx` and @@ -2931,14 +2932,20 @@ setting, and its API does not say what that will be. The engine remembers each model's last window per service address for as long as it runs, not on disk. `most` is the most the model itself can hold, when the server says. A model the server only forwards to another machine has no `small_window`. A server that -sends no capability list has no `no_tools`. A list that runs out of time before +sends no capability list has no `no_tools`, and a model whose capability list +lacks `completion` (an embedding model) has no limits at all. A list that runs out of time before it can ask about a model repeats that model's limits from the last list that could. Engines before `last_loaded` could send `source` `default` with no `window`; an app reads it as nothing measured and shows no warning for it. When a turn ends on an Ollama model the server was not running at the last -`models.list`, the engine emits `models.changed` once: the turn loaded the -model, so the next list reads the window the server really gave it. +`models.list`, or one that list gave a `small_window`, the engine emits +`models.changed` once for that turn: the turn loaded the model, or may have +reloaded it with a larger window after the person raised Ollama's setting, so +the next list reads the window the server really gave it. A model the server +lists as running without a window is not counted as not running, and a model +the list after such a notice still finds not running raises no further notice +for not running until a list sees it running. ## orders methods diff --git a/internal/appwire/wire.go b/internal/appwire/wire.go index 1d2954b802..b3e046658f 100644 --- a/internal/appwire/wire.go +++ b/internal/appwire/wire.go @@ -751,7 +751,7 @@ type ModelLimit struct { Needs int `json:"needs,omitempty"` // Most is the most the model itself can hold, when the server says. Only with small_window. Most int `json:"most,omitempty"` - // Source says how Window is known: "loaded" (the server is running it with this window), "modelfile" (not loaded, and its Modelfile sets num_ctx, which overrides the server's own setting) or "last_loaded" (not loaded, nothing sets it, and this window is what the server gave it when this engine last saw it running). Only with small_window. Engines before last_loaded could send "default", with no window; an app reads that as nothing measured. + // Source says how Window is known: "loaded" (the server is running it with this window and its Modelfile sets no num_ctx), "modelfile" (its Modelfile sets num_ctx, which overrides the server's own setting; Window is the running window when it is loaded, else the Modelfile's) or "last_loaded" (not loaded, nothing sets it, and this window is what the server gave it when this engine last saw it running). Only with small_window. Engines before last_loaded could send "default", with no window; an app reads that as nothing measured. Source string `json:"source,omitempty" enum:"loaded,modelfile,last_loaded"` } diff --git a/internal/ollamalimits/ollamalimits.go b/internal/ollamalimits/ollamalimits.go index 2848986699..dadad3e0ba 100644 --- a/internal/ollamalimits/ollamalimits.go +++ b/internal/ollamalimits/ollamalimits.go @@ -144,11 +144,15 @@ type Reading struct { // Limits is where the model falls short, empty when nothing is known // against it. Limits []appwire.ModelLimit - // Unloaded says the server answered that it is not running the model. + // Loaded says the server answered that it is running the model, and with + // what window; Unloaded that it is not running the model at all. A server + // that lists the model as running without a window (one from before the + // field was added) has said neither, and neither does a list it refused. + Loaded bool Unloaded bool // Stale says this list ran out of time before the server could answer - // about the model, so Limits and Unloaded are those of the last list that - // could (nothing, when none could). + // about the model, so Limits, Loaded and Unloaded are those of the last + // list that could (nothing, when none could). Stale bool } @@ -204,16 +208,17 @@ func (p Probe) Read(ctx context.Context, names []string, needs int) map[string]R ctx, cancel := context.WithTimeout(ctx, Whole) defer cancel() var ( - running map[string]int - listed outcome - wait sync.WaitGroup + running map[string]int + windowless map[string]bool + listed outcome + wait sync.WaitGroup ) shows := make([]shown, len(names)) gate := make(chan struct{}, atOnce) wait.Add(1 + len(names)) guard.Go("ollamalimits/loaded", func() { defer wait.Done() - running, listed = p.loaded(ctx) + running, windowless, listed = p.loaded(ctx) }) for i, name := range names { guard.Go("ollamalimits/show", func() { @@ -237,15 +242,24 @@ func (p Probe) Read(ctx context.Context, names []string, needs int) map[string]R var reading Reading if listed == answered { loaded := running[tagged(name)] - reading.Unloaded = loaded == 0 - if limit, small := smallWindow(loaded, p.Memory.lastWindow(p.base, name), shows[i], needs); small { + reading.Loaded = loaded > 0 + reading.Unloaded = loaded == 0 && !windowless[tagged(name)] + } + // A MODEL THAT CANNOT HOLD A CONVERSATION IS NOT A WEAK CHAT MODEL. An + // embedding model says so in its capabilities (no "completion"), and + // Ollama's listing carries it beside the chat models: a window or a lack + // of tools said of it would be advice about a conversation it cannot + // have. A server that sends no list has not said so either way. + chats := len(shows[i].capabilities) == 0 || slices.Contains(shows[i].capabilities, "completion") + if listed == answered && chats { + if limit, small := smallWindow(running[tagged(name)], p.Memory.lastWindow(p.base, name), shows[i], needs); small { reading.Limits = append(reading.Limits, limit) } } // A SERVER THAT SENDS NO LIST HAS NOT SAID THE MODEL LACKS TOOLS. Older // servers send none at all, and reading that as "no tools" would warn // about every model they hold. - if len(shows[i].capabilities) > 0 && !slices.Contains(shows[i].capabilities, "tools") { + if chats && len(shows[i].capabilities) > 0 && !slices.Contains(shows[i].capabilities, "tools") { reading.Limits = append(reading.Limits, appwire.ModelLimit{Kind: appwire.LimitNoTools}) } p.Memory.keep(p.base, name, reading) @@ -259,20 +273,28 @@ func (p Probe) Read(ctx context.Context, names []string, needs int) map[string]R // (last), either 0 when there is none. Whether the server answered /api/ps at // all is the caller's: without that nobody knows which window counts. // -// A window running now is believed over the Modelfile's, which only says what -// the next load would ask for; the Modelfile's over the last load's, because -// it overrides the server's own setting; and a model with none of the three +// A window running now is the figure believed over the Modelfile's, which only +// says what the next load would ask for, and over the last load's. What is +// said of where it comes from follows the server's own order: its setting +// first, then a Modelfile's num_ctx over it. So a model whose Modelfile sets +// num_ctx is said to have its window from the Modelfile whether or not it is +// loaded, because raising the server's setting would not change it; with +// nothing loaded its figure is the Modelfile's, and only a model that sets +// none is read by the window it last ran with. A model with none of the three // has no window limit. The server decides its default when it loads a model, // from the machine's memory or a setting the person may have raised, and no // API says what it is, so a warning without a figure would be a guess. func smallWindow(loaded, last int, model shown, needs int) (appwire.ModelLimit, bool) { limit := appwire.ModelLimit{Kind: appwire.LimitSmallWindow, Needs: needs, Most: model.most} + modelfile := model.asked == answered && !model.remote && model.numCtx > 0 switch { + case loaded > 0 && modelfile: + limit.Window, limit.Source = loaded, appwire.WindowModelfile case loaded > 0: limit.Window, limit.Source = loaded, appwire.WindowLoaded case model.asked != answered || model.remote: return limit, false - case model.numCtx > 0: + case modelfile: limit.Window, limit.Source = model.numCtx, appwire.WindowModelfile case last > 0: limit.Window, limit.Source = last, appwire.WindowLastLoaded @@ -282,9 +304,10 @@ func smallWindow(loaded, last int, model shown, needs int) (appwire.ModelLimit, return limit, limit.Window < needs } -// loaded is the window of every model the server is running now, by name, and -// how the question went. -func (p Probe) loaded(ctx context.Context) (map[string]int, outcome) { +// loaded is the window of every model the server is running now, by name, the +// models it says it is running without saying the window, and how the +// question went. +func (p Probe) loaded(ctx context.Context) (map[string]int, map[string]bool, outcome) { var answer struct { Models *[]struct { Name string `json:"name"` @@ -293,22 +316,26 @@ func (p Probe) loaded(ctx context.Context) (map[string]int, outcome) { } `json:"models"` } if asked := p.ask(ctx, http.MethodGet, "/api/ps", nil, &answer); asked != answered { - return nil, asked + return nil, nil, asked } if answer.Models == nil { - return nil, refused + return nil, nil, refused } - running := map[string]int{} + running, windowless := map[string]int{}, map[string]bool{} for _, model := range *answer.Models { // A server from before the field was added sends no window; such a - // model is then read by its Modelfile as though it were not loaded. + // model is then read by its Modelfile as though it were not loaded, + // though it is not said to be unloaded: it is running, and a turn on + // it would learn nothing new. if model.ContextLength <= 0 { + windowless[tagged(model.Name)] = true + windowless[tagged(model.Model)] = true continue } running[tagged(model.Name)] = model.ContextLength running[tagged(model.Model)] = model.ContextLength } - return running, answered + return running, windowless, answered } // show is what the server says about one model. diff --git a/internal/ollamalimits/ollamalimits_test.go b/internal/ollamalimits/ollamalimits_test.go index 3eaed2013d..8893c3ad54 100644 --- a/internal/ollamalimits/ollamalimits_test.go +++ b/internal/ollamalimits/ollamalimits_test.go @@ -104,20 +104,53 @@ const ( plainModel = `{"capabilities":["completion","tools","thinking"],"parameters":"temperature 0.6\nstop \"<|im_end|>\"","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}` ) -// The window the server is running a model with is the one a turn gets, so it -// is reported over whatever the Modelfile asks for. +// The window the server is running a model with is the figure reported, over +// whatever the Modelfile asks for. Where it comes from follows the server's own +// order: a Modelfile's num_ctx overrides the server's setting, so a loaded +// model whose Modelfile sets one is said to have its window from the Modelfile, +// and only a model that sets none is said to be running with the server's. func TestALoadedWindowIsBelievedOverTheModelfile(t *testing.T) { stub := &stubServer{ - ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096}]}`, - show: map[string]string{"qwen3:8b": `{"capabilities":["completion","tools"],"parameters":"num_ctx 65536","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`}, + ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096},{"name":"plain:latest","model":"plain:latest","context_length":4096}]}`, + show: map[string]string{ + "qwen3:8b": `{"capabilities":["completion","tools"],"parameters":"num_ctx 65536","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`, + "plain": plainModel, + }, + } + got := limitsFrom(t, stub, "qwen3:8b", "plain") + want := map[string][]appwire.ModelLimit{ + "qwen3:8b": {{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowModelfile}}, + "plain": {{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowLoaded}}, } - got := limitsFrom(t, stub, "qwen3:8b") - want := map[string][]appwire.ModelLimit{"qwen3:8b": {{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowLoaded}}} if !reflect.DeepEqual(got, want) { t.Fatalf("limits = %+v, want %+v", got, want) } } +// A model whose Modelfile sets a small num_ctx is said to have that window from +// its Modelfile, loaded or not: raising the server's setting cannot change it, +// so the advice must not flip with the model loading and unloading. +func TestALoadedModelWithASmallModelfileWindowIsTheModelfiles(t *testing.T) { + stub := &stubServer{ + ps: `{"models":[{"name":"pinned:latest","model":"pinned:latest","context_length":4096}]}`, + show: map[string]string{"pinned": `{"capabilities":["completion","tools"],"parameters":"num_ctx 4096","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`}, + } + server := httptest.NewServer(stub) + defer server.Close() + probe, _ := At(server.URL+"/v1", "") + probe.Memory = &Memory{} + want := []appwire.ModelLimit{{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowModelfile}} + loaded := probe.Read(context.Background(), []string{"pinned"}, needs)["pinned"] + if !loaded.Loaded || loaded.Unloaded || !reflect.DeepEqual(loaded.Limits, want) { + t.Fatalf("loaded reading = %+v, want loaded with %+v", loaded, want) + } + stub.ps = nothingRunning + unloaded := probe.Read(context.Background(), []string{"pinned"}, needs)["pinned"] + if unloaded.Loaded || !unloaded.Unloaded || !reflect.DeepEqual(unloaded.Limits, want) { + t.Fatalf("unloaded reading = %+v, want unloaded with %+v", unloaded, want) + } +} + // A model loaded with room enough has no window limit, however small its // Modelfile's own figure is. func TestALoadedWindowLargeEnoughReportsNothing(t *testing.T) { @@ -182,7 +215,7 @@ func TestALastLoadedWindowIsRememberedPerServer(t *testing.T) { ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096},{"name":"pinned:latest","model":"pinned:latest","context_length":4096}]}`, show: map[string]string{ "qwen3:8b": plainModel, - "pinned": `{"capabilities":["tools"],"parameters":"num_ctx 8192"}`, + "pinned": `{"capabilities":["completion","tools"],"parameters":"num_ctx 8192"}`, }, } server := httptest.NewServer(stub) @@ -266,15 +299,38 @@ func TestALateListAnswersTheLastFinishedReading(t *testing.T) { } // A server that runs a model from before it reported windows says the model is -// loaded and not with what, so the model is read as though it were not. +// loaded and not with what, so the model is read by its Modelfile as though it +// were not loaded. It is not said to be unloaded either: it is running, and a +// turn on it would load nothing the next list could read. func TestALoadedModelWithNoWindowIsReadByItsModelfile(t *testing.T) { stub := &stubServer{ - ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b"}]}`, - show: map[string]string{"qwen3:8b": `{"parameters":"num_ctx 4096"}`}, + ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b"},{"name":"plain:latest","model":"plain:latest"}]}`, + show: map[string]string{"qwen3:8b": `{"parameters":"num_ctx 4096"}`, "plain": plainModel}, + } + server := httptest.NewServer(stub) + defer server.Close() + probe, _ := At(server.URL+"/v1", "") + got := probe.Read(context.Background(), []string{"qwen3:8b", "plain"}, needs) + if r := got["qwen3:8b"]; r.Loaded || r.Unloaded || len(r.Limits) != 1 || r.Limits[0].Source != appwire.WindowModelfile || r.Limits[0].Window != 4096 { + t.Fatalf("reading = %+v, want the Modelfile's window, neither loaded nor unloaded", r) + } + if r := got["plain"]; !reflect.DeepEqual(r, Reading{}) { + t.Fatalf("a running model with no window and no num_ctx = %+v, want nothing", r) } - got := limitsFrom(t, stub, "qwen3:8b")["qwen3:8b"] - if len(got) != 1 || got[0].Source != appwire.WindowModelfile || got[0].Window != 4096 { - t.Fatalf("limits = %+v, want the Modelfile's window", got) +} + +// A model that cannot hold a conversation (an embedding model, whose +// capabilities lack "completion") is not a weak chat model: neither a window +// nor a lack of tools is reported for it, whatever its Modelfile sets. +func TestAModelThatCannotChatHasNoLimits(t *testing.T) { + stub := &stubServer{ps: `{"models":[{"name":"nomic-embed-text:latest","context_length":2048}]}`, show: map[string]string{ + "nomic-embed-text": `{"capabilities":["embedding"],"parameters":"num_ctx 2048","model_info":{"general.architecture":"nomic-bert","nomic-bert.context_length":2048}}`, + "mxbai-embed": `{"capabilities":["embedding"],"parameters":"num_ctx 512"}`, + "tiny": `{"capabilities":["completion"],"parameters":"num_ctx 2048"}`, + }} + got := limitsFrom(t, stub, "nomic-embed-text", "mxbai-embed", "tiny") + if len(got) != 1 || len(got["tiny"]) != 2 { + t.Fatalf("limits = %+v, want only the chat model's", got) } } @@ -350,8 +406,8 @@ func TestAFailedOrOddAnswerReportsNothingForThatModel(t *testing.T) { // either still reports the window, with no most. func TestMostIsAbsentWhenTheServerDoesNotSayIt(t *testing.T) { stub := &stubServer{ps: nothingRunning, show: map[string]string{ - "bare": `{"capabilities":["tools"],"parameters":"num_ctx 4096","model_info":{"general.architecture":"llama"}}`, - "words": `{"capabilities":["tools"],"parameters":"num_ctx 4096","model_info":{"general.architecture":"llama","llama.context_length":"many"}}`, + "bare": `{"capabilities":["completion","tools"],"parameters":"num_ctx 4096","model_info":{"general.architecture":"llama"}}`, + "words": `{"capabilities":["completion","tools"],"parameters":"num_ctx 4096","model_info":{"general.architecture":"llama","llama.context_length":"many"}}`, }} got := limitsFrom(t, stub, "bare", "words") for _, name := range []string{"bare", "words"} { From 013d162d81d03e65ff585eef51aaccd599aa8017 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:43:56 -0500 Subject: [PATCH 33/37] teams: a pause ends the turn through its own door, and Resume carries the work on The app's Pause stopped a member's turn through the person's Stop, so it began the stop hold: what arrived next was kept as stopped work, the manager was told "stopped by the person", and Resume started nothing. Pause now ends the turn through StopByPause (the app's members.pause, and the "paused" stop line wherever the app or a terminal reads it back). It begins no hold and tells no manager anything; a turn it cuts on handed work keeps that work, and Resume starts one turn told why it began. A stop of the paused member withdraws that turn and ends the work. A program landing a hold kept said its limit twice with two notices and wrapped the hold's sentence inside the program's note; it is said once and the sentence follows the note. Co-Authored-By: Claude Opus 5.5 --- cmd/codeaf/appcrewmembers.go | 39 ++++- cmd/codeaf/appcrews.go | 12 +- cmd/codeaf/appcrewstops_test.go | 76 +++++++++ internal/manual/chat/team-manager.md | 36 +++-- internal/session/stopcause.go | 7 + internal/session/stopcause_test.go | 2 +- internal/session/task_run_belt.go | 36 +++-- internal/session/team_pause.go | 40 +++++ internal/session/team_pause_test.go | 222 +++++++++++++++++++++++++++ internal/session/team_stophold.go | 10 +- internal/session/teamevent.go | 8 + internal/teams/traffic.go | 11 ++ internal/tui3/app.go | 8 + internal/tui3/teamtraffic.go | 31 ++++ internal/tui3/teamtraffic_test.go | 15 ++ 15 files changed, 522 insertions(+), 31 deletions(-) diff --git a/cmd/codeaf/appcrewmembers.go b/cmd/codeaf/appcrewmembers.go index e30c201ae2..f9fded3e7a 100644 --- a/cmd/codeaf/appcrewmembers.go +++ b/cmd/codeaf/appcrewmembers.go @@ -8,8 +8,8 @@ package main // has to make a field true it does so through doors the engine already has: // a role's instructions are a message in the member's own conversation, its // model the conversation's model, a member's budget the agent's own spending -// limit, and a pause the crew's own stop with every turn the conversation -// starts by itself stopped until the person resumes it (appwakes.go). +// limit, and a pause the team's own record with the running turn ended +// through the pause's door, which Resume takes up again (pauseStop). // // A PROPOSAL is the agent's own: the app asks its model, beside its chat and // never in it, for complete JSON lines naming the crew and the helpers it would @@ -61,9 +61,10 @@ func (b *appBackend) Member(verb string, ask appwire.MemberAsk) (appwire.CrewMem // before the running turn is stopped: the member's own session reads // it and starts nothing on the crew's traffic until the person // resumes it, the manager's view of its crew says "paused", and a - // directive sent meanwhile waits on the log. + // directive sent meanwhile waits on the log. The turn is ended + // through the pause's own door ([appBackend.pauseStop]). if err = b.crewEdit(func(f *teamstore.File) error { return f.SetPaused(crew, m.Key, true) }); err == nil { - err = b.memberStop(t, m, agent, "paused") + err = b.memberStop(t, m, agent, teamstore.PausedStopText) } case "resume": // THE RESUME IS SAID WHEREVER THE PAUSE HELD. A pause holds the @@ -262,11 +263,41 @@ func (b *appBackend) memberStop(t teamstore.Team, m teamstore.Member, agent, rea return appEngineError(err) } if b.isHeld(agent) { + if reason == teamstore.PausedStopText { + return b.pauseStop(agent) + } return b.Stop(agent) } return nil } +// pauseStop ends the running turn of a member the person paused, through the +// pause's own door ([session.StopByPause]). +// +// A PAUSE IS NOT A STOP. Through the person's Stop it began the stop hold: a +// command's ending was kept with the stop's words, the manager was told the +// work was "stopped by the person" and not to hand it out again, and Resume +// started nothing. A pause is temporary, so the turn it ends is taken up again +// when the person resumes the member. A conversation still being opened is +// left to its engine, which starts nothing on its own for a paused member. +func (b *appBackend) pauseStop(id string) error { + a, endRead, err := b.findCrewOwner(id) + if err != nil { + return err + } + defer endRead() + starting := false + b.locked(func() { starting = a.starting }) + if starting { + return nil + } + if live := b.liveOf(a); live != nil { + b.locked(func() { live.stopping = live.running }) + appInterruptFor(live.conn.Conv, session.StopByPause) + } + return nil +} + // memberCap is a member's budget: the agent's own spending limit. func (b *appBackend) memberCap(agent string, usd *float64) error { if usd == nil || *usd <= 0 { diff --git a/cmd/codeaf/appcrews.go b/cmd/codeaf/appcrews.go index a1bdc8fbb7..0838e1ed12 100644 --- a/cmd/codeaf/appcrews.go +++ b/cmd/codeaf/appcrews.go @@ -864,9 +864,17 @@ func (b *appBackend) crewAct(run *appCrewRun, read appCrewRead, t teamstore.Team return } agent := appMemberAgent(m) - if b.isHeld(agent) { - _ = b.Stop(agent) + if !b.isHeld(agent) { + return + } + // The app's own Pause writes a stop line too, and it is read back + // here: it ends the turn through the pause's door, never the + // person's Stop, which would end the work the pause keeps. + if e.PauseStop() { + _ = b.pauseStop(agent) + return } + _ = b.Stop(agent) case teamstore.KindStart: manager, ok := t.Member(t.Manager) if !ok || !b.isHeld(appMemberAgent(manager)) { diff --git a/cmd/codeaf/appcrewstops_test.go b/cmd/codeaf/appcrewstops_test.go index b98519874e..a684ea687e 100644 --- a/cmd/codeaf/appcrewstops_test.go +++ b/cmd/codeaf/appcrewstops_test.go @@ -185,3 +185,79 @@ func TestAppMovePausesToStoreKeepsAPauseItCouldNotCarry(t *testing.T) { t.Fatalf("a settled pause is still in the app's file: crew=%v gone=%v", flag(crew), flag(gone)) } } + +// A PAUSE ENDS THE TURN THROUGH THE PAUSE'S OWN DOOR, never the person's Stop. +// Through the person's door the engine began the stop hold: a command's ending +// was kept as stopped work, the manager was told "stopped by the person" and +// not to hand the work out again, and Resume started nothing. The stop line the +// pause writes is read back the same way, and a real Stop still uses the +// person's door. +func TestAppPauseEndsTheTurnThroughThePausesDoor(t *testing.T) { + backend, conv, agent := dooredBackend(t, false) + crew := teamstore.NewID() + if err := teamstore.Update(backend.profileDir, func(f *teamstore.File) error { + f.Teams = append(f.Teams, teamstore.Team{ID: crew, Name: "crew"}) + lead := filepath.Join(t.TempDir(), "lead", "transcript.jsonl") + if err := f.AddMember(crew, teamstore.Member{Key: lead, File: lead, Handle: "lead"}); err != nil { + return err + } + if err := f.AddMember(crew, teamstore.Member{Key: appFakeTranscript, File: appFakeTranscript, Handle: "scout", Started: true}); err != nil { + return err + } + return f.SetManager(crew, lead) + }); err != nil { + t.Fatal(err) + } + only := func(want session.StopDoor) { + t.Helper() + got := conv.stops() + if len(got) == 0 { + t.Fatalf("nothing was stopped, want %q", want) + } + for _, door := range got { + if door != want { + t.Fatalf("the member was stopped through %v, want only %q", got, want) + } + } + } + + if _, err := backend.Member("pause", appwire.MemberAsk{Crew: crew, Agent: agent.ID}); err != nil { + t.Fatal(err) + } + only(session.StopByPause) + + entries, err := teamstore.ReadTraffic(backend.profileDir, crew, "", 100) + if err != nil { + t.Fatal(err) + } + file, err := teamstore.Load(backend.profileDir) + if err != nil { + t.Fatal(err) + } + team, _ := file.Team(crew) + conv.doorMu.Lock() + conv.doors = nil + conv.doorMu.Unlock() + pauses := 0 + for _, entry := range entries { + if entry.PauseStop() { + pauses++ + backend.crewAct(&appCrewRun{acted: map[string]bool{}}, appCrewRead{file: file}, team, entry) + } + } + if pauses != 1 { + t.Fatalf("the pause wrote %d stop lines, want one", pauses) + } + only(session.StopByPause) + + if _, err := backend.Member("resume", appwire.MemberAsk{Crew: crew, Agent: agent.ID}); err != nil { + t.Fatal(err) + } + conv.doorMu.Lock() + conv.doors = nil + conv.doorMu.Unlock() + if _, err := backend.Member("stop", appwire.MemberAsk{Crew: crew, Agent: agent.ID}); err != nil { + t.Fatal(err) + } + only(session.StopByPerson) +} diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 8a723d43b1..9b91e30c19 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -335,8 +335,8 @@ would never write in a message: - `finished` when a turn ends, `stopped by the person` when you stopped a member that was on its manager's work (a directive, or the brief it was started on), `stopped` for every - other stop (its manager's, codeaf ending it, or your stop when none of the manager's work - was under way), and `failed: ` with the error's first line when a turn ends on one; + other stop (its manager's, codeaf ending it, your pause, or your stop when none of the + manager's work was under way), and `failed: ` with the error's first line when a turn ends on one; - when it starts waiting on you: the permission line for a permission prompt (`needs your ok to run bash`), or `asks: ` and the question for anything else; - `no longer waiting` when the last of those questions comes down. @@ -351,8 +351,8 @@ the work is not done, that you chose to stop it, and not to hand it out again un The work is under way from the hand-off until a turn finishes with no background command left that the member waits on. So a turn such a command's ending starts is still on it, and so is a turn you opened by typing to the member while it waits on one. Stopping a member -with none of the manager's work under way tells the manager nothing, and neither does codeaf -quitting or a paused member's stray wake being ended. The global +with none of the manager's work under way tells the manager nothing, and neither does pausing +a member, codeaf quitting or a paused member's stray wake being ended. The global manager is not woken by a member of `All teams` being stopped (see **The global manager**). ## A stopped member's command is still running — why it did not start again when the command ended @@ -663,10 +663,12 @@ leaves the directive unread in the traffic for that turn. ## Pausing a crew member — pause, resume, why a directive did not start, held You can pause a member of a crew in the desktop app: **Pause** on its row in the Members tab -or in the member's menu, and **Resume** to lift it. A pause stops the member's current turn -and is kept on the team's own record, so the member's session, its manager and every window -read the same answer. A crew's manager, and a member that manages a crew of its own, cannot -be paused; stop its turn instead. +or in the member's menu, and **Resume** to lift it. A pause ends the member's current turn, +which ends `stopped` and wakes nobody: a pause is not a stop, so the manager is not told +`stopped by the person` and the work is kept for Resume. The pause is kept on the team's own +record, so the member's session, its manager and every window read the same answer. A +crew's manager, and a member that manages a crew of its own, cannot be paused; stop its turn +instead. While a member is paused, team traffic starts no turn for it, in any crew it belongs to, and Resume from any of those crews lifts it: @@ -679,15 +681,27 @@ Resume from any of those crews lifts it: - `team_status` shows the member as `paused by the person; it starts nothing until they resume it`, with `has not started on #22` when a directive is waiting. - codeaf does not open the member's conversation for traffic it would only hold. +- A command ending, a watch firing, a task landing and news at its last turn's end start no + turn either: each is written into the conversation as a record that says it arrived while + the conversation was paused. + +## Resume after a pause — what starts again, the paused work carried on, a stop while paused **Resume** writes `resumed` to the log of each crew the member is in, and a directive that waited starts the member's turn within a second or two, including after codeaf was closed in between. With the team's auto-wake off, a resumed member reads it at its next turn like any other message. -A command ending, a watch firing, a task landing and news at its last turn's end start no -turn either: each is written into the conversation as a record. Resume starts one turn that -reads them (with a waiting directive), unless a stop since holds them. +With no directive waiting, Resume starts one turn when the pause ended a turn on the +manager's work or held a record. That turn opens with "The person paused this conversation +and has now resumed it, which started this turn. Carry on with the work you were on; anything +above that arrived while it was paused is a record of what happened meanwhile." A member +paused while it waited on a command for that work starts again when the command ends, or at +Resume if it ended meanwhile. + +A pause is temporary and a stop is final. **Stop** on a paused member, or a stop before the +pause, ends the work as any stop does: its manager is told `stopped by the person` when the +work was the manager's, and Resume starts nothing. Not held: your own words (that turn reads what was waiting, so Resume starts nothing more), your answer to its question, a decision you hand it, and codeaf continuing a reply it was diff --git a/internal/session/stopcause.go b/internal/session/stopcause.go index 3bbac54dae..6a658c4dd1 100644 --- a/internal/session/stopcause.go +++ b/internal/session/stopcause.go @@ -45,6 +45,11 @@ const ( // session (team_wakewatch.go): the person's Stop in every respect but who // asked, so the member's conversation says the manager did it. StopByManager StopDoor = "stopped by its manager" + // StopByPause is the person pausing a team member (team_pause.go): their + // act, but a temporary one. It begins no stop hold and tells no manager + // the work was stopped, and the turn it cuts on handed work is taken up + // again when they resume the member ([Agent.teamPauseOwedWake]). + StopByPause StopDoor = "person paused" // StopByTakeover is another window taking this conversation over // (takeover.go). The turn dies where it stands, mid-reply or not. StopByTakeover StopDoor = "taken over" @@ -163,6 +168,8 @@ func stopSentence(door StopDoor, name string) string { return "" case StopByManager: return "the manager stopped this turn" + case StopByPause: + return "you paused this conversation, so the reply stopped here" case StopByTakeover: return "this conversation was opened in another window, so the reply stopped here — ask again to pick it up" case StopByLeaving: diff --git a/internal/session/stopcause_test.go b/internal/session/stopcause_test.go index 7f4c07ea55..9c5aefa532 100644 --- a/internal/session/stopcause_test.go +++ b/internal/session/stopcause_test.go @@ -121,7 +121,7 @@ func TestATurnThePersonStoppedSaysNothingAboutIt(t *testing.T) { // at nothing, and there is exactly one that is allowed to. func TestEveryDoorNamesItselfAndOnlyThePersonsIsSilent(t *testing.T) { doors := []StopDoor{ - StopByPerson, StopByManager, StopByTakeover, StopByLeaving, StopByClosing, + StopByPerson, StopByManager, StopByPause, StopByTakeover, StopByLeaving, StopByClosing, StopByAbandoned, StopByWorkStopped, StopByRetired, StopByEngineStopped, } seen := map[string]StopDoor{} diff --git a/internal/session/task_run_belt.go b/internal/session/task_run_belt.go index 95c7e4c46d..ba7df23c20 100644 --- a/internal/session/task_run_belt.go +++ b/internal/session/task_run_belt.go @@ -2449,17 +2449,22 @@ var beltLandingAdmissionWaits func() func (a *Agent) deliverBeltRunLanding(run *beltRun, summary RunSummary, landing RunLanding) { line := run.outcomeNote(summary, landing, a.beltRunSpan(run)) + // A PROGRAM'S LIMIT IS SAID ONCE, here, whatever becomes of the landing: a + // quiet receipt, a wake, or a receipt a hold keeps. Each of those used to + // say it again, and a landing a hold kept was told twice with two notices. + if run.delegate != nil { + if limit := programLimitLine(run, summary, landing); limit != "" { + a.recordProgramLimit(limit) + } + } if a.beltRunQuiet(run) { - a.recordQuietBeltLanding(run, summary, line, landing) + a.recordQuietBeltLanding(run, summary, line, "") return } if beltLandingAdmissionWaits != nil { beltLandingAdmissionWaits() } if run.delegate != nil { - if limit := programLimitLine(run, summary, landing); limit != "" { - a.recordProgramLimit(limit) - } a.admitBeltLanding(run, summary, line, landing, a.programLandingNote(run, summary, line)) return } @@ -2501,27 +2506,36 @@ func (a *Agent) admitBeltLanding(run *beltRun, summary RunSummary, line string, run.deliveryMu.Lock() if a.beltRunQuiet(run) { run.deliveryMu.Unlock() - a.recordQuietBeltLanding(run, summary, line, landing) + a.recordQuietBeltLanding(run, summary, line, "") return } // The receipt is written under deliveryMu, which is the order page Stop // takes its locks in (stoprun.go): deliveryMu, then beltMu and a.mu. + // + // A LANDING THE PERSON STILL OWED AN ANSWER LOSES ITS BOUNDED SETTLE TURN + // when a hold keeps it: the turn that later reads the receipt is the + // person's own, a manager's hand-off, or the one Resume starts on whatever + // else the pause cut and held, and the settle's ceiling and model would cut + // any of those short. It reads the receipt as an ordinary turn does. note.cause = wakeLanding - note.heldReceipt = func(why string) { a.recordQuietBeltLanding(run, summary, line+"\n"+why, landing) } + note.heldReceipt = func(why string) { a.recordQuietBeltLanding(run, summary, line, why) } a.accept(delivery{origin: fromRuntime, kind: msgResult, note: note}) run.deliveryMu.Unlock() } // recordQuietBeltLanding preserves the actual result and its operational -// attribution after a late stop, without admitting another model turn. -func (a *Agent) recordQuietBeltLanding(run *beltRun, summary RunSummary, line string, landing RunLanding) { +// attribution after a late stop, without admitting another model turn. why is +// the sentence a standing hold gives for keeping it, "" for a late stop: it +// follows the whole receipt, a program's outcome note included, and is never +// read as part of the program's account. +func (a *Agent) recordQuietBeltLanding(run *beltRun, summary RunSummary, line, why string) { note := userText(line) if run.delegate != nil { - if limit := programLimitLine(run, summary, landing); limit != "" { - a.recordProgramLimit(limit) - } note = a.programLandingNote(run, summary, line) } + if why = strings.TrimSpace(why); why != "" { + note.message = textMessage("user", strings.TrimSpace(note.text())+"\n"+why) + } note.wake = false note.completionOnly = true note.replyTags = plainBeltLandingReplyTags(run, run.store.Task(run.root), summary) diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index c0dfd2cee1..354b6abe8a 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -50,6 +50,16 @@ package session // anything has it open. A start has no send behind it: a member paused before // its first turn writes that line itself, once ([Agent.teamWakeStart]). // +// A PAUSE IS TEMPORARY AND A STOP IS FINAL. The interface ends a paused +// member's running turn through the pause's own door ([StopByPause]), not the +// person's Stop: through that door the pause began the stop hold, so what +// arrived next was kept as stopped work, the manager was told the person had +// stopped what it handed out, and Resume started nothing. The pause's door +// begins no hold and tells no manager anything; a turn it cuts on handed work +// keeps that work, and Resume starts one turn that carries on with it +// ([Agent.teamPauseCut]). A stop of the paused member still ends the work, and +// withdraws that turn ([Agent.teamStopHoldLocked]). +// // THE PERSON'S OWN WORDS ARE NOT HELD, as with the daily cap (team_cap.go): a // person typing into a paused member's conversation starts its turn, and that // turn reads what was waiting. @@ -71,6 +81,10 @@ const teamPausedWhy = "the person paused it; it starts on this when they resume // had the conversation paused. const teamPauseHeldRule = "This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened." +// teamPauseResumedRule opens the turn Resume starts on what a pause kept: the +// work a pause cut, the news it held, or both ([Agent.teamPauseOwedWake]). +const teamPauseResumedRule = "The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on; anything above that arrived while it was paused is a record of what happened meanwhile." + // teamPauseHold is one conversation's pause, for the wakes that are decided // under the agent's lock and may read neither the teams file nor the seat's // lock there. @@ -100,6 +114,25 @@ func (a *Agent) teamPauseFreshSeated() { // reads what the pause kept. func (a *Agent) teamPauseOwedOver() { a.team.pauseHold.owed.Store(false) } +// teamPauseCut is a turn the person's Pause ended ([StopByPause]). Work a +// manager handed this conversation is kept, not ended: the turn Resume starts +// carries on with it, and a stop of the paused member is the stop of that work +// ([Agent.teamStopHoldLocked]). A turn on none of a manager's work owes nothing +// for its own sake. +func (a *Agent) teamPauseCut(origin turnOrigin) { + a.team.mu.Lock() + handed := len(a.team.handed) > 0 + a.team.mu.Unlock() + if !handed { + return + } + hold := &a.team.stopHold + hold.mu.Lock() + hold.origin = origin + hold.mu.Unlock() + a.team.pauseHold.owed.Store(true) +} + // teamPauseOwedWake starts the turn a lifted pause owes the news it held. // // A PAUSE IS TEMPORARY. What the pause kept from starting a turn is in the @@ -120,6 +153,13 @@ func (a *Agent) teamPauseOwedWake() { if a.running || hold.paused.Load() || !hold.owed.Swap(false) || a.team.stopHold.held.Load() { return } + if gate, _ := a.wakeRefusalLocked(false, false); gate != wakeGateOpen { + return + } + // THE TURN IS TOLD WHY IT BEGAN, in one sentence ahead of anything the + // pause kept: a turn the pause cut ended mid-work with no word of why, and + // without this one it reads its own unfinished reply and nothing after it. + a.steering = append(a.steering, userMessage{message: textMessage("user", teamPauseResumedRule), wake: true, authored: true}) a.wakeLocked() } diff --git a/internal/session/team_pause_test.go b/internal/session/team_pause_test.go index 83bbe6ba38..53ff23296f 100644 --- a/internal/session/team_pause_test.go +++ b/internal/session/team_pause_test.go @@ -855,3 +855,225 @@ func TestTeamResumeStartsATurnOnNewsThePauseHeld(t *testing.T) { t.Fatalf("Resume started %d turns, want one", got-1) } } + +// pauseLikeTheApp is the desktop app's Pause: the pause on the team's record, +// then the member's turn ended through the pause's own door +// (cmd/codeaf's appcrewmembers.go). It used to end it through the person's. +func pauseLikeTheApp(t *testing.T, fixture teamFixture, web *Agent) { + t.Helper() + setPaused(t, fixture, fixture.web, true) + web.InterruptFor(StopByPause) +} + +// A PAUSE IS NOT A STOP: RESUME CARRIES ON WITH THE WORK THE PAUSE CUT. The +// member was in a turn on its manager's directive and the person paused it. +// The turn ends "stopped", which wakes nobody, the manager is not told the +// person stopped its work, and nothing starts while the member is paused. +// Resume starts one turn, which is told why it began. +func TestTeamPauseMidTurnOnHandedWorkResumesIt(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(8) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + streaming := make(chan struct{}) + calls := &scriptedCompleter{steps: []step{thinkingStep(streaming), okStep(), okStep()}} + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + + pauseLikeTheApp(t, fixture, web) + waitQuiet(t, web) + waitTeamEvents(t, fixture, "stopped", 1) + quietFor() + web.settleTeamEvents() + if got := calls.requests(); got != 1 { + t.Fatalf("the paused member was asked %d times, want only the turn the pause cut", got) + } + if web.team.stopHold.held.Load() { + t.Fatal("the pause began the stop hold") + } + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 0 { + t.Fatalf("a pause was told to the manager as the person's stop: %v", said) + } + for i := 0; i < managerCalls.requests(); i++ { + if strings.Contains(userTextIn(managerCalls.request(i)), teamStoppedByPersonLine) { + t.Fatal("the manager was told the person stopped work that was only paused") + } + } + + setPaused(t, fixture, fixture.web, false) + waitRequests(t, calls, 2) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, teamPauseResumedRule) { + t.Fatalf("the turn Resume started was not told why it began:\n%s", asked) + } + waitQuiet(t, web) + quietFor() + if got := calls.requests(); got != 2 { + t.Fatalf("Resume started %d turns, want one", got-1) + } +} + +// A PAUSE OF A MEMBER WAITING ON A COMMAND HOLDS ITS ENDING AS THE PAUSE'S. The +// member's turn on the directive finished waiting on a command; the person +// paused it the way the app does and the command ended. No turn starts, the +// ending is a record in the pause's words (not the stop's "do not take the +// stopped work up again"), the manager is told nothing, and Resume starts one +// turn that reads it. +func TestTeamPauseOfAMemberWaitingOnACommandResumesOnItsEnding(t *testing.T) { + fixture, managerCalls, web, calls, clock, started := waitingMember(t, okStep(), okStep()) + pauseLikeTheApp(t, fixture, web) + web.jobs.settleExit(<-started, 7) + clock.advance(jobWakeDelay) + quietFor() + web.settleTeamEvents() + if got := calls.requests(); got != 1 { + t.Fatalf("the paused member was asked %d times, want only its first turn", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), teamPauseHeldRule) || strings.Contains(string(journal), teamStopHeldRule) { + t.Fatalf("the command's ending was not kept in the pause's words:\n%s", journal) + } + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 0 { + t.Fatalf("a pause was told to the manager as the person's stop: %v", said) + } + for i := 0; i < managerCalls.requests(); i++ { + if strings.Contains(userTextIn(managerCalls.request(i)), teamStoppedByPersonLine) { + t.Fatal("the manager was told the person stopped work that was only paused") + } + } + + setPaused(t, fixture, fixture.web, false) + waitRequests(t, calls, 2) + asked := userTextIn(calls.request(1)) + for _, want := range []string{"job 1 exited 7", teamPauseHeldRule, teamPauseResumedRule} { + if !strings.Contains(asked, want) { + t.Fatalf("the turn Resume started did not read %q:\n%s", want, asked) + } + } + waitQuiet(t, web) + quietFor() + if got := calls.requests(); got != 2 { + t.Fatalf("Resume started %d turns, want one", got-1) + } +} + +// A STOP WINS OVER A PAUSE. The person paused a member mid-turn on handed work +// and then stopped it: the stop is final, so Resume starts nothing, the +// manager is told the person stopped the work, and a command's ending after it +// is kept in the stop's words. +func TestTeamPersonStopOfAPausedMemberHoldsThroughResume(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(8) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + streaming := make(chan struct{}) + calls := &scriptedCompleter{steps: []step{thinkingStep(streaming), okStep(), okStep()}} + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + pauseLikeTheApp(t, fixture, web) + waitQuiet(t, web) + waitTeamEvents(t, fixture, "stopped", 1) + + web.Interrupt() + waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) + waitManagerToldOfStop(t, managerCalls) + if !web.team.stopHold.held.Load() { + t.Fatal("the person's stop of a paused member began no hold") + } + setPaused(t, fixture, fixture.web, false) + web.enqueueJobNote("job 8 exited 0") + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times after Resume, want only the turn the pause cut", got) + } + journal, err := os.ReadFile(fixture.web) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), teamStopHeldRule) { + t.Fatalf("a command's ending after the stop was not kept in the stop's words:\n%s", journal) + } + web.settleTeamEvents() + if said := trafficEvents(t, fixture, teams.StoppedByPerson); len(said) != 1 { + t.Fatalf("the stop was logged %d times, want once", len(said)) + } +} + +// A PROGRAM'S LANDING A HOLD KEEPS IS RECORDED ONCE. The landing said the +// program's limit, then its held receipt said it again with a second notice, +// and rebuilt the program's note around the hold's sentence, so the record read +// as if the sentence were the program's own account. The limit is said once, +// and the hold's sentence follows the program's note. +func TestTeamHeldProgramLandingIsRecordedOnce(t *testing.T) { + fixture := newWakingTeamFixture(t) + setPaused(t, fixture, fixture.web, true) + calls := oneAnswer(1) + web := teamAgent(t, fixture, fixture.web, calls, func(config *Config) { config.teamWatchManual = true }) + store := askStore(t, "repair parser") + defer store.Close() + program := testPrograms("senior-dev")[0] + run := &beltRun{store: store, root: store.RootID(), row: 7, delegate: &program, ground: "/project", costCeiling: 1} + web.beltMu.Lock() + web.beltRun = run + web.beltMu.Unlock() + t.Cleanup(func() { web.beltMu.Lock(); web.beltRun = nil; web.beltMu.Unlock() }) + updates, stop := web.WatchTaskUpdates() + defer stop() + summary, landing := RunSummary{Outcome: "a limit you set stopped it", Limit: RunLimitCost, USD: 1.2}, RunLanding{Branch: "task/repair"} + limit := programLimitLine(run, summary, landing) + if limit == "" { + t.Fatal("the fixture's landing names no limit") + } + web.deliverBeltRunLanding(run, summary, landing) + if calls.requests() != 0 { + t.Fatal("a program's landing started a paused member's turn") + } + + web.mu.Lock() + var texts []string + for _, message := range web.messages { + texts = append(texts, messageContentText(message)) + } + web.mu.Unlock() + all := strings.Join(texts, "\n") + if got := strings.Count(all, limit); got != 1 { + t.Fatalf("the program's limit was recorded %d times, want once:\n%s", got, all) + } + held := "" + for _, text := range texts { + if strings.Contains(text, teamPauseHeldRule) { + held = text + } + } + marker := "ended — for you to act on]" + if !strings.HasSuffix(held, "\n"+teamPauseHeldRule) || !strings.Contains(held, marker) || strings.Index(held, marker) > strings.Index(held, teamPauseHeldRule) { + t.Fatalf("the hold's sentence is not after the program's note:\n%s", held) + } + notices := 0 + deadline := time.After(300 * time.Millisecond) + for done := false; !done; { + select { + case event := <-updates: + if event.Kind == EventNotice && strings.Contains(event.Text, limit) { + notices++ + } + case <-deadline: + done = true + } + } + if notices != 1 { + t.Fatalf("the open surface was sent the limit %d times, want once", notices) + } +} diff --git a/internal/session/team_stophold.go b/internal/session/team_stophold.go index 15fe3d2c95..39b1f2b519 100644 --- a/internal/session/team_stophold.go +++ b/internal/session/team_stophold.go @@ -100,8 +100,13 @@ func (a *Agent) teamStopHoldLocked(door StopDoor) (waiting, withdrew bool) { } // A command that failed moments ago has its wake on a clock, and that turn // would end the hold: the clock is withdrawn and its notes stay queued - // for the next turn. + // for the next turn. So is the turn a pause owes Resume: a pause is + // temporary and a stop is final, so the stop of a paused member is the stop + // of the work the pause cut and of what it held ([Agent.teamPauseOwedWake]). withdrew = a.jobWake != nil + if a.team.pauseHold.owed.Swap(false) { + withdrew = true + } if !withdrew && (a.jobs == nil || !a.jobs.newsPending()) { return false, false } @@ -177,7 +182,8 @@ func (a *Agent) teamWorkGoesOn() bool { // teamStopHoldSaid tells the managers whose work this conversation is still on // that it was stopped while it waited on a command or a watch, or on the wake -// the hold withdrew. It ends that work: the stop is reported. A member waiting +// the hold withdrew, the turn Resume would have started among them. It ends +// that work: the stop is reported. A member waiting // on nothing finished its work, however long ago, and its managers are told // nothing. It reads the jobs and the teams' logs, so it runs away from the // stop's own path and outside a.mu. diff --git a/internal/session/teamevent.go b/internal/session/teamevent.go index 62c831e1b5..e7555680cd 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -243,6 +243,14 @@ func (a *Agent) teamTurnEnded(ctx context.Context, hub *eventHub) { a.teamEventOwedFor(origin, teams.StateIdle, "stopped", a.teamStoppedByPerson(door, a.teamHandedTake())) return } + if stopped && door == StopByPause { + // A PAUSE IS TEMPORARY: the handed work is not over, only waiting on + // the person (team_pause.go). Its ending is the plain "stopped", which + // wakes nobody, and Resume takes the work up again. + a.teamPauseCut(origin) + a.teamEventOwed(origin, teams.StateIdle, "stopped") + return + } a.teamHandedCarried(origin) if stopped { a.teamEventOwed(origin, teams.StateIdle, "stopped") diff --git a/internal/teams/traffic.go b/internal/teams/traffic.go index ac014fdfd2..a35a00ac13 100644 --- a/internal/teams/traffic.go +++ b/internal/teams/traffic.go @@ -62,6 +62,17 @@ const ( ToSeveral = "several" ) +// PausedStopText is the text of the stop line the person's Pause writes, from +// you, beside the pause on the team's record ([File.SetPaused]). +const PausedStopText = "paused" + +// PauseStop reports whether e is the stop line a Pause wrote. An interface +// holding the member ends its turn through the pause's own door, which keeps +// the work for Resume, and not through the person's Stop, which ends it. +func (e Entry) PauseStop() bool { + return e.Kind == KindStop && e.From == FromYou && e.Text == PausedStopText +} + var kinds = map[string]bool{ KindEvent: true, KindNote: true, KindDirective: true, KindStop: true, KindStart: true, KindYou: true, KindQuestion: true, KindAnswer: true, KindPacket: true, KindClose: true, KindReopen: true, diff --git a/internal/tui3/app.go b/internal/tui3/app.go index a448986d6b..62a3e3ab3f 100644 --- a/internal/tui3/app.go +++ b/internal/tui3/app.go @@ -9344,6 +9344,14 @@ func (a *app) interruptTurn() { return } a.agent.Interrupt() + a.turnInterrupted() +} + +// turnInterrupted is what the screen does once the turn in front has been told +// to stop: by the person's own key ([app.interruptTurn]), or by a pause of the +// member in front (teamtraffic.go's [app.trafficPause]), which ends the turn +// the same way on screen. +func (a *app) turnInterrupted() { a.flushUpdatePrefix() a.finishResponse(true) a.state = stateInterrupted diff --git a/internal/tui3/teamtraffic.go b/internal/tui3/teamtraffic.go index 094b1ef86d..31dda43154 100644 --- a/internal/tui3/teamtraffic.go +++ b/internal/tui3/teamtraffic.go @@ -7,6 +7,7 @@ import ( tea "charm.land/bubbletea/v2" + "github.com/Agent-Field/codeaf/internal/session" teamstore "github.com/Agent-Field/codeaf/internal/teams" ) @@ -481,6 +482,9 @@ func (a *app) trafficAct(teamID string, e teamstore.Entry) tea.Cmd { return nil } a.traffic.done[done] = true + if e.PauseStop() { + return a.trafficPause(key) + } a.trafficStop(key) return nil case teamstore.KindStart: @@ -522,6 +526,33 @@ func (a *app) trafficStop(key string) { } } +// trafficPause ends the turn of a member the person paused (the stop line the +// desktop app's Pause writes) through the pause's own door. The person's Stop +// would end the work itself: the engine would hold what the member waits on +// as stopped and tell its manager not to hand the work out again, where a +// pause keeps that work for Resume (internal/session's team_pause.go). The +// door is asked off the update loop (offloop.go); the screen ends the turn in +// front at once, as the person's own stop does. +func (a *app) trafficPause(key string) tea.Cmd { + var agent Agent + if key == a.frontTabKey() { + if a.state != stateWorking || a.agent == nil { + return nil + } + agent = a.agent + a.turnInterrupted() + } else if held := a.behind[key]; held != nil && held.conv.Agent != nil { + agent = held.conv.Agent + } + if agent == nil { + return nil + } + return a.offLoop(func() func(bool) tea.Cmd { + agent.InterruptFor(session.StopByPause) + return nil + }) +} + // trafficStart is the manager's start: a new conversation in the team's // folder, opened BEHIND the one in front and never brought forward, in the // team under the handle the manager chose. diff --git a/internal/tui3/teamtraffic_test.go b/internal/tui3/teamtraffic_test.go index 7fd49d2d02..3b845dbf1e 100644 --- a/internal/tui3/teamtraffic_test.go +++ b/internal/tui3/teamtraffic_test.go @@ -610,3 +610,18 @@ func TestTrafficStartedRecordsTheStartLineOnTheMembership(t *testing.T) { t.Fatalf("StartFor = %+v %v %v", got, ok, err) } } + +// A PAUSE'S STOP LINE ENDS THE TURN THROUGH THE PAUSE'S DOOR. The desktop app's +// Pause writes a stop line from you saying "paused"; a window holding the member +// ends its turn as a pause, which keeps the work for Resume, and not as the +// person's Stop, which would end it and tell its manager so. +func TestTrafficPauseStopEndsTheTurnAsAPause(t *testing.T) { + a, harbor, older, _ := trafficApp(t) + price, _ := trafficHandle(t, a, harbor, "openrouter") + trafficReadNow(t, a) + trafficAppend(t, a, harbor, teamstore.Entry{Kind: teamstore.KindStop, From: teamstore.FromYou, To: price, Text: teamstore.PausedStopText}) + trafficReadNow(t, a) + if older.stops != 1 || older.stopDoor != session.StopByPause { + t.Fatalf("the pause stopped the member %d times through %q, want once through %q", older.stops, older.stopDoor, session.StopByPause) + } +} From c26635700f4673c8b02ce2363aa341cb63be657a Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:43:56 -0500 Subject: [PATCH 34/37] teams: handed-over lines survive a late gate, a stop drops the directive before it A seat or factory gate that closed after the wake was decided threw away lines the boundary had already handed over; they are kept as an ordinary line for the next turn. A manager's stop read in the same look as the directive before it no longer starts a turn on that directive. A note in a conversation with no team seat no longer reads the teams file for a pause. Tests cover these and a pause between a failed command's ending and its wake's clock. Co-Authored-By: Claude Opus 5.5 --- .../unreleased/2897-crew-handoff-outcome.md | 11 +- internal/session/agent.go | 5 +- internal/session/team_wake_gates_test.go | 130 ++++++++++++++++++ internal/session/team_wakewatch.go | 27 +++- 4 files changed, 160 insertions(+), 13 deletions(-) create mode 100644 internal/session/team_wake_gates_test.go diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index fcb419dd3b..0ecd5e443c 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -7,7 +7,7 @@ invalidates: - "team_send answered every directive with \"A member that is idle starts a turn on it now, and a busy one reads it at its next step\" whatever happened. It now waits up to four seconds on the team's traffic and says for each member one of: \"@web started a turn on it.\", \"@web is in a turn and reads it at the next step.\", \"@web did NOT start: .\", \"@web is waiting on the person and reads it once they answer.\", or \"@web has shown no sign of starting yet; team_status says whether it did.\" Where a member did not start, the answer also tells the manager not to tell the person the work is under way." - "A member's pause lived only in the desktop app's own file (app/crews.json, members./.paused) and the engine did not know of it: a directive opened a paused member, started its turn and logged \"woke @x\", and the app then stopped that turn, so the directive was consumed and Resume replayed nothing. The pause is now the team's record (teams.Member.Paused, File.SetPaused). A member paused in any of its teams is not opened or woken by any team's traffic (File.PausedAnywhere), shows as paused in each of its crews, and is resumed from any of them (SetPaused false clears every membership); the directive stays undelivered and starts the member's turn when the person resumes it, including after a restart. A turn something else starts in a paused member (a command's ending, a task landing) is handed none of its teams' traffic and moves no cursor; a turn the person's own words open still reads what waited, and Resume then starts no turn on lines already read. The app carries an earlier build's pause onto the team's record once." - "A directive to a paused member wrote \"woke @x\" then \"stopped\" to the traffic. It now writes one line from system, \"held @x: the person paused it; it starts on this when they resume it\", answering the directive, and Resume writes an event from you with the text \"resumed\" to every open crew the member belongs to, whichever one it was pressed in." - - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A stop by the person of a member that is on its manager's work (a directive, or the brief a started member begins on) now ends \"stopped by the person\" (teams.StoppedByPerson), once per hand-off; it wakes the manager and is delivered as \"@x's turn on what you handed it was stopped by the person before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask.\" The work is under way from the hand-off until a turn finishes, or fails, with no background command left that the member waits on (one whose ending it is owed or asked to be notified of, or a watch that has not fired): a turn such a command's ending starts is still on it, and so is a turn the person opened with their own words while the member waits on one. A stop by the person with none of the manager's work under way, a stop by the manager's team_stop (whichever interface performs it), the desktop app quitting, and the app ending a paused member's stray wake still end \"stopped\" and still wake nobody; the app's two stops now cancel through StopByClosing and StopByWorkStopped, where they used the person's door. The global manager is not woken by either." + - "A member's turn that anybody stopped ended with the event text \"stopped\" (state idle), which neither woke the manager nor was delivered to it. A stop by the person of a member that is on its manager's work (a directive, or the brief a started member begins on) now ends \"stopped by the person\" (teams.StoppedByPerson), once per hand-off; it wakes the manager and is delivered as \"@x's turn on what you handed it was stopped by the person before it finished, so that work is not done. The person chose to stop it: tell them where it stands, and do not hand it out again unless they ask.\" The work is under way from the hand-off until a turn finishes, or fails, with no background command left that the member waits on (one whose ending it is owed or asked to be notified of, or a watch that has not fired): a turn such a command's ending starts is still on it, and so is a turn the person opened with their own words while the member waits on one. A stop by the person with none of the manager's work under way, a stop by the manager's team_stop (whichever interface performs it), the desktop app quitting, the person's Pause, and the app ending a paused member's stray wake still end \"stopped\" and still wake nobody; the app's three stops now cancel through StopByClosing, StopByPause and StopByWorkStopped, where they used the person's door. The global manager is not woken by either." - "team_status and the manager's digest gave a member's state as running, asking, idle or failed only. A member's line may now read \"paused by the person; it starts nothing until they resume it\" or \"on standby; no work handed out yet\", carries the member's role after its handle (\"- @dev, macOS developer\"), and may add \"has not started on #22\" (only for a member that is not in a turn) or \"its last turn was stopped by the person\"." - "Accepting a crew proposal (crews.create from proposal) started every helper at once on its brief. Each helper now joins on standby (teams.Member.Standby, cleared by the member's session once its start line is handed to it): its start line starts no turn, however much later the first directive comes, the traffic says \"opened @x on standby; it starts on its manager's first directive\", and the first directive hands it that line marked \"◆ your standing role from manager (what you are here for, not work to begin; work arrives as a directive)\" in place of \"◆ brief from manager\". team_start and members.start still start a member on its brief at once." - "A proposal's role name was kept only as an app-layer role with no instructions, so it reached neither the member nor the manager. It is now also the team's record (teams.Member.Role, File.SetRole): the member's team note says \"Your role in this team: .\", and the manager's roster shows the role in place of the title (\"@dev (macOS developer)\"). members.role and a role's rename write it too." @@ -28,12 +28,13 @@ invalidates: - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one whose Modelfile sets `num_ctx`, which overrides the server's own setting, so raising that setting cannot help (its `window` is the running window when loaded, else the Modelfile's, and `loaded` is only for a model whose Modelfile sets none); `source` `last_loaded` is one that is not loaded, sets nothing, and was last seen running in `/api/ps` with that `window` (remembered per service address and model for the life of the engine process, not on disk). A model that is not loaded, sets nothing and has not been seen running carries no `small_window`, because the server's default window depends on the machine and the person's setting and no API reports it; there is no `source` `default`. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`; a model whose list lacks `completion` (an embedding model) carries no limits. A server that is absent, refuses or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine; a list that runs out of time repeats each unasked model's limits from the last list that could ask. A turn ending on an Ollama model the server was not running at the last list, or one that list gave a `small_window`, emits `models.changed` once for that turn; a model the server lists as running without a window is not counted as not running, and one still not running at the list after such a notice raises no further notice for that until a list sees it running. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." - - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." + - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines Where the job's refusal or the seat's gate closes only after that decision, once the lines are handed over, they are kept queued as an ordinary line for the next turn instead of being dropped. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." - - "A pause held team traffic only: in a paused member a background command ending, a watch firing, a task landing, and news recorded as a turn ended each started a turn, which the desktop app then stopped where it held the member (appwakes.go) and nothing stopped where it did not. The engine now decides those by cause (wakeStanding and Agent.standingHoldLocked in internal/session/team_wakedecide.go): while a conversation is paused in any of its teams and no turn is running, a command's ending and a watch's firing are written into it as a record ending \"This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened.\" (teamPauseHeldRule), a task landing (a background task's, or the result of a task the conversation divided, Agent.postTaskMessage) is recorded as its quiet receipt with that sentence, keeping its task's identity, and news a turn's end recorded starts no further turn and is followed by that sentence. The next turn reads them: one the person's own words open, which is never held, or the one turn Resume starts (Agent.teamPauseOwedWake), on a directive that waited or, with none, on what the pause held alone, unless a stop since holds it. The person's own words, a question's answer, a decision the person hands over and codeaf continuing a reply it was closed in the middle of still start their turn, and the app's stop of a paused member's stray wake is unchanged." - - "Under the stop hold a background task's landing still started the stopped conversation: only a command's ending and a watch's firing were kept as a record. For a conversation with a role in any team, from a stop of a running turn until a turn next begins, a landing that would start a turn, a background task's (Agent.admitBeltLanding, recordQuietBeltLanding) or the result of a task the conversation divided (Agent.postTaskMessage), is now recorded as its quiet receipt ending \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. The person's own message and the manager's next hand-off still start a turn, which ends the hold and reads the record. A landing in a conversation nobody stopped, and in a conversation in no team, starts its turn as before." - - "A manager's team_stop began the stop hold only for a turn that was running: the member's own session looked for the stop only while a turn ran (teamStopTick), so a member with no window that had started a command, ended its turn and waited was woken by the command's ending and took the stopped work up again. A member's idle watch now reads its manager's stop too and begins the same hold when a command or a watch is still running there (Agent.teamStopWaiting), including in a team whose auto-wake is off, whose log it reads for that only while such a command runs, from a place of its own, so a directive sent meanwhile still wakes the member once the person turns auto-wake on. The command's ending is then kept as a record that starts no turn. Nothing is written to the traffic for it, it is never said as \"stopped by the person\", and the manager is not woken by its own stop." + - "A pause held team traffic only: in a paused member a background command ending, a watch firing, a task landing, and news recorded as a turn ended each started a turn, which the desktop app then stopped where it held the member (appwakes.go) and nothing stopped where it did not. The engine now decides those by cause (wakeStanding and Agent.standingHoldLocked in internal/session/team_wakedecide.go): while a conversation is paused in any of its teams and no turn is running, a command's ending and a watch's firing are written into it as a record ending \"This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened.\" (teamPauseHeldRule), a task landing (a background task's, or the result of a task the conversation divided, Agent.postTaskMessage) is recorded as its quiet receipt with that sentence, keeping its task's identity, and news a turn's end recorded starts no further turn and is followed by that sentence. The next turn reads them: one the person's own words open, which is never held, or the one turn Resume starts (Agent.teamPauseOwedWake), on a directive that waited or, with none, on what the pause held or the work it cut, unless a stop since holds it. The person's own words, a question's answer, a decision the person hands over and codeaf continuing a reply it was closed in the middle of still start their turn, and the app's stop of a paused member's stray wake is unchanged." + - "The desktop app's Pause ended a member's running turn through the person's own Stop (Interrupt), so it was also a stop: it began the stop hold, a command's ending or a watch's firing after it was kept with the stop's words (\"do not take the stopped work up again\"), a member on handed work told its manager \"stopped by the person\" and not to hand the work out again, and Resume started nothing. Pause (members.pause, and its stop line from you with the text \"paused\", teams.Entry.PauseStop, wherever the app or a terminal window reads it back) now ends the turn through a door of its own (session.StopByPause): it begins no stop hold and tells no manager anything, the turn ends \"stopped\", and the conversation's notice reads \"you paused this conversation, so the reply stopped here\". When that turn was on its manager's work (a directive, or the brief it was started on), the work is kept and Resume starts one turn, as it does when the pause held a record; the turn Resume starts opens with \"The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on; anything above that arrived while it was paused is a record of what happened meanwhile.\" (teamPauseResumedRule). A pause of a member waiting on a command for that work holds the command's ending with the pause's words and Resume then starts one turn. A Stop by the person, or a manager's team_stop, of a paused member withdraws that turn and begins the stop hold; through the person's door the manager of handed work is told \"stopped by the person\". The \"stop\" line with the text \"paused\" is written as before." + - "Under the stop hold a background task's landing still started the stopped conversation: only a command's ending and a watch's firing were kept as a record. For a conversation with a role in any team, from a stop of a running turn until a turn next begins, a landing that would start a turn, a background task's (Agent.admitBeltLanding, recordQuietBeltLanding) or the result of a task the conversation divided (Agent.postTaskMessage), is now recorded as its quiet receipt ending \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A program's landing kept this way, or by a pause, says the program's limit once with one notice, and the hold's sentence follows the program's outcome note rather than sitting inside it; a landing that owed the person an answer is read by the next turn as an ordinary turn, without the bounded settle turn its own wake would have had. The person's own message and the manager's next hand-off still start a turn, which ends the hold and reads the record. A landing in a conversation nobody stopped, and in a conversation in no team, starts its turn as before." + - "A manager's team_stop began the stop hold only for a turn that was running: the member's own session looked for the stop only while a turn ran (teamStopTick), so a member with no window that had started a command, ended its turn and waited was woken by the command's ending and took the stopped work up again. A member's idle watch now reads its manager's stop too and begins the same hold when a command or a watch is still running there (Agent.teamStopWaiting), including in a team whose auto-wake is off, whose log it reads for that only while such a command runs, from a place of its own, so a directive sent meanwhile still wakes the member once the person turns auto-wake on. A directive read in the same look before the stop starts no turn; one after it still does. The command's ending is then kept as a record that starts no turn. Nothing is written to the traffic for it, it is never said as \"stopped by the person\", and the manager is not woken by its own stop." --- A manager model reports what its tools tell it. In the measured run a member the diff --git a/internal/session/agent.go b/internal/session/agent.go index f4f4366782..dceab19ca2 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -4459,7 +4459,10 @@ func (a *Agent) enqueueNote(note userMessage) bool { if wakeStanding[note.cause].pause { // The pause this note may be held by is read now, off the lock: it is // the person's word in a file another process writes (team_pause.go). - a.teamPauseFresh() + // Only a conversation with a role in a team can be paused, and every + // other one, a belt landing holding its run's delivery lock among them, + // pays nothing for it. + a.teamPauseFreshSeated() } taken, receipt, why := a.enqueueNoteLocked(note, text) if receipt != nil { diff --git a/internal/session/team_wake_gates_test.go b/internal/session/team_wake_gates_test.go new file mode 100644 index 0000000000..aa9e4019a4 --- /dev/null +++ b/internal/session/team_wake_gates_test.go @@ -0,0 +1,130 @@ +package session + +import ( + "errors" + "path/filepath" + "strings" + "testing" + "time" + + procexec "github.com/Agent-Field/codeaf/internal/executor" + "github.com/Agent-Field/codeaf/internal/teams" +) + +// refusingSeat is a seat that may not work now ([Agent.CheckWork]). +type refusingSeat struct{ procexec.Seat } + +func (refusingSeat) CheckWork() error { return errors.New("this seat is someone else's now") } + +// LINES THE BOUNDARY HANDED OVER ARE NOT DROPPED BY A GATE THAT CLOSED SINCE. +// The watch decided a wake could start, the boundary moved and saved the +// delivery cursor past the directive, and by the time the turn was to start +// the seat could no longer work: the text was thrown away and no turn ever read +// the directive. It is kept as an ordinary line for the next turn, and starts +// nothing now. +func TestTeamWakeWithKeepsTheLinesWhenTheSeatClosedSinceTheDecision(t *testing.T) { + calls := &scriptedCompleter{} + agent, _ := newTestAgent(t, calls, func(config *Config) { config.Seat = refusingSeat{Seat: procexec.Host} }) + d := agent.wakeWith("Your manager started this turn.\n\nFix the header.") + if d.gate != wakeGateSeat { + t.Fatalf("the wake was decided %+v, want the seat's gate", d) + } + agent.mu.Lock() + running, steering := agent.running, append([]userMessage(nil), agent.steering...) + agent.mu.Unlock() + if running || calls.requests() != 0 { + t.Fatal("a seat that may not work started a turn") + } + if len(steering) != 1 || steering[0].wake || !strings.Contains(steering[0].text(), "Fix the header.") { + t.Fatalf("the handed-over lines were not kept for the next turn: %+v", steering) + } +} + +// A MANAGER'S STOP READ IN THE SAME LOOK AS THE DIRECTIVE BEFORE IT STOPS THAT +// DIRECTIVE. The member waited on a command; the manager sent a directive and +// stopped it at once, and one idle look read both: the stop held what the +// member waits on, and then a turn was started on the stopped directive. No +// turn starts now, and a directive after the stop still wakes the member. +func TestTeamManagerStopAfterADirectiveInOneLookStartsNoTurn(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + var web *Agent + started := make(chan *job, 1) + calls := &scriptedCompleter{steps: []step{waitedStep(func() *Agent { return web }, started), okStep(), okStep()}} + web = teamAgent(t, fixture, fixture.web, calls, func(config *Config) { config.teamWatchManual = true }) + collect(t, mustSubmit(t, web, "start the build and wait for it")) + waitQuiet(t, web) + <-started + + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Fix the header."}) + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindStop, From: teams.FromManager, To: "web", Text: "stop"}) + web.teamWatchTick(fixture.profile, time.Now()) + if !web.team.stopHold.held.Load() { + t.Fatal("the member did not hold on its manager's stop") + } + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the member was asked %d times, want only the person's turn: the directive was stopped", got) + } + + appendTraffic(t, fixture, teams.Entry{Kind: teams.KindDirective, From: teams.FromManager, To: "web", Text: "Now the footer."}) + web.teamWatchTick(fixture.profile, time.Now()) + waitRequests(t, calls, 2) + waitQuiet(t, web) + web.settleTeamEvents() +} + +// A CONVERSATION IN NO TEAM PAYS NOTHING FOR THE PAUSE. The pause a command's +// ending might be held by was read afresh for every conversation with a +// profile, a stat of the teams file and a read of it whenever it had moved. +// Only a conversation with a role in a team can be paused. +func TestNoTeamNoteDoesNotReadTheTeamsFile(t *testing.T) { + fixture := newWakingTeamFixture(t) + solo := filepath.Join(t.TempDir(), "solo", "transcript.jsonl") + agent := teamAgent(t, fixture, solo, &scriptedCompleter{}, func(config *Config) { config.teamWatchManual = true }) + if len(agent.teamRoles()) != 0 || agent.team.stopHold.seated.Load() { + t.Fatal("the fixture's conversation has a seat in a team") + } + agent.team.mu.Lock() + before := agent.team.teamsAt + agent.team.mu.Unlock() + if err := teams.Update(fixture.profile, func(file *teams.File) error { + file.Teams = append(file.Teams, teams.Team{ID: teams.NewID(), Name: "elsewhere"}) + return nil + }); err != nil { + t.Fatal(err) + } + // No turn may start and read the file at its own boundary. + agent.mu.Lock() + agent.workStopped = true + agent.mu.Unlock() + agent.enqueueJobNote("job 1 exited 0") + agent.team.mu.Lock() + after := agent.team.teamsAt + agent.team.mu.Unlock() + if after != before { + t.Fatal("a command's ending in a conversation in no team read the teams file") + } +} + +// A PAUSE BETWEEN A FAILED COMMAND'S ENDING AND ITS WAKE'S CLOCK HOLDS THE +// WAKE. The ending was queued before the person paused the member, and the +// clock that would start its turn fired after: the turn is the one the pause is +// there to keep from starting. Resume starts it, and it reads the ending. +func TestTeamPauseBeforeAFailedCommandsWakeFiresHoldsIt(t *testing.T) { + fixture, _, web, calls, clock, started := waitingMember(t, okStep(), okStep()) + web.jobs.settleExit(<-started, 7) + setPaused(t, fixture, fixture.web, true) + clock.advance(jobWakeDelay) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the paused member was asked %d times, want only its first turn", got) + } + + setPaused(t, fixture, fixture.web, false) + waitRequests(t, calls, 2) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, "job 1 exited 7") { + t.Fatalf("the turn Resume started did not read the failed command's ending:\n%s", asked) + } + waitQuiet(t, web) +} diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index 9eebd983de..a63df342a2 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -259,6 +259,11 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { // waits on. One written before this session began is history. if teamManagerStops(role, entry) && !entry.At.Before(a.startedAt) { stopped = true + // WHAT ASKED FOR A TURN BEFORE THE STOP IN THIS LOOK IS WHAT + // IT STOPS. Kept, it started a turn on the very directive the + // manager had just stopped, right after the stop held what + // the member waits on. A directive after the stop still wakes. + waking = waking[:0] } if !role.wakes { continue @@ -766,19 +771,27 @@ func (a *Agent) teamWakeWith(text string) (bool, string) { // ITS CALLER HAS ALREADY DECIDED, AND THIS DECIDES AGAIN. The text is what a // boundary just handed over, read after [Agent.decideWake] said a turn could // start, and the agent's lock was let go in between: a turn may have begun, or -// a gate closed. So the answer here is the one that counts, and what it does -// with text that can no longer start a turn is what every other note gets. A -// turn that began takes it at its next step. A seat that may not work and a -// job that refuses automatic work keep nothing ([Agent.enqueueNote], -// [Agent.wakeAnsweringLocked]), nor does a closed session, whose queue nothing -// drains. Every other gate leaves it queued for the next turn. +// a gate closed. So the answer here is the one that counts. A turn that began +// takes the text at its next step, and every gate but one leaves it queued for +// the next turn. A closed session keeps nothing, since nothing drains its queue. +// +// THE TEXT IS LINES THE BOUNDARY HAS ALREADY HANDED OVER: their cursor has +// moved and been saved, so text dropped here is never read by any turn. A seat +// that may not work and a job that refuses automatic work keep it as an +// ordinary line, not a wake, which is what the boundary of the next turn would +// have handed over had the gate closed before the decision: such a job drops +// automatic work it refuses ([Agent.wakeAnsweringLocked]), not team lines. func (a *Agent) wakeWith(text string) wakeDecision { note := userMessage{message: textMessage("user", strings.TrimSpace(text)), wake: true, authored: true} a.mu.Lock() defer a.mu.Unlock() d := a.decideWakeLocked() switch d.gate { - case wakeGateFactory, wakeGateSeat, wakeGateClosed: + case wakeGateClosed: + return d + case wakeGateFactory, wakeGateSeat: + note.wake = false + a.steering = append(a.steering, note) return d } a.steering = append(a.steering, note) From 2e0131bd128789ab2ad5ed376d5ca111cd2c5d36 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:15:21 -0500 Subject: [PATCH 35/37] app: a Modelfile's window is judged by its own figure, and an unchanged small window asks for one list A model whose Modelfile sets num_ctx is judged by that figure, loaded or not: the engine's requests set no window, so its next turn loads the model with the Modelfile's figure, and a running window may be another client's. The figure is judged clamped to the most the model can hold, as Ollama clamps it, and reported as the Modelfile's own. A small window marks its model for a re-list only when it differs from the one the first list after the last notice read, so turns on an unchanged small window no longer emit models.changed each time. A hosted chat's turn no longer marks local Ollama models. The process's memory of windows and readings keeps at most 512 models each, dropping the oldest. Co-Authored-By: Claude Opus 5.5 --- cmd/codeaf/app.go | 22 ++-- cmd/codeaf/appmodellimits.go | 34 ++++-- cmd/codeaf/appmodellimits_test.go | 55 +++++++-- .../unreleased/2897-crew-handoff-outcome.md | 2 +- docs/design/app-v3/PROTOCOL.md | 36 +++--- internal/appwire/wire.go | 2 +- internal/ollamalimits/ollamalimits.go | 90 ++++++++++----- internal/ollamalimits/ollamalimits_test.go | 106 ++++++++++++++---- 8 files changed, 254 insertions(+), 93 deletions(-) diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 28dbe7eba5..b02b0471d6 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -810,14 +810,16 @@ type appBackend struct { // ollamaRelist is the models of the Ollama service a turn's end should ask // the app to list again (not running, or a small window, at the last list), // ollamaRelisted those a turn has asked that for since, ollamaQuiet those - // whose asked-for list still found them unloaded, and ollamaSeen what this - // app has seen of that service's models, for the lists after + // whose asked-for list still found them unloaded, ollamaToldWindow the + // small window the first list after such a notice read, and ollamaSeen + // what this app has seen of that service's models, for the lists after // ([appBackend.addModelLimits]). - tellModels func() - ollamaRelist map[string]bool - ollamaRelisted map[string]bool - ollamaQuiet map[string]bool - ollamaSeen *ollamalimits.Memory + tellModels func() + ollamaRelist map[string]bool + ollamaRelisted map[string]bool + ollamaQuiet map[string]bool + ollamaToldWindow map[string]int + ollamaSeen *ollamalimits.Memory // state is the app's own file: setup, its settings, budgets and raises. state *appState // dayAuth is the daily limit's one-time hand-over from this file's old cap. @@ -3292,7 +3294,11 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n b.resetCloseAfterReply(id) } live.box.Event(appwire.EventTurnDone, appwire.TurnDone{Agent: id, Turn: turn, OK: ok, Error: failure, ErrorKind: kind, Status: status}) - b.modelLoadedBy(live.conn.Conv.Model()) + // A hosted chat's turn ran on its organisation's server, whose models are + // not this computer's Ollama ones, however alike their names. + if a.hosted == nil { + b.modelLoadedBy(live.conn.Conv.Model()) + } held := false var view appwire.Agent b.locked(func() { diff --git a/cmd/codeaf/appmodellimits.go b/cmd/codeaf/appmodellimits.go index 6ffcf91e3f..dab51ce5cd 100644 --- a/cmd/codeaf/appmodellimits.go +++ b/cmd/codeaf/appmodellimits.go @@ -25,6 +25,13 @@ import ( // last list remembered of it, so a slow answer neither hides a warning for one // list nor loses that request. // +// A SMALL WINDOW THAT STAYS THE SAME IS ASKED ABOUT ONCE. The first list after +// a turn's notice has read the window that turn left the model with, and each +// list costs a question per model to the server and a redraw in the app: so a +// small window is marked again only when it differs from the one that list +// read. A person who raised the setting and restarted Ollama finds the model +// unloaded, or loaded with another window, and either is marked again. +// // A MODEL THE SERVER NEVER KEEPS LOADED IS ASKED ABOUT ONCE. When the list a // turn asked for still finds the model unloaded (a server that unloads it at // once, keep_alive 0), another turn would find the same, and every list costs @@ -50,6 +57,16 @@ func (b *appBackend) addModelLimits(until time.Time, models []appwire.Model, sou } continue } + small := appSmallWindow(reading.Limits) + switch { + case small == 0: + delete(b.ollamaToldWindow, name) + case b.ollamaRelisted[name]: + if b.ollamaToldWindow == nil { + b.ollamaToldWindow = map[string]int{} + } + b.ollamaToldWindow[name] = small + } switch { case reading.Loaded: delete(b.ollamaRelisted, name) @@ -61,7 +78,7 @@ func (b *appBackend) addModelLimits(until time.Time, models []appwire.Model, sou } b.ollamaQuiet[name] = true } - if (reading.Unloaded && !b.ollamaQuiet[name]) || appSmallWindow(reading.Limits) { + if (reading.Unloaded && !b.ollamaQuiet[name]) || (small > 0 && small != b.ollamaToldWindow[name]) { relist[name] = true } } @@ -69,14 +86,14 @@ func (b *appBackend) addModelLimits(until time.Time, models []appwire.Model, sou }) } -// appSmallWindow says whether limits carry a small window. -func appSmallWindow(limits []appwire.ModelLimit) bool { +// appSmallWindow is the small window limits carry, or 0 when they carry none. +func appSmallWindow(limits []appwire.ModelLimit) int { for _, limit := range limits { if limit.Kind == appwire.LimitSmallWindow { - return true + return limit.Window } } - return false + return 0 } // appOllamaLimits fills the limits of the rows an Ollama service serves, and @@ -122,9 +139,10 @@ func appOllamaLimits(ctx context.Context, models []appwire.Model, sources models // modelLoadedBy is called when a turn on model has ended. A turn on an Ollama // model the server was not running at the last list has loaded it, and one on a -// model listed with a small window may have reloaded it with a larger one, so -// the server can now say what it gave the model: the app is told the models -// changed, once, and its next list reads the window the model really has. +// model listed with a small window it was not known to have after an earlier +// notice may have reloaded it with a larger one, so the server can now say what +// it gave the model: the app is told the models changed, once, and its next list +// reads the window the model really has. It is not called for a hosted chat. func (b *appBackend) modelLoadedBy(model string) { if proc := openedEngineProcess(); proc != nil { _, sources := proc.currentAccount() diff --git a/cmd/codeaf/appmodellimits_test.go b/cmd/codeaf/appmodellimits_test.go index 62351424fa..7308c0f6b2 100644 --- a/cmd/codeaf/appmodellimits_test.go +++ b/cmd/codeaf/appmodellimits_test.go @@ -370,7 +370,10 @@ func TestAppATurnOnAnUnloadedOllamaModelBringsItsWindowToTheList(t *testing.T) { // A turn on a model listed with a small window asks for one new list, whether // the model was loaded at that list or not: the person may have raised Ollama's // setting and restarted it, and only a new list reads the window the turn's -// reload gave. One turn asks once, however the model is marked. +// reload gave. One turn asks once, however the model is marked, and once that +// list has read the window, turns on a model whose small window stays the same +// ask for no more: every list costs a question per model to the server and a +// redraw in the app. A window that changes is asked about once again. func TestAppTurnOnASmallWindowModelAsksForOneNewList(t *testing.T) { var mu sync.Mutex window := 4096 @@ -396,22 +399,58 @@ func TestAppTurnOnASmallWindowModelAsksForOneNewList(t *testing.T) { if small := list(); len(small[0].Limits) != 1 || small[0].Limits[0].Source != appwire.WindowLoaded { t.Fatalf("limits = %+v, want the loaded small window", small[0].Limits) } - backend.ollamaLoaded(sources, "ollama/qwen3:8b") - backend.ollamaLoaded(sources, "ollama/qwen3:8b") + turn := func() { backend.ollamaLoaded(sources, "ollama/qwen3:8b") } + setWindow := func(n int) { + mu.Lock() + window = n + mu.Unlock() + } + turn() + turn() if told != 1 { t.Fatalf("turns on a loaded small-window model told the app %d times, want once before a new list", told) } + // The asked-for list and the turns and lists after it: the window is the + // one that list read, so nothing more is asked for. + for i := range 4 { + if same := list(); len(same[0].Limits) != 1 || same[0].Limits[0].Window != 4096 { + t.Fatalf("list %d: limits = %+v, want the same small window", i, same[0].Limits) + } + turn() + } + if told != 1 { + t.Fatalf("turns on an unchanged small window told the app %d times, want once in all", told) + } - mu.Lock() - window = 32768 - mu.Unlock() + setWindow(8192) + if other := list(); len(other[0].Limits) != 1 || other[0].Limits[0].Window != 8192 { + t.Fatalf("limits = %+v, want the other small window", other[0].Limits) + } + turn() + turn() + for range 3 { + list() + turn() + } + if told != 2 { + t.Fatalf("a changed small window told the app %d times in all, want 2", told) + } + + setWindow(32768) if raised := list(); raised[0].Limits != nil { t.Fatalf("limits after the raise = %+v, want none", raised[0].Limits) } - backend.ollamaLoaded(sources, "ollama/qwen3:8b") - if told != 1 { + turn() + if told != 2 { t.Fatalf("a turn on a model loaded with room enough told the app again (%d)", told) } + // Small again later, at the window it once had: that is news again. + setWindow(4096) + list() + turn() + if told != 3 { + t.Fatalf("a window that fell back told the app %d times in all, want 3", told) + } } // A server that never keeps a model loaded (keep_alive 0), or one too old to diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index 0ecd5e443c..a49018e872 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -27,7 +27,7 @@ invalidates: - "A hand-off that joined a live run was told about its own stand: a reference that joined a run working in a copy of the same ground got the read-only receipt and its worker the read-only note. The receipt sentence and the worker's note of a joined hand-off are now decided by the mode of the run it joined (startOrJoinTaskRunVia answers that mode). A hand-off that joined a run which only reads its ground, the home folder apart, is not given the starting task's sentence or \"It joined the work already underway and shares its copy.\": its receipt reads \"It joined the work already underway, which only reads and writes in a folder of its own, so nothing in changes while it is part of that run. To change , propose the work once that run has ended.\" (taskJoinedReadsSentence), whatever files its own proposal named." - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." - - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one whose Modelfile sets `num_ctx`, which overrides the server's own setting, so raising that setting cannot help (its `window` is the running window when loaded, else the Modelfile's, and `loaded` is only for a model whose Modelfile sets none); `source` `last_loaded` is one that is not loaded, sets nothing, and was last seen running in `/api/ps` with that `window` (remembered per service address and model for the life of the engine process, not on disk). A model that is not loaded, sets nothing and has not been seen running carries no `small_window`, because the server's default window depends on the machine and the person's setting and no API reports it; there is no `source` `default`. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`; a model whose list lacks `completion` (an embedding model) carries no limits. A server that is absent, refuses or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine; a list that runs out of time repeats each unasked model's limits from the last list that could ask. A turn ending on an Ollama model the server was not running at the last list, or one that list gave a `small_window`, emits `models.changed` once for that turn; a model the server lists as running without a window is not counted as not running, and one still not running at the list after such a notice raises no further notice for that until a list sees it running. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." + - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one whose Modelfile sets `num_ctx`, which overrides the server's own setting, so raising that setting cannot help: its `window` is the Modelfile's figure whether or not the model is loaded, because the engine's requests set no window and so its next turn loads the model with that figure, while a running window may be another client's (judged clamped to `most`, as the server clamps it; `loaded` is only for a model whose Modelfile sets none); `source` `last_loaded` is one that is not loaded, sets nothing, and was last seen running in `/api/ps` at a list with that `window` (remembered per service address and model for the life of the engine process, not on disk, at most 512 models, the oldest dropped). A model that is not loaded, sets nothing and has not been seen running carries no `small_window`, because the server's default window depends on the machine and the person's setting and no API reports it; there is no `source` `default`. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`; a model whose list lacks `completion` (an embedding model) carries no limits. A server that is absent, refuses or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine; a list that runs out of time repeats each unasked model's limits from the last list that could ask. A turn ending on an Ollama model the server was not running at the last list, or one that list gave a `small_window` of a size other than the one the first list after its last such notice read, emits `models.changed` once for that turn, so an unchanged small window raises one notice and not one per turn, and a hosted chat's turn raises none; a model the server lists as running without a window is not counted as not running, and one still not running at the list after such a notice raises no further notice for that until a list sees it running. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines Where the job's refusal or the seat's gate closes only after that decision, once the lines are handed over, they are kept queued as an ordinary line for the next turn instead of being dropped. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 0e79bbcd7a..25c6be3456 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -2990,15 +2990,20 @@ that is absent, refuses or answers in an unknown shape reports no limit. `needs` is the window the app's prompts ask for, 32000 tokens (the engine's lean threshold). `source` says how `window` is known: `loaded` (the server is running the model with this window and its Modelfile sets no `num_ctx`), `modelfile` -(its Modelfile sets `num_ctx`, which overrides the server's own setting; -`window` is the window it runs with when it is loaded, else the Modelfile's) or -`last_loaded` (not loaded, nothing sets it, and `window` is what the server gave -the model when this engine last saw it running in `GET /api/ps`). A window of -`needs` or more is no limit. A model that is not loaded, sets no `num_ctx` and -has not been seen running has no `small_window`: the server decides its default -window when it loads a model, from the machine's memory or the person's -setting, and its API does not say what that will be. The engine remembers each -model's last window per service address for as long as it runs, not on disk. +(its Modelfile sets `num_ctx`, which overrides the server's own setting and is +what the app's next turn loads the model with, since the engine's requests set +no window; `window` is the Modelfile's figure whether or not the model is +loaded, because a running window may be another client's) or `last_loaded` (not +loaded, nothing sets it, and `window` is what this engine last saw the server +running the model with in `GET /api/ps`, at a list). A window of `needs` or more +is no limit; a Modelfile's figure is judged clamped to `most`, as the server +clamps it, so a Modelfile asking for more than the model can hold still has a +`small_window` when `most` is under `needs`. A model that is not loaded, sets no +`num_ctx` and has not been seen running has no `small_window`: the server +decides its default window when it loads a model, from the machine's memory or +the person's setting, and its API does not say what that will be. The engine +remembers each model's last window per service address for as long as it runs, +not on disk, and at most a few hundred models' windows, dropping the oldest. `most` is the most the model itself can hold, when the server says. A model the server only forwards to another machine has no `small_window`. A server that sends no capability list has no `no_tools`, and a model whose capability list @@ -3008,13 +3013,16 @@ could. Engines before `last_loaded` could send `source` `default` with no `window`; an app reads it as nothing measured and shows no warning for it. When a turn ends on an Ollama model the server was not running at the last -`models.list`, or one that list gave a `small_window`, the engine emits +`models.list`, or one that list gave a `small_window` of a size other than the +one it had when a turn last raised such a notice, the engine emits `models.changed` once for that turn: the turn loaded the model, or may have reloaded it with a larger window after the person raised Ollama's setting, so -the next list reads the window the server really gave it. A model the server -lists as running without a window is not counted as not running, and a model -the list after such a notice still finds not running raises no further notice -for not running until a list sees it running. +the next list reads the window the server really gave it. A small window that +stays the same raises one notice, not one per turn. A model the server lists as +running without a window is not counted as not running, and a model the list +after such a notice still finds not running raises no further notice for not +running until a list sees it running. A turn of a hosted chat, which runs on +its organisation's server, raises none. ## orders methods diff --git a/internal/appwire/wire.go b/internal/appwire/wire.go index d5e8320332..1068329572 100644 --- a/internal/appwire/wire.go +++ b/internal/appwire/wire.go @@ -752,7 +752,7 @@ type ModelLimit struct { Needs int `json:"needs,omitempty"` // Most is the most the model itself can hold, when the server says. Only with small_window. Most int `json:"most,omitempty"` - // Source says how Window is known: "loaded" (the server is running it with this window and its Modelfile sets no num_ctx), "modelfile" (its Modelfile sets num_ctx, which overrides the server's own setting; Window is the running window when it is loaded, else the Modelfile's) or "last_loaded" (not loaded, nothing sets it, and this window is what the server gave it when this engine last saw it running). Only with small_window. Engines before last_loaded could send "default", with no window; an app reads that as nothing measured. + // Source says how Window is known: "loaded" (the server is running it with this window and its Modelfile sets no num_ctx), "modelfile" (its Modelfile sets num_ctx, which overrides the server's own setting and is what the app's next turn loads it with; Window is the Modelfile's figure, loaded or not, and the limit is sent when that figure, clamped to Most, is under Needs) or "last_loaded" (not loaded, nothing sets it, and this window is what this engine last saw the server running it with in /api/ps, at a list). Only with small_window. Engines before last_loaded could send "default", with no window; an app reads that as nothing measured. Source string `json:"source,omitempty" enum:"loaded,modelfile,last_loaded"` } diff --git a/internal/ollamalimits/ollamalimits.go b/internal/ollamalimits/ollamalimits.go index dadad3e0ba..330b7534ab 100644 --- a/internal/ollamalimits/ollamalimits.go +++ b/internal/ollamalimits/ollamalimits.go @@ -76,14 +76,44 @@ func At(address, key string) (Probe, bool) { // model's last reading that a list could finish. // // IT IS KEPT IN MEMORY ONLY, FOR THE LIFE OF THE PROCESS. A remembered window -// is what the server gave the model when it last loaded it, and a restart of +// is what a list last saw the server running the model with, and a restart of // the app is commonly a restart of Ollama too, or comes after its setting was // changed: a figure carried across that from disk would be one nobody has // measured since. Forgetting costs only the warning until the model next loads. +// +// IT IS BOUNDED. The names come from the server, and an odd one that answers +// with ever-changing names would otherwise grow it for the life of the process: +// each table keeps at most remembers entries and drops the one written longest +// ago, which a person's own models, written at every list, never are. type Memory struct { mu sync.Mutex - windows map[string]int - readings map[string]Reading + windows latest[int] + readings latest[Reading] +} + +// remembers is how many models of all servers each table of [Memory] keeps: +// far more than anyone keeps, few enough to cost nothing. +const remembers = 512 + +// latest is a table that keeps the remembers entries written most recently. +type latest[V any] struct { + at map[string]V + order []string +} + +func (l *latest[V]) set(key string, value V) { + if l.at == nil { + l.at = map[string]V{} + } + if _, known := l.at[key]; known { + l.order = slices.DeleteFunc(l.order, func(k string) bool { return k == key }) + } + l.at[key] = value + l.order = append(l.order, key) + for len(l.order) > remembers { + delete(l.at, l.order[0]) + l.order = slices.Delete(l.order, 0, 1) + } } // remembered is the key of one model of one server. @@ -96,11 +126,8 @@ func (m *Memory) sawRunning(base string, running map[string]int) { } m.mu.Lock() defer m.mu.Unlock() - if m.windows == nil { - m.windows = map[string]int{} - } for name, window := range running { - m.windows[remembered(base, name)] = window + m.windows.set(remembered(base, name), window) } } @@ -111,7 +138,7 @@ func (m *Memory) lastWindow(base, name string) int { } m.mu.Lock() defer m.mu.Unlock() - return m.windows[remembered(base, name)] + return m.windows.at[remembered(base, name)] } // keep remembers a reading a list finished, and recall answers it again for a @@ -122,10 +149,7 @@ func (m *Memory) keep(base, name string, reading Reading) { } m.mu.Lock() defer m.mu.Unlock() - if m.readings == nil { - m.readings = map[string]Reading{} - } - m.readings[remembered(base, name)] = reading + m.readings.set(remembered(base, name), reading) } func (m *Memory) recall(base, name string) Reading { @@ -134,7 +158,7 @@ func (m *Memory) recall(base, name string) Reading { } m.mu.Lock() defer m.mu.Unlock() - reading := m.readings[remembered(base, name)] + reading := m.readings.at[remembered(base, name)] reading.Stale = true return reading } @@ -273,29 +297,37 @@ func (p Probe) Read(ctx context.Context, names []string, needs int) map[string]R // (last), either 0 when there is none. Whether the server answered /api/ps at // all is the caller's: without that nobody knows which window counts. // -// A window running now is the figure believed over the Modelfile's, which only -// says what the next load would ask for, and over the last load's. What is -// said of where it comes from follows the server's own order: its setting -// first, then a Modelfile's num_ctx over it. So a model whose Modelfile sets -// num_ctx is said to have its window from the Modelfile whether or not it is -// loaded, because raising the server's setting would not change it; with -// nothing loaded its figure is the Modelfile's, and only a model that sets -// none is read by the window it last ran with. A model with none of the three -// has no window limit. The server decides its default when it loads a model, -// from the machine's memory or a setting the person may have raised, and no -// API says what it is, so a warning without a figure would be a guess. +// The server's own order decides which figure counts: its setting first, then +// a Modelfile's num_ctx over it, then a request's options over both, and a +// request whose options differ from the loaded model's reloads it. So a model +// whose Modelfile sets num_ctx is judged by that figure, loaded or not: it is +// what the app's own next turn loads the model with, because the app's requests +// set no window. A window running now may be another client's, asked for with +// options of its own, and says nothing about the app's next turn on the model. +// The server also clamps a window to the most the model can hold, so the +// Modelfile's figure is judged clamped, though the figure reported is the +// Modelfile's own: the app says what the Modelfile sets, and the most beside it. +// +// A model that sets none is judged by the window it is running with now, and +// when it is not running by the window it last ran with. A model with none of +// these has no window limit. The server decides its default when it loads a +// model, from the machine's memory or a setting the person may have raised, +// and no API says what it is, so a warning without a figure would be a guess. func smallWindow(loaded, last int, model shown, needs int) (appwire.ModelLimit, bool) { limit := appwire.ModelLimit{Kind: appwire.LimitSmallWindow, Needs: needs, Most: model.most} - modelfile := model.asked == answered && !model.remote && model.numCtx > 0 + if model.asked == answered && !model.remote && model.numCtx > 0 { + gets := model.numCtx + if model.most > 0 && model.most < gets { + gets = model.most + } + limit.Window, limit.Source = model.numCtx, appwire.WindowModelfile + return limit, gets < needs + } switch { - case loaded > 0 && modelfile: - limit.Window, limit.Source = loaded, appwire.WindowModelfile case loaded > 0: limit.Window, limit.Source = loaded, appwire.WindowLoaded case model.asked != answered || model.remote: return limit, false - case modelfile: - limit.Window, limit.Source = model.numCtx, appwire.WindowModelfile case last > 0: limit.Window, limit.Source = last, appwire.WindowLastLoaded default: diff --git a/internal/ollamalimits/ollamalimits_test.go b/internal/ollamalimits/ollamalimits_test.go index 8893c3ad54..12a9fdb7de 100644 --- a/internal/ollamalimits/ollamalimits_test.go +++ b/internal/ollamalimits/ollamalimits_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "reflect" + "strconv" "sync" "testing" "time" @@ -104,23 +105,59 @@ const ( plainModel = `{"capabilities":["completion","tools","thinking"],"parameters":"temperature 0.6\nstop \"<|im_end|>\"","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}` ) -// The window the server is running a model with is the figure reported, over -// whatever the Modelfile asks for. Where it comes from follows the server's own -// order: a Modelfile's num_ctx overrides the server's setting, so a loaded -// model whose Modelfile sets one is said to have its window from the Modelfile, -// and only a model that sets none is said to be running with the server's. -func TestALoadedWindowIsBelievedOverTheModelfile(t *testing.T) { +// A model loaded with a window of the server's own setting is said to be +// running with it: only a model whose Modelfile sets no num_ctx is. +func TestALoadedWindowIsTheServersWhenTheModelfileSetsNone(t *testing.T) { stub := &stubServer{ - ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":4096},{"name":"plain:latest","model":"plain:latest","context_length":4096}]}`, + ps: `{"models":[{"name":"plain:latest","model":"plain:latest","context_length":4096}]}`, + show: map[string]string{"plain": plainModel}, + } + got := limitsFrom(t, stub, "plain") + want := map[string][]appwire.ModelLimit{"plain": {{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowLoaded}}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("limits = %+v, want %+v", got, want) + } +} + +// A model whose Modelfile sets num_ctx is judged by that figure, loaded or not: +// the app's requests set no window, so its next turn loads the model with the +// Modelfile's, and a running window that differs is another client's, asked +// for with options of its own. A Modelfile of room enough is no limit however +// small the window the model happens to run with, and a small one is reported +// as the Modelfile's figure however large the window running now. +func TestAModelfileWindowIsJudgedOverARunningOne(t *testing.T) { + stub := &stubServer{ + ps: `{"models":[{"name":"roomy:latest","model":"roomy:latest","context_length":4096},{"name":"tight:latest","model":"tight:latest","context_length":32768}]}`, + show: map[string]string{ + "roomy": `{"capabilities":["completion","tools"],"parameters":"num_ctx 65536","model_info":{"general.architecture":"qwen3","qwen3.context_length":131072}}`, + "tight": `{"capabilities":["completion","tools"],"parameters":"num_ctx 2048","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`, + }, + } + got := limitsFrom(t, stub, "roomy", "tight") + want := map[string][]appwire.ModelLimit{"tight": {{Kind: appwire.LimitSmallWindow, Window: 2048, Needs: needs, Most: 40960, Source: appwire.WindowModelfile}}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("limits = %+v, want %+v", got, want) + } +} + +// The server clamps a window to the most the model can hold. A Modelfile asking +// for more than that is reported with its own figure and the most beside it, +// both true, and judged by what the server gives: a model that holds 8192 has a +// small window whatever its Modelfile asks for, and one asking for more than a +// model that holds enough has none. +func TestAModelfileWindowIsJudgedClampedToTheMost(t *testing.T) { + stub := &stubServer{ + ps: `{"models":[{"name":"short:latest","model":"short:latest","context_length":8192}]}`, show: map[string]string{ - "qwen3:8b": `{"capabilities":["completion","tools"],"parameters":"num_ctx 65536","model_info":{"general.architecture":"qwen3","qwen3.context_length":40960}}`, - "plain": plainModel, + "short": `{"capabilities":["completion","tools"],"parameters":"num_ctx 16384","model_info":{"general.architecture":"llama","llama.context_length":8192}}`, + "greedy": `{"capabilities":["completion","tools"],"parameters":"num_ctx 65536","model_info":{"general.architecture":"llama","llama.context_length":8192}}`, + "ample": `{"capabilities":["completion","tools"],"parameters":"num_ctx 65536","model_info":{"general.architecture":"llama","llama.context_length":40960}}`, }, } - got := limitsFrom(t, stub, "qwen3:8b", "plain") + got := limitsFrom(t, stub, "short", "greedy", "ample") want := map[string][]appwire.ModelLimit{ - "qwen3:8b": {{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowModelfile}}, - "plain": {{Kind: appwire.LimitSmallWindow, Window: 4096, Needs: needs, Most: 40960, Source: appwire.WindowLoaded}}, + "short": {{Kind: appwire.LimitSmallWindow, Window: 16384, Needs: needs, Most: 8192, Source: appwire.WindowModelfile}}, + "greedy": {{Kind: appwire.LimitSmallWindow, Window: 65536, Needs: needs, Most: 8192, Source: appwire.WindowModelfile}}, } if !reflect.DeepEqual(got, want) { t.Fatalf("limits = %+v, want %+v", got, want) @@ -151,18 +188,6 @@ func TestALoadedModelWithASmallModelfileWindowIsTheModelfiles(t *testing.T) { } } -// A model loaded with room enough has no window limit, however small its -// Modelfile's own figure is. -func TestALoadedWindowLargeEnoughReportsNothing(t *testing.T) { - stub := &stubServer{ - ps: `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":32000}]}`, - show: map[string]string{"qwen3:8b": `{"capabilities":["completion","tools"],"parameters":"num_ctx 2048"}`}, - } - if got := limitsFrom(t, stub, "qwen3:8b"); len(got) != 0 { - t.Fatalf("limits = %+v, want none", got) - } -} - // The server names a running model with its tag, and a model listed without // one is the same model. func TestALoadedModelIsFoundWithoutItsTag(t *testing.T) { @@ -520,3 +545,36 @@ func TestTheLimitsTravelUnderTheirWireNames(t *testing.T) { t.Fatalf("wire = %s %v, want %s", data, err, want) } } + +// An odd server answering with ever-changing names cannot grow what this +// process remembers without end: each table keeps the models written most +// recently, and a model seen again is not the oldest however early it was +// first seen. +func TestTheMemoryKeepsOnlyTheLatestModels(t *testing.T) { + seen := &Memory{} + seen.sawRunning("http://a", map[string]int{"mine": 4096}) + seen.keep("http://a", "mine", Reading{Loaded: true}) + for i := range remembers { + name := "odd-" + strconv.Itoa(i) + seen.sawRunning("http://a", map[string]int{name: 2048}) + seen.keep("http://a", name, Reading{Loaded: true}) + if i == remembers/2 { + seen.sawRunning("http://a", map[string]int{"mine": 4096}) + seen.keep("http://a", "mine", Reading{Loaded: true}) + } + } + seen.sawRunning("http://a", map[string]int{"one-more": 2048}) + seen.keep("http://a", "one-more", Reading{Loaded: true}) + if len(seen.windows.at) != remembers || len(seen.windows.order) != remembers || len(seen.readings.at) != remembers || len(seen.readings.order) != remembers { + t.Fatalf("kept %d/%d windows and %d/%d readings, want %d of each", len(seen.windows.at), len(seen.windows.order), len(seen.readings.at), len(seen.readings.order), remembers) + } + if seen.lastWindow("http://a", "odd-1") != 0 || seen.recall("http://a", "odd-1").Loaded { + t.Fatal("the oldest models are still remembered") + } + if seen.lastWindow("http://a", "mine") != 4096 || !seen.recall("http://a", "mine").Loaded { + t.Fatal("a model seen again was dropped as the oldest") + } + if seen.lastWindow("http://a", "one-more") != 2048 || seen.lastWindow("http://a", "odd-2") != 2048 { + t.Fatal("a recent model was dropped") + } +} From 48539018e4821ead24be1cb37e19cf091d5371d6 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:38:07 -0500 Subject: [PATCH 36/37] teams: a pause owes its cut turn, a stop ends what it held, and Pause is bounded A Stop of a paused member now also ends the directives the pause held, so Resume starts nothing on them; one sent after the stop still starts the member. The turn Resume owes keeps to the hour's wake limit and the daily cap and stays owed while they or a gate refuse it. A turn the Pause cut is owed whatever opened it, and what its end drained is read at Resume; a follow-up the person queued is no longer dropped by Pause. Pause carries the Stop's bound through its own door (InterruptWithinFor, Within honoured for the pause door). Lines kept after a late seat or factory refusal drop the wake's lead, which was false when the next turn is the person's. Co-Authored-By: Claude Opus 5.5 --- cmd/codeaf/app_lend.go | 4 + cmd/codeaf/appcrewmembers.go | 18 +- cmd/codeaf/appcrewstops_test.go | 61 +++++ .../unreleased/2897-crew-handoff-outcome.md | 4 +- internal/manual/chat/team-manager.md | 27 +- internal/remote/client.go | 7 + internal/remote/server.go | 16 +- internal/remote/stopbound_test.go | 55 +++++ internal/remote/wire.go | 8 +- internal/session/abandon.go | 24 +- internal/session/abandon_test.go | 57 +++++ internal/session/agent.go | 13 +- internal/session/image.go | 5 +- internal/session/team_pause.go | 86 +++++-- internal/session/team_pause_test.go | 231 ++++++++++++++++++ internal/session/team_stophold.go | 5 +- internal/session/team_wake_gates_test.go | 21 ++ internal/session/team_wakedecide.go | 25 +- internal/session/team_wakewatch.go | 14 +- internal/session/teamwake_note.go | 17 ++ 20 files changed, 640 insertions(+), 58 deletions(-) diff --git a/cmd/codeaf/app_lend.go b/cmd/codeaf/app_lend.go index f2a828309b..ec62a211eb 100644 --- a/cmd/codeaf/app_lend.go +++ b/cmd/codeaf/app_lend.go @@ -180,6 +180,10 @@ func (l lentAgent) InterruptFor(door session.StopDoor) { // that had not ended. The job's own Stop is the door that ends a stage. func (l lentAgent) InterruptWithin(time.Duration) { l.Agent.Interrupt() } +// InterruptWithinFor is [lentAgent.InterruptFor] without the bound, for the +// reason [lentAgent.InterruptWithin] has none. +func (l lentAgent) InterruptWithinFor(door session.StopDoor, _ time.Duration) { l.InterruptFor(door) } + // InterruptNamed is [lentAgent.InterruptFor] with the window the door named. func (l lentAgent) InterruptNamed(door session.StopDoor, name string) { if endsAView(door) { diff --git a/cmd/codeaf/appcrewmembers.go b/cmd/codeaf/appcrewmembers.go index f9fded3e7a..a074788b96 100644 --- a/cmd/codeaf/appcrewmembers.go +++ b/cmd/codeaf/appcrewmembers.go @@ -26,6 +26,7 @@ import ( "fmt" "strings" "sync" + "time" "github.com/Agent-Field/codeaf/internal/appwire" "github.com/Agent-Field/codeaf/internal/guard" @@ -293,11 +294,26 @@ func (b *appBackend) pauseStop(id string) error { } if live := b.liveOf(a); live != nil { b.locked(func() { live.stopping = live.running }) - appInterruptFor(live.conn.Conv, session.StopByPause) + appPauseInterrupt(live.conn.Conv) } return nil } +// appPauseInterrupt ends the turn through the pause's door WITH THE BOUND THE +// PERSON'S STOP CARRIES ([appStopByPerson]): a turn parked on a wait that +// ignores its context stayed "working" after Pause, which has no second key +// either. A conversation that cannot bound a named door is stopped through the +// door unbounded. +func appPauseInterrupt(conv appConversation) { + if bounded, ok := conv.(interface { + InterruptWithinFor(session.StopDoor, time.Duration) + }); ok { + bounded.InterruptWithinFor(session.StopByPause, session.StopGrace) + return + } + appInterruptFor(conv, session.StopByPause) +} + // memberCap is a member's budget: the agent's own spending limit. func (b *appBackend) memberCap(agent string, usd *float64) error { if usd == nil || *usd <= 0 { diff --git a/cmd/codeaf/appcrewstops_test.go b/cmd/codeaf/appcrewstops_test.go index a684ea687e..1b02210d59 100644 --- a/cmd/codeaf/appcrewstops_test.go +++ b/cmd/codeaf/appcrewstops_test.go @@ -6,6 +6,7 @@ import ( "slices" "sync" "testing" + "time" "github.com/Agent-Field/codeaf/internal/appwire" "github.com/Agent-Field/codeaf/internal/session" @@ -34,6 +35,20 @@ func (d *dooredConversation) stops() []session.StopDoor { return slices.Clone(d.doors) } +// boundedDooredConversation is a [dooredConversation] whose stop through a +// named door can carry its bound, as one reached across a connection can. +type boundedDooredConversation struct { + *dooredConversation + graces []time.Duration +} + +func (b *boundedDooredConversation) InterruptWithinFor(door session.StopDoor, grace time.Duration) { + b.InterruptFor(door) + b.doorMu.Lock() + defer b.doorMu.Unlock() + b.graces = append(b.graces, grace) +} + // dooredBackend holds one conversation that records its stops. func dooredBackend(t *testing.T, assembled bool) (*appBackend, *dooredConversation, appwire.Agent) { t.Helper() @@ -261,3 +276,49 @@ func TestAppPauseEndsTheTurnThroughThePausesDoor(t *testing.T) { } only(session.StopByPerson) } + +// A PAUSE CARRIES THE BOUND THE PERSON'S STOP CARRIES. Through an unbounded +// interrupt a turn parked on a wait that ignores its context stayed "working" +// after Pause; the conversation is given the stop's own grace with the pause's +// door. +func TestAppPauseIsBoundedLikeTheStop(t *testing.T) { + state, profile := t.TempDir(), t.TempDir() + conv := &boundedDooredConversation{dooredConversation: &dooredConversation{fakeConversation: &fakeConversation{}}} + backend := newFakeBackend(newAppRecorder(), func(ask appOpenAsk) (*appConn, error) { + return &appConn{Conv: conv, Workspace: ask.Workspace, Transcript: appFakeTranscript, Release: func() {}}, nil + }) + t.Cleanup(func() { backend.Close() }) + backend.state = &appState{path: filepath.Join(state, appStateName)} + backend.profileDir = profile + agent, err := mustCreate(t, backend, appwire.CreateAsk{Workspace: t.TempDir()}) + if err != nil { + t.Fatal(err) + } + crew := teamstore.NewID() + if err := teamstore.Update(backend.profileDir, func(f *teamstore.File) error { + f.Teams = append(f.Teams, teamstore.Team{ID: crew, Name: "crew"}) + lead := filepath.Join(t.TempDir(), "lead", "transcript.jsonl") + if err := f.AddMember(crew, teamstore.Member{Key: lead, File: lead, Handle: "lead"}); err != nil { + return err + } + if err := f.AddMember(crew, teamstore.Member{Key: appFakeTranscript, File: appFakeTranscript, Handle: "scout", Started: true}); err != nil { + return err + } + return f.SetManager(crew, lead) + }); err != nil { + t.Fatal(err) + } + if _, err := backend.Member("pause", appwire.MemberAsk{Crew: crew, Agent: agent.ID}); err != nil { + t.Fatal(err) + } + conv.doorMu.Lock() + defer conv.doorMu.Unlock() + if len(conv.doors) == 0 || len(conv.graces) != len(conv.doors) { + t.Fatalf("the pause stopped through %v with bounds %v, want each stop bounded", conv.doors, conv.graces) + } + for i, door := range conv.doors { + if door != session.StopByPause || conv.graces[i] != session.StopGrace { + t.Fatalf("the pause stopped through %v with bounds %v, want the pause's door with %v", conv.doors, conv.graces, session.StopGrace) + } + } +} diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index a49018e872..ed4bbcc3a2 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -28,11 +28,11 @@ invalidates: - "Over the home folder, the read-only note of a run was appended to the run's brief before its crew was routed (withHomeReadingNote in startOrJoinTaskRunVia), so the brief a crew kept (taskCrew.brief, TaskCrewRecord.Brief) and the text it was routed on carried the note. Over every ground a run only reads, the note is now added only to what the workers are given: the store's root description, RunSpec.Brief, and the brief a deferred run keeps (beltRun.brief, PendingRunRecord.Brief). The crew's kept brief, which `/redo stronger` and a rerun with routing read again as a contract, is the brief as it was handed in." - "The manager's first law ended \"Asked what is happening, answer from the team.\" It now adds \"A task (propose_task) is not a member: use one only for work no member is here for, or when the person asks for a task, and never to get round a member that did not start. When a member did not start, team_send's answer says why: tell the person that.\" The law's earlier sentences are as they were." - "A `models.list` row said nothing about whether its model is fit for the app: an Ollama model's `context_length` is absent, so a model the server runs with 4,096 tokens looked like any other. A row may now carry `limits` (appwire.ModelLimit), facts the desktop app words as a warning. On every `models.list` the engine asks a connected Ollama service's own API (`GET /api/ps` and `POST /api/show`, at the service's address without `/v1`, 300 ms each and 600 ms in all inside the list's three seconds; internal/ollamalimits) and no other provider. `{\"kind\":\"small_window\",\"window\":4096,\"needs\":32000,\"most\":40960,\"source\":\"loaded\"}` is a model the server is running with a window under the lean threshold (session.LeanWindow); `source` `modelfile` is one whose Modelfile sets `num_ctx`, which overrides the server's own setting, so raising that setting cannot help: its `window` is the Modelfile's figure whether or not the model is loaded, because the engine's requests set no window and so its next turn loads the model with that figure, while a running window may be another client's (judged clamped to `most`, as the server clamps it; `loaded` is only for a model whose Modelfile sets none); `source` `last_loaded` is one that is not loaded, sets nothing, and was last seen running in `/api/ps` at a list with that `window` (remembered per service address and model for the life of the engine process, not on disk, at most 512 models, the oldest dropped). A model that is not loaded, sets nothing and has not been seen running carries no `small_window`, because the server's default window depends on the machine and the person's setting and no API reports it; there is no `source` `default`. `{\"kind\":\"no_tools\"}` is a model whose capability list lacks `tools`; a model whose list lacks `completion` (an embedding model) carries no limits. A server that is absent, refuses or answers in an unknown shape reports nothing, as do a server that sends no capability list and a model the server forwards to another machine; a list that runs out of time repeats each unasked model's limits from the last list that could ask. A turn ending on an Ollama model the server was not running at the last list, or one that list gave a `small_window` of a size other than the one the first list after its last such notice read, emits `models.changed` once for that turn, so an unchanged small window raises one notice and not one per turn, and a hosted chat's turn raises none; a model the server lists as running without a window is not counted as not running, and one still not running at the list after such a notice raises no further notice for that until a list sees it running. The engine's own fallback window of 128,000 tokens for such a model, its prompt and its compaction are unchanged." - - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines Where the job's refusal or the seat's gate closes only after that decision, once the lines are handed over, they are kept queued as an ordinary line for the next turn instead of being dropped. The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." + - "The traffic watch handed a directive, or a team's replies, to the conversation before asking whether a turn could start, so a refused wake had already moved the delivery cursor past them. A job refusing automatic work (Config.FactoryWorkRefusal) and a seat that may not work kept nothing, and the directive was never handed to any turn; the other refusals left it queued in memory under \"Your manager started this turn\". The decision is now made before anything is read (decideWake in internal/session/team_wakedecide.go): a refused wake still writes \"could not wake @x: \", moves no cursor, and the lines are handed over by the next turn's own boundary as ordinary team lines. Where the job's refusal or the seat's gate closes only after that decision, once the lines are handed over, they are kept queued as an ordinary line for the next turn instead of being dropped, without the wake's opening \"Your manager started this turn (a directive, or the answer to your question); the person did not speak.\" or a manager's \"Your team's replies started this turn; …\" and the delivery rule after it, since the next turn may be the person's own (teamWakeKept). The reason in that line is now the gate that refused (Agent.wakeRefusalLocked), where two gates refusing at once used to be reported in an order of their own." - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." - "A pause held team traffic only: in a paused member a background command ending, a watch firing, a task landing, and news recorded as a turn ended each started a turn, which the desktop app then stopped where it held the member (appwakes.go) and nothing stopped where it did not. The engine now decides those by cause (wakeStanding and Agent.standingHoldLocked in internal/session/team_wakedecide.go): while a conversation is paused in any of its teams and no turn is running, a command's ending and a watch's firing are written into it as a record ending \"This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened.\" (teamPauseHeldRule), a task landing (a background task's, or the result of a task the conversation divided, Agent.postTaskMessage) is recorded as its quiet receipt with that sentence, keeping its task's identity, and news a turn's end recorded starts no further turn and is followed by that sentence. The next turn reads them: one the person's own words open, which is never held, or the one turn Resume starts (Agent.teamPauseOwedWake), on a directive that waited or, with none, on what the pause held or the work it cut, unless a stop since holds it. The person's own words, a question's answer, a decision the person hands over and codeaf continuing a reply it was closed in the middle of still start their turn, and the app's stop of a paused member's stray wake is unchanged." - - "The desktop app's Pause ended a member's running turn through the person's own Stop (Interrupt), so it was also a stop: it began the stop hold, a command's ending or a watch's firing after it was kept with the stop's words (\"do not take the stopped work up again\"), a member on handed work told its manager \"stopped by the person\" and not to hand the work out again, and Resume started nothing. Pause (members.pause, and its stop line from you with the text \"paused\", teams.Entry.PauseStop, wherever the app or a terminal window reads it back) now ends the turn through a door of its own (session.StopByPause): it begins no stop hold and tells no manager anything, the turn ends \"stopped\", and the conversation's notice reads \"you paused this conversation, so the reply stopped here\". When that turn was on its manager's work (a directive, or the brief it was started on), the work is kept and Resume starts one turn, as it does when the pause held a record; the turn Resume starts opens with \"The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on; anything above that arrived while it was paused is a record of what happened meanwhile.\" (teamPauseResumedRule). A pause of a member waiting on a command for that work holds the command's ending with the pause's words and Resume then starts one turn. A Stop by the person, or a manager's team_stop, of a paused member withdraws that turn and begins the stop hold; through the person's door the manager of handed work is told \"stopped by the person\". The \"stop\" line with the text \"paused\" is written as before." + - "The desktop app's Pause ended a member's running turn through the person's own Stop (Interrupt), so it was also a stop: it began the stop hold, a command's ending or a watch's firing after it was kept with the stop's words (\"do not take the stopped work up again\"), a member on handed work told its manager \"stopped by the person\" and not to hand the work out again, and Resume started nothing. Pause (members.pause, and its stop line from you with the text \"paused\", teams.Entry.PauseStop, wherever the app or a terminal window reads it back) now ends the turn through a door of its own (session.StopByPause): it begins no stop hold and tells no manager anything, the turn ends \"stopped\", and the conversation's notice reads \"you paused this conversation, so the reply stopped here\". Whatever opened that turn (the person's own words, its manager's work, or a directive the pause had held), its work is kept and Resume starts one turn, as it does when the pause held a record, and that turn reads what the cut turn's end wrote into the conversation as it wound down; the turn Resume starts opens with \"The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on; anything above that arrived while it was paused is a record of what happened meanwhile.\" (teamPauseResumedRule). A pause of a member waiting on a command for that work holds the command's ending with the pause's words and Resume then starts one turn. A Stop by the person, or a manager's team_stop, of a paused member withdraws that turn and begins the stop hold, and Resume then starts no turn on a directive the pause held before that stop either (it is read at the member's next turn; one sent after the stop still starts the member at Resume); through the person's door the manager of handed work is told \"stopped by the person\". The turn Resume owes is held by the crew's hourly wake limit and daily cap as a directive's wake is, writing their line once, and stays owed until they allow and the engine's own gates let a turn start; it is kept in memory only, so a restart while paused loses it. Pause is bounded as the person's Stop is: the app sends it with session.StopGrace (InterruptArgs.Within, now honoured for the pause's door and still for no machinery door; Agent.InterruptWithinFor), and a turn that has not let go by then is abandoned and still owed to Resume. A follow-up the person had queued behind the paused turn is no longer dropped: it starts its turn when the cut turn ends, as their words always do, unless that bound had to let the turn go. The \"stop\" line with the text \"paused\" is written as before." - "Under the stop hold a background task's landing still started the stopped conversation: only a command's ending and a watch's firing were kept as a record. For a conversation with a role in any team, from a stop of a running turn until a turn next begins, a landing that would start a turn, a background task's (Agent.admitBeltLanding, recordQuietBeltLanding) or the result of a task the conversation divided (Agent.postTaskMessage), is now recorded as its quiet receipt ending \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A program's landing kept this way, or by a pause, says the program's limit once with one notice, and the hold's sentence follows the program's outcome note rather than sitting inside it; a landing that owed the person an answer is read by the next turn as an ordinary turn, without the bounded settle turn its own wake would have had. The person's own message and the manager's next hand-off still start a turn, which ends the hold and reads the record. A landing in a conversation nobody stopped, and in a conversation in no team, starts its turn as before." - "A manager's team_stop began the stop hold only for a turn that was running: the member's own session looked for the stop only while a turn ran (teamStopTick), so a member with no window that had started a command, ended its turn and waited was woken by the command's ending and took the stopped work up again. A member's idle watch now reads its manager's stop too and begins the same hold when a command or a watch is still running there (Agent.teamStopWaiting), including in a team whose auto-wake is off, whose log it reads for that only while such a command runs, from a place of its own, so a directive sent meanwhile still wakes the member once the person turns auto-wake on. A directive read in the same look before the stop starts no turn; one after it still does. The command's ending is then kept as a record that starts no turn. Nothing is written to the traffic for it, it is never said as \"stopped by the person\", and the manager is not woken by its own stop." --- diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 9b91e30c19..cdf236e9bb 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -664,6 +664,7 @@ leaves the directive unread in the traffic for that turn. You can pause a member of a crew in the desktop app: **Pause** on its row in the Members tab or in the member's menu, and **Resume** to lift it. A pause ends the member's current turn, +bounded as the app's Stop is (a turn that has not let go ten seconds later is let go of), which ends `stopped` and wakes nobody: a pause is not a stop, so the manager is not told `stopped by the person` and the work is kept for Resume. The pause is kept on the team's own record, so the member's session, its manager and every window read the same answer. A @@ -692,19 +693,25 @@ waited starts the member's turn within a second or two, including after codeaf w between. With the team's auto-wake off, a resumed member reads it at its next turn like any other message. -With no directive waiting, Resume starts one turn when the pause ended a turn on the -manager's work or held a record. That turn opens with "The person paused this conversation +With no directive waiting, Resume starts one turn when the pause ended a turn, whatever +started it, or held a record. That turn opens with "The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on; anything above that arrived while it was paused is a record of what happened meanwhile." A member paused while it waited on a command for that work starts again when the command ends, or at -Resume if it ended meanwhile. - -A pause is temporary and a stop is final. **Stop** on a paused member, or a stop before the -pause, ends the work as any stop does: its manager is told `stopped by the person` when the -work was the manager's, and Resume starts nothing. - -Not held: your own words (that turn reads what was waiting, so Resume starts nothing more), -your answer to its question, a decision you hand it, and codeaf continuing a reply it was +Resume if it ended meanwhile. The crew's hourly wake limit and daily cap hold that turn as +they hold a directive, and it starts once they allow. That turn is kept in memory only: if +codeaf is closed while the member is paused, Resume starts only a directive that waited. + +A pause is temporary and a stop is final. **Stop** on a paused member that is in a turn, or +whose pause cut a turn or waits on a command, ends the work as any stop does: its manager is +told `stopped by the person` when the work was the manager's, and Resume starts nothing, not +even on a directive that waited; that directive is read at the member's next turn. A +directive sent after the Stop still starts the member at Resume. A Stop that finds nothing +to end changes nothing about Resume. + +Not held: your own words, including one queued behind the turn Pause ended (that turn reads +what was waiting, so Resume starts nothing more), your answer to its question, a decision you +hand it, and codeaf continuing a reply it was closed in the middle of. An earlier app's pause moves onto the team's record when the updated app first opens. diff --git a/internal/remote/client.go b/internal/remote/client.go index 05e5d0e7ef..62dac59d35 100644 --- a/internal/remote/client.go +++ b/internal/remote/client.go @@ -2171,6 +2171,13 @@ func (a *Agent) InterruptWithinErr(grace time.Duration) error { return err } +// InterruptWithinFor is [Agent.InterruptWithin] through a named door. The +// engine bounds the person's Pause as it bounds their Stop; an engine built +// before that reads the door and stops the turn unbounded. +func (a *Agent) InterruptWithinFor(door session.StopDoor, grace time.Duration) { + _, _ = a.c.call(nil, MethodInterrupt, InterruptArgs{Door: string(door), Within: grace.Milliseconds()}) +} + // AnswerLaneOffer answers the question a stalled PINNED lane raises: the // machine this person named has gone quiet, there is somewhere else to go, and // a pin is asked rather than overridden. The `y` they pressed takes this road diff --git a/internal/remote/server.go b/internal/remote/server.go index de45ac9f8f..4ad9e24595 100644 --- a/internal/remote/server.go +++ b/internal/remote/server.go @@ -136,6 +136,13 @@ type boundedStopper interface { InterruptWithin(grace time.Duration) } +// doorBoundedStopper is a [boundedStopper] whose bounded stop names its door: +// the person's Pause ([session.StopByPause]) is bounded as their Stop is. +// Machinery's stops are never bounded, whatever a surface sends. +type doorBoundedStopper interface { + InterruptWithinFor(door session.StopDoor, grace time.Duration) +} + // Engine is one opened conversation and the doors that replace it. The door // that builds it (cmd/codeaf) owns config resolution, session-file resolution // and the locked-file fallback; this package owns nothing about how an agent is @@ -3122,7 +3129,14 @@ func (s *server) invoke(call Frame) (out json.RawMessage, err error) { if err != nil { return nil, err } - if door := session.StopDoor(strings.TrimSpace(args.Door)); door != "" && door != session.StopByPerson { + door := session.StopDoor(strings.TrimSpace(args.Door)) + // THE PERSON'S PAUSE CARRIES THE SAME BOUND: it is their act from the + // same surface, through a door of its own ([doorBoundedStopper]). + if bounded, ok := agent.(doorBoundedStopper); ok && door == session.StopByPause && args.Within > 0 { + bounded.InterruptWithinFor(door, time.Duration(args.Within)*time.Millisecond) + return nil, nil + } + if door != "" && door != session.StopByPerson { agent.InterruptFor(door) return nil, nil } diff --git a/internal/remote/stopbound_test.go b/internal/remote/stopbound_test.go index efc67dce6c..e47e2b40ef 100644 --- a/internal/remote/stopbound_test.go +++ b/internal/remote/stopbound_test.go @@ -20,6 +20,7 @@ import ( // stage by an optional interface, so a rename on the session's side would // leave every hosted stop unbounded again with these tests still passing. var _ boundedStopper = (*session.Agent)(nil) +var _ doorBoundedStopper = (*session.Agent)(nil) // boundedFakeAgent is a [fakeAgent] whose stop can carry its second stage. type boundedFakeAgent struct { @@ -27,6 +28,7 @@ type boundedFakeAgent struct { mu sync.Mutex graces []time.Duration + doors []session.StopDoor } func (a *boundedFakeAgent) InterruptWithin(grace time.Duration) { @@ -35,6 +37,19 @@ func (a *boundedFakeAgent) InterruptWithin(grace time.Duration) { a.graces = append(a.graces, grace) } +func (a *boundedFakeAgent) InterruptWithinFor(door session.StopDoor, grace time.Duration) { + a.mu.Lock() + defer a.mu.Unlock() + a.doors = append(a.doors, door) + a.graces = append(a.graces, grace) +} + +func (a *boundedFakeAgent) boundDoors() []session.StopDoor { + a.mu.Lock() + defer a.mu.Unlock() + return append([]session.StopDoor(nil), a.doors...) +} + func (a *boundedFakeAgent) bounds() []time.Duration { a.mu.Lock() defer a.mu.Unlock() @@ -114,3 +129,43 @@ func TestTheClientsBoundedStopSendsItsBound(t *testing.T) { t.Fatalf("stop args = %+v", args) } } + +// THE PERSON'S PAUSE CARRIES ITS BOUND ACROSS THE WIRE TOO, through its own +// door: the desktop app's Pause has no second key either. +func TestAPausesBoundedStopReachesTheAgentsSecondStage(t *testing.T) { + plain := &fakeAgent{} + bounded := &boundedFakeAgent{fakeAgent: plain} + engine := engineOn(plain) + engine.Agent = bounded + sess := NewSession(engine, true) + t.Cleanup(func() { _ = sess.Close() }) + l := dialSession(t, sess) + l.hello(Hello{Version: Version}) + + l.ok(1, MethodInterrupt, InterruptArgs{Door: string(session.StopByPause), Within: 2500}) + if got, doors := bounded.bounds(), bounded.boundDoors(); len(got) != 1 || got[0] != 2500*time.Millisecond || len(doors) != 1 || doors[0] != session.StopByPause { + t.Fatalf("the bounded pause armed %v through %v, want one bound of 2.5s through the pause's door", got, doors) + } + plain.mu.Lock() + interrupts := plain.interrupts + plain.mu.Unlock() + if interrupts != 0 { + t.Fatalf("a bounded pause also sent %d plain interrupts", interrupts) + } +} + +func TestTheClientsBoundedPauseSendsItsDoorAndBound(t *testing.T) { + client, e := newEngine(t) + client.Agent().InterruptWithinFor(session.StopByPause, 10*time.Second) + calls := e.calls(MethodInterrupt) + if len(calls) != 1 { + t.Fatalf("the bounded pause travelled %d times", len(calls)) + } + var args InterruptArgs + if err := json.Unmarshal(calls[0].Payload, &args); err != nil { + t.Fatalf("stop payload: %v", err) + } + if args.Door != string(session.StopByPause) || args.Within != 10_000 { + t.Fatalf("pause args = %+v", args) + } +} diff --git a/internal/remote/wire.go b/internal/remote/wire.go index 8e19995f9a..c661cd7205 100644 --- a/internal/remote/wire.go +++ b/internal/remote/wire.go @@ -1615,9 +1615,11 @@ type Moved struct { // // WITHIN IS THE STOP'S BOUND, IN MILLISECONDS, for a surface that cannot keep // the deadline itself: a turn that has not let go by then is abandoned by the -// engine ([session.Agent.InterruptWithin]). Zero is the plain stop every -// surface sent before the field existed, and an engine too old to read it -// stops as it always did, with no second stage: the field can only add one. +// engine ([session.Agent.InterruptWithin]). It is honoured on the person's +// door and on their Pause ([session.StopByPause]), and on no other. Zero is +// the plain stop every surface sent before the field existed, and an engine +// too old to read it stops as it always did, with no second stage: the field +// can only add one. type InterruptArgs struct { Door string `json:"door,omitempty"` Within int64 `json:"within,omitempty"` diff --git a/internal/session/abandon.go b/internal/session/abandon.go index 20432fc89e..6582346d6e 100644 --- a/internal/session/abandon.go +++ b/internal/session/abandon.go @@ -150,19 +150,29 @@ const StopGrace = 10 * time.Second // with no error, and the runner would carry on over work that had not ended. // The person's stop still cuts the turn; the job's own Stop ends the run. A // person's own turn in the same conversation keeps the bound. -func (a *Agent) InterruptWithin(grace time.Duration) { +func (a *Agent) InterruptWithin(grace time.Duration) { a.InterruptWithinFor(StopByPerson, grace) } + +// InterruptWithinFor is [Agent.InterruptWithin] through a named door, for the +// person's Pause ([StopByPause]): it is the person's act too, from the same +// app with no second key, and a turn parked on a wait that ignores its context +// stayed "working" after Pause once the pause had a door of its own. The bound +// arms only for those two doors; machinery's stops are never bounded. A turn +// the pause's bound lets go of is still owed to Resume, as a cut turn that +// ends is ([Agent.teamPauseCutLocked]), since a turn let go of runs none of +// its own ending. +func (a *Agent) InterruptWithinFor(door StopDoor, grace time.Duration) { a.mu.Lock() - if a.running && !a.closed && a.done != nil && !a.runnerTurn && grace > 0 { - a.armAbandonTimerLocked(grace, a.done) + if (door == StopByPerson || door == StopByPause) && a.running && !a.closed && a.done != nil && !a.runnerTurn && grace > 0 { + a.armAbandonTimerLocked(grace, a.done, door) } a.mu.Unlock() - a.Interrupt() + a.interruptNamed(door, "") } // armAbandonTimerLocked schedules the second stage of a stop for the turn // whose `done` channel is turn, with a.mu held. Any timer still standing from // an earlier stop on this turn is replaced. -func (a *Agent) armAbandonTimerLocked(grace time.Duration, turn chan struct{}) { +func (a *Agent) armAbandonTimerLocked(grace time.Duration, turn chan struct{}, door StopDoor) { a.stopAbandonTimerLocked() after := time.AfterFunc if a.abandonAfter != nil { @@ -174,7 +184,9 @@ func (a *Agent) armAbandonTimerLocked(grace time.Duration, turn chan struct{}) { // The timer's goroutine is no tool loop's and no surface's, so nothing // above it would absorb a fault in the journal write below. defer guard.Recover("session bounded stop") - a.abandonTurn(AbandonStopTimeout, turn) + if _, let := a.abandonTurn(AbandonStopTimeout, turn); let && door == StopByPause { + a.team.pauseHold.owed.Store(true) + } }) } diff --git a/internal/session/abandon_test.go b/internal/session/abandon_test.go index a4fae1e564..784fc3c628 100644 --- a/internal/session/abandon_test.go +++ b/internal/session/abandon_test.go @@ -184,6 +184,63 @@ func TestABoundedStopAbandonsATurnThatWouldNotLetGo(t *testing.T) { } } +// THE PERSON'S PAUSE IS BOUNDED AS THEIR STOP IS. Once the pause had a door of +// its own it was the first stage alone, so a turn parked on a wait that ignores +// its context stayed "working" after Pause. The bound lets go of it, the turn +// stays owed to Resume, and a machinery stop through the same call arms nothing. +func TestABoundedPauseAbandonsATurnThatWouldNotLetGo(t *testing.T) { + completer := &scriptedCompleter{steps: []step{ + func(context.Context, []ai.Message) (*ai.Response, error) { + return toolResponse("call-1", "wedge", `{}`), nil + }, + }} + agent, entered, journal := wedged(t, completer) + events, err := agent.Submit(context.Background(), "park on something that cannot be cancelled") + if err != nil { + t.Fatalf("Submit: %v", err) + } + waitUntilClosed(t, "the turn parking on the wedge", entered, 10*time.Second) + + agent.InterruptWithinFor(StopByPause, 50*time.Millisecond) + closed := make(chan struct{}) + go func() { + for range events { + } + close(closed) + }() + waitUntilClosed(t, "the bounded pause letting go of the turn", closed, 10*time.Second) + waitFor(t, "the abandoned line in the journal", func() bool { return len(abandonedLines(t, journal)) > 0 }) + if lines := abandonedLines(t, journal); len(lines) != 1 || lines[0].Reason != string(AbandonStopTimeout) { + t.Fatalf("want one abandoned line saying %q, got %+v", AbandonStopTimeout, lines) + } + waitFor(t, "the let-go turn owed to Resume", agent.team.pauseHold.owed.Load) +} + +func TestABoundedMachineryStopArmsNothing(t *testing.T) { + completer := &scriptedCompleter{steps: []step{ + func(context.Context, []ai.Message) (*ai.Response, error) { + return toolResponse("call-1", "wedge", `{}`), nil + }, + }} + agent, entered, _ := wedged(t, completer) + clock := holdAbandon(agent) + events, err := agent.Submit(context.Background(), "park on something that cannot be cancelled") + if err != nil { + t.Fatalf("Submit: %v", err) + } + waitUntilClosed(t, "the turn parking on the wedge", entered, 10*time.Second) + agent.InterruptWithinFor(StopByLeaving, StopGrace) + clock.mu.Lock() + armed := clock.armed + clock.mu.Unlock() + if armed != 0 { + t.Fatalf("a window leaving armed the bound %d times", armed) + } + agent.Abandon(AbandonStopTimeout) + for range events { + } +} + // controlledAbandon holds the bounded stop's timer in the test's hand: a real // timer is returned so Stop can be observed, and its duration is a day so only // trigger fires the callback. diff --git a/internal/session/agent.go b/internal/session/agent.go index dceab19ca2..3f45d8d1e1 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -2343,6 +2343,7 @@ func (a *Agent) startTurnLocked(ctx context.Context, user userMessage, watcher * // is told as theirs. The cause is still the stop's: the turn's own // cancel(nil) is deferred first, so it runs after this. door, stopped := stopCause(turnCtx) + pauseCut := a.teamPauseCutLocked(door, stopped) a.programOutcomeUnansweredLocked(hub, completed, stopped && door == StopByPerson) // AND THE SECOND LOOK AT A YOUNG COMMAND IS LET GO OF WITH THE TURN // IT WAS ARMED IN. It re-checks this turn's number before it touches @@ -2370,7 +2371,10 @@ func (a *Agent) startTurnLocked(ctx context.Context, user userMessage, watcher * // have the follow-up land behind it, out of the order the person // typed them in. var retired []Question - if next, ok := a.nextFollowUpLocked(completed); ok { + // A PAUSE IS NOT A STOP: a follow-up the person queued is their own + // words, which a pause never holds, so the turn it cut starts it + // (team_pause.go's [Agent.teamPauseCutLocked]). + if next, ok := a.nextFollowUpLocked(completed || pauseCut); ok { // THE PERSON'S QUEUED WORDS ARE THEIR REPLY once their turn // starts, as a sent message's are (said below, after the unlock). retired = a.personClosesQuestionsLocked(next.message) @@ -2663,7 +2667,12 @@ func (a *Agent) interruptNamed(door StopDoor, name string) { cancel := a.cancel waiting, withdrew := a.teamStopHoldLocked(door) cutPass := a.cutManualPassLocked() - a.dropFollowUpsLocked() + // THE PERSON'S PAUSE KEEPS WHAT THEY QUEUED. It is not a stop of their + // words, which a pause never holds: the cut turn's end starts the + // follow-up (team_pause.go's [Agent.teamPauseCutLocked]). + if door != StopByPause { + a.dropFollowUpsLocked() + } // AND THE SECOND LOOK AT A YOUNG COMMAND IS RELEASED BEFORE THIS LOCK IS, // not later by the turn's own cleanup. The cancel below is made with the // lock let go of, so a watch left armed has a real interval in which the diff --git a/internal/session/image.go b/internal/session/image.go index 3e9105289e..4935dabe41 100644 --- a/internal/session/image.go +++ b/internal/session/image.go @@ -511,7 +511,10 @@ func (a *Agent) startVisionTurnLocked(ctx context.Context, kept userMessage, liv a.abandon = nil close(done) var retired []Question - if next, ok := a.nextFollowUpLocked(completed); ok { + // A turn the person's Pause cut is owed to Resume, and a follow-up + // they queued still starts, as for an ordinary turn (agent.go). + pauseCut := a.teamPauseCutLocked(stopCause(turnCtx)) + if next, ok := a.nextFollowUpLocked(completed || pauseCut); ok { // The person's queued words are their reply once their turn // starts, as a sent message's are. retired = a.personClosesQuestionsLocked(next.message) diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index 354b6abe8a..adf0a755ad 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -55,10 +55,11 @@ package session // person's Stop: through that door the pause began the stop hold, so what // arrived next was kept as stopped work, the manager was told the person had // stopped what it handed out, and Resume started nothing. The pause's door -// begins no hold and tells no manager anything; a turn it cuts on handed work -// keeps that work, and Resume starts one turn that carries on with it -// ([Agent.teamPauseCut]). A stop of the paused member still ends the work, and -// withdraws that turn ([Agent.teamStopHoldLocked]). +// begins no hold and tells no manager anything; a turn it cuts keeps its work, +// whatever opened it, and Resume starts one turn that carries on with it +// ([Agent.teamPauseCutLocked]). A stop of the paused member still ends the +// work, and withdraws that turn and the directives the pause held +// ([Agent.teamStopHoldLocked]). // // THE PERSON'S OWN WORDS ARE NOT HELD, as with the daily cap (team_cap.go): a // person typing into a paused member's conversation starts its turn, and that @@ -93,11 +94,19 @@ type teamPauseHold struct { // teams, as of the last time its roles were read. Read without a lock or a // disk. paused atomic.Bool - // owed is set when the pause kept news from starting a turn (a command's - // ending, a watch's firing, a task landing, what a turn's end recorded), - // and cleared when a turn next begins, which reads it. Resume starts that - // turn ([Agent.teamPauseOwedWake]). + // owed is set when the pause cut a turn ([Agent.teamPauseCutLocked]) or + // kept news from starting one (a command's ending, a watch's firing, a + // task landing, what a turn's end recorded), and cleared when a turn next + // begins, which reads it. Resume starts that turn ([Agent.teamPauseOwedWake]). It lives in + // this process alone: a restart while paused loses it, and the records stay + // in the conversation for the next turn. owed atomic.Bool + // stopped is set when a stop's hold begins ([Agent.teamStopHoldLocked]), + // and the watch's next idle look forgets the directives the pause held + // ([teamWatch].pausedHeld): the stop ended that work, so Resume does not + // start a turn on it. A directive the pause holds after the stop is a new + // hand-off and still starts the member at Resume. + stopped atomic.Bool } // teamPauseFreshSeated is [Agent.teamPauseFresh] for a conversation that has a @@ -114,11 +123,30 @@ func (a *Agent) teamPauseFreshSeated() { // reads what the pause kept. func (a *Agent) teamPauseOwedOver() { a.team.pauseHold.owed.Store(false) } -// teamPauseCut is a turn the person's Pause ended ([StopByPause]). Work a -// manager handed this conversation is kept, not ended: the turn Resume starts -// carries on with it, and a stop of the paused member is the stop of that work -// ([Agent.teamStopHoldLocked]). A turn on none of a manager's work owes nothing -// for its own sake. +// teamPauseCutLocked reports whether the turn ending was cut by the person's +// Pause ([StopByPause]), and marks it owed when it was. It is asked where the +// turn ends, under a.mu, before a follow-up the person queued may start. +// +// THE CUT TURN IS OWED WHATEVER OPENED IT, the person's own words, a manager's +// handed work or a directive the pause had held: Resume carries on with the +// work it was on, and reads whatever the cut turn's end drained into the +// conversation (a command's ending, a task's result that arrived while it +// wound down). Only a turn on handed work used to be owed, so the rest stayed +// unread after Resume. A follow-up the person queued is their own words, which +// are never held: it starts its turn here, which reads all of it and so clears +// what this marked ([Agent.startTurnLocked]). +func (a *Agent) teamPauseCutLocked(door StopDoor, stopped bool) bool { + if !stopped || door != StopByPause { + return false + } + a.team.pauseHold.owed.Store(true) + return true +} + +// teamPauseCut keeps the work a manager handed this conversation when the +// person's Pause cut its turn: the work is not ended, the turn Resume starts +// carries on with it ([Agent.teamPauseCutLocked]), and a stop of the paused +// member is the stop of that work ([Agent.teamStopHoldLocked]). func (a *Agent) teamPauseCut(origin turnOrigin) { a.team.mu.Lock() handed := len(a.team.handed) > 0 @@ -130,7 +158,6 @@ func (a *Agent) teamPauseCut(origin turnOrigin) { hold.mu.Lock() hold.origin = origin hold.mu.Unlock() - a.team.pauseHold.owed.Store(true) } // teamPauseOwedWake starts the turn a lifted pause owes the news it held. @@ -141,16 +168,37 @@ func (a *Agent) teamPauseCut(origin turnOrigin) { // command used to stay idle after Resume with the command's ending unread, // unless a directive had also waited. A stop is different: what its hold // keeps starts nothing even later ([teamStopHeldRule]), so a stop since the -// pause leaves the records where they are. The traffic is told nothing: this -// turn is the member's own news, not its team's. -func (a *Agent) teamPauseOwedWake() { +// pause leaves the records where they are. The traffic is told nothing when +// the turn starts: this turn is the member's own news, not its team's. +// +// THE TEAM'S BOUNDS STILL BIND IT. Its boundary hands over a directive the +// pause held, so the hour's limit and the cap that just held that directive's +// wake hold this turn too, and their line is the one the directive's wake +// wrote, said once ([Agent.wakeSayOnce]): a turn started past them delivered +// the directive the traffic had just said could not wake the member. And owed +// is cleared only by the turn beginning ([Agent.startTurnLocked]), so a bound +// or a gate that refuses now leaves it for a later look. +func (a *Agent) teamPauseOwedWake(profile string, roles []teamRole, now time.Time) { hold := &a.team.pauseHold - if !hold.owed.Load() { + if !hold.owed.Load() || hold.paused.Load() || a.team.stopHold.held.Load() { return } + var members []teamRole + for _, role := range roles { + if role.managed && !role.manager && role.handle != "" { + members = append(members, role) + } + } + cause := wakeCause{kind: wakeDirective, roles: members} + for _, rule := range []wakeRule{wakeLimitRule, wakeCapRule} { + if d := rule(a, profile, &cause, now); d.by != heldByNothing { + a.sayWake(profile, cause, d, now) + return + } + } a.mu.Lock() defer a.mu.Unlock() - if a.running || hold.paused.Load() || !hold.owed.Swap(false) || a.team.stopHold.held.Load() { + if a.running || hold.paused.Load() || !hold.owed.Load() || a.team.stopHold.held.Load() { return } if gate, _ := a.wakeRefusalLocked(false, false); gate != wakeGateOpen { diff --git a/internal/session/team_pause_test.go b/internal/session/team_pause_test.go index 53ff23296f..6cecc739c2 100644 --- a/internal/session/team_pause_test.go +++ b/internal/session/team_pause_test.go @@ -1077,3 +1077,234 @@ func TestTeamHeldProgramLandingIsRecordedOnce(t *testing.T) { t.Fatalf("the open surface was sent the limit %d times, want once", notices) } } + +// pauseCutHandedTurn is a member in a turn on its manager's directive, cut by +// the person's Pause the way the app cuts it; later turns take the steps after. +func pauseCutHandedTurn(t *testing.T, after ...step) (teamFixture, *Agent, *scriptedCompleter, *Agent, *scriptedCompleter) { + t.Helper() + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + managerCalls := oneAnswer(8) + manager := teamAgent(t, fixture, fixture.manager, managerCalls, nil) + streaming := make(chan struct{}) + calls := &scriptedCompleter{steps: append([]step{thinkingStep(streaming)}, after...)} + web := teamAgent(t, fixture, fixture.web, calls, nil) + sendDirective(t, manager, "web") + select { + case <-streaming: + case <-time.After(5 * time.Second): + t.Fatal("the member did not start on the directive") + } + pauseLikeTheApp(t, fixture, web) + waitQuiet(t, web) + waitTeamEvents(t, fixture, "stopped", 1) + web.settleTeamEvents() + return fixture, manager, managerCalls, web, calls +} + +// pauseCutPersonsTurn is a member in a turn the person's own words opened, cut +// by Pause; steps is that turn's step and the ones after. +func pauseCutPersonsTurn(t *testing.T, cut chan struct{}, steps ...step) (teamFixture, *Agent, *scriptedCompleter) { + t.Helper() + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + calls := &scriptedCompleter{steps: steps} + web := teamAgent(t, fixture, fixture.web, calls, nil) + events := mustSubmit(t, web, "start the build") + go func() { + for range events { + } + }() + select { + case <-cut: + case <-time.After(5 * time.Second): + t.Fatal("the person's turn did not start") + } + pauseLikeTheApp(t, fixture, web) + waitQuiet(t, web) + waitTeamEvents(t, fixture, "stopped", 1) + web.settleTeamEvents() + return fixture, web, calls +} + +// A STOP OF A PAUSED MEMBER ENDS THE DIRECTIVE THE PAUSE HELD TOO. The member +// was on handed work, the person paused it, the manager sent another directive +// (held), and the person pressed Stop: the manager was told the work was +// stopped and not to hand it out again. Resume used to start the member on the +// held directive anyway, with `woke @web`. It starts nothing now; a directive +// sent after the stop is a new hand-off and starts the member. +func TestTeamStopOfAPausedMemberDropsTheDirectiveThePauseHeld(t *testing.T) { + fixture, manager, managerCalls, web, calls := pauseCutHandedTurn(t, okStep(), okStep()) + sendDirective(t, manager, "web") + waitTeamEvents(t, fixture, teamHeldPausedText("web"), 1) + quietFor() + + web.Interrupt() + waitTeamEvents(t, fixture, teams.StoppedByPerson, 1) + waitManagerToldOfStop(t, managerCalls) + quietFor() + setPaused(t, fixture, fixture.web, false) + quietFor() + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the stopped member was asked %d times after Resume, want only the turn the pause cut", got) + } + if woke := trafficEvents(t, fixture, "woke @web"); len(woke) != 1 { + t.Fatalf("the traffic says the member woke %d times, want only for the first directive", len(woke)) + } + + sendDirective(t, manager, "web") + waitRequests(t, calls, 2) + waitQuiet(t, web) +} + +// THE TURN RESUME OWES KEEPS TO THE HOUR'S LIMIT. A directive waited on the +// paused member; at Resume the hour's limit held its wake and the traffic said +// `could not wake @web`, and in the same look the turn the pause owed started +// anyway and handed the directive over. The owed turn is held by the same +// limit, and stays owed. +func TestTeamResumeOwedTurnKeepsToTheHourLimit(t *testing.T) { + fixture, manager, _, web, calls := pauseCutHandedTurn(t, okStep(), okStep()) + sendDirective(t, manager, "web") + waitTeamEvents(t, fixture, teamHeldPausedText("web"), 1) + quietFor() + web.team.mu.Lock() + for range teamWakesPerHour { + web.team.watch.woken = append(web.team.watch.woken, time.Now()) + } + web.team.mu.Unlock() + + setPaused(t, fixture, fixture.web, false) + waitTeamEvents(t, fixture, teamCouldNotPrefix+"@web", 1) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the member was asked %d times, want only the turn the pause cut: the hour's limit holds", got) + } + if !web.team.pauseHold.owed.Load() { + t.Fatal("the hour's limit spent the turn the pause owes") + } + if said := trafficEvents(t, fixture, teamCouldNotPrefix+"@web"); len(said) != 1 { + t.Fatalf("the limit was said %d times, want once", len(said)) + } +} + +// RESUME CARRIES ON A TURN THE PERSON'S OWN WORDS OPENED. The pause cut it, and +// only a turn on a manager's handed work used to be owed: Resume started +// nothing. It starts one turn now, told why it began. +func TestTeamPauseOfThePersonsOwnTurnResumesIt(t *testing.T) { + cut := make(chan struct{}) + fixture, web, calls := pauseCutPersonsTurn(t, cut, thinkingStep(cut), okStep(), okStep()) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the paused member was asked %d times, want only the turn the pause cut", got) + } + setPaused(t, fixture, fixture.web, false) + waitRequests(t, calls, 2) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, teamPauseResumedRule) { + t.Fatalf("the turn Resume started was not told why it began:\n%s", asked) + } + waitQuiet(t, web) + quietFor() + if got := calls.requests(); got != 2 { + t.Fatalf("Resume started %d turns, want one", got-1) + } +} + +// NEWS THE CUT TURN DRAINS AS IT WINDS DOWN IS READ AT RESUME. A command ended +// while the turn the Pause cut was still running; the turn's end wrote it into +// the conversation with nothing to answer it, and nothing marked it owed, so +// it stayed unread after Resume. The turn Resume starts reads it. +func TestTeamNewsTheCutTurnDrainsIsReadAtResume(t *testing.T) { + cut := make(chan struct{}) + var web *Agent + windDown := func(ctx context.Context, _ []ai.Message) (*ai.Response, error) { + close(cut) + <-ctx.Done() + web.enqueueJobNote("job 8 exited 0") + return nil, ctx.Err() + } + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + calls := &scriptedCompleter{steps: []step{windDown, okStep(), okStep()}} + web = teamAgent(t, fixture, fixture.web, calls, nil) + events := mustSubmit(t, web, "start the build") + go func() { + for range events { + } + }() + <-cut + pauseLikeTheApp(t, fixture, web) + waitQuiet(t, web) + waitTeamEvents(t, fixture, "stopped", 1) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the paused member was asked %d times, want only the turn the pause cut", got) + } + setPaused(t, fixture, fixture.web, false) + waitRequests(t, calls, 2) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, "job 8 exited 0") { + t.Fatalf("the turn Resume started did not read the ending the cut turn drained:\n%s", asked) + } +} + +// A GATE THAT REFUSES AT RESUME DOES NOT SPEND THE OWED TURN. Owed was cleared +// before the gate was asked, so a refusal lost the turn for good. It starts +// once the gate opens. +func TestTeamResumeOwedTurnSurvivesAGateThatRefuses(t *testing.T) { + fixture, _, _, web, calls := pauseCutHandedTurn(t, okStep(), okStep()) + web.mu.Lock() + web.workStopped = true + web.mu.Unlock() + setPaused(t, fixture, fixture.web, false) + quietFor() + if got := calls.requests(); got != 1 { + t.Fatalf("the member was asked %d times while its work was stopped", got) + } + if !web.team.pauseHold.owed.Load() { + t.Fatal("a refusing gate spent the turn the pause owes") + } + web.mu.Lock() + web.workStopped = false + web.mu.Unlock() + waitRequests(t, calls, 2) + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, teamPauseResumedRule) { + t.Fatalf("the owed turn was not told why it began:\n%s", asked) + } +} + +// A PAUSE KEEPS WHAT THE PERSON QUEUED. The pause ran the stop's path, which +// drops every queued follow-up, so the words the person had queued behind the +// running turn were lost. Their words are never held: the follow-up starts its +// own turn when the cut turn ends, and that turn reads what the pause kept, so +// Resume starts nothing more. +func TestTeamPauseKeepsThePersonsQueuedFollowUp(t *testing.T) { + fastTeamWake(t) + fixture := newWakingTeamFixture(t) + streaming := make(chan struct{}) + calls := &scriptedCompleter{steps: []step{thinkingStep(streaming), okStep(), okStep()}} + web := teamAgent(t, fixture, fixture.web, calls, nil) + events := mustSubmit(t, web, "start the build") + go func() { + for range events { + } + }() + <-streaming + queued, err := web.FollowUp("then write it up") + if err != nil { + t.Fatal(err) + } + pauseLikeTheApp(t, fixture, web) + collect(t, queued) + if got := calls.requests(); got != 2 { + t.Fatalf("the model was asked %d times, want the cut turn and the person's follow-up", got) + } + if asked := userTextIn(calls.request(1)); !strings.Contains(asked, "then write it up") { + t.Fatalf("the follow-up's turn did not carry the person's words:\n%s", asked) + } + waitQuiet(t, web) + setPaused(t, fixture, fixture.web, false) + quietFor() + if got := calls.requests(); got != 2 { + t.Fatalf("Resume started a turn on what the follow-up's turn already read: %d calls", got) + } +} diff --git a/internal/session/team_stophold.go b/internal/session/team_stophold.go index 39b1f2b519..2baa4a32ef 100644 --- a/internal/session/team_stophold.go +++ b/internal/session/team_stophold.go @@ -96,13 +96,15 @@ func (a *Agent) teamStopHoldLocked(door StopDoor) (waiting, withdrew bool) { } if a.running { hold.held.Store(true) + a.team.pauseHold.stopped.Store(true) return false, false } // A command that failed moments ago has its wake on a clock, and that turn // would end the hold: the clock is withdrawn and its notes stay queued // for the next turn. So is the turn a pause owes Resume: a pause is // temporary and a stop is final, so the stop of a paused member is the stop - // of the work the pause cut and of what it held ([Agent.teamPauseOwedWake]). + // of the work the pause cut and of what it held ([Agent.teamPauseOwedWake]), + // directives it held among them ([teamPauseHold].stopped). withdrew = a.jobWake != nil if a.team.pauseHold.owed.Swap(false) { withdrew = true @@ -111,6 +113,7 @@ func (a *Agent) teamStopHoldLocked(door StopDoor) (waiting, withdrew bool) { return false, false } a.stopJobWakeLocked() + a.team.pauseHold.stopped.Store(true) return !hold.held.Swap(true), withdrew } diff --git a/internal/session/team_wake_gates_test.go b/internal/session/team_wake_gates_test.go index aa9e4019a4..d0f034cc7c 100644 --- a/internal/session/team_wake_gates_test.go +++ b/internal/session/team_wake_gates_test.go @@ -40,6 +40,27 @@ func TestTeamWakeWithKeepsTheLinesWhenTheSeatClosedSinceTheDecision(t *testing.T } } +// THE KEPT LINES SAY NOTHING THAT IS FALSE OF THE TURN THAT READS THEM. They +// kept the wake's lead, "Your manager started this turn …; the person did not +// speak", and the turn that next read them could be the person's own. They are +// kept as the next turn's boundary would have handed them over. +func TestTeamWakeWithKeepsTheLinesWithoutTheWakesLead(t *testing.T) { + calls := &scriptedCompleter{} + agent, _ := newTestAgent(t, calls, func(config *Config) { config.Seat = refusingSeat{Seat: procexec.Host} }) + agent.wakeWith(teamWakeMemberLead + "\n\nFix the header.") + agent.wakeWith(teamWakeManagerLead + "\n\n" + teamWakeDeliveryRule + "\n\n@web finished.") + agent.mu.Lock() + steering := append([]userMessage(nil), agent.steering...) + agent.mu.Unlock() + if len(steering) != 2 || steering[0].text() != "Fix the header." || steering[1].text() != "@web finished." { + var texts []string + for _, note := range steering { + texts = append(texts, note.text()) + } + t.Fatalf("the kept lines are not the lines alone: %q", texts) + } +} + // A MANAGER'S STOP READ IN THE SAME LOOK AS THE DIRECTIVE BEFORE IT STOPS THAT // DIRECTIVE. The member waited on a command; the manager sent a directive and // stopped it at once, and one idle look read both: the stop held what the diff --git a/internal/session/team_wakedecide.go b/internal/session/team_wakedecide.go index 6e4f5a8422..175d5ae212 100644 --- a/internal/session/team_wakedecide.go +++ b/internal/session/team_wakedecide.go @@ -29,8 +29,10 @@ package session // begins, and the person's pause. They bind the news that arrives through the // session's own queue (a command's ending, a watch's firing, a task landing, // what a turn's end recorded), and are read where that news is queued -// ([wakeStanding], [Agent.standingHoldLocked]). What they hold is kept in the -// conversation as a record that starts no turn, and that record is its line. +// ([wakeStanding], [Agent.standingHoldLocked]). What they hold starts no turn +// and is read by the next one: kept in the conversation as a record, and that +// record is its line, or, for endings already queued when a command's wake +// clock fires, left on the queue that turn drains ([Agent.deferJobWakeLocked]). import ( "fmt" @@ -153,8 +155,9 @@ func init() { // wakeStanding is which of a conversation's standing holds bind which cause. // A standing hold is the agent's own state, read under a.mu where the news is -// queued, and what it holds is kept in the conversation as a record that -// starts no turn: the record is its line, and the traffic is told nothing. +// queued, and what it holds starts no turn: it is kept in the conversation as +// a record, which is its line, or left queued for the next turn when it was +// queued before the hold began, and the traffic is told nothing. // // A STOP HOLDS WHAT THE STOPPED WORK LEFT BEHIND: a command's ending, a watch's // firing and a background task's landing. The person's own words and a @@ -180,12 +183,14 @@ var wakeStanding = map[wakeKind]struct{ stop, pause bool }{ // starting a turn, with the sentence its record is given as why; the zero // decision when none does. The caller holds a.mu. // -// A PAUSE HOLDS NOTHING FROM A TURN IN FLIGHT. The only turn that runs in a -// paused conversation is one the person's own words opened, and news that -// arrives while it runs is that turn's to read at its next step, as anywhere. -// What it leaves unread at its end is asked about again there -// ([Agent.turnEndHeldLocked]). A stop holds through the turn it stopped, which -// is still winding down when a command it left behind ends. +// A PAUSE HOLDS NOTHING FROM A TURN IN FLIGHT. A turn runs in a paused +// conversation when the person's own words opened it, or while the turn the +// Pause cut is still winding down, and news that arrives meanwhile is that +// turn's to read at its next step, as anywhere. What a turn the person opened +// leaves unread at its end is asked about again there +// ([Agent.turnEndHeldLocked]); what the cut turn's end drains is owed the turn +// Resume starts ([Agent.teamPauseCut]). A stop holds through the turn it +// stopped, which is still winding down when a command it left behind ends. func (a *Agent) standingHoldLocked(kind wakeKind) wakeDecision { binds := wakeStanding[kind] if binds.stop && a.team.stopHold.held.Load() { diff --git a/internal/session/team_wakewatch.go b/internal/session/team_wakewatch.go index a63df342a2..1229486669 100644 --- a/internal/session/team_wakewatch.go +++ b/internal/session/team_wakewatch.go @@ -226,6 +226,13 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { return true } a.team.mu.Lock() + // A STOP SINCE THE LAST LOOK ENDED WHAT THE PAUSE HELD. The directives it + // held are the stopped work, so Resume does not start a turn on them; they + // stay on the log for the next turn (team_pause.go). A directive read from + // here on is held afresh. + if a.team.pauseHold.stopped.Swap(false) { + a.team.watch.pausedHeld = nil + } roles := a.team.roles if sharedTeamsStamp(profile) != a.team.teamsAt { roles = a.teamRolesLocked(profile) @@ -317,7 +324,7 @@ func (a *Agent) teamWatchTick(profile string, now time.Time) bool { } // Last, so a directive that waited is what a resumed member starts on, and // news its pause kept is read in that same turn. - a.teamPauseOwedWake() + a.teamPauseOwedWake(profile, roles, now) return true } @@ -780,7 +787,9 @@ func (a *Agent) teamWakeWith(text string) (bool, string) { // that may not work and a job that refuses automatic work keep it as an // ordinary line, not a wake, which is what the boundary of the next turn would // have handed over had the gate closed before the decision: such a job drops -// automatic work it refuses ([Agent.wakeAnsweringLocked]), not team lines. +// automatic work it refuses ([Agent.wakeAnsweringLocked]), not team lines. So +// the line is kept without the lead that says who started the turn, which is +// false when the next turn is the person's ([teamWakeKept]). func (a *Agent) wakeWith(text string) wakeDecision { note := userMessage{message: textMessage("user", strings.TrimSpace(text)), wake: true, authored: true} a.mu.Lock() @@ -791,6 +800,7 @@ func (a *Agent) wakeWith(text string) wakeDecision { return d case wakeGateFactory, wakeGateSeat: note.wake = false + note.message = textMessage("user", teamWakeKept(text)) a.steering = append(a.steering, note) return d } diff --git a/internal/session/teamwake_note.go b/internal/session/teamwake_note.go index 8e44311718..902d62a744 100644 --- a/internal/session/teamwake_note.go +++ b/internal/session/teamwake_note.go @@ -39,3 +39,20 @@ func TeamWakeNote(text string) bool { } return false } + +// teamWakeKept is a wake note kept as an ordinary line when the turn it was to +// start was refused after its lines were handed over ([Agent.wakeWith]). The +// lead that says the manager or the team started the turn is dropped, with the +// delivery rule after a manager's, because the turn that next reads the line +// may be the person's own: what is left is the lines as the next turn's +// boundary would have handed them over. +func teamWakeKept(text string) string { + text = strings.TrimSpace(text) + for _, lead := range []string{teamWakeMemberLead, teamWakeManagerLead} { + if rest, ok := strings.CutPrefix(text, lead); ok { + rest = strings.TrimSpace(rest) + return strings.TrimSpace(strings.TrimPrefix(rest, teamWakeDeliveryRule)) + } + } + return text +} From 3c4653aeb9fa2de3fea3cd6204408abe55622bc4 Mon Sep 17 00:00:00 2001 From: Ara Ghukasyan <329227198+ZeroPoint95@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:51:08 -0500 Subject: [PATCH 37/37] teams: Resume says the cut step did not finish, so the member does it again Told only to carry on, the resumed member read the command the pause had ended as a failure to report and stopped there, twice in the built app. The Resume sentence now says the cut step did not finish and is to be done again before the work is finished. Co-Authored-By: Claude Opus 5.5 --- docs/changes/unreleased/2897-crew-handoff-outcome.md | 2 +- internal/manual/chat/team-manager.md | 6 ++++-- internal/session/team_pause.go | 7 +++++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/changes/unreleased/2897-crew-handoff-outcome.md b/docs/changes/unreleased/2897-crew-handoff-outcome.md index ed4bbcc3a2..dc86ca087a 100644 --- a/docs/changes/unreleased/2897-crew-handoff-outcome.md +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -32,7 +32,7 @@ invalidates: - "A wake that found a turn already running wrote \"woke @x\" or \"woke ◆\" for it, and counted it against the hour's twenty wakes and a manager's ten rounds. It now writes no line and counts as neither: the running turn reads the lines at its next step, the watch looks at them again once that turn has ended, and team_send answers \"@x is in a turn and reads it at the next step.\" for a member whose turn began during its four-second wait." - "A member its manager had just started, whose first turn was held, wrote nothing to the traffic when the hold was its team's daily cap or the person's pause, and at the cap its brief was read off the log and queued without a wake. A first turn is now decided where the traffic watch's wakes are (teamWakeStart and decideWake in internal/session): at the cap the member writes \"held @x: reached its $5 cap today …\", once per conversation and reason; paused, it writes \"held @x: the person paused it; it starts on this when they resume it\" once, answering its start; and a first turn one of the engine's own gates refuses writes \"could not wake @x: \". In each case the brief stays unread on the team's log and is handed over by the member's next turn." - "A pause held team traffic only: in a paused member a background command ending, a watch firing, a task landing, and news recorded as a turn ended each started a turn, which the desktop app then stopped where it held the member (appwakes.go) and nothing stopped where it did not. The engine now decides those by cause (wakeStanding and Agent.standingHoldLocked in internal/session/team_wakedecide.go): while a conversation is paused in any of its teams and no turn is running, a command's ending and a watch's firing are written into it as a record ending \"This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened.\" (teamPauseHeldRule), a task landing (a background task's, or the result of a task the conversation divided, Agent.postTaskMessage) is recorded as its quiet receipt with that sentence, keeping its task's identity, and news a turn's end recorded starts no further turn and is followed by that sentence. The next turn reads them: one the person's own words open, which is never held, or the one turn Resume starts (Agent.teamPauseOwedWake), on a directive that waited or, with none, on what the pause held or the work it cut, unless a stop since holds it. The person's own words, a question's answer, a decision the person hands over and codeaf continuing a reply it was closed in the middle of still start their turn, and the app's stop of a paused member's stray wake is unchanged." - - "The desktop app's Pause ended a member's running turn through the person's own Stop (Interrupt), so it was also a stop: it began the stop hold, a command's ending or a watch's firing after it was kept with the stop's words (\"do not take the stopped work up again\"), a member on handed work told its manager \"stopped by the person\" and not to hand the work out again, and Resume started nothing. Pause (members.pause, and its stop line from you with the text \"paused\", teams.Entry.PauseStop, wherever the app or a terminal window reads it back) now ends the turn through a door of its own (session.StopByPause): it begins no stop hold and tells no manager anything, the turn ends \"stopped\", and the conversation's notice reads \"you paused this conversation, so the reply stopped here\". Whatever opened that turn (the person's own words, its manager's work, or a directive the pause had held), its work is kept and Resume starts one turn, as it does when the pause held a record, and that turn reads what the cut turn's end wrote into the conversation as it wound down; the turn Resume starts opens with \"The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on; anything above that arrived while it was paused is a record of what happened meanwhile.\" (teamPauseResumedRule). A pause of a member waiting on a command for that work holds the command's ending with the pause's words and Resume then starts one turn. A Stop by the person, or a manager's team_stop, of a paused member withdraws that turn and begins the stop hold, and Resume then starts no turn on a directive the pause held before that stop either (it is read at the member's next turn; one sent after the stop still starts the member at Resume); through the person's door the manager of handed work is told \"stopped by the person\". The turn Resume owes is held by the crew's hourly wake limit and daily cap as a directive's wake is, writing their line once, and stays owed until they allow and the engine's own gates let a turn start; it is kept in memory only, so a restart while paused loses it. Pause is bounded as the person's Stop is: the app sends it with session.StopGrace (InterruptArgs.Within, now honoured for the pause's door and still for no machinery door; Agent.InterruptWithinFor), and a turn that has not let go by then is abandoned and still owed to Resume. A follow-up the person had queued behind the paused turn is no longer dropped: it starts its turn when the cut turn ends, as their words always do, unless that bound had to let the turn go. The \"stop\" line with the text \"paused\" is written as before." + - "The desktop app's Pause ended a member's running turn through the person's own Stop (Interrupt), so it was also a stop: it began the stop hold, a command's ending or a watch's firing after it was kept with the stop's words (\"do not take the stopped work up again\"), a member on handed work told its manager \"stopped by the person\" and not to hand the work out again, and Resume started nothing. Pause (members.pause, and its stop line from you with the text \"paused\", teams.Entry.PauseStop, wherever the app or a terminal window reads it back) now ends the turn through a door of its own (session.StopByPause): it begins no stop hold and tells no manager anything, the turn ends \"stopped\", and the conversation's notice reads \"you paused this conversation, so the reply stopped here\". Whatever opened that turn (the person's own words, its manager's work, or a directive the pause had held), its work is kept and Resume starts one turn, as it does when the pause held a record, and that turn reads what the cut turn's end wrote into the conversation as it wound down; the turn Resume starts opens with \"The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on. The pause cut off whatever was in progress (a command it ended did not finish), so do that step again and then finish the work; anything above that arrived while it was paused is a record of what happened meanwhile.\" (teamPauseResumedRule). A pause of a member waiting on a command for that work holds the command's ending with the pause's words and Resume then starts one turn. A Stop by the person, or a manager's team_stop, of a paused member withdraws that turn and begins the stop hold, and Resume then starts no turn on a directive the pause held before that stop either (it is read at the member's next turn; one sent after the stop still starts the member at Resume); through the person's door the manager of handed work is told \"stopped by the person\". The turn Resume owes is held by the crew's hourly wake limit and daily cap as a directive's wake is, writing their line once, and stays owed until they allow and the engine's own gates let a turn start; it is kept in memory only, so a restart while paused loses it. Pause is bounded as the person's Stop is: the app sends it with session.StopGrace (InterruptArgs.Within, now honoured for the pause's door and still for no machinery door; Agent.InterruptWithinFor), and a turn that has not let go by then is abandoned and still owed to Resume. A follow-up the person had queued behind the paused turn is no longer dropped: it starts its turn when the cut turn ends, as their words always do, unless that bound had to let the turn go. The \"stop\" line with the text \"paused\" is written as before." - "Under the stop hold a background task's landing still started the stopped conversation: only a command's ending and a watch's firing were kept as a record. For a conversation with a role in any team, from a stop of a running turn until a turn next begins, a landing that would start a turn, a background task's (Agent.admitBeltLanding, recordQuietBeltLanding) or the result of a task the conversation divided (Agent.postTaskMessage), is now recorded as its quiet receipt ending \"This arrived after this conversation's turn was stopped, so it started no turn. It is a record of what happened: do not take the stopped work up again because of it.\" and starts no turn. A program's landing kept this way, or by a pause, says the program's limit once with one notice, and the hold's sentence follows the program's outcome note rather than sitting inside it; a landing that owed the person an answer is read by the next turn as an ordinary turn, without the bounded settle turn its own wake would have had. The person's own message and the manager's next hand-off still start a turn, which ends the hold and reads the record. A landing in a conversation nobody stopped, and in a conversation in no team, starts its turn as before." - "A manager's team_stop began the stop hold only for a turn that was running: the member's own session looked for the stop only while a turn ran (teamStopTick), so a member with no window that had started a command, ended its turn and waited was woken by the command's ending and took the stopped work up again. A member's idle watch now reads its manager's stop too and begins the same hold when a command or a watch is still running there (Agent.teamStopWaiting), including in a team whose auto-wake is off, whose log it reads for that only while such a command runs, from a place of its own, so a directive sent meanwhile still wakes the member once the person turns auto-wake on. A directive read in the same look before the stop starts no turn; one after it still does. The command's ending is then kept as a record that starts no turn. Nothing is written to the traffic for it, it is never said as \"stopped by the person\", and the manager is not woken by its own stop." --- diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index cdf236e9bb..238b6830b7 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -695,8 +695,10 @@ other message. With no directive waiting, Resume starts one turn when the pause ended a turn, whatever started it, or held a record. That turn opens with "The person paused this conversation -and has now resumed it, which started this turn. Carry on with the work you were on; anything -above that arrived while it was paused is a record of what happened meanwhile." A member +and has now resumed it, which started this turn. Carry on with the work you were on. The pause +cut off whatever was in progress (a command it ended did not finish), so do that step again and +then finish the work; anything above that arrived while it was paused is a record of what +happened meanwhile." A member paused while it waited on a command for that work starts again when the command ends, or at Resume if it ended meanwhile. The crew's hourly wake limit and daily cap hold that turn as they hold a directive, and it starts once they allow. That turn is kept in memory only: if diff --git a/internal/session/team_pause.go b/internal/session/team_pause.go index adf0a755ad..fe886b1280 100644 --- a/internal/session/team_pause.go +++ b/internal/session/team_pause.go @@ -83,8 +83,11 @@ const teamPausedWhy = "the person paused it; it starts on this when they resume const teamPauseHeldRule = "This arrived while the person had this conversation paused, so it started no turn. It is a record of what happened." // teamPauseResumedRule opens the turn Resume starts on what a pause kept: the -// work a pause cut, the news it held, or both ([Agent.teamPauseOwedWake]). -const teamPauseResumedRule = "The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on; anything above that arrived while it was paused is a record of what happened meanwhile." +// work a pause cut, the news it held, or both ([Agent.teamPauseOwedWake]). It +// says the cut step did not finish: told only to carry on, a model read the +// ended command as a failure to report and stopped there (seen in the built app, +// twice), which is not what the person resuming it asked for. +const teamPauseResumedRule = "The person paused this conversation and has now resumed it, which started this turn. Carry on with the work you were on. The pause cut off whatever was in progress (a command it ended did not finish), so do that step again and then finish the work; anything above that arrived while it was paused is a record of what happened meanwhile." // teamPauseHold is one conversation's pause, for the wakes that are decided // under the agent's lock and may read neither the teams file nor the seat's