diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 45ee90f09d..b02b0471d6 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" @@ -690,7 +691,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. @@ -805,6 +806,20 @@ 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; + // 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, 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 + 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. @@ -3279,6 +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}) + // 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() { @@ -4584,12 +4604,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 @@ -4695,7 +4736,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 @@ -5095,7 +5136,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/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/appcrewlayer.go b/cmd/codeaf/appcrewlayer.go index c816cdb419..3c5b6b2b46 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,75 @@ 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, 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) { 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) } } }) - return paused + 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 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 settled { + if m := f.Members[key]; m != nil { + m.Paused = false + } + } + return nil + }) } diff --git a/cmd/codeaf/appcrewmembers.go b/cmd/codeaf/appcrewmembers.go index bc7fa531dc..a074788b96 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 @@ -26,6 +26,7 @@ import ( "fmt" "strings" "sync" + "time" "github.com/Agent-Field/codeaf/internal/appwire" "github.com/Agent-Field/codeaf/internal/guard" @@ -57,11 +58,47 @@ 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. 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, teamstore.PausedStopText) } case "resume": - err = b.layerMember(crew, agent, func(x *appMemberExtra) { x.Paused = false }) + // 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, + })) + } 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 +128,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) @@ -215,11 +264,56 @@ 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 }) + 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 { @@ -240,6 +334,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 } @@ -254,7 +351,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 @@ -322,6 +419,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 appEngineError(err) + } + } + } return b.tellRole(agent, crew, given) } @@ -423,6 +531,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 = "" @@ -461,8 +578,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 +1024,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 +1049,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 +1091,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..0838e1ed12 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,14 @@ 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.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 } @@ -857,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)) { @@ -1020,6 +1035,14 @@ 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. + // 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 @@ -1037,9 +1060,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/appcrewstops_test.go b/cmd/codeaf/appcrewstops_test.go new file mode 100644 index 0000000000..1b02210d59 --- /dev/null +++ b/cmd/codeaf/appcrewstops_test.go @@ -0,0 +1,324 @@ +package main + +import ( + "os" + "path/filepath" + "slices" + "sync" + "testing" + "time" + + "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) +} + +// 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() + 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)) + } +} + +// 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) +} + +// 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/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..dab51ce5cd --- /dev/null +++ b/cmd/codeaf/appmodellimits.go @@ -0,0 +1,177 @@ +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 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 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 +// 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() + var seen *ollamalimits.Memory + b.locked(func() { + if b.ollamaSeen == nil { + b.ollamaSeen = &ollamalimits.Memory{} + } + seen = b.ollamaSeen + }) + readings := appOllamaLimits(ctx, models, sources, nil, seen) + b.locked(func() { + relist := map[string]bool{} + for name, reading := range readings { + if reading.Stale { + if b.ollamaRelist[name] { + relist[name] = true + } + 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) + delete(b.ollamaQuiet, name) + case reading.Unloaded && b.ollamaRelisted[name]: + delete(b.ollamaRelisted, name) + if b.ollamaQuiet == nil { + b.ollamaQuiet = map[string]bool{} + } + b.ollamaQuiet[name] = true + } + if (reading.Unloaded && !b.ollamaQuiet[name]) || (small > 0 && small != b.ollamaToldWindow[name]) { + relist[name] = true + } + } + b.ollamaRelist = relist + }) +} + +// 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 limit.Window + } + } + return 0 +} + +// 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) map[string]ollamalimits.Reading { + 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, probe.Memory = client, seen + 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) + } + readings := probe.Read(ctx, names, session.LeanWindow()) + for name, reading := range readings { + for _, i := range rows[name] { + models[i].Limits = reading.Limits + } + } + 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, and one on a +// 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() + b.ollamaLoaded(sources, model) + } +} + +// 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) + if !strings.EqualFold(owner.Source.ID, ollamalimits.SourceID) { + return + } + var tell func() + b.locked(func() { + if b.ollamaRelist[bare] { + delete(b.ollamaRelist, bare) + if b.ollamaRelisted == nil { + b.ollamaRelisted = map[string]bool{} + } + b.ollamaRelisted[bare] = true + 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..7308c0f6b2 --- /dev/null +++ b/cmd/codeaf/appmodellimits_test.go @@ -0,0 +1,523 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "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" +) + +// 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"}, + } + 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. + 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) + } + } + 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(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]) + 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) + } +} + +// 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 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 { + 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(), 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 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 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++ }, 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) + } + } + 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{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 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}]}` + 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 || !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.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.ollamaRelist["qwen3:8b"] { + t.Fatalf("late: limits %+v, to list again %v", late[0].Limits, backend.ollamaRelist) + } +} + +// 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, 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 { + case "/v1/models": + io.WriteString(w, `{"object":"list","data":[{"id":"qwen3:8b","object":"model","owned_by":"library"}]}`) + case "/api/ps": + mu.Lock() + loaded, size := running, window + mu.Unlock() + if loaded { + fmt.Fprintf(w, `{"models":[{"name":"qwen3:8b","model":"qwen3:8b","context_length":%d}]}`, size) + 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) + } + + 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) + } + + // 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, 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 + 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) + } + 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) + } + + 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) + } + 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 +// 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/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/appproposalaccept_test.go b/cmd/codeaf/appproposalaccept_test.go index 5fcbcd52ad..23677bed9a 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,140 @@ 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 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 + 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/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/cmd/codeaf/appwakes.go b/cmd/codeaf/appwakes.go index 4a932aa9f9..64238ef99f 100644 --- a/cmd/codeaf/appwakes.go +++ b/cmd/codeaf/appwakes.go @@ -20,9 +20,21 @@ 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. + +// 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) { + 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. @@ -159,10 +171,17 @@ func (b *appBackend) wokenTurn(a *appAgent, live *appLive, elsewhere appTurnElse live.msgBase, live.noteBase = msgs, notes }) } - if a.hosted == nil && 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. - live.conn.Conv.Interrupt() + if a.hosted == nil && elsewhere.said == "" && b.crewPaused(id) { + // The person paused this member (a hosted chat runs on the org server and + // is not the app's to stop), 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. 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) } 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 new file mode 100644 index 0000000000..dc86ca087a --- /dev/null +++ b/docs/changes/unreleased/2897-crew-handoff-outcome.md @@ -0,0 +1,55 @@ +--- +kind: changed +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: + - "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, 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." + - "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 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 `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, 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\". 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." +--- + +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. + +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/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 4052a7dcd0..25c6be3456 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -2972,6 +2972,58 @@ 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, refuses or answers in an unknown shape reports no limit. + +| `kind` | sent when | other fields | +|---|---|---| +| `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 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 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 +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`, 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 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 | method | params | result | diff --git a/internal/appwire/model_facts_test.go b/internal/appwire/model_facts_test.go index 3dd8b12393..a73a9e9f5d 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, 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"}) + 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, 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","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) + } + 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), `"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 96d114970e..1068329572 100644 --- a/internal/appwire/wire.go +++ b/internal/appwire/wire.go @@ -723,6 +723,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" + WindowLastLoaded = "last_loaded" +) + +// 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 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 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"` } // FeatureAgentEffortRungs announces the terminal's full conversation effort dial. diff --git a/internal/manual/chat/how-tasks-run.md b/internal/manual/chat/how-tasks-run.md index 68e56eb455..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 @@ -108,6 +110,36 @@ 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 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, +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 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`. + ## 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/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..238b6830b7 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -333,8 +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 somebody stopped it, 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, 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. @@ -344,6 +346,39 @@ 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 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 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 + +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`, with or without a window on +the member) until a turn next begins, the +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, +the command's ending starts no turn, and its manager is told the work it handed out was +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. + +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. + ## 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 @@ -376,9 +411,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 | @@ -390,6 +425,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 @@ -505,6 +545,20 @@ 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. +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 When two or more conversations need incompatible things (the form posts JSON, the endpoint @@ -556,18 +610,28 @@ 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 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. + already ran. Replies arriving within a few seconds are gathered into one turn. The global + 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 that opens it later joins the running conversation. A manager that moved to another window, and 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 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. + ## 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 +655,87 @@ 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 +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 +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: + +- 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 + 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. + +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. 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 +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. + +## 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'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, `@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, +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..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 @@ -149,4 +150,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/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/ollamalimits/ollamalimits.go b/internal/ollamalimits/ollamalimits.go new file mode 100644 index 0000000000..330b7534ab --- /dev/null +++ b/internal/ollamalimits/ollamalimits.go @@ -0,0 +1,470 @@ +// 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. 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 +// 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 +} + +// 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 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 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. +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() + for name, window := range running { + m.windows.set(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.at[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() + m.readings.set(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.at[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 + // 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, Loaded 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 { + // 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. + 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 +} + +// 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 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 + 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, windowless, 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(): + shows[i] = shown{asked: late} + } + }) + } + wait.Wait() + p.Memory.sawRunning(p.base, running) + for i, name := range names { + 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.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 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) + readings[name] = reading + } + return readings +} + +// 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. +// +// 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} + 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: + limit.Window, limit.Source = loaded, appwire.WindowLoaded + case model.asked != answered || model.remote: + return limit, false + case last > 0: + limit.Window, limit.Source = last, appwire.WindowLastLoaded + default: + return limit, false + } + return limit, limit.Window < needs +} + +// 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"` + Model string `json:"model"` + ContextLength int `json:"context_length"` + } `json:"models"` + } + if asked := p.ask(ctx, http.MethodGet, "/api/ps", nil, &answer); asked != answered { + return nil, nil, asked + } + if answer.Models == nil { + return nil, nil, refused + } + 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, + // 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, windowless, answered +} + +// 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 { + return shown{asked: refused} + } + if asked := p.ask(ctx, http.MethodPost, "/api/show", body, &answer); asked != answered { + return shown{asked: asked} + } + return shown{ + asked: answered, + 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 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 refused + } + 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 failed() + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return refused + } + if json.NewDecoder(io.LimitReader(response.Body, answerLimit)).Decode(into) != nil { + return failed() + } + return answered +} + +// 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..12a9fdb7de --- /dev/null +++ b/internal/ollamalimits/ollamalimits_test.go @@ -0,0 +1,580 @@ +package ollamalimits + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strconv" + "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, 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) + 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 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 ( + 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}}` +) + +// 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":"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{ + "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, "short", "greedy", "ample") + want := map[string][]appwire.ModelLimit{ + "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) + } +} + +// 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) + } +} + +// 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 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}} + 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":["completion","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 +// 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"},{"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) + } +} + +// 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) + } +} + +// 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: `{"models":[{"name":"plain:latest","context_length":4096}]}`, 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":["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"} { + 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) + } + } +} + +// 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 := 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) + } +} + +// 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 + } + 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)) + } +} + +// 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 := limitsOf(probe.Read(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.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.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) + } +} + +// 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) + } +} + +// 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") + } +} 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 36066243eb..3f45d8d1e1 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -1446,6 +1446,15 @@ 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 + // 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 @@ -2104,6 +2113,8 @@ func (a *Agent) startTurnLocked(ctx context.Context, user userMessage, watcher * a.rebindClientLocked(a.model) 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 @@ -2281,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 @@ -2329,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 @@ -2356,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) @@ -2366,7 +2384,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 @@ -2647,8 +2665,14 @@ func (a *Agent) interruptNamed(door StopDoor, name string) { a.interrupt.begin() a.mu.Lock() 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 @@ -2664,6 +2688,9 @@ func (a *Agent) interruptNamed(door StopDoor, name string) { if cancel != nil { cancel(stopAs(door, name)) } + if waiting { + a.teamStopHoldSaid(withdrew) + } } // Title is the session's name, empty until it has one (title.go). @@ -3856,7 +3883,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() @@ -4233,13 +4260,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) { - 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) { note := jobNote(text) + note.cause = wakeCommand note.deferJobWake = true a.enqueueNote(note) } @@ -4247,14 +4277,38 @@ 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) { + 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 } if a.running || !a.opened { @@ -4289,6 +4343,7 @@ func (a *Agent) enqueueJobNoteQuiet(text string) { func (a *Agent) enqueueWatchNote(name, text string, fired bool) { if fired { note := wakeNote(text) + note.cause = wakeWatch note.otherResults = true note.attention = true a.enqueueNote(note) @@ -4410,10 +4465,49 @@ 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). + // 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 { + 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 + // (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 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() + 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 { @@ -4442,7 +4536,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 @@ -4769,7 +4863,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 { @@ -4778,23 +4877,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 } @@ -4845,6 +4928,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/hermetic_test.go b/internal/session/hermetic_test.go index fa76b520e3..286278d463 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" @@ -59,6 +60,14 @@ func runTests(m *testing.M) int { fmt.Fprintf(os.Stderr, "session tests: %v\n", err) return 1 } + // 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]). + 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 diff --git a/internal/session/image.go b/internal/session/image.go index 7180988a3d..4935dabe41 100644 --- a/internal/session/image.go +++ b/internal/session/image.go @@ -449,6 +449,8 @@ func (a *Agent) startVisionTurnLocked(ctx context.Context, kept userMessage, liv return refusedStream(err) } a.running = true + a.teamStopHoldOver() + a.teamPauseOwedOver() a.runnerTurn = false hub := a.newReplayHubLocked() a.hub = hub @@ -481,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): @@ -506,14 +511,17 @@ 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) // 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..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 @@ -37,6 +39,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/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. 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.go b/internal/session/task.go index fe850994a5..2af3c05d68 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,12 +1147,26 @@ 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, 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 } @@ -1211,10 +1229,16 @@ 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) + } + // 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 copy of its own. %s", id, on, spec.title, taskHandoffWakeSentence) - return withElsewhere(withReport(withReport(result, taskStandSentence(stand)), stand.redirect), elsewhere) + 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) } // taskStandSentence says WHERE the task works whenever that was read from the @@ -1227,12 +1251,24 @@ 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): + // 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 + // 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 +1277,50 @@ 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 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 + "." +} + +// 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_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..bebd6d252c --- /dev/null +++ b/internal/session/task_reference_test.go @@ -0,0 +1,620 @@ +package session + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "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 +// 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 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) + } + } + 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) + } + 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 := 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 := 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) + } +} + +// 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) + } + } +} + +// 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 !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}, + {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.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") + } 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) +} + +// 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) +} + +// 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.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 09d2f61f6e..ba7df23c20 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,7 +711,9 @@ func (a *Agent) startOrJoinTaskRunVia(ctx context.Context, id uint64, title, bri PlanTask: planStoreID(storeID), }) a.publishJoinedRunRows(g, live) - return 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 @@ -717,10 +722,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 @@ -731,7 +738,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 @@ -798,7 +813,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 @@ -816,7 +831,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 } @@ -839,7 +857,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{}), @@ -855,7 +873,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 @@ -990,8 +1008,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) @@ -2331,6 +2353,9 @@ func (a *Agent) landBeltRun(ctx context.Context, engine RunEngine, run *beltRun) 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 { @@ -2344,6 +2369,37 @@ func (a *Agent) landBeltRun(ctx context.Context, engine RunEngine, run *beltRun) 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. 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{} + } + 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 @@ -2393,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 } @@ -2433,27 +2494,48 @@ 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, 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). 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) { 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, 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) @@ -2829,7 +2911,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/task_run_resolve.go b/internal/session/task_run_resolve.go index eeb2df3ead..dc72d43195 100644 --- a/internal/session/task_run_resolve.go +++ b/internal/session/task_run_resolve.go @@ -94,11 +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 } + if line := referenceLandingLine(tree); line != "" && kept.WorkspaceSet == nil { + 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 != "" { 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/team.go b/internal/session/team.go index e8f5ab06a7..128cef631e 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 + // 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). @@ -152,6 +158,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 @@ -249,6 +264,18 @@ 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 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). + 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 @@ -361,6 +388,8 @@ 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) + a.team.pauseHold.paused.Store(false) return nil } file, err := teamView(profile, keys) @@ -374,6 +403,8 @@ 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) + a.team.pauseHold.paused.Store(pausedRoles(a.team.roles)) return a.team.roles } @@ -435,12 +466,16 @@ func rolesFor(file *teams.File, keys []string, d teams.Defaults) []teamRole { boss: boss, bossName: bossName, root: team.Root, + top: team.Root && topManager(file, member.Key), key: member.Key, wakes: effective.Wake, questionsUp: effective.QuestionsUp, 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 { @@ -457,6 +492,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 } @@ -487,7 +534,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 == "" { @@ -497,7 +549,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 { @@ -689,8 +741,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 "" } @@ -709,6 +762,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] @@ -735,6 +795,11 @@ func (a *Agent) teamNewsLocked(profile string, roles []teamRole) string { } 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. @@ -751,6 +816,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)) @@ -785,10 +852,25 @@ 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 } + // 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 @@ -1237,6 +1319,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")) @@ -1541,7 +1624,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" + @@ -1657,7 +1741,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 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" if t, ok := file.Team(home.Team); ok { @@ -1696,7 +1782,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. 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 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 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 } // teamRoster names the manager's members by handle, with the start of each @@ -1719,7 +1811,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 { @@ -1745,9 +1841,15 @@ func teamMemberRole(role teamRole) string { if role.handle != "" { you = "@" + role.handle } - if role.root { + // 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.", 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 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 { 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.", @@ -1767,6 +1869,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_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 3d76796870..2bf1e7e74d 100644 --- a/internal/session/team_nest_test.go +++ b/internal/session/team_nest_test.go @@ -9,11 +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" ) @@ -520,3 +524,282 @@ 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. 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") + 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) + gm := teamAgent(t, n.fixture, n.paths["gm"], gmCalls, 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, 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() + // 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)) + } + 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) + } + waitRequests(t, gmCalls, 1) + asked := userTextIn(gmCalls.request(0)) + 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) + } + } + 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, 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 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 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") + 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) + 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) + } + since := time.Now() + 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 + } + // 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) + } + } + 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) + 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() + if failed := trafficEvents(t, all, "failed: "); len(failed) != 1 || failed[0].State != teams.StateFailed { + 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 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") + } +} + +// 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 + 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("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_pause.go b/internal/session/team_pause.go new file mode 100644 index 0000000000..fe886b1280 --- /dev/null +++ b/internal/session/team_pause.go @@ -0,0 +1,473 @@ +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 `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. +// +// 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, 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 +// 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 +// the directive is held ([teamHeldPausedText]). The paused member writes +// 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]). +// +// 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 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 +// turn reads what was waiting. + +import ( + "strings" + "sync/atomic" + "time" + + "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. +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." + +// teamPauseResumedRule opens the turn Resume starts on what a pause kept: the +// 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 +// 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 + // 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 +// 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) } + +// 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 + a.team.mu.Unlock() + if !handed { + return + } + hold := &a.team.stopHold + hold.mu.Lock() + hold.origin = origin + hold.mu.Unlock() +} + +// 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 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() || 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.Load() || 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() +} + +// 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 { + 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. +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 + // 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 +} + +// 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 +} + +// 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" +} + +// 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 true + } + for _, entry := range tail { + if entry.Kind == teams.KindEvent && entry.Member == line.Member && entry.Text == line.Text && entry.Answers == line.Answers { + return true + } + } + return false +} + +// 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." + +// 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 + } + 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, paused +} + +// 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{} + } + // 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, +// 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() + 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, 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 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 +// 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 door != StopByPerson || profile == "" || len(handed) == 0 { + return nil + } + var by map[string]bool + for _, role := range a.teamRoles() { + 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 teamManagerStops(role, entry) && !entry.At.Before(since) { + managers = true + } + } + if !managers { + if by == nil { + by = map[string]bool{} + } + by[role.id] = 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 new file mode 100644 index 0000000000..6cecc739c2 --- /dev/null +++ b/internal/session/team_pause_test.go @@ -0,0 +1,1310 @@ +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" +) + +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) + + 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) + } + 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)) + } + // 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) + } + 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 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 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) + 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.Interrupt() + waitRequests(t, managerCalls, 1) + asked := userTextIn(managerCalls.request(0)) + 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 { + 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) + } + } +} + +// 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) + } + } +} + +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) + } +} + +// 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) + 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") + web.enqueueWatchNote("checks", "the checks settled", true) + quietFor() + 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, 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 +// 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) + } +} + +// 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) + } +} + +// 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) + } +} + +// 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_pending.go b/internal/session/team_pending.go index 96287dceea..f490644d68 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) @@ -42,14 +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 { - return true - } - 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_sendoutcome.go b/internal/session/team_sendoutcome.go new file mode 100644 index 0000000000..75aed14c4b --- /dev/null +++ b/internal/session/team_sendoutcome.go @@ -0,0 +1,228 @@ +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, 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. +// +// 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, read under +// teamWatchClockMu like the watch's own clocks ([teamSendWait]). +var ( + teamSendSettle = 4 * time.Second + teamSendLook = 200 * time.Millisecond +) + +// 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 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, asking, 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 { + 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 + } + settle, look := teamSendWait() + deadline := now.Add(settle) + 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(look): + } + } + for _, member := range ready { + if _, still := waiting[member.Key]; still { + 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 + 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(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, 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)) + } + 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, 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 { + _, elsewhere := file.PausedAnywhere(member.Key) + if (member.Paused || elsewhere) && 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" +} + +// teamSendWakesSentence is what a send's answer says comes back on its own. +// 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 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_stophold.go b/internal/session/team_stophold.go new file mode 100644 index 0000000000..2baa4a32ef --- /dev/null +++ b/internal/session/team_stophold.go @@ -0,0 +1,255 @@ +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, 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] +// for a turn, [Agent.teamStopWaiting] for a member with none). +// The command itself is left running, as an interrupt always leaves it. Only +// 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. +// +// 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 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. +// +// 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]) +// 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 ( + "sync" + "sync/atomic" + + "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. +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 the person's stop or a manager's and cleared when a turn + // next begins. + held atomic.Bool + + mu sync.Mutex + // 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 +} + +// 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, 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() { + return false, false + } + 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]), + // directives it held among them ([teamPauseHold].stopped). + withdrew = a.jobWake != nil + if a.team.pauseHold.owed.Swap(false) { + withdrew = true + } + if !withdrew && (a.jobs == nil || !a.jobs.newsPending()) { + return false, false + } + a.stopJobWakeLocked() + a.team.pauseHold.stopped.Store(true) + 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) } + +// 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.mu.Lock() + hold.origin = 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 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, 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. +func (a *Agent) teamStopHoldSaid(withdrew bool) { + if !withdrew && (a.jobs == nil || !a.jobs.awaited()) { + return + } + 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 { + 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 +} + +// 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 +} diff --git a/internal/session/team_stophold_test.go b/internal/session/team_stophold_test.go new file mode 100644 index 0000000000..15332a405a --- /dev/null +++ b/internal/session/team_stophold_test.go @@ -0,0 +1,708 @@ +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" +) + +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 +// 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") + } +} + +// 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) { + fixture, managerCalls, web, calls, clock, started := waitingMember(t, okStep()) + + web.Interrupt() + 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 { + 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)) + } + waitManagerToldOfStop(t, managerCalls) +} + +// 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) { + 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) + } +} + +// 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) +} + +// 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) + } +} + +// 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) + } +} + +// 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_wake.go b/internal/session/team_wake.go index 37ba6495a6..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,37 +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.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 @@ -153,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_gates_test.go b/internal/session/team_wake_gates_test.go new file mode 100644 index 0000000000..d0f034cc7c --- /dev/null +++ b/internal/session/team_wake_gates_test.go @@ -0,0 +1,151 @@ +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) + } +} + +// 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 +// 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_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 new file mode 100644 index 0000000000..175d5ae212 --- /dev/null +++ b/internal/session/team_wakedecide.go @@ -0,0 +1,468 @@ +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. +// +// 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 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" + "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 + // 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 + // 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]). + wakeAnswer +) + +// 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 + // 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. + heldByAutoWakeOff +) + +// 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 + // 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. +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]). +// +// 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 +// pause was meant to keep. A manager is never paused, so its row has no pause; +// 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 +// 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}, + wakeStart: {wakeStandbyRule, wakePauseRule, wakeAutoWakeOffRule, wakeCapRule}, + } +} + +// 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 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 +// 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 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}, + wakeLanding: {stop: true, 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. 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() { + 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{} +} + +// 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. +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} +} + +// 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. +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 { + 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{} +} + +// 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, 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{} +} + +// 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 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 `, +// 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 { + entry, ok := a.wakeLine(c, role, d) + if !ok || (wakeSaidPerEntry(c, 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. +// +// 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 +// 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 == 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 && 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 { + // 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.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. + 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 13cb8d9179..1229486669 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 @@ -132,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 @@ -148,19 +156,36 @@ 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, + // 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 @@ -201,29 +226,72 @@ 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) } 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) + // 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 { - if role.manager && entry.Kind == teams.KindEvent && entry.State == teams.StateFinished && - teamFinishedAfterReply(profile, role.id, entry) { + // 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 + // 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 } // 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 wakes, _ := teamEntryWakes(profile, role, entry, a.teamOwnStart(role, entry)); wakes { waking = append(waking, entry) + a.teamAskedLocked(role, entry) } } - if len(waking) == 0 { + 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). + if a.teamPauseHoldLocked(role, len(waking) > 0) { + continue + } + if len(waking) == 0 && !a.teamPauseReleasedLocked(role) { continue } if role.manager { @@ -243,15 +311,29 @@ 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) } 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(profile, roles, now) 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 @@ -292,9 +374,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 } } @@ -320,6 +400,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() @@ -336,6 +420,7 @@ func (a *Agent) interruptTeamTurn(serial uint64) { return } cancel := a.cancel + a.teamStopHoldLocked(StopByManager) a.dropFollowUpsLocked() a.stopSteerGraceLocked() a.mu.Unlock() @@ -388,8 +473,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 } @@ -397,31 +499,112 @@ 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 } +// 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 +} + +// 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 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) +} + +// 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() { + if m.Key == key { + return true + } + } + 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 // 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 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 @@ -443,10 +626,7 @@ 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 - } + return teamEventWakesManagerOf(role.root, entry.State, entry.Text) } return false } @@ -458,72 +638,105 @@ 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). +// +// 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) { - 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) + cause := wakeCause{kind: wakeDirective, roles: roles} + 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 } - text := teamWakeMemberLead + "\n\n" + news - woke, reason := a.teamWakeWith(text) - if woke { + d := a.wakeWith(teamWakeMemberLead + "\n\n" + news) + 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 { - // 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: "woke @" + 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, - }) - } + 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 { 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.decideWake(profile, &cause, now); d.verdict != wakeStarts { + a.teamWakeDeclined(profile, cause, d, now) return } news := a.teamBoundary() @@ -540,67 +753,62 @@ 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 == wakeStarts { 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: "could not wake ◆: " + 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. +// +// 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. 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. 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() defer a.mu.Unlock() - if a.closed { - return false, "its conversation has closed" + d := a.decideWakeLocked() + switch d.gate { + case wakeGateClosed: + return d + case wakeGateFactory, wakeGateSeat: + note.wake = false + note.message = textMessage("user", teamWakeKept(text)) + a.steering = append(a.steering, note) + return d } a.steering = append(a.steering, note) - if a.running { - return true, "" + if d.verdict == wakeStarts { + a.wakeLocked() } - if a.wakeLocked() { - return true, "" - } - 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 ────────────────────────────────────────────────────────────── @@ -631,60 +839,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: "held " + 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: "could not wake " + 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 @@ -693,26 +856,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 ──────────────────────────────────────────────────────────── @@ -742,6 +896,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+teamStoppedByPersonLine) + } } } return lines @@ -878,7 +1036,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 5e60efcbe6..4dee0bd05d 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" @@ -26,11 +27,17 @@ 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 + // 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 = 3*time.Second, 5*time.Millisecond teamWatchClockMu.Unlock() t.Cleanup(func() { forgetRouses() teamWatchClockMu.Lock() teamWatchEvery, teamWakeSettle, teamRouseRetry, teamRouseRetryMax = every, settle, retry, longest + teamSendSettle, teamSendLook = sendSettle, sendLook teamWatchClockMu.Unlock() }) } @@ -644,9 +651,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 +665,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) @@ -719,3 +730,162 @@ 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)) + } +} + +// 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/session/teamevent.go b/internal/session/teamevent.go index 15388939a7..e7555680cd 100644 --- a/internal/session/teamevent.go +++ b/internal/session/teamevent.go @@ -76,6 +76,12 @@ 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 + // only writes the event in the byPerson teams and no other. + only bool } // eventfulRoles reports whether roles make this conversation one whose events @@ -91,13 +97,30 @@ 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) { + 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}) + lane.queue = append(lane.queue, event) if lane.done == nil { done := make(chan struct{}) lane.done = done @@ -136,6 +159,13 @@ 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 + } // 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 +174,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,8 +184,7 @@ func (a *Agent) writeTeamEvent(event teamEvent) { if err != nil || !role.wakes { continue } - switch event.state { - case teams.StateFinished, teams.StateFailed, teams.StateAsking: + 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)) @@ -204,10 +233,26 @@ func (a *Agent) teamTurnEnded(ctx context.Context, hub *eventHub) { a.dropOwedResume() origin := turnOriginFrom(ctx) if err := hub.turnError(); err != nil { + a.teamHandedCarried(origin) a.teamEventOwed(origin, teams.StateFailed, "failed: "+firstLineTeam(err.Error())) return } - if ctx.Err() != nil { + 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 + } + 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") return } @@ -378,20 +423,34 @@ 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) 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/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/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 +} diff --git a/internal/session/tools_team.go b/internal/session/tools_team.go index e4aad9632e..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. " + + "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 } @@ -503,18 +504,33 @@ 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(file, team, local) + 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 + // 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, + }) } - 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 + 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/session/workspace_ownership.go b/internal/session/workspace_ownership.go index 24d29e62ab..538e9e729a 100644 --- a/internal/session/workspace_ownership.go +++ b/internal/session/workspace_ownership.go @@ -100,12 +100,13 @@ 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 -// their folder as the assigned working directory and read the run's words. -func withHomeReadingNote(place Place, brief string, stand taskStand) string { +// 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 withTaskReadsNote(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") } diff --git a/internal/teams/digest.go b/internal/teams/digest.go index 51b6ec0939..9a326b1810 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" @@ -39,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. @@ -47,6 +55,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 +71,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 +115,67 @@ 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; 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" +) + +// 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 && 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 + } + 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 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)) 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 +186,23 @@ func memberLine(m Member, s MemberState, manager bool) string { if s.ReportsTo != "" && state == StateRunning { state = "busy for " + s.ReportsTo } + resting := state != StateRunning && state != StateAsking && !strings.HasPrefix(state, "busy for ") + quiet := state == StateIdle || state == "unknown" + switch { + case manager: + case (m.Paused || s.Paused) && quiet: + state = DigestPaused + case m.Paused || s.Paused: + state += ", " + DigestPaused + case m.Standby && quiet: + state = DigestStandby + } b.WriteString(": " + state) + // 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 { 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..9aaa445797 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,161 @@ 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"}, + {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{ + {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}, + // 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}, + // 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 + `, 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) + } + } + // 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 whose standby is over 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) + } +} + +// 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") + } +} + +// 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") + } +} 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/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 65e80921df..b18f05835d 100644 --- a/internal/teams/teams.go +++ b/internal/teams/teams.go @@ -75,6 +75,24 @@ 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 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 } @@ -574,6 +592,16 @@ 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, 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].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 { // Explicitly assigning the optional global role reconnects its current @@ -627,6 +655,94 @@ 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) + } + 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 +} + +// 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 { + 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 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) + } +}