Compare commits

..
Author SHA1 Message Date
weichen 6d76111a16 Add leader progress ledger, replan cap, and mailbox with actor attribution (Q2 WP2)
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: Q2 acceptance requires leader runs to detect stuck delegation loops and
cap replans instead of spinning to the turn limit, and a mailbox primitive
whose messages can never resolve a pending permission approval (acceptance 3).

Evidence: squad conformance tests (leader_mailbox_conformance_test.go):
ledger stuck->replan, replan cap finalize, mailbox delivery after hold,
mailbox-cannot-approve-permission (structural + actor second defense),
post guards; full suite green with -race.

Impact: LeaderState gains Progress/StuckTurns/Replans/MaxReplans/ReplanNote
(persisted in leader.json); RunState gains Mailbox (persisted in
runstate.json); RespondDecision gains Actor - non-human actors are rejected
on choice gates; step briefs and leader task briefs include pending mail.

Refs: Q2 plan WP2 (2026-10-07-agent-stack-q2q3-plans.md); task card
.task/feature-agent-stack-q2.md
2026-10-08 00:34:46 +00:00
weichen 8103b8da35 Merge pull request 'Add the topology surface with loop, router, and deadline mechanics (Q2 WP1)' (#42) from feature/q2-topology-wp1 into main
ci / vet-and-test (push) Successful in 25s
ci / docker-checkout-hostgateway (push) Successful in 1s
Add the topology surface with loop, router, and deadline mechanics (Q2 WP1)
2026-10-08 00:05:06 +00:00
weichen f3a67ced9c Add the topology surface with loop, router, and deadline mechanics (Q2 WP1)
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: the completion doc Q2 requires twelve builtin topologies each with
a scripted-backend conformance; today the engine has only the
standard/leader mode string with no topology abstraction, no loop
re-arm (cycles are fail-closed by design), no in-graph routing, and no
run deadline.
Evidence: GOWORK=off go vet + go test -count=1 green across squad and
all three adapter modules; ten conformance/validation tests:
sequential, parallel, loop-until-field (exact iteration count +
persisted LoopRuns), loop-budget-exhausted (loop_exhausted event, run
still completes), router-selects-branch (loser skipped, run NOT
degraded), router-no-match fail-closed, evaluator-optimizer (draft
re-armed via loop body until verdict=pass), long-running deadline
(pending steps skipped, degraded closeout), unknown/primitive/
unregistered-driver fail-closed, builtin registry completeness (12).
Impact: additive — Topology/Deadline on RunOptions, Topology on
Blueprint, Loop/LoopRuns/Branches/Handoff on StepSpec; empty topology
keeps byte-identical standard behavior; MaxIterations is the total
iteration cap (first run included); router-skipped steps are exempt
from degraded derivation; runParallel now preserves the first specific
RunFailed error instead of re-wrapping via failStep; deadline metadata
uses RFC3339Nano (second-precision RFC3339 truncated sub-second
deadlines into instant expiry).
Refs: Agent-System-Documents#44 (Q2 plan WP1)
2026-10-08 00:03:24 +00:00
weichen c462bc4ae5 Merge pull request 'Carry the split usage fields through squad events (N3 WP6)' (#41) from feature/n3-usage-fields-wp6-r1 into main
ci / vet-and-test (push) Successful in 22s
ci / docker-checkout-hostgateway (push) Successful in 1s
Carry the split usage fields through squad events (N3 WP6)
2026-10-07 17:13:55 +00:00
weichen cff355d7e6 Carry the split usage fields through squad events (N3 WP6)
ci / vet-and-test (pull_request) Successful in 21s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: the exec bridge now threads Last*/cache (Agent-Native#39); squad
ProcessEvent carries them to hosts (the product's squad runner reads
them for usage accounting).
Evidence: GOWORK=off go vet green across squad and adapters/native;
nested pin at the merged native.
Impact: additive event fields.
Refs: Agent-Native#39, N3 plan WP6
2026-10-07 17:12:24 +00:00
weichen 8b1000eb09 Merge pull request 'Point the nested agent-native pin at the cache-on-message_end follow-up' (#40) from feature/n3-wp6-followup-cascade into main
ci / vet-and-test (push) Successful in 23s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the cache-on-message_end follow-up
2026-10-07 17:06:09 +00:00
weichen ef17c6630a Point the nested agent-native pin at the cache-on-message_end follow-up
ci / vet-and-test (pull_request) Successful in 23s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: native main carries the cache-on-message_end follow-up; the Dev
combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#37
2026-10-07 17:04:39 +00:00
weichen 40ce140cad Merge pull request 'Point the nested agent-native pin at the usage split and default retry' (#39) from feature/n3-wp6-cascade into main
ci / vet-and-test (push) Successful in 25s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the usage split and default retry
2026-10-07 16:33:36 +00:00
weichen b72bbe48a1 Point the nested agent-native pin at the usage split and default retry
ci / vet-and-test (pull_request) Successful in 23s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: native main carries the WP6 usage split and default retry; the
Dev combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#35
2026-10-07 16:32:54 +00:00
weichen bf7fe8429b Merge pull request 'Point the nested agent-native pin at the memory port work' (#38) from feature/n3-wp5-cascade into main
ci / vet-and-test (push) Successful in 22s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the memory port work
2026-10-07 16:23:00 +00:00
weichen 6dc03c02a9 Point the nested agent-native pin at the memory port work
ci / vet-and-test (pull_request) Successful in 22s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: native main carries the memory port and memory_write (N3 WP5);
the Dev combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#34
2026-10-07 16:22:15 +00:00
weichen ff36b23191 Merge pull request 'Point the nested agent-native pin at the checkpoint closure work' (#37) from feature/n3-wp3-cascade into main
ci / vet-and-test (push) Successful in 23s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the checkpoint closure work
2026-10-07 15:52:54 +00:00
weichen d775b4b205 Point the nested agent-native pin at the checkpoint closure work
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: native main carries the checkpoint closure (N3 WP3); the Dev
combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#33
2026-10-07 15:51:23 +00:00
weichen f38cf7c441 Merge pull request 'Point the nested agent-native pin at the OTel GenAI alignment' (#36) from feature/n3-wp4-cascade into main
ci / vet-and-test (push) Successful in 24s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the OTel GenAI alignment
2026-10-07 15:39:54 +00:00
weichen a9948da781 Point the nested agent-native pin at the OTel GenAI alignment
ci / vet-and-test (pull_request) Successful in 25s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: native main carries the GenAI span convention work (N3 WP4); the
Dev combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#32
2026-10-07 15:38:08 +00:00
weichen 90077b6601 Merge pull request 'Point the nested agent-native pin at the JournalOnly session work' (#35) from feature/n3-wp2-cascade into main
ci / vet-and-test (push) Successful in 26s
ci / docker-checkout-hostgateway (push) Successful in 0s
Point the nested agent-native pin at the JournalOnly session work
2026-10-07 15:25:05 +00:00
weichen b3363e83b9 Point the nested agent-native pin at the JournalOnly session work
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: native main carries JournalOnly sessions and the seed-persist fix
(N3 WP2); the Dev combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#31
2026-10-07 15:23:26 +00:00
weichen 931e5ae410 Merge pull request 'Point the nested agent-native pin at the RunState repair work' (#34) from feature/n3-wp1-cascade into main
ci / vet-and-test (push) Successful in 24s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the RunState repair work
2026-10-07 15:05:33 +00:00
weichen ec2c6a3495 Point the nested agent-native pin at the RunState repair work
ci / vet-and-test (pull_request) Successful in 25s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: native main carries repairOrphanTail and the N6 fix (N3 WP1); the
Dev combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#30
2026-10-07 15:03:54 +00:00
weichen 6306451552 Merge pull request 'Point the nested agent-native pin at the subagent Background field' (#33) from feature/n2-wp5-cascade into main
ci / vet-and-test (push) Successful in 42s
ci / docker-checkout-hostgateway (push) Successful in 0s
Point the nested agent-native pin at the subagent Background field
2026-10-07 14:17:52 +00:00
weichen 088d7f8543 Point the nested agent-native pin at the subagent Background field
ci / vet-and-test (pull_request) Successful in 26s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: native main carries subagent Request.Background (N2 WP5); the Dev
combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#29
2026-10-07 14:11:09 +00:00
weichen 9d3faefb97 Merge pull request 'Point the nested agent-native pin at the skills spec validation' (#32) from feature/n2-wp4-cascade into main
ci / vet-and-test (push) Successful in 29s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the skills spec validation
2026-10-07 13:54:30 +00:00
weichen c70d7c96d9 Point the nested agent-native pin at the skills spec validation
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
ci / vet-and-test (pull_request) Successful in 27s
Why: native main (7425b32b) validates skills against the open spec
(N2 WP4); the Dev combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#28, N2 WP4 cascade
2026-10-07 13:53:03 +00:00
weichen 92f4e925d2 Merge pull request 'Point the nested agent-native pin at the MCP 2026-07-28 work' (#31) from feature/n2-wp3-cascade into main
ci / vet-and-test (push) Successful in 29s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the MCP 2026-07-28 work
2026-10-07 13:42:03 +00:00
weichen 1bd42ab980 Point the nested agent-native pin at the MCP 2026-07-28 work
ci / vet-and-test (pull_request) Successful in 26s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: native main (77e7f978) aligns the MCP client with 2026-07-28
(N2 WP3); the Dev combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#27, N2 WP3 cascade
2026-10-07 13:40:27 +00:00
weichen 41ea27668c Merge pull request 'Point the nested agent-native pin at the Anthropic client work' (#30) from feature/n2-wp2-cascade into main
ci / vet-and-test (push) Successful in 26s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the Anthropic client work
2026-10-07 13:24:26 +00:00
weichen b4f1d26f33 Point the nested agent-native pin at the Anthropic client work
ci / vet-and-test (pull_request) Successful in 26s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: native main (d6053baf) adds the native Anthropic Messages client
(N2 WP2); the Dev combination check requires the nested pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#26, N2 WP2 cascade
2026-10-07 13:22:51 +00:00
weichen 56941bf8ea Merge pull request 'Point the nested agent-native pin at the N2 WP1 work' (#29) from feature/n2-wp1-cascade into main
ci / vet-and-test (push) Successful in 43s
ci / docker-checkout-hostgateway (push) Successful in 1s
Point the nested agent-native pin at the N2 WP1 work
2026-10-07 13:11:16 +00:00
weichen fe8de0e057 Point the nested agent-native pin at the N2 WP1 work
ci / vet-and-test (pull_request) Successful in 25s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: native main (64b8bd4c) adds the tool-result spill and cache
contract tests (N2 WP1); the Dev combination check requires the nested
pin to follow.
Evidence: tree-only pin move.
Impact: none.
Refs: Agent-Native#25, N2 WP1 cascade
2026-10-07 13:05:53 +00:00
weichen 029edc08e7 Merge pull request 'Point the nested agent-native pin at the CWD-clean fix' (#28) from feature/native-cascade-follow into main
ci / vet-and-test (push) Successful in 35s
ci / docker-checkout-hostgateway (push) Successful in 0s
Point the nested agent-native pin at the CWD-clean fix
2026-10-07 11:50:46 +00:00
weichen 1d86344c85 Point the nested agent-native pin at the CWD-clean fix
ci / vet-and-test (pull_request) Successful in 35s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: native main (ead690be) keeps workspace-less requests out of the
process CWD; the Dev CI build step requires a clean tree after tests.
Evidence: go build ./... green; tree-only pin move.
Impact: none beyond the pin.
Refs: Agent-Native#24, Agent-System-Dev#242
2026-10-07 11:48:58 +00:00
weichen 551e11ec19 Merge pull request 'Point the nested agent-intent and agent-native pins at the I2 cascade' (#27) from feature/agent-stack-i2 into main
ci / vet-and-test (push) Successful in 28s
ci / docker-checkout-hostgateway (push) Successful in 0s
Point the nested agent-intent and agent-native pins at the I2 cascade
2026-10-07 11:32:47 +00:00
weichen 83e72b4eaa Point the nested agent-intent and agent-native pins at the I2 cascade
ci / vet-and-test (pull_request) Successful in 23s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: the Dev combination check requires every nested agent-intent pin
to equal 343b1e6 (I2 increments 1-2 on intent main); the nested native
pin follows to 3a1ad5a (which itself carries intent 343b1e6).
Evidence: tree-only pin moves; squad code does not consume the new
ports.
Impact: none.
Refs: Agent-Native#23, I2 increment 3 cascade
2026-10-07 11:31:25 +00:00
weichen eba77e782f Merge pull request 'Converge run persistence on SQLite through the Store port (Q1 WP5)' (#26) from feature/agent-stack-q1 into main
ci / vet-and-test (push) Successful in 41s
ci / docker-checkout-hostgateway (push) Successful in 1s
2026-10-07 10:31:16 +00:00
weichen 90ac98ea65 Converge run persistence on SQLite through the Store port
ci / vet-and-test (pull_request) Successful in 23s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: Q1 WP5 - platform's SQLite becomes an implementation of the
squad Store port so run state and orchestration state live in one
database, and platform's in-process execution goes through the
Executor port instead of bypassing it (X6).

Evidence: all five modules go vet clean and go test ok, including
engine-on-SQLite (state in DB, no run-level JSON files, second
engine recovers from the same DB), SQLiteStore round trip, and the
full squad compatibility net.

Impact: runState/hitlGate exported so the port is implementable;
Options.Store wires into engineDeps; leader persistence and
checkpoints route through the port; PrepareWorkspace no longer
writes run-level JSON (st.save owns it); platform RunInProcess
takes squad.Executor (callers updated); serve mounts the engine on
platform's RunStore - single orchestration.db for both.

Refs: Documents proposal 2026-10-07-agent-stack-n1q1i1-plans.md Q1 WP5
2026-10-07 10:29:47 +00:00
weichen 1c3995beaa Merge pull request 'Add the Store port with tiered checkpoints and centralize termination (Q1 WP4/WP6/WP7)' (#25) from feature/agent-stack-q1 into main
ci / vet-and-test (push) Successful in 25s
ci / docker-checkout-hostgateway (push) Successful in 0s
2026-10-07 10:02:01 +00:00
weichen 626b2a3f34 Add the Store port with tiered checkpoints and centralize termination
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: Q1 WP4/WP6/WP7 - run persistence goes through a Store port
(FileStore carries the current layout), superstep boundaries write
tiered snapshots with a graph fingerprint for recovery continuity,
and the four hardcoded stop conditions move behind one Termination
registry with And/Or composition.

Evidence: go vet clean; full suite ok including new checkpoint,
continuity-rejection, termination-primitive, grant-cap and the
Q23-updated leader closeout tests; cmd module green with
SweepExpired wired into the sweeper loop.

Impact: runState saves via Store (FileStore unchanged by default);
advance writes sync/async/on_exit checkpoints and Resume rejects
graph-shape changes from the crash window; leader turn cap now
degrades through finalize instead of a bare failure (Q23); manual
repair grants are bounded (Q26); wakeup cap and step timeout read
from the same registry; the dead SweepExpired is now called (Q6).

Refs: Documents proposal 2026-10-07-agent-stack-n1q1i1-plans.md Q1 WP4/WP6/WP7
2026-10-07 10:00:33 +00:00
weichen b34d6ed187 Merge pull request 'Persist attempt ids and verify products on interrupted recovery (Q1 WP3)' (#24) from feature/agent-stack-q1 into main
ci / vet-and-test (push) Successful in 24s
ci / docker-checkout-hostgateway (push) Successful in 0s
2026-10-07 09:19:15 +00:00
weichen 96d1e0e49c Persist attempt ids and verify products on interrupted recovery
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: Q1 WP3 - each step execution carries a stable attempt id
(runID/stepID/N) for audit and idempotency, and auto-mode
interrupted recovery must not re-execute a step whose products all
landed before the crash (side effects exactly once).

Evidence: go vet clean; full squad suite ok, including the new
kill-at-superstep-boundary test (completed steps never re-execute,
running-with-products judged complete by attempt) and
missing-product retry tests.

Impact: StepSpec gains AttemptID set when entering running and used
as the execution id; recoverInterrupted (HitlAuto) checks the
step's targets first - all present means completed with artifact
merge, otherwise the legacy pending retry. Transient retries share
the same AttemptID.

Refs: Documents proposal 2026-10-07-agent-stack-n1q1i1-plans.md Q1 WP3
2026-10-07 09:18:08 +00:00
weichen 3870489614 Merge pull request 'Drive workflow execution as supersteps over a compiled dependency graph (Q1 WP1/WP2)' (#23) from feature/agent-stack-q1 into main
ci / vet-and-test (push) Successful in 24s
ci / docker-checkout-hostgateway (push) Successful in 1s
2026-10-07 09:08:21 +00:00
weichen f90abafe79 Drive workflow execution as supersteps over a compiled dependency graph
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: Q1 WP1/WP2 - replace the linear step scan with per-round graph
compilation and layer advancement so Needs drives scheduling and
write-conflicting steps never run concurrently.

Evidence: go vet clean in all five modules; go test ok everywhere,
including the full compatibility net (engine, leader, recovery, r2
regression, intent, evaluator suites) and new graph tests.

Impact: new squad/graph.go (compile/layer/conflict); StepSpec gains
Writes; advance advances by superstep (parallel run of
conflict-free members, serial for write-conflicts, single-member
groups keep dynamic adjustment). Legacy semantics preserved:
adjacent-Parallel mapping, degraded-continue on non-critical
failure (failed counts as satisfied), empty status = pending,
cycle/unknown/dup needs fail-closed.

Refs: Documents proposal 2026-10-07-agent-stack-n1q1i1-plans.md Q1 WP1/WP2
2026-10-07 09:06:52 +00:00
weichen bb02683d89 Merge pull request 'Point the nested agent-native pin at the intent-archive cascade head' (#22) from feature/agent-stack-i1 into main
ci / vet-and-test (push) Successful in 23s
ci / docker-checkout-hostgateway (push) Successful in 0s
2026-10-07 08:28:25 +00:00
weichen 4e8d684125 Point the nested agent-native pin at the intent-archive cascade
ci / vet-and-test (pull_request) Successful in 22s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: Agent-Native PR #22 landed after Squad #21; squad's nested
native must carry the same head or Dev check-pins fails.

Evidence: 78b6c647 is the #22 merge on agent-native main.

Impact: Nested pin only.
2026-10-07 08:27:39 +00:00
weichen 5403b6e7a9 Merge pull request 'Point the nested intent pin at the eval-v2 head' (#21) from feature/agent-stack-i1 into main
ci / vet-and-test (push) Successful in 26s
ci / docker-checkout-hostgateway (push) Successful in 1s
2026-10-07 08:24:36 +00:00
weichen ebbebdf20b Point the nested intent pins at the eval-v2 head
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: Agent-Intent PR #8 landed the multi-turn eval format; nested
copies must carry it or Dev check-pins fails.

Evidence: intent main head is the #8 merge.

Impact: Nested pins only.
2026-10-07 08:22:54 +00:00
weichen 592a410288 Merge pull request 'Point the nested agent-native pin at the intent cascade head' (#20) from feature/agent-stack-i1 into main
ci / vet-and-test (push) Successful in 23s
ci / docker-checkout-hostgateway (push) Successful in 1s
2026-10-07 07:49:50 +00:00
weichen 7fe41e86a1 Point the nested agent-native pin at the intent cascade head
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 0s
Why: Agent-Native PR #21 landed the nested intent bump; squad's
nested native must carry the same head or Dev check-pins fails.

Evidence: 6ea69293 is the #21 merge on agent-native main; squad
modules run next.

Impact: Nested pin only.
2026-10-07 07:48:40 +00:00
weichen 6b7a991750 Merge pull request 'Enable NFKC folding in the squad intent gate (I1 WP4)' (#19) from feature/agent-stack-i1 into main
ci / vet-and-test (push) Successful in 26s
ci / docker-checkout-hostgateway (push) Successful in 0s
2026-10-07 07:44:14 +00:00
weichen cb398dadc6 Enable NFKC folding in the squad intent gate and bump the intent pin
ci / vet-and-test (pull_request) Successful in 24s
ci / docker-checkout-hostgateway (pull_request) Successful in 1s
Why: Both intent hosts should fold compatibility-equivalent input
(backend intentgate already does); the nested pin carries the I1
command model the gate depends on.

Evidence: adapters/intent suite ok; all five squad modules green.

Impact: NFKC on in NewFromOverlay; nested agent-intent at 2554b50.
2026-10-07 07:42:52 +00:00
weichen 7ecc04ee61 Merge pull request 'Point the nested agent-native pin at the WP5 head' (#18) from feature/agent-stack-n1 into main
ci / vet-and-test (push) Successful in 22s
ci / docker-checkout-hostgateway (push) Successful in 0s
2026-10-07 06:38:25 +00:00
33 changed files with 3353 additions and 217 deletions
+2
View File
@@ -33,11 +33,13 @@ type Options struct {
// NewFromOverlay 从 JSON overlay 构造闸门,并把 guard 域标成受保护域。
// 命令行用它,这样命令本身不必 import agent-intent。
// NFKC 开启:全角/兼容等价输入与词条同形折叠(与 backend intentgate 一致)。
func NewFromOverlay(ctx context.Context, fsys fs.FS, roots ...string) (*Gate, error) {
return New(ctx, Options{
IntentOptions: intent.Options{
GuardDomains: []string{"guard"},
ProtectedDomains: []string{"guard"},
NFKC: true,
},
FS: fsys,
Roots: roots,
+2
View File
@@ -138,6 +138,8 @@ func toNative(req squad.ExecRequest) exec.Request {
prev(squad.ProcessEvent{
Type: ev.Type, Text: ev.Text, Tool: ev.Tool, Detail: ev.Detail,
PromptTokens: ev.PromptTokens, CompletionTokens: ev.CompletionTokens,
LastPromptTokens: ev.LastPromptTokens, LastCompletionTokens: ev.LastCompletionTokens,
CacheReadTokens: ev.CacheReadTokens, CacheWriteTokens: ev.CacheWriteTokens,
})
}
}
+2
View File
@@ -4,10 +4,12 @@ go 1.27
require (
agent-native v0.0.0
agent-squad v0.0.0
modernc.org/sqlite v1.37.0
)
require (
error-code-system v0.0.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
+5 -7
View File
@@ -11,7 +11,7 @@ import (
"testing"
"time"
"agent-native/runtime/llm"
agentsquad "agent-squad/squad"
)
func TestOrchestrationFlow(t *testing.T) {
@@ -116,12 +116,10 @@ func TestOrchestrationFlow(t *testing.T) {
if err != nil {
t.Fatal(err)
}
text, err := s.RunInProcess(context.Background(), woke, work, func(ctx context.Context, model string, messages []llm.Message, td []llm.ToolDecl, opts llm.StreamOptions) <-chan llm.Event {
ch := make(chan llm.Event, 1)
ch <- llm.Event{Kind: llm.KindMessageEnd, Message: llm.Message{Role: llm.RoleAssistant, Content: "done", StopReason: llm.StopEnd}}
close(ch)
return ch
})
text, err := s.RunInProcess(context.Background(), woke, work, stubExecutor{result: &agentsquad.ExecResult{
Success: true, Logs: "done",
Patches: map[string][]byte{"output.md": []byte("done")},
}})
if err != nil || text != "done" {
t.Fatalf("in-process %q %v", text, err)
}
+230
View File
@@ -0,0 +1,230 @@
package platform
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"time"
"agent-squad/squad"
)
// SQLiteStore 把 squad 的 Store 端口落到本库(Q1 WP5):run/gate/checkpoint/leader
// 与平台其余表同一个 SQLite 文件——运行状态与平台状态不再各记一份。
// 表名带 squad_run_ 前缀,与平台既有 23 张表并存不冲突。
type SQLiteStore struct {
db *sql.DB
}
// OpenRunStore 在本 Store 的底层连接上提供 squad.Store 端口(schema 随 migrate 建)。
func (s *Store) RunStore() *SQLiteStore {
return &SQLiteStore{db: s.db}
}
const runSchema = `
CREATE TABLE IF NOT EXISTS squad_run_state (
ws_dir TEXT PRIMARY KEY,
meta TEXT NOT NULL, workflow TEXT NOT NULL, squad TEXT NOT NULL, bb TEXT NOT NULL,
template TEXT, approved TEXT, repair_budget_remaining INTEGER NOT NULL DEFAULT 0,
repair_budget_granted INTEGER NOT NULL DEFAULT 0,
clarifications TEXT, steering TEXT, usage TEXT, updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS squad_run_gate (
ws_dir TEXT PRIMARY KEY, gate TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS squad_run_checkpoint (
ws_dir TEXT NOT NULL, superstep INTEGER NOT NULL, at TEXT NOT NULL,
graph_hash TEXT NOT NULL, steps TEXT NOT NULL,
PRIMARY KEY (ws_dir, superstep)
);
CREATE TABLE IF NOT EXISTS squad_run_leader (
ws_dir TEXT PRIMARY KEY, data TEXT NOT NULL
);
`
func (s *SQLiteStore) migrate() error {
_, err := s.db.Exec(runSchema)
return err
}
// OpenSQLiteStore 独立打开一个 squad.Store(不经 platform.Store 的场景,如测试)。
func OpenSQLiteStore(path string) (*SQLiteStore, error) {
db, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)")
if err != nil {
return nil, err
}
s := &SQLiteStore{db: db}
if err := s.migrate(); err != nil {
_ = db.Close()
return nil, err
}
return s, nil
}
func j(v any) string {
b, err := json.Marshal(v)
if err != nil {
return ""
}
return string(b)
}
func (s *SQLiteStore) SaveRun(st *squad.RunState) error {
if err := s.migrate(); err != nil {
return err
}
_, err := s.db.Exec(`INSERT INTO squad_run_state
(ws_dir, meta, workflow, squad, bb, template, approved, repair_budget_remaining, repair_budget_granted, clarifications, steering, usage, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(ws_dir) DO UPDATE SET
meta=excluded.meta, workflow=excluded.workflow, squad=excluded.squad, bb=excluded.bb,
template=excluded.template, approved=excluded.approved,
repair_budget_remaining=excluded.repair_budget_remaining,
repair_budget_granted=excluded.repair_budget_granted,
clarifications=excluded.clarifications, steering=excluded.steering,
usage=excluded.usage, updated_at=excluded.updated_at`,
st.Meta.WorkDir, j(st.Meta), j(st.Plan.Workflow), j(st.Plan.Squad), j(st.BB),
st.Template, j(st.Approved), st.RepairBudgetRemaining, st.RepairBudgetGranted,
j(st.Clarifications), j(st.Steering), j(st.Usage), now())
return err
}
func (s *SQLiteStore) LoadRun(wsDir string) (*squad.RunState, error) {
if err := s.migrate(); err != nil {
return nil, err
}
st := &squad.RunState{}
var meta, wf, sq, bb, template, approved, clar, steering, usage string
row := s.db.QueryRow(`SELECT meta, workflow, squad, bb, template, approved,
repair_budget_remaining, repair_budget_granted, clarifications, steering, usage
FROM squad_run_state WHERE ws_dir = ?`, wsDir)
var granted int
err := row.Scan(&meta, &wf, &sq, &bb, &template, &approved,
&st.RepairBudgetRemaining, &granted, &clar, &steering, &usage)
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("load run %s: %w", wsDir, os.ErrNotExist)
}
return nil, err
}
st.RepairBudgetGranted = granted
for pair, dst := range map[string]any{
meta: &st.Meta, wf: &st.Plan.Workflow, sq: &st.Plan.Squad, bb: &st.BB,
approved: &st.Approved, clar: &st.Clarifications, steering: &st.Steering, usage: &st.Usage,
} {
if err := json.Unmarshal([]byte(pair), dst); err != nil {
return nil, fmt.Errorf("load run %s: parse: %w", wsDir, err)
}
}
st.Template = template
if st.Approved == nil {
st.Approved = map[string]bool{}
}
return st, nil
}
func (s *SQLiteStore) SaveGate(wsDir string, gate *squad.HitlGate) error {
if err := s.migrate(); err != nil {
return err
}
if gate == nil {
_, err := s.db.Exec(`DELETE FROM squad_run_gate WHERE ws_dir = ?`, wsDir)
return err
}
_, err := s.db.Exec(`INSERT INTO squad_run_gate (ws_dir, gate) VALUES (?,?)
ON CONFLICT(ws_dir) DO UPDATE SET gate=excluded.gate`, wsDir, j(gate))
return err
}
func (s *SQLiteStore) LoadGate(wsDir string) (*squad.HitlGate, error) {
if err := s.migrate(); err != nil {
return nil, err
}
var raw string
err := s.db.QueryRow(`SELECT gate FROM squad_run_gate WHERE ws_dir = ?`, wsDir).Scan(&raw)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
gate := &squad.HitlGate{}
if err := json.Unmarshal([]byte(raw), gate); err != nil {
return nil, fmt.Errorf("parse gate: %w", err)
}
return gate, nil
}
func (s *SQLiteStore) SaveCheckpoint(wsDir string, cp squad.Checkpoint) error {
if err := s.migrate(); err != nil {
return err
}
_, err := s.db.Exec(`INSERT INTO squad_run_checkpoint (ws_dir, superstep, at, graph_hash, steps)
VALUES (?,?,?,?,?)
ON CONFLICT(ws_dir, superstep) DO UPDATE SET at=excluded.at, graph_hash=excluded.graph_hash, steps=excluded.steps`,
wsDir, cp.Superstep, cp.At.UTC().Format("2006-01-02T15:04:05Z07:00"), cp.GraphHash, j(cp.StepStates))
return err
}
func (s *SQLiteStore) LoadLatestCheckpoint(wsDir string) (*squad.Checkpoint, error) {
if err := s.migrate(); err != nil {
return nil, err
}
var cp squad.Checkpoint
var at, steps string
err := s.db.QueryRow(`SELECT superstep, at, graph_hash, steps FROM squad_run_checkpoint
WHERE ws_dir = ? ORDER BY superstep DESC LIMIT 1`, wsDir).
Scan(&cp.Superstep, &at, &cp.GraphHash, &steps)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
t, _ := parseTime(at)
cp.At = t
if err := json.Unmarshal([]byte(steps), &cp.StepStates); err != nil {
return nil, fmt.Errorf("parse checkpoint steps: %w", err)
}
return &cp, nil
}
func (s *SQLiteStore) SaveLeader(wsDir string, data []byte) error {
if err := s.migrate(); err != nil {
return err
}
_, err := s.db.Exec(`INSERT INTO squad_run_leader (ws_dir, data) VALUES (?,?)
ON CONFLICT(ws_dir) DO UPDATE SET data=excluded.data`, wsDir, string(data))
return err
}
func (s *SQLiteStore) LoadLeader(wsDir string) ([]byte, error) {
if err := s.migrate(); err != nil {
return nil, err
}
var raw string
err := s.db.QueryRow(`SELECT data FROM squad_run_leader WHERE ws_dir = ?`, wsDir).Scan(&raw)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return []byte(raw), nil
}
// Close 只在独立打开(OpenSQLiteStore)时调用;经 platform.Store 打开时由平台统一关闭。
func (s *SQLiteStore) Close() error { return s.db.Close() }
var _ squad.Store = (*SQLiteStore)(nil)
// parseTime 解析检查点时间(RFC3339Nano 与 RFC3339 两态)。
func parseTime(s string) (time.Time, error) {
for _, layout := range []string{time.RFC3339Nano, time.RFC3339} {
if t, err := time.Parse(layout, s); err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("bad time %q", s)
}
+188
View File
@@ -0,0 +1,188 @@
package platform
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"agent-squad/squad"
)
func newTestRunState(wsDir string) *squad.RunState {
return &squad.RunState{
Meta: squad.RunMetadata{
ID: "run_test", Status: "executing", WorkDir: wsDir,
CreatedAt: time.Now(), UpdatedAt: time.Now(),
Metadata: map[string]string{"mode": ""},
},
Plan: squad.SquadPlan{
Workflow: squad.WorkflowPlan{
WorkflowID: "wf1", Status: "in_progress",
Steps: []squad.StepSpec{
{ID: "s1", Role: "researcher", Status: "completed", Attempts: 1, AttemptID: "run_test/s1/1"},
{ID: "s2", Role: "writer", Status: "pending"},
},
},
Squad: squad.SquadConfig{SquadName: "demo"},
},
BB: squad.BlackboardState{Facts: []squad.FactItem{{ID: "f1", Claim: "x"}}},
Template: "tpl",
Approved: map[string]bool{"step:s1": true},
RepairBudgetRemaining: 1,
RepairBudgetGranted: 0,
Clarifications: []string{"c1"},
Steering: []string{"st1"},
Usage: map[string]*squad.Usage{"writer": {PromptTokens: 10, CompletionTokens: 5, Steps: 1}},
}
}
// TestSQLiteStoreRoundTrip:run/gate/checkpoint/leader 全链路(Q1 WP5 端口实现)。
func TestSQLiteStoreRoundTrip(t *testing.T) {
st, err := OpenSQLiteStore(filepath.Join(t.TempDir(), "runs.db"))
if err != nil {
t.Fatal(err)
}
defer st.Close()
ws := filepath.Join(t.TempDir(), "runs", "run_test")
orig := newTestRunState(ws)
if err := st.SaveRun(orig); err != nil {
t.Fatal(err)
}
got, err := st.LoadRun(ws)
if err != nil {
t.Fatal(err)
}
if got.Meta.ID != "run_test" || got.Plan.Workflow.WorkflowID != "wf1" || got.Template != "tpl" {
t.Fatalf("loaded = %+v", got.Meta)
}
if !got.Approved["step:s1"] || got.RepairBudgetRemaining != 1 || len(got.Clarifications) != 1 || len(got.Steering) != 1 {
t.Fatalf("scalars = %+v", got)
}
if got.Usage["writer"].PromptTokens != 10 {
t.Fatalf("usage = %+v", got.Usage)
}
if _, err := st.LoadRun(filepath.Join(t.TempDir(), "nope")); err == nil {
t.Fatal("missing run should error")
}
// gate:写→读→删。
gate := &squad.HitlGate{PrevStatus: squad.RunExecuting}
if err := st.SaveGate(ws, gate); err != nil {
t.Fatal(err)
}
if g2, err := st.LoadGate(ws); err != nil || g2 == nil {
t.Fatalf("load gate: %v %+v", err, g2)
}
if err := st.SaveGate(ws, nil); err != nil {
t.Fatal(err)
}
if g2, err := st.LoadGate(ws); err != nil || g2 != nil {
t.Fatalf("gate after delete: %v %+v", err, g2)
}
// checkpoint:两层,latest 取最大 superstep。
if err := st.SaveCheckpoint(ws, squad.Checkpoint{Superstep: 1, At: time.Now(), GraphHash: "h1", StepStates: []squad.StepSnapshot{{ID: "s1", Status: "completed", AttemptID: "run_test/s1/1"}}}); err != nil {
t.Fatal(err)
}
if err := st.SaveCheckpoint(ws, squad.Checkpoint{Superstep: 2, At: time.Now(), GraphHash: "h2"}); err != nil {
t.Fatal(err)
}
latest, err := st.LoadLatestCheckpoint(ws)
if err != nil || latest == nil {
t.Fatalf("latest: %v", err)
}
if latest.Superstep != 2 || latest.GraphHash != "h2" {
t.Fatalf("latest = %+v", latest)
}
if l2, err := st.LoadLatestCheckpoint(filepath.Join(t.TempDir(), "nope")); err != nil || l2 != nil {
t.Fatalf("latest for unknown: %v %+v", err, l2)
}
// leader bytes。
if err := st.SaveLeader(ws, []byte(`{"turns":2}`)); err != nil {
t.Fatal(err)
}
data, err := st.LoadLeader(ws)
if err != nil || string(data) != `{"turns":2}` {
t.Fatalf("leader = %q %v", data, err)
}
}
// TestEngineRunsOnSQLiteStore:引擎注入 SQLiteStore 后运行状态进 SQLite、
// 不再写 run 级 JSON 文件;第二引擎可从中恢复(验收第三条的实证形态)。
func TestEngineRunsOnSQLiteStore(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "runs.db")
runStore, err := OpenSQLiteStore(dbPath)
if err != nil {
t.Fatal(err)
}
defer runStore.Close()
dir := t.TempDir()
reg := squad.NewRoleRegistry()
for _, spec := range []squad.RoleSpec{{Role: "researcher", Backend: "script"}, {Role: "writer", Backend: "script"}, {Role: "reviewer", Backend: "script"}} {
if err := reg.Register(spec); err != nil {
t.Fatal(err)
}
}
backends := squad.NewBackendResolver()
backends.RegisterInstance("script", stubExecutor{result: &squad.ExecResult{Success: false, Logs: "ok", Patches: map[string][]byte{"output.md": []byte(goodReportLite), "notes.md": []byte(goodReportLite), "fields.json": []byte("{}")}}})
blueprints := squad.NewBlueprintRegistry()
if err := blueprints.Register(squad.Blueprint{
Key: "demo", Title: "入库演示", Match: []string{"入库演示"},
Steps: []squad.StepSpec{
{ID: "s1", Role: "researcher", Title: "调研", Targets: []string{"notes.md", "fields.json"}},
{ID: "s2", Role: "writer", Title: "成文", Targets: []string{"output.md"}},
{ID: "s3", Role: "reviewer", Title: "终审", Targets: []string{"output.md"}},
},
}); err != nil {
t.Fatal(err)
}
eng, err := squad.NewEngine(squad.Options{
DataDir: dir, Registry: reg, Blueprints: blueprints,
Planner: squad.NewRulePlanner(),
Backends: backends, Sink: squad.NopSink{},
Store: runStore,
})
if err != nil {
t.Fatal(err)
}
res, err := eng.Run(context.Background(), squad.Goal{Text: "做一个三步入库演示", HitlMode: squad.HitlAuto}, squad.RunOptions{})
if err != nil || res.Status != squad.RunCompleted {
t.Fatalf("run: %v %+v", err, res)
}
// run 级 JSON 不在盘上(状态全进了 SQLite)。
for _, f := range []string{"workspace.json", "workflow.json", "squad.json", "blackboard.json", "runstate.json"} {
if _, err := os.Stat(filepath.Join(res.WorkDir, f)); !os.IsNotExist(err) {
t.Fatalf("%s should not be on disk with SQLite store (err=%v)", f, err)
}
}
// 状态可经端口读回。
st, err := runStore.LoadRun(res.WorkDir)
if err != nil {
t.Fatal(err)
}
if st.Plan.Workflow.Status != "completed" {
t.Fatalf("workflow status = %s", st.Plan.Workflow.Status)
}
latest, err := runStore.LoadLatestCheckpoint(res.WorkDir)
if err != nil || latest == nil {
t.Fatalf("latest checkpoint: %v", err)
}
// 第二引擎(同库)恢复可用。
eng2, err := squad.NewEngine(squad.Options{
DataDir: dir, Registry: reg, Blueprints: blueprints,
Planner: squad.NewRulePlanner(),
Backends: backends, Sink: squad.NopSink{},
Store: runStore,
})
if err != nil {
t.Fatal(err)
}
if _, err := eng2.Inspect(res.RunID); err != nil {
t.Fatalf("inspect from second engine: %v", err)
}
}
const goodReportLite = "# 测试交付物\n\n## 概述\n\n这是由脚本后端生成的合格交付物,长度超过五十个字符以满足最小质检要求。\n"
+35 -18
View File
@@ -9,8 +9,7 @@ import (
"path/filepath"
"strings"
"agent-native/runtime"
"agent-native/runtime/llm"
"agent-squad/squad"
)
// CLICommands are the external tools a daemon probes, in order.
@@ -196,36 +195,54 @@ func (s *Store) RunCommand(ctx context.Context, task Task, command, workdir stri
return s.FinishTask(task.ID, "completed", "")
}
// RunInProcess executes the task with AgentSession. stream is required; the
// product supplies a provider, tests supply a script.
func (s *Store) RunInProcess(ctx context.Context, task Task, workdir string, stream llm.StreamFunc) (string, error) {
// RunInProcess executes the task through the squad.Executor port(Q1 WP5 修 X6:
// 不再绕过执行端口直驱 agent-native runtime)。调用方经 adapters/native 等
// 适配器构造 Executor;nil 即 fail-closed。
func (s *Store) RunInProcess(ctx context.Context, task Task, workdir string, exec squad.Executor) (string, error) {
if exec == nil {
return "", fmt.Errorf("RunInProcess requires an executor (no bypass)")
}
if err := s.MarkRunning(task.ID); err != nil {
return "", err
}
issue, _ := s.GetIssue(task.IssueID)
agent := runtime.NewAgentSession(runtime.Config{
Model: "agent-native",
Stream: stream,
MaxTurns: 4,
OnEvent: func(ev runtime.Event) {
res, err := exec.Execute(ctx, squad.ExecRequest{
WorkDir: workdir,
Prompt: issue.Title + "\n" + issue.Body,
Targets: []string{"output.md"},
OnEvent: func(ev squad.ProcessEvent) {
_ = s.AddTaskMessage(task.ID, ev.Type, ev.Text)
},
})
res, err := agent.Prompt(ctx, llm.Message{Role: llm.RoleUser, Content: issue.Title + "\n" + issue.Body})
if err != nil {
_ = s.FinishTask(task.ID, "failed", "config")
return "", err
}
if res.Err != nil {
_ = s.FinishTask(task.ID, "failed", "model")
return res.Text, res.Err
if res == nil || !res.Success {
reason := "model"
if res != nil && res.ErrorReason != "" {
reason = res.ErrorReason
}
_ = s.FinishTask(task.ID, "failed", reason)
if res != nil {
return res.Logs, fmt.Errorf("executor failed: %s", res.ErrorReason)
}
return "", fmt.Errorf("executor failed")
}
_ = s.AddUsage(task.ID, "agent-native", res.Usage.PromptTokens, res.Usage.CompletionTokens, res.Usage.CacheReadTokens, res.Usage.CacheWriteTokens)
if len(res.Patches) > 0 {
_, _ = squad.MaterializeTargets(workdir, []string{"output.md"}, res.Patches)
}
_ = s.AddUsage(task.ID, exec.Name(), res.PromptTokens, res.CompletionTokens, 0, 0)
if err := s.FinishTask(task.ID, "completed", ""); err != nil {
return res.Text, err
return res.Logs, err
}
_ = os.WriteFile(filepath.Join(workdir, "output.md"), []byte(res.Text), 0o644)
return res.Text, nil
if data, rerr := os.ReadFile(filepath.Join(workdir, "output.md")); rerr == nil {
return string(data), nil
}
if err := os.WriteFile(filepath.Join(workdir, "output.md"), []byte(res.Logs), 0o644); err != nil {
return res.Logs, err
}
return res.Logs, nil
}
// AgentCLI applies a task-token command: comment, status, sub-issue, or activity.
+30
View File
@@ -0,0 +1,30 @@
package platform
import (
"context"
"agent-squad/squad"
)
// stubExecutor 是测试用的 squad.Executor(X6 后调用方经端口注入)。
type stubExecutor struct {
result *squad.ExecResult
err error
}
func (s stubExecutor) Name() string { return "stub" }
func (s stubExecutor) Execute(ctx context.Context, req squad.ExecRequest) (*squad.ExecResult, error) {
if s.result == nil {
return nil, s.err
}
// 每次调用返回拷贝:调用方会改写 Success 字段,共享指针会跨步骤串味。
cp := *s.result
if s.result.Patches != nil {
cp.Patches = map[string][]byte{}
for k, v := range s.result.Patches {
cp.Patches[k] = v
}
}
return &cp, s.err
}
+13 -7
View File
@@ -86,6 +86,7 @@ type app struct {
files *store.FileEventSink
st *store.FileStore
log *logsys.Logger
plat *platform.Store
}
func dataDir() string {
@@ -159,12 +160,20 @@ func assemble(dir, plannerName, modelOverride, intentRoot string) (*app, error)
}
}
}
// 单库收编(Q1 WP5):引擎运行状态与平台编排状态进同一个 SQLite。
// 库打不开即失败(与 serve 现状一致),不允许静默退回文件态。
plat, err := platform.Open(filepath.Join(dir, "orchestration.db"))
if err != nil {
return nil, fmt.Errorf("编排库打开失败: %w", err)
}
engine, err := squad.NewEngine(squad.Options{
DataDir: dir, Registry: reg, Blueprints: bps, Planner: planner,
Backends: backends, Sink: fileSink, IntentGate: gate,
IntentCatalog: catalog, IntentRunner: runner,
Store: plat.RunStore(),
})
if err != nil {
_ = plat.Close()
return nil, err
}
logCfg, err := config.Load("")
@@ -178,7 +187,7 @@ func assemble(dir, plannerName, modelOverride, intentRoot string) (*app, error)
if err != nil {
return nil, err
}
return &app{engine: engine, sink: fanout, files: fileSink, st: st, log: logger}, nil
return &app{engine: engine, sink: fanout, files: fileSink, st: st, log: logger, plat: plat}, nil
}
func (a *app) close() {
@@ -223,12 +232,9 @@ func cmdServe(args []string) int {
srv := server.New(a.engine, a.sink, a.st)
srv.SetToken(*token)
srv.SetLogger(a.log)
if plat, err := platform.Open(filepath.Join(*data, "orchestration.db")); err != nil {
fmt.Fprintln(os.Stderr, "编排库打开失败:", err)
return 1
} else {
srv.SetPlatform(plat)
defer plat.Close()
if a.plat != nil {
srv.SetPlatform(a.plat)
defer a.plat.Close()
}
stopSweep := srv.StartWakeupSweeper(15 * time.Second)
defer stopSweep()
+12 -7
View File
@@ -9,8 +9,8 @@ import (
"path/filepath"
"time"
"agent-native/runtime/llm"
platform "agent-squad/adapters/sqlite"
"agent-squad/squad"
)
func cmdPlatform(args []string) int {
@@ -99,7 +99,7 @@ func cmdPlatform(args []string) int {
return 1
}
}
text, err := st.RunInProcess(context.Background(), task, fs.Arg(1), scriptedOK)
text, err := st.RunInProcess(context.Background(), task, fs.Arg(1), scriptedExecutor{})
return printPlatform(map[string]string{"text": text}, err)
default:
fmt.Fprintln(os.Stderr, "未知编排命令", args[0], args[1])
@@ -111,11 +111,16 @@ func taskByID(st *platform.Store, id string) (platform.Task, error) {
return st.TaskByToken(id)
}
func scriptedOK(ctx context.Context, model string, messages []llm.Message, td []llm.ToolDecl, opts llm.StreamOptions) <-chan llm.Event {
ch := make(chan llm.Event, 1)
ch <- llm.Event{Kind: llm.KindMessageEnd, Message: llm.Message{Role: llm.RoleAssistant, Content: "ok", StopReason: llm.StopEnd}}
close(ch)
return ch
// scriptedExecutor 是 daemon run-native 冒烟路径的脚本执行器(X6 后经端口注入)。
type scriptedExecutor struct{}
func (scriptedExecutor) Name() string { return "scripted" }
func (scriptedExecutor) Execute(ctx context.Context, req squad.ExecRequest) (*squad.ExecResult, error) {
return &squad.ExecResult{
Success: true, Logs: "ok",
Patches: map[string][]byte{"output.md": []byte("ok")},
}, nil
}
func printPlatform(v any, err error) int {
+2
View File
@@ -462,6 +462,8 @@ func (s *Server) StartWakeupSweeper(interval time.Duration) (stop func()) {
return
case <-t.C:
s.engine.SweepWakeups(context.Background())
// Q6:与事件唤醒并列,过期挂起按 ExpireAction 合成决策(此前是死代码)。
s.engine.SweepExpired(context.Background(), time.Now())
}
}
}()
+173
View File
@@ -0,0 +1,173 @@
package squad
import (
"context"
"os"
"path/filepath"
"sync"
"testing"
)
// perStepRecordingBackend 按子工作区归因计数(steps 的 role→tasks/NN_role 布局)。
type perStepRecordingBackend struct {
mu sync.Mutex
calls map[string]int
}
func (b *perStepRecordingBackend) Name() string { return "recording" }
func (b *perStepRecordingBackend) Execute(ctx context.Context, req ExecRequest) (*ExecResult, error) {
b.mu.Lock()
if b.calls == nil {
b.calls = map[string]int{}
}
b.calls[filepath.Base(req.WorkDir)]++
b.mu.Unlock()
out := map[string][]byte{}
for _, t := range req.Targets {
out[t] = []byte(goodReport)
}
if _, err := MaterializeTargets(req.WorkDir, req.Targets, out); err != nil {
return &ExecResult{Success: false, ErrorReason: err.Error()}, nil
}
return &ExecResult{Success: true, Logs: "ok"}, nil
}
func (b *perStepRecordingBackend) countOf(sub string) int {
b.mu.Lock()
defer b.mu.Unlock()
return b.calls[sub]
}
func newAttemptTestEngine(t *testing.T, backend *perStepRecordingBackend, dir string) *SquadEngine {
t.Helper()
reg := NewRoleRegistry()
for _, role := range []string{"researcher", "writer", "reviewer"} {
if err := reg.Register(RoleSpec{Role: role, Backend: "recording"}); err != nil {
t.Fatal(err)
}
}
backends := NewBackendResolver()
backends.RegisterInstance("recording", backend)
eng, err := NewEngine(Options{
DataDir: dir, Registry: reg, Planner: mockScriptPlanner(baseSteps()...),
Backends: backends, Sink: NopSink{},
})
if err != nil {
t.Fatal(err)
}
return eng
}
func flipToInterrupted(t *testing.T, workDir string, stepIdx int) {
t.Helper()
st, err := loadRunState(workDir)
if err != nil {
t.Fatal(err)
}
st.Meta.Status = string(RunExecuting)
st.Meta.CompletedAt = nil
wf := st.Workflow()
wf.Status = "running"
wf.Steps[stepIdx].Status = "running"
wf.Steps[stepIdx].Attempts = 1
st.setWorkflow(wf)
if err := st.save(); err != nil {
t.Fatal(err)
}
}
// TestAttemptIDFormat:attempt id 稳定落盘且形如 runID/stepID/N(Q1 WP3)。
func TestAttemptIDFormat(t *testing.T) {
backend := &perStepRecordingBackend{}
dir := t.TempDir()
eng := newAttemptTestEngine(t, backend, dir)
res, err := eng.Run(context.Background(), Goal{Text: "格式"}, RunOptions{})
if err != nil || res.Status != RunCompleted {
t.Fatalf("run: %v %+v", err, res)
}
if res.Plan == nil {
t.Fatal("no plan")
}
for _, s := range res.Plan.Steps {
want := res.RunID + "/" + s.ID + "/1"
if s.AttemptID != want {
t.Fatalf("step %s attempt id = %q, want %q", s.ID, s.AttemptID, want)
}
}
}
// TestKilledAtSuperstepBoundarySideEffectsOnce:杀进程于 superstep 边界后恢复,
// 已完成步骤不重新执行(执行次数=1);running 且产物齐全的步骤按 attempt 判定
// 完成、不 rerun——Q1 验收第一条(WP3)。
func TestKilledAtSuperstepBoundarySideEffectsOnce(t *testing.T) {
backend := &perStepRecordingBackend{}
dir := t.TempDir()
eng := newAttemptTestEngine(t, backend, dir)
res, err := eng.Run(context.Background(), Goal{Text: "先跑完再中断", HitlMode: HitlAuto}, RunOptions{})
if err != nil || res.Status != RunCompleted {
t.Fatalf("setup run: %v %+v", err, res)
}
before := map[string]int{}
st, err := loadRunState(res.WorkDir)
if err != nil {
t.Fatal(err)
}
for _, s := range st.Plan.Workflow.Steps {
before[s.ID] = backend.countOf(filepath.Base(filepath.FromSlash(s.SubWorkspace)))
}
// 第二步停在 running(产物其实在盘上——首次运行真实写出的)。
flipToInterrupted(t, res.WorkDir, 1)
eng2 := newAttemptTestEngine(t, backend, dir)
res, err = eng2.Resume(context.Background(), res.RunID)
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("resume: %+v", res)
}
for _, s := range res.Plan.Steps {
if s.Status != "completed" && s.Status != "skipped" {
t.Fatalf("step %s not finished: %s", s.ID, s.Status)
}
got := backend.countOf(filepath.Base(filepath.FromSlash(s.SubWorkspace)))
if got != before[s.ID] {
t.Fatalf("step %s executed %d times after kill (before=%d)——已完成/running 步骤被重复执行", s.ID, got, before[s.ID])
}
}
}
// TestInterruptedMissingProductsRetries:running 崩溃且产物缺失时按 auto 一次重试(WP3)。
func TestInterruptedMissingProductsRetries(t *testing.T) {
backend := &perStepRecordingBackend{}
dir := t.TempDir()
eng := newAttemptTestEngine(t, backend, dir)
res, err := eng.Run(context.Background(), Goal{Text: "先跑完再中断", HitlMode: HitlAuto}, RunOptions{})
if err != nil || res.Status != RunCompleted {
t.Fatalf("setup run: %v %+v", err, res)
}
// 第二步停 running 并删掉其交付物(副作用未发生的形态)。
flipToInterrupted(t, res.WorkDir, 1)
st, err := loadRunState(res.WorkDir)
if err != nil {
t.Fatal(err)
}
sub := filepath.FromSlash(st.Plan.Workflow.Steps[1].SubWorkspace)
if err := os.Remove(filepath.Join(res.WorkDir, sub, "output.md")); err != nil {
t.Fatal(err)
}
eng2 := newAttemptTestEngine(t, backend, dir)
res, err = eng2.Resume(context.Background(), res.RunID)
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("resume: %+v", res)
}
got := backend.countOf(filepath.Base(sub))
if got != 2 {
t.Fatalf("missing-product step executed %d times, want 2(auto 一次重试)", got)
}
}
+113
View File
@@ -0,0 +1,113 @@
package squad
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// TestCheckpointFilesAtBoundaries:sync 默认档——每个 superstep 边界有快照,
// latest 指向最后一层且图指纹与重编译一致(Q1 WP4)。
func TestCheckpointFilesAtBoundaries(t *testing.T) {
eng, _ := newTestEngine(t, mockScriptPlanner(baseSteps()...), map[string]map[string]string{
"01_researcher": {"notes.md": goodReport, "fields.json": "{}"},
"02_writer": {"output.md": goodReport},
"03_reviewer": {"output.md": goodReport},
}, NopSink{})
res, err := eng.Run(context.Background(), Goal{Text: "快照"}, RunOptions{})
if err != nil || res.Status != RunCompleted {
t.Fatalf("run: %v %+v", err, res)
}
latest, err := FileStore{}.LoadLatestCheckpoint(res.WorkDir)
if err != nil || latest == nil {
t.Fatalf("latest checkpoint: %v", err)
}
if latest.Superstep < 3 {
t.Fatalf("superstep = %d, want >= 3(三步各占一层)", latest.Superstep)
}
g, err := compileGraph(res.Plan.Steps)
if err != nil {
t.Fatal(err)
}
if latest.GraphHash != g.hash() {
t.Fatalf("hash = %s, want %s", latest.GraphHash, g.hash())
}
if len(latest.StepStates) != 3 {
t.Fatalf("step states = %d", len(latest.StepStates))
}
if _, err := os.Stat(filepath.Join(res.WorkDir, "checkpoints", "001.json")); err != nil {
t.Fatalf("first boundary snapshot missing: %v", err)
}
}
// TestCheckpointAsyncAndOnExit:async 在退出前落完;on_exit 只有最终快照。
func TestCheckpointAsyncAndOnExit(t *testing.T) {
for _, mode := range []string{"async", "on_exit"} {
eng, _ := newTestEngine(t, mockScriptPlanner(baseSteps()...), map[string]map[string]string{
"01_researcher": {"notes.md": goodReport, "fields.json": "{}"},
"02_writer": {"output.md": goodReport},
"03_reviewer": {"output.md": goodReport},
}, NopSink{})
res, err := eng.Run(context.Background(), Goal{Text: "快照"}, RunOptions{CheckpointMode: mode})
if err != nil || res.Status != RunCompleted {
t.Fatalf("%s run: %v %+v", mode, err, res)
}
latest, err := FileStore{}.LoadLatestCheckpoint(res.WorkDir)
if err != nil || latest == nil {
t.Fatalf("%s latest: %v", mode, err)
}
if latest.Superstep < 3 {
t.Fatalf("%s superstep = %d", mode, latest.Superstep)
}
}
}
// TestGraphContinuityRejectsStructuralChange:崩溃期间图形态被改则拒绝恢复(WP1 裁定)。
func TestGraphContinuityRejectsStructuralChange(t *testing.T) {
eng, _ := newTestEngine(t, mockScriptPlanner(baseSteps()...), map[string]map[string]string{
"01_researcher": {"notes.md": goodReport, "fields.json": "{}"},
"02_writer": {"output.md": goodReport},
"03_reviewer": {"output.md": goodReport},
}, NopSink{})
dir := eng.opts.DataDir
res, err := eng.Run(context.Background(), Goal{Text: "先跑完再中断", HitlMode: HitlAuto}, RunOptions{})
if err != nil || res.Status != RunCompleted {
t.Fatalf("setup run: %v %+v", err, res)
}
// 翻回 running(仅状态变化,图结构不变——应先过连续性校验)。
st, err := loadRunState(res.WorkDir)
if err != nil {
t.Fatal(err)
}
st.Meta.Status = string(RunExecuting)
st.Meta.CompletedAt = nil
wf := st.Workflow()
wf.Status = "running"
wf.Steps[1].Status = "running"
wf.Steps[1].Attempts = 1
// 再改结构:把 s3 的 needs 改成另一个合法 id——编译能过但指纹必变。
wf.Steps[2].Needs = []string{"s1"}
st.setWorkflow(wf)
if err := st.save(); err != nil {
t.Fatal(err)
}
// 用一个新的引擎在同一目录上恢复(图编译本身合法:needs 引用存在的 id)。
reg := NewRoleRegistry()
for _, role := range []string{"researcher", "writer", "reviewer"} {
if err := reg.Register(RoleSpec{Role: role, Backend: "script"}); err != nil {
t.Fatal(err)
}
}
backends := NewBackendResolver()
backends.RegisterInstance("script", &scriptBackend{script: map[string]map[string]string{}})
eng2, err := NewEngine(Options{DataDir: dir, Registry: reg, Planner: eng.opts.Planner, Backends: backends, Sink: NopSink{}})
if err != nil {
t.Fatal(err)
}
_, err = eng2.Resume(context.Background(), res.RunID)
if err == nil || !strings.Contains(err.Error(), "图形态不一致") && !strings.Contains(err.Error(), "graph continuity") {
t.Fatalf("expected continuity rejection, got %v", err)
}
}
+158 -34
View File
@@ -35,6 +35,9 @@ type Options struct {
HitlPolicy HitlPolicy
// RepairBudget 质检失败自动修复次数(默认 1)。
RepairBudget int
// Store 运行状态持久化端口(Q1 WP4/WP5);nil 回落 FileStore。
// 注入 SQLiteStore 后运行状态进 SQLite(装配期一次,跨 run 一致)。
Store Store
// IntentGate 可选意图闸门:Run 入口一次确定性裁决(nil = 不启用,
// 行为与原实现一致)。见 intent.go;实现方为 squadintent 适配器。
IntentGate IntentGate
@@ -60,6 +63,31 @@ type engineDeps struct {
StepTimeout time.Duration
HitlPolicy HitlPolicy
IntentRunner IntentRunner
// Store 运行状态持久化端口(Q1 WP4);nil 回落 FileStore(装配期注入替换实现)。
Store Store
}
// storeOr 返回注入的 Store,缺省 FileStore。
func (d engineDeps) storeOr() Store {
if d.Store != nil {
return d.Store
}
return FileStore{}
}
// loadRun 经端口加载运行状态,并让它携带同一端口(后续 save 自然走同一实现)。
// runDir 是运行的工作区目录(所有 run 级 JSON 的根)。
func (e *SquadEngine) runDir(runID string) string {
return filepath.Join(e.opts.DataDir, "runs", runID)
}
func (e *SquadEngine) loadRun(wsDir string) (*RunState, error) {
st, err := e.deps.storeOr().LoadRun(wsDir)
if err != nil {
return nil, err
}
st.store = e.deps.storeOr()
return st, nil
}
// RunOptions 单次运行的可选项。
@@ -75,6 +103,17 @@ type RunOptions struct {
LeaderRole string `json:"leader_role,omitempty"`
// MaxLeaderTurns leader 模式每运行的 leader 轮次上限(默认 8,防失控)。
MaxLeaderTurns int `json:"max_leader_turns,omitempty"`
// CheckpointMode superstep 边界快照档位(Q1 WP4):sync(默认)| async | on_exit。
CheckpointMode string `json:"checkpoint_mode,omitempty"`
// Topology 显式拓扑名(Q2;优先于 Blueprint.Topology;空 = standard 图)。
// 未注册名 / primitive 单跑 / driver 未点亮均 fail-closed。
Topology string `json:"topology,omitempty"`
// Deadline 运行级截止时刻(Q2 long_running):superstep 边界检查,
// 超期把未完步骤置 skipped 并降级收口。零值 = 不设限。
Deadline time.Time `json:"deadline,omitempty"`
// MaxReplans leader 模式的重规划上限(Q2;与 MaxLeaderTurns 独立)。
// 0 = 默认 DefaultMaxReplans。
MaxReplans int `json:"max_replans,omitempty"`
}
// SquadEngine 小队引擎门面:Run / Respond / Resume / Inspect / ListRuns。
@@ -131,7 +170,7 @@ func NewEngine(opts Options) (*SquadEngine, error) {
Registry: opts.Registry, Backends: opts.Backends, Evaluator: opts.Evaluator,
Checker: opts.Checker, Sink: opts.Sink, Workspaces: ws,
StepTimeout: opts.StepTimeout, HitlPolicy: opts.HitlPolicy,
IntentRunner: opts.IntentRunner,
IntentRunner: opts.IntentRunner, Store: opts.Store,
}
return &SquadEngine{opts: opts, deps: deps, ws: ws, runLocks: map[string]*sync.Mutex{}}, nil
}
@@ -206,6 +245,19 @@ func (e *SquadEngine) Run(ctx context.Context, goal Goal, runOpts RunOptions) (*
meta.Metadata["max_leader_turns"] = fmt.Sprintf("%d", runOpts.MaxLeaderTurns)
}
}
if runOpts.CheckpointMode != "" {
meta.Metadata["checkpoint_mode"] = runOpts.CheckpointMode
}
if runOpts.Topology != "" {
meta.Metadata["topology"] = runOpts.Topology
}
if !runOpts.Deadline.IsZero() {
// RFC3339Nano:秒级 RFC3339 会截断亚秒精度,短截止会被立刻判超期。
meta.Metadata["deadline"] = runOpts.Deadline.UTC().Format(time.RFC3339Nano)
}
if runOpts.MaxReplans > 0 {
meta.Metadata["max_replans"] = fmt.Sprintf("%d", runOpts.MaxReplans)
}
e.deps.Sink.Emit(Event{Type: EvRunStarted, RunID: runID, Text: goal.Text, At: time.Now()})
// 意图闸门(可选,入口一次裁决;显式 TaskKey 优先,不重复过闸)。
@@ -239,12 +291,12 @@ func (e *SquadEngine) Run(ctx context.Context, goal Goal, runOpts RunOptions) (*
}
}
st := &runState{Meta: meta, Approved: map[string]bool{}, RepairBudgetRemaining: e.opts.RepairBudget}
st := &RunState{Meta: meta, Approved: map[string]bool{}, RepairBudgetRemaining: e.opts.RepairBudget, store: e.deps.storeOr()}
return e.planAndExecute(ctx, st, runOpts)
}
// planAndExecute 规划 → 挂起或执行;st 可为已有运行状态(澄清续跑复用)。
func (e *SquadEngine) planAndExecute(ctx context.Context, st *runState, runOpts RunOptions) (*RunResult, error) {
func (e *SquadEngine) planAndExecute(ctx context.Context, st *RunState, runOpts RunOptions) (*RunResult, error) {
drv := &flowDriver{opts: e.deps}
meta := &st.Meta
@@ -266,6 +318,10 @@ func (e *SquadEngine) planAndExecute(ctx context.Context, st *runState, runOpts
planOut = &PlanOutput{Plan: plan}
} else {
bpMatch, _ := e.opts.Blueprints.Match(meta.Goal.Text, runOpts.TaskKey)
// 拓扑解析(Q2):RunOptions 优先,Blueprint 兜底。
if meta.Metadata["topology"] == "" && bpMatch.Topology != "" {
meta.Metadata["topology"] = bpMatch.Topology
}
planOut, err = e.opts.Planner.Plan(ctx, PlanInput{
Goal: meta.Goal, Blueprint: bpPtr(bpMatch), Registry: e.opts.Registry, RunID: meta.ID,
IntentCatalog: e.opts.IntentCatalog,
@@ -299,7 +355,7 @@ func (e *SquadEngine) planAndExecute(ctx context.Context, st *runState, runOpts
Context: fmt.Sprintf("原因:%s\n问题:\n%s", planOut.Clarification.Reason, strings.Join(qs, "\n")),
CreatedAt: time.Now(), Status: "pending",
}
gate := &hitlGate{Request: *req, PrevStatus: RunPlanning}
gate := &HitlGate{Request: *req, PrevStatus: RunPlanning}
// 澄清挂起也需要工作区承载 pending.json。
if err := e.materializeWorkspace(meta, st, &SquadPlan{Workflow: WorkflowPlan{WorkflowID: NewPlanID(), Status: "pending", Steps: nil}}); err != nil {
return nil, err
@@ -339,7 +395,7 @@ func (e *SquadEngine) planAndExecute(ctx context.Context, st *runState, runOpts
CreatedAt: time.Now(), Status: "pending",
Reason: "plan",
}
gate := &hitlGate{Request: *req, Plan: planOut.Plan, PrevStatus: RunPlanning}
gate := &HitlGate{Request: *req, Plan: planOut.Plan, PrevStatus: RunPlanning}
if err := st.saveGate(gate); err != nil {
return nil, err
}
@@ -352,6 +408,20 @@ func (e *SquadEngine) planAndExecute(ctx context.Context, st *runState, runOpts
if err := e.materializeWorkspace(meta, st, planOut.Plan); err != nil {
return nil, err
}
// 拓扑校验与分发(Q2):未注册名 / primitive 单跑 / driver 未点亮 fail-closed;
// leader 拓扑映射到既有 Mode 委派循环(不新造执行面)。
if topo := meta.Metadata["topology"]; topo != "" {
kind, terr := checkTopology(topo)
if terr != nil {
return e.failNew(meta, terr)
}
if kind == TopologyMode && topo == TopologyLeader {
if meta.Metadata["mode"] == "" {
meta.Metadata["mode"] = "leader"
}
}
e.deps.Sink.Emit(Event{Type: EvPhase, RunID: meta.ID, Text: "拓扑 " + topo, At: time.Now()})
}
// leader-delegation 模式:忽略规划步骤,进 leader 委派循环。
if meta.Metadata["mode"] == "leader" {
e.initLeaderState(st)
@@ -373,7 +443,7 @@ func (e *SquadEngine) planAndExecute(ctx context.Context, st *runState, runOpts
}
// initLeaderState 按运行选项初始化 leader 循环状态。
func (e *SquadEngine) initLeaderState(st *runState) {
func (e *SquadEngine) initLeaderState(st *RunState) {
leaderRole := st.Meta.Metadata["leader_role"]
if leaderRole == "" {
if _, ok := findAgent(st.Plan.Squad.Agents, "leader"); ok {
@@ -386,7 +456,13 @@ func (e *SquadEngine) initLeaderState(st *runState) {
maxTurns = n
}
}
st.Leader = &LeaderState{LeaderRole: leaderRole, MaxTurns: maxTurns}
maxReplans := DefaultMaxReplans
if v := st.Meta.Metadata["max_replans"]; v != "" {
if n := parseIntDefault(v, DefaultMaxReplans); n > 0 {
maxReplans = n
}
}
st.Leader = &LeaderState{LeaderRole: leaderRole, MaxTurns: maxTurns, MaxReplans: maxReplans}
st.saveLeader()
}
@@ -402,12 +478,12 @@ func parseIntDefault(s string, def int) int {
}
// isLeaderRun 该运行是否处于 leader-delegation 模式。
func (e *SquadEngine) isLeaderRun(st *runState) bool {
func (e *SquadEngine) isLeaderRun(st *RunState) bool {
return st.Meta.Metadata["mode"] == "leader"
}
// resumeAfterHold 挂起解除后的统一续跑入口(按模式分发)。
func (e *SquadEngine) resumeAfterHold(ctx context.Context, st *runState) (*RunResult, error) {
func (e *SquadEngine) resumeAfterHold(ctx context.Context, st *RunState) (*RunResult, error) {
if e.isLeaderRun(st) {
out, gate, err := e.runLeaderLoop(ctx, st)
if err != nil {
@@ -428,16 +504,16 @@ func (e *SquadEngine) resumeAfterHold(ctx context.Context, st *runState) (*RunRe
}
// materializeWorkspace 落盘工作区与子工作区(已存在则只更新计划并重建待执行子目录)。
func (e *SquadEngine) materializeWorkspace(meta *RunMetadata, st *runState, plan *SquadPlan) error {
func (e *SquadEngine) materializeWorkspace(meta *RunMetadata, st *RunState, plan *SquadPlan) error {
if st.Meta.WorkDir == "" {
st.Meta = *meta
wsDir, err := e.ws.PrepareWorkspace(&st.Meta, plan)
_, err := e.ws.PrepareWorkspace(&st.Meta, plan)
if err != nil {
return err
}
st.Template = plan.Template
bb, _ := loadBlackboard(wsDir)
st.BB = *bb
// 新运行的黑板在内存初始化;持久化由后续 st.save() 经 Store 端口完成。
st.BB = BlackboardState{Fields: map[string]string{}}
} else {
// 复用既有工作区:磁盘黑板为权威(澄清续跑/计划更新场景)。
if bb, err := loadBlackboard(st.Meta.WorkDir); err == nil {
@@ -489,7 +565,7 @@ func (e *SquadEngine) Respond(ctx context.Context, runID string, decision Respon
func (e *SquadEngine) respondLocked(ctx context.Context, runID string, decision RespondDecision) (*RunResult, error) {
wsDir := filepath.Join(e.opts.DataDir, "runs", runID)
st, err := loadRunState(wsDir)
st, err := e.loadRun(wsDir)
if err != nil {
return nil, fmt.Errorf("load run %s: %w", runID, err)
}
@@ -509,6 +585,17 @@ func (e *SquadEngine) respondLocked(ctx context.Context, runID string, decision
}
req := &gate.Request
// 非 human actor 不得决议 choice 门(Q2 验收三的第二道防线:邮箱/代理
// 消息即便伪造 Respond 调用也清不掉 permission/confirmation/quality 门)。
if decision.Actor != "" && decision.Actor != ActorHuman && choiceHoldKind(req.Kind) &&
strings.TrimSpace(decision.Choice) != "" {
e.deps.Sink.Emit(Event{Type: EvPhase, RunID: runID,
Text: fmt.Sprintf("拒绝非人工 actor(%s) 决议 %s 门(请求 %s)", decision.Actor, req.Kind, req.ID), At: time.Now()})
return e.noteAndKeepHold(st, gate, RespondDecision{
RequestID: decision.RequestID,
Answer: fmt.Sprintf("[blocked] 非人工 actor(%s) 尝试决议本门,已拒绝;等待人工裁决。", decision.Actor),
})
}
if strings.TrimSpace(decision.Choice) == "" && strings.TrimSpace(decision.Answer) != "" && choiceHoldKind(req.Kind) {
return e.noteAndKeepHold(st, gate, decision)
}
@@ -543,7 +630,7 @@ func choiceHoldKind(kind HumanRequestKind) bool {
}
}
func (e *SquadEngine) noteAndKeepHold(st *runState, gate *hitlGate, decision RespondDecision) (*RunResult, error) {
func (e *SquadEngine) noteAndKeepHold(st *RunState, gate *HitlGate, decision RespondDecision) (*RunResult, error) {
if err := st.addSteering(decision.Answer); err != nil {
return nil, err
}
@@ -555,7 +642,7 @@ func (e *SquadEngine) noteAndKeepHold(st *runState, gate *hitlGate, decision Res
return heldResult(st, gate), nil
}
func clearSameGate(st *runState, requestID string) error {
func clearSameGate(st *RunState, requestID string) error {
current, err := loadGate(st.Meta.WorkDir)
if err != nil || current == nil || current.Request.ID != requestID {
return err
@@ -563,7 +650,7 @@ func clearSameGate(st *runState, requestID string) error {
return st.saveGate(nil)
}
func (e *SquadEngine) applyDecision(ctx context.Context, st *runState, gate *hitlGate, decision RespondDecision) (*RunResult, error) {
func (e *SquadEngine) applyDecision(ctx context.Context, st *RunState, gate *HitlGate, decision RespondDecision) (*RunResult, error) {
req := &gate.Request
now := time.Now()
drv := &flowDriver{opts: e.deps}
@@ -694,8 +781,17 @@ func (e *SquadEngine) applyDecision(ctx context.Context, st *runState, gate *hit
case "approve":
return e.manualPass(st, decision)
case "retry":
// 追加一次修复预算并重跑交付步骤。
// 追加一次修复预算并重跑交付步骤。累计追加有上限(Q26),
// 上限内才加——无上限的人工 retry 会把运行变成永动机。
term := e.terminationOf(st)
if st.RepairBudgetGranted >= term.MaxRepairGranted {
drv.emit(st, Event{Type: EvPhase, Text: fmt.Sprintf("人工修复追加已达上限 %d,不再追加(Q26)", term.MaxRepairGranted)})
return &RunResult{RunID: st.Meta.ID, Status: RunFailed, Plan: planPtr(st),
Error: fmt.Sprintf("repair budget grants exhausted (%d/%d)", st.RepairBudgetGranted, term.MaxRepairGranted),
WorkDir: st.Meta.WorkDir}, nil
}
st.RepairBudgetRemaining++
st.RepairBudgetGranted++
st.Meta.Status = string(RunExecuting)
_ = st.save()
deliverStepID := lastCompletedStepID(st)
@@ -722,7 +818,7 @@ func (e *SquadEngine) applyDecision(ctx context.Context, st *runState, gate *hit
}
// respondClarification 澄清回应:答案并入目标后重新规划。
func (e *SquadEngine) respondClarification(ctx context.Context, st *runState, gate *hitlGate, decision RespondDecision) (*RunResult, error) {
func (e *SquadEngine) respondClarification(ctx context.Context, st *RunState, gate *HitlGate, decision RespondDecision) (*RunResult, error) {
choice := strings.ToLower(decision.Choice)
if choice == "abort" {
return e.cancelRun(st, "人工中止(澄清阶段)"), nil
@@ -757,7 +853,7 @@ func (e *SquadEngine) respondClarification(ctx context.Context, st *runState, ga
}
// bootstrapMinimalSquad 注册通用最小编制(organizer/specialist/writer/leader)。
func (e *SquadEngine) bootstrapMinimalSquad(st *runState) {
func (e *SquadEngine) bootstrapMinimalSquad(st *RunState) {
backend := st.Meta.Backend
if backend == "" {
backend = e.opts.DefaultBackend
@@ -777,7 +873,7 @@ func (e *SquadEngine) bootstrapMinimalSquad(st *runState) {
}
// manualPass 人工放行质检:标记 ManualPass 并收口。
func (e *SquadEngine) manualPass(st *runState, decision RespondDecision) (*RunResult, error) {
func (e *SquadEngine) manualPass(st *RunState, decision RespondDecision) (*RunResult, error) {
report := e.deps.Checker.Check(CheckRequest{
RunID: st.Meta.ID, Workspace: st.Meta.WorkDir, Deliverable: "output.md",
Plan: planPtr(st), Squad: &st.Plan.Squad, Template: st.Template,
@@ -806,7 +902,7 @@ func (e *SquadEngine) manualPass(st *runState, decision RespondDecision) (*RunRe
Summary: summarize(st, *report, status) + "(质检人工放行)"}, nil
}
func (e *SquadEngine) cancelRun(st *runState, reason string) *RunResult {
func (e *SquadEngine) cancelRun(st *RunState, reason string) *RunResult {
now := time.Now()
st.Meta.Status = string(RunCancelled)
st.Meta.CompletedAt = &now
@@ -820,11 +916,11 @@ func (e *SquadEngine) cancelRun(st *runState, reason string) *RunResult {
}
// failStepResume 权限拒绝后的失败步骤处理(关键失败/非关键降级)。
func (d *flowDriver) failStepResume(ctx context.Context, st *runState, idx int) (*RunResult, *hitlGate, error) {
func (d *flowDriver) failStepResume(ctx context.Context, st *RunState, idx int) (*RunResult, *HitlGate, error) {
return d.failStep(ctx, st, idx)
}
func (e *SquadEngine) respondStepApproval(ctx context.Context, st *runState, req *HumanRequest, decision RespondDecision) (*RunResult, error) {
func (e *SquadEngine) respondStepApproval(ctx context.Context, st *RunState, req *HumanRequest, decision RespondDecision) (*RunResult, error) {
switch strings.ToLower(decision.Choice) {
case "approve":
st.Approved["step:"+req.StepID] = true
@@ -842,7 +938,7 @@ func (e *SquadEngine) respondStepApproval(ctx context.Context, st *runState, req
return e.resumeAfterHold(ctx, st)
}
func (e *SquadEngine) respondInterrupted(ctx context.Context, st *runState, req *HumanRequest, decision RespondDecision) (*RunResult, error) {
func (e *SquadEngine) respondInterrupted(ctx context.Context, st *RunState, req *HumanRequest, decision RespondDecision) (*RunResult, error) {
switch strings.ToLower(decision.Choice) {
case "retry":
if !markStep(st, req.StepID, "pending", "") {
@@ -862,7 +958,7 @@ func (e *SquadEngine) respondInterrupted(ctx context.Context, st *runState, req
return e.resumeAfterHold(ctx, st)
}
func markStep(st *runState, id, status, errText string) bool {
func markStep(st *RunState, id, status, errText string) bool {
for i := range st.Plan.Workflow.Steps {
if st.Plan.Workflow.Steps[i].ID != id {
continue
@@ -876,7 +972,7 @@ func markStep(st *runState, id, status, errText string) bool {
// recoverInterrupted 处理崩溃时停在 running 的步骤。
// interactive 挂起确认,不自动再执行;auto 允许一次重试;disabled 直接失败。
func (e *SquadEngine) recoverInterrupted(ctx context.Context, st *runState) (*RunResult, error) {
func (e *SquadEngine) recoverInterrupted(ctx context.Context, st *RunState) (*RunResult, error) {
for i := range st.Plan.Workflow.Steps {
step := st.Plan.Workflow.Steps[i]
if step.Status != "running" {
@@ -903,6 +999,29 @@ func (e *SquadEngine) recoverInterrupted(ctx context.Context, st *runState) (*Ru
out, _, err := drv.failStep(ctx, st, i)
return out, err
}
// Q1 WP3 产物校验:步骤在 running 崩溃,但其交付物已全部落盘——
// 副作用实际发生过,直接判定完成而不是重新执行(副作用次数=1)。
subDir := filepath.Join(st.Meta.WorkDir, filepath.FromSlash(orDefault(step.SubWorkspace, fmt.Sprintf("tasks/%02d_%s", i+1, step.Role))))
targets := step.Targets
if len(targets) == 0 {
targets = []string{"output.md"}
}
if missingTargets(subDir, targets) == nil {
step.Status = "completed"
step.Error = ""
st.Plan.Workflow.Steps[i] = step
st.mu.Lock()
_ = mergeStepArtifacts(&st.BB, subDir)
err := st.save()
st.mu.Unlock()
if err != nil {
return nil, err
}
drv := &flowDriver{opts: e.deps}
drv.emit(st, Event{Type: EvStepCompleted, StepID: step.ID, Role: step.Role,
Text: fmt.Sprintf("中断恢复:产物齐全,按 attempt %s 判定完成", step.AttemptID)})
continue
}
st.Plan.Workflow.Steps[i].Status = "pending"
if err := st.save(); err != nil {
return nil, err
@@ -933,7 +1052,7 @@ func (e *SquadEngine) Resume(ctx context.Context, runID string) (*RunResult, err
defer release()
wsDir := filepath.Join(e.opts.DataDir, "runs", runID)
st, err := loadRunState(wsDir)
st, err := e.loadRun(wsDir)
if err != nil {
return nil, fmt.Errorf("load run %s: %w", runID, err)
}
@@ -944,6 +1063,11 @@ func (e *SquadEngine) Resume(ctx context.Context, runID string) (*RunResult, err
if RunStatus(st.Meta.Status).Terminal() {
return e.Inspect(runID)
}
// 图连续性校验(Q1 WP4/WP1 裁定):崩溃期间的检查点图指纹与当前 Steps
// 重编译不一致 = 图形态被改过(动态调整或外力),拒绝恢复并提示重新规划。
if err := validateGraphContinuity(st); err != nil {
return nil, err
}
if out, err := e.recoverInterrupted(ctx, st); out != nil || err != nil {
return out, err
}
@@ -956,7 +1080,7 @@ func (e *SquadEngine) Inspect(runID string) (*RunResult, error) {
return nil, invalidID(runID)
}
wsDir := filepath.Join(e.opts.DataDir, "runs", runID)
st, err := loadRunState(wsDir)
st, err := e.loadRun(wsDir)
if err != nil {
return nil, fmt.Errorf("load run %s: %w", runID, err)
}
@@ -1003,7 +1127,7 @@ func (e *SquadEngine) ListRuns() ([]RunMetadata, error) {
if !ent.IsDir() {
continue
}
st, err := loadRunState(filepath.Join(runsDir, ent.Name()))
st, err := e.loadRun(filepath.Join(runsDir, ent.Name()))
if err != nil {
continue
}
@@ -1037,7 +1161,7 @@ func (e *SquadEngine) Steer(runID, text string) error {
}
defer release()
st, err := loadRunState(filepath.Join(e.opts.DataDir, "runs", runID))
st, err := e.loadRun(filepath.Join(e.opts.DataDir, "runs", runID))
if err != nil {
return fmt.Errorf("load run %s: %w", runID, err)
}
@@ -1061,7 +1185,7 @@ func (e *SquadEngine) SetBlackboardField(runID, key, value string) error {
}
defer release()
st, err := loadRunState(filepath.Join(e.opts.DataDir, "runs", runID))
st, err := e.loadRun(filepath.Join(e.opts.DataDir, "runs", runID))
if err != nil {
return fmt.Errorf("load run %s: %w", runID, err)
}
@@ -1143,7 +1267,7 @@ func (e *SquadEngine) fireWakeup(ctx context.Context, runID string) bool {
if err := writeJSON(filepath.Join(e.opts.DataDir, "runs", runID, "pending.json"), gate); err != nil {
return false
}
if gate.Request.WakeupFires >= MaxWakeupFires {
if gate.Request.WakeupFires >= e.terminationOf(nil).MaxWakeupFires {
_, err := e.respondLocked(ctx, runID, RespondDecision{RequestID: gate.Request.ID, Choice: "abort",
Answer: "自动唤醒次数达上限,自动中止"})
return err == nil
@@ -1248,7 +1372,7 @@ func appendAnswer(d RespondDecision) string {
return "(" + d.Answer + ")"
}
func lastCompletedStepID(st *runState) string {
func lastCompletedStepID(st *RunState) string {
id := ""
for _, s := range st.Plan.Workflow.Steps {
if s.Status == "completed" {
+253
View File
@@ -0,0 +1,253 @@
package squad
import (
"fmt"
"hash/fnv"
"strings"
)
// graph 是一次执行图:由权威 Steps 现场编译(Steps 仍是唯一真相源,
// 动态调整改 Steps 后下一轮自然生效)。只携带调度所需的派生信息:
// 依赖、写集与可执行分层。
type graph struct {
needs map[string][]string // step id → 依赖 id(含相邻 Parallel 兼容映射产生的)
order []string // 声明序
writes map[string][]string // step id → 写集
}
// compileGraph 编译步骤图为调度图。规则:
// - 声明 Needs 的步骤:依赖即其 Needs(未知引用/环 fail-closed)。
// - 未声明 Needs 的步骤:保持现状语义——相邻 Parallel=true 的步骤同层
// (依赖 = 上一个「非本组」步骤),非 Parallel 步骤依赖前一个步骤。
// - 混合图允许:Needs 提供剪枝,未声明处保持线性。
func compileGraph(steps []StepSpec) (*graph, error) {
g := &graph{
needs: map[string][]string{},
order: make([]string, 0, len(steps)),
writes: map[string][]string{},
}
ids := map[string]bool{}
for _, s := range steps {
if s.ID == "" {
return nil, fmt.Errorf("graph: 存在空 id 的步骤")
}
if ids[s.ID] {
return nil, fmt.Errorf("graph: 步骤 id 重复:%s", s.ID)
}
ids[s.ID] = true
}
prevNonGroup := -1 // 上一个「非本 Parallel 组」的步骤索引
for i, s := range steps {
g.order = append(g.order, s.ID)
g.writes[s.ID] = append([]string(nil), s.Writes...)
needsDecl := len(s.Needs) > 0
switch {
case needsDecl:
for _, n := range s.Needs {
if !ids[n] {
return nil, fmt.Errorf("graph: 步骤 %s 的 needs 引用未知步骤 %s", s.ID, n)
}
if n == s.ID {
return nil, fmt.Errorf("graph: 步骤 %s 的 needs 引用自身", s.ID)
}
}
g.needs[s.ID] = append([]string(nil), s.Needs...)
prevNonGroup = i
case s.Parallel:
// 相邻 Parallel 组:依赖上一个组外步骤(没有则无依赖)。
if prevNonGroup >= 0 {
g.needs[s.ID] = []string{steps[prevNonGroup].ID}
}
// Parallel 步骤不推进 prevNonGroup:相邻同伴同层。
default:
// 非 Parallel:依赖紧邻的前一步(与旧线性扫描的执行序一致——
// 整组 Parallel 完成后才轮到它,而不是只等组外前一步)。
if i > 0 {
g.needs[s.ID] = []string{steps[i-1].ID}
}
prevNonGroup = i
}
}
if cycle := g.findCycle(); cycle != nil {
return nil, fmt.Errorf("graph: needs 依赖成环:%s", strings.Join(cycle, " → "))
}
// 循环步与路由步校验(Q2):预算必须显式,引用必须存在,两者互斥
//(同一步既循环又分支的语义未定义,fail-closed)。
for _, s := range steps {
if s.Loop != nil && len(s.Branches) > 0 {
return nil, fmt.Errorf("graph: 步骤 %s 不得同时声明 loop 与 branches", s.ID)
}
if s.Loop != nil {
if s.Loop.MaxIterations <= 0 {
return nil, fmt.Errorf("graph: 步骤 %s 的 loop.max_iterations 必须 > 0", s.ID)
}
for _, b := range s.Loop.Body {
if !ids[b] {
return nil, fmt.Errorf("graph: 步骤 %s 的 loop.body 引用未知步骤 %s", s.ID, b)
}
if b == s.ID {
return nil, fmt.Errorf("graph: 步骤 %s 的 loop.body 引用自身", s.ID)
}
}
}
for _, br := range s.Branches {
if br.When.Field == "" {
return nil, fmt.Errorf("graph: 步骤 %s 的分支缺少 when.field", s.ID)
}
if br.When.Equals == "" && br.When.NotEquals == "" {
return nil, fmt.Errorf("graph: 步骤 %s 的分支 when 需要 equals 或 not_equals", s.ID)
}
if len(br.Then) == 0 {
return nil, fmt.Errorf("graph: 步骤 %s 的分支 then 为空", s.ID)
}
for _, t := range br.Then {
if !ids[t] {
return nil, fmt.Errorf("graph: 步骤 %s 的分支 then 引用未知步骤 %s", s.ID, t)
}
if t == s.ID {
return nil, fmt.Errorf("graph: 步骤 %s 的分支 then 引用自身", s.ID)
}
}
}
}
return g, nil
}
// findCycle 报告一条依赖环(没有则 nil)。
func (g *graph) findCycle() []string {
const (
white = iota
gray
black
)
color := map[string]int{}
var stack []string
var visit func(id string) []string
visit = func(id string) []string {
if color[id] == gray {
return append(stack, id)
}
if color[id] == black {
return nil
}
color[id] = gray
stack = append(stack, id)
for _, n := range g.needs[id] {
if c := visit(n); c != nil {
return c
}
}
stack = stack[:len(stack)-1]
color[id] = black
return nil
}
for _, id := range g.order {
if c := visit(id); c != nil {
return c
}
}
return nil
}
// layer 是一个 superstep 的可执行集合:seq 为有写集冲突需按声明序串行的
// 步骤索引,par 为可并行的步骤索引。先执行 par 组(runParallel 语义),
// 再逐个执行 seq(含动态调整),与现状「并行组先于后续顺序步骤」一致。
type layer struct {
par []int
seq []int
}
// stepPending 报告步骤是否仍待执行。蓝图登记的步骤不带 status(空串),
// 旧线性扫描将其视为可执行——这里与之一致:空串等同 pending。
func stepPending(status string) bool {
return status == "" || status == "pending" || status == "running"
}
// nextLayer 计算当前可执行层:状态为 pending/running 且全部依赖已「满足」。
// 依赖满足 = completed/skipped/failed——failed 视为满足与现状「非关键失败
// 降级继续」的线性扫描一致(关键失败时运行已终止,不会走到这里)。
// 无可执行步骤时返回 (layer{}, false):可能全部完成,也可能调度卡死
// (由调用方用 pendingCount 区分)。
func (g *graph) nextLayer(steps []StepSpec) (layer, bool) {
idxOf := map[string]int{}
for i, s := range steps {
idxOf[s.ID] = i
}
satisfied := func(id string) bool {
st := steps[idxOf[id]].Status
return st == "completed" || st == "skipped" || st == "failed"
}
var out layer
for i, s := range steps {
if !stepPending(s.Status) {
continue
}
ready := true
for _, n := range g.needs[s.ID] {
if !satisfied(n) {
ready = false
break
}
}
if !ready {
continue
}
if g.conflictsWithEarlier(out, i, steps) {
out.seq = append(out.seq, i)
} else {
out.par = append(out.par, i)
}
}
return out, len(out.par)+len(out.seq) > 0
}
// conflictsWithEarlier 报告步骤 i 的写集与本层中更早的可执行步骤相交。
func (g *graph) conflictsWithEarlier(l layer, i int, steps []StepSpec) bool {
wi := g.writes[steps[i].ID]
if len(wi) == 0 {
return false
}
earlier := append(append([]int(nil), l.par...), l.seq...)
for _, j := range earlier {
for _, w := range g.writes[steps[j].ID] {
for _, v := range wi {
if w == v {
return true
}
}
}
}
return false
}
// pendingCount 统计仍未终结(pending/running/空串)的步骤数。
func pendingCount(steps []StepSpec) int {
n := 0
for _, s := range steps {
if stepPending(s.Status) {
n++
}
}
return n
}
// hash 是图结构指纹:声明序、依赖与写集的稳定散列。
// 恢复连续性校验用它比对崩溃前后的图形态(Q1 WP4;WP1 的图版本裁定落点)。
func (g *graph) hash() string {
h := fnv.New64a()
for _, id := range g.order {
h.Write([]byte(id))
h.Write([]byte{0})
for _, n := range g.needs[id] {
h.Write([]byte(">"))
h.Write([]byte(n))
}
h.Write([]byte{1})
for _, w := range g.writes[id] {
h.Write([]byte("w"))
h.Write([]byte(w))
}
h.Write([]byte{2})
}
return fmt.Sprintf("%016x", h.Sum64())
}
+139
View File
@@ -0,0 +1,139 @@
package squad
import (
"strings"
"testing"
)
func stepsOf(specs ...StepSpec) []StepSpec {
out := make([]StepSpec, len(specs))
copy(out, specs)
return out
}
func TestCompileGraphLinearAndAdjacentParallel(t *testing.T) {
steps := stepsOf(
StepSpec{ID: "a", Status: "pending"},
StepSpec{ID: "b", Status: "pending", Parallel: true},
StepSpec{ID: "c", Status: "pending", Parallel: true},
StepSpec{ID: "d", Status: "pending"},
)
g, err := compileGraph(steps)
if err != nil {
t.Fatal(err)
}
// 线性链:b/c 同层依赖 a,d 依赖 c。
if len(g.needs["a"]) != 0 {
t.Fatalf("a needs = %v", g.needs["a"])
}
if len(g.needs["b"]) != 1 || g.needs["b"][0] != "a" || g.needs["c"][0] != "a" {
t.Fatalf("parallel needs = %v %v", g.needs["b"], g.needs["c"])
}
if len(g.needs["d"]) != 1 || g.needs["d"][0] != "c" {
t.Fatalf("d needs = %v", g.needs["d"])
}
// 首轮可执行:只有 a。
layer, ok := g.nextLayer(steps)
if !ok || len(layer.par) != 1 || layer.par[0] != 0 || len(layer.seq) != 0 {
t.Fatalf("first layer = %+v", layer)
}
// a 完成后:b、c 同层并行。
steps[0].Status = "completed"
layer, ok = g.nextLayer(steps)
if !ok || len(layer.par) != 2 || layer.par[0] != 1 || layer.par[1] != 2 {
t.Fatalf("second layer = %+v", layer)
}
}
func TestCompileGraphNeedsPruneAndMixed(t *testing.T) {
steps := stepsOf(
StepSpec{ID: "a", Status: "pending"},
StepSpec{ID: "b", Status: "pending"},
StepSpec{ID: "c", Status: "pending", Needs: []string{"a"}},
)
g, err := compileGraph(steps)
if err != nil {
t.Fatal(err)
}
// a 完成后:b(线性依赖 a)与 c(needs a)同层。
steps[0].Status = "completed"
layer, ok := g.nextLayer(steps)
if !ok || len(layer.par) != 2 {
t.Fatalf("layer = %+v", layer)
}
// b 失败(非关键降级)后 c 仍按 needs 调度(与线性扫描的降级继续一致)。
steps[1].Status = "failed"
layer, ok = g.nextLayer(steps)
if !ok || len(layer.par)+len(layer.seq) == 0 {
t.Fatalf("after b failed: layer = %+v", layer)
}
}
func TestCompileGraphRejectsUnknownAndCycleAndDup(t *testing.T) {
if _, err := compileGraph(stepsOf(
StepSpec{ID: "a", Status: "pending", Needs: []string{"ghost"}},
)); err == nil || !strings.Contains(err.Error(), "未知步骤") {
t.Fatalf("unknown ref: %v", err)
}
if _, err := compileGraph(stepsOf(
StepSpec{ID: "a", Status: "pending", Needs: []string{"b"}},
StepSpec{ID: "b", Status: "pending", Needs: []string{"a"}},
)); err == nil || !strings.Contains(err.Error(), "成环") {
t.Fatalf("cycle: %v", err)
}
if _, err := compileGraph(stepsOf(
StepSpec{ID: "a", Status: "pending"},
StepSpec{ID: "a", Status: "pending"},
)); err == nil || !strings.Contains(err.Error(), "重复") {
t.Fatalf("dup: %v", err)
}
if _, err := compileGraph(stepsOf(
StepSpec{ID: "a", Status: "pending", Needs: []string{"a"}},
)); err == nil || !strings.Contains(err.Error(), "自身") {
t.Fatalf("self ref: %v", err)
}
}
func TestWriteSetConflictSerializes(t *testing.T) {
steps := stepsOf(
StepSpec{ID: "z", Status: "completed"},
StepSpec{ID: "a", Status: "pending", Parallel: true, Writes: []string{"report.md"}},
StepSpec{ID: "b", Status: "pending", Parallel: true, Writes: []string{"report.md"}},
StepSpec{ID: "c", Status: "pending", Parallel: true, Writes: []string{"notes.md"}},
StepSpec{ID: "d", Status: "pending", Parallel: true},
)
// 全部首轮可执行(无依赖):b 与 a 冲突 → b 串行;c、d 无冲突 → 并行。
g, err := compileGraph(steps)
if err != nil {
t.Fatal(err)
}
layer, ok := g.nextLayer(steps)
if !ok {
t.Fatal("no layer")
}
if len(layer.seq) != 1 || layer.seq[0] != 2 {
t.Fatalf("seq = %v", layer.seq)
}
if len(layer.par) != 3 || layer.par[0] != 1 || layer.par[1] != 3 || layer.par[2] != 4 {
t.Fatalf("par = %v", layer.par)
}
}
func TestFailedDependencyStillSchedules(t *testing.T) {
// 与线性扫描的「非关键失败降级继续」一致:依赖 failed 仍视为满足。
steps := stepsOf(
StepSpec{ID: "b", Status: "failed"},
StepSpec{ID: "a", Status: "pending", Needs: []string{"b"}},
)
g, err := compileGraph(steps)
if err != nil {
t.Fatal(err)
}
layer, ok := g.nextLayer(steps)
if !ok || len(layer.par) != 1 || layer.par[0] != 1 {
t.Fatalf("failed dependency should still schedule: %+v", layer)
}
if pendingCount(steps) != 1 {
t.Fatalf("pending = %d", pendingCount(steps))
}
}
+13 -2
View File
@@ -105,8 +105,19 @@ type RespondDecision struct {
Choice string `json:"choice,omitempty"`
// EditPlan 确认计划时的修改指令(附加在 Answer 上传递给引擎)。
EditPlan string `json:"edit_plan,omitempty"`
// Actor 决议发起方(Q2):"" 或 human = 人工(默认,兼容既有调用方);
// agent/system = 非人工。非人工 actor 的 choice 决议在
// permission/confirmation/quality_review 门上一律被拒绝(验收三)。
Actor string `json:"actor,omitempty"`
}
// Actor 归属常量。
const (
ActorHuman = "human"
ActorAgent = "agent"
ActorSystem = "system"
)
// newRequestID 生成请求 ID。
func newRequestID() string {
b := make([]byte, 8)
@@ -136,8 +147,8 @@ func expiredDecision(req HumanRequest, policy HitlPolicy, now time.Time) (Respon
return RespondDecision{RequestID: req.ID, Choice: choice, Answer: "expired"}, true
}
// hitlGate 引擎内部:一次挂起的完整上下文(落盘 pending.json)。
type hitlGate struct {
// HitlGate 引擎内部:一次挂起的完整上下文(落盘 pending.json)。
type HitlGate struct {
Request HumanRequest `json:"request"`
Plan *SquadPlan `json:"plan,omitempty"` // confirmation 时携带候选计划
Steps []StepSpec `json:"steps,omitempty"` // adjustment:建议追加的步骤
+122 -16
View File
@@ -13,7 +13,7 @@ import (
// leaderExecRequest 构造 leader 轮次的执行请求:与标准步骤同等装配
// (过程事件桥、ToolProfile/Skills/工具白名单、执行标识与预算)——
// 修平此前 leader 轮丢弃 OnEvent 与 ToolProfile 的缺口。
func leaderExecRequest(drv *flowDriver, st *runState, leader RoleSpec, workDir, prompt, instructions string, targets []string, timeout time.Duration) ExecRequest {
func leaderExecRequest(drv *flowDriver, st *RunState, leader RoleSpec, workDir, prompt, instructions string, targets []string, timeout time.Duration) ExecRequest {
stepID := fmt.Sprintf("leader_turn_%d", st.Leader.Turns)
var budget *ExecBudget
if timeout > 0 {
@@ -47,12 +47,34 @@ func leaderExecRequest(drv *flowDriver, st *runState, leader RoleSpec, workDir,
// DefaultMaxLeaderTurns leader 模式每运行的 leader 轮次上限。
const DefaultMaxLeaderTurns = 8
// DefaultMaxReplans leader 卡顿触发的重规划上限(Q2;与轮次上限独立)。
const DefaultMaxReplans = 3
// DefaultStuckThreshold 连续无进展轮数达到该值触发一次重规划(Q2)。
const DefaultStuckThreshold = 2
// LeaderState leader 循环状态(workspace leader.json 持久化,重启可恢复)。
type LeaderState struct {
Turns int `json:"turns"`
MaxTurns int `json:"max_turns"`
LeaderRole string `json:"leader_role"`
Delegations []DelegationRecord `json:"delegations"`
// 进度账本(Q2):每轮委派后记一条进展评估;卡顿检测与重规划的凭据。
Progress []ProgressEntry `json:"progress,omitempty"`
// StuckTurns 连续无进展轮数(有进展即清零)。
StuckTurns int `json:"stuck_turns,omitempty"`
// Replans 已触发的重规划次数;MaxReplans 触顶降级收口。
Replans int `json:"replans,omitempty"`
MaxReplans int `json:"max_replans,omitempty"`
// ReplanNote 一次性重规划指令(并入下一轮 leader 任务书后清空)。
ReplanNote string `json:"replan_note,omitempty"`
}
// ProgressEntry 是进度账本的一条评估记录。
type ProgressEntry struct {
Turn int `json:"turn"`
Signal string `json:"signal"` // progress | stuck
Detail string `json:"detail,omitempty"`
}
// DelegationRecord 一次已执行的委派(历史注入下一轮 leader 上下文)。
@@ -80,22 +102,24 @@ type delegation struct {
const leaderSubWorkspace = "tasks/00_leader"
func (st *runState) loadLeader() {
func (st *RunState) loadLeader() {
if st.Leader != nil {
return
}
st.Leader = &LeaderState{MaxTurns: DefaultMaxLeaderTurns}
data, err := os.ReadFile(filepath.Join(st.Meta.WorkDir, "leader.json"))
if err == nil {
data, err := st.storeOr().LoadLeader(st.Meta.WorkDir)
if err == nil && data != nil {
_ = json.Unmarshal(data, st.Leader)
}
}
func (st *runState) saveLeader() {
func (st *RunState) saveLeader() {
if st.Leader == nil {
return
}
_ = writeJSON(filepath.Join(st.Meta.WorkDir, "leader.json"), st.Leader)
if data, err := json.Marshal(st.Leader); err == nil {
_ = st.storeOr().SaveLeader(st.Meta.WorkDir, data)
}
}
// leaderPrompt 组装 leader 的系统指令(协调契约 + 通用守则)。
@@ -132,7 +156,7 @@ func leaderPrompt(members []RoleSpec, catalogMd string) string {
}
// leaderTaskBrief 组装 leader 本轮的 TASK.md(目标 + 黑板 + 委派历史)。
func leaderTaskBrief(st *runState) string {
func leaderTaskBrief(st *RunState, mail []MailMessage) string {
var b strings.Builder
b.WriteString("# Leader 轮次:评估并委派\n\n")
fmt.Fprintf(&b, "## 运行目标\n%s\n\n", st.Meta.Goal.Text)
@@ -169,13 +193,28 @@ func leaderTaskBrief(st *runState) string {
} else {
b.WriteString("(尚无委派,这是第一轮。)\n\n")
}
if len(st.Leader.Progress) > 0 {
b.WriteString("## 进度账本\n")
for _, p := range st.Leader.Progress {
fmt.Fprintf(&b, "- 第%d轮 [%s] %s\n", p.Turn, p.Signal, p.Detail)
}
fmt.Fprintf(&b, "- 已重规划 %d/%d 次\n\n", st.Leader.Replans, st.Leader.MaxReplans)
}
if st.Leader.ReplanNote != "" {
fmt.Fprintf(&b, "%s\n\n", st.Leader.ReplanNote)
}
if section := formatMailSection(mail); section != "" {
b.WriteString(strings.TrimPrefix(section, "\n\n"))
b.WriteString("\n")
}
b.WriteString("## 本轮产出要求\n\n写 delegation.json(结构见你的指令)到本子目录。\n")
return b.String()
}
// runLeaderLoop leader-delegation 主循环:委派→执行→唤醒,直到
// close/failed/上限/挂起(escalation/gap/权限等由 HITL 处理后重入本函数)。
func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResult, *hitlGate, error) {
func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *RunState) (*RunResult, *HitlGate, error) {
st.loadLeader()
drv := &flowDriver{opts: e.deps}
leader, ok := findAgent(st.Plan.Squad.Agents, st.Leader.LeaderRole)
@@ -204,7 +243,8 @@ func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResu
}
_ = snapshotContextInto(st.Meta.WorkDir, subDir)
for st.Leader.Turns < st.Leader.MaxTurns {
term := e.terminationOf(st)
for st.Leader.Turns < term.MaxLeaderTurns {
// HITL:leader 角色权限升级(与标准模式同语义)。
if leader.BashPermission == "ask" && !st.Approved["role:"+leader.Role] {
if drv.policy(st).mode() != HitlInteractive {
@@ -220,7 +260,7 @@ func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResu
},
CreatedAt: time.Now(), Status: "pending",
}
gate := &hitlGate{Request: *req, PrevStatus: RunExecuting}
gate := &HitlGate{Request: *req, PrevStatus: RunExecuting}
if err := st.saveGate(gate); err == nil {
st.Meta.Status = string(RunWaitingHuman)
_ = st.save()
@@ -230,9 +270,20 @@ func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResu
}
// 每轮重写 leader 上下文(黑板/委派历史已变化)。
if err := os.WriteFile(filepath.Join(subDir, "TASK.md"), []byte(leaderTaskBrief(st)), 0o644); err != nil {
// 邮箱消息与重规划指令是一次性的:并入本轮任务书后清空并落盘。
st.mu.Lock()
leaderMail := takeMailFor(st, st.Leader.LeaderRole)
st.mu.Unlock()
if err := os.WriteFile(filepath.Join(subDir, "TASK.md"), []byte(leaderTaskBrief(st, leaderMail)), 0o644); err != nil {
return nil, nil, err
}
if len(leaderMail) > 0 {
_ = st.save()
}
if st.Leader.ReplanNote != "" {
st.Leader.ReplanNote = ""
st.saveLeader()
}
if err := os.WriteFile(filepath.Join(subDir, "AGENTS.md"), []byte(leaderPrompt(members, e.opts.IntentCatalog.intentCatalogMd())), 0o644); err != nil {
return nil, nil, err
}
@@ -246,7 +297,7 @@ func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResu
if err != nil {
return e.leaderFail(st, err.Error()), nil, nil
}
prompt := readFileOr(filepath.Join(subDir, "TASK.md"), leaderTaskBrief(st))
prompt := readFileOr(filepath.Join(subDir, "TASK.md"), leaderTaskBrief(st, nil))
prompt = st.injectSteering(prompt)
instructions := readFileOr(filepath.Join(subDir, "AGENTS.md"), leaderPrompt(members, e.opts.IntentCatalog.intentCatalogMd()))
result, execErr := backend.Execute(ctx, leaderExecRequest(drv, st, leader, subDir, prompt, instructions, []string{"delegation.json"}, e.deps.StepTimeout))
@@ -292,7 +343,7 @@ func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResu
},
CreatedAt: time.Now(), Status: "pending",
}
gate := &hitlGate{Request: *req, PrevStatus: RunExecuting}
gate := &HitlGate{Request: *req, PrevStatus: RunExecuting}
if err := st.saveGate(gate); err == nil {
st.Meta.Status = string(RunWaitingHuman)
_ = st.save()
@@ -335,6 +386,7 @@ func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResu
memberBrief += "\n\n## Leader 补充指令\n" + dec.Briefing
_ = os.WriteFile(filepath.Join(st.Meta.WorkDir, filepath.FromSlash(step.SubWorkspace), "TASK.md"), []byte(memberBrief), 0o644)
}
factsBefore := len(st.BB.Facts)
out, gate, err := drv.runOneStep(ctx, st, idx)
if err != nil {
return nil, nil, err
@@ -352,6 +404,50 @@ func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResu
return out, gate, nil // 挂起(gap/权限等),Respond 后重入循环
}
st.Leader.Delegations = append(st.Leader.Delegations, rec)
// 进度账本(Q2):委派完成且有新事实、或不是与上轮同题重复 → 有进展。
factsGrew := len(st.BB.Facts) > factsBefore
sameAsPrev := false
if n := len(st.Leader.Delegations); n >= 2 {
prev := st.Leader.Delegations[n-2]
sameAsPrev = prev.Member == rec.Member && prev.Title == rec.Title
}
if factsGrew || !sameAsPrev {
st.Leader.StuckTurns = 0
st.Leader.Progress = append(st.Leader.Progress, ProgressEntry{
Turn: rec.Turn, Signal: "progress",
Detail: fmt.Sprintf("%s:%s(新事实 %v)", rec.Member, rec.Title, factsGrew),
})
} else {
st.Leader.StuckTurns++
st.Leader.Progress = append(st.Leader.Progress, ProgressEntry{
Turn: rec.Turn, Signal: "stuck",
Detail: fmt.Sprintf("与上轮同题重复且无新事实(连续 %d 轮)", st.Leader.StuckTurns),
})
}
// 卡顿 → 重规划;重规划触顶 → 降级收口(与轮次上限同款 Q23 语义)。
if st.Leader.StuckTurns >= DefaultStuckThreshold {
st.Leader.StuckTurns = 0
st.Leader.Replans++
if st.Leader.Replans >= st.Leader.MaxReplans {
st.saveLeader()
drv.emit(st, Event{Type: EvPhase, Text: fmt.Sprintf(
"重规划达上限 %d,按现有产出降级收口(Q2)", st.Leader.MaxReplans)})
out2, gate2, err2 := drv.finalize(ctx, st)
if err2 != nil {
return nil, nil, err2
}
if gate2 != nil {
return heldResult(st, gate2), gate2, nil
}
return out2, nil, nil
}
st.Leader.ReplanNote = fmt.Sprintf(
"【重规划指令】连续 %d 轮无进展(同题重复且无新事实),已触发第 %d/%d 次重规划。"+
"本轮必须改变策略:换成员、把任务拆小、补充缺失输入,或 escalate 问人;不得原样重发上一次委派。",
DefaultStuckThreshold, st.Leader.Replans, st.Leader.MaxReplans)
drv.emit(st, Event{Type: EvPhase, Text: fmt.Sprintf(
"卡顿检测:触发重规划 %d/%d", st.Leader.Replans, st.Leader.MaxReplans)})
}
st.saveLeader()
// 成员交付快照进 leader inbox(leader 工具沙箱看不到成员目录,
// 须物化到 leader 工作区才能自查交付——InputLayoutSnapshot 的对称应用)。
@@ -368,11 +464,21 @@ func (e *SquadEngine) runLeaderLoop(ctx context.Context, st *runState) (*RunResu
return e.leaderFail(st, fmt.Sprintf("leader 输出了未知 action %q", dec.Action)), nil, nil
}
}
return e.leaderFail(st, fmt.Sprintf("leader 轮次达上限 %d(防失控护栏),运行停止;可提高 MaxLeaderTurns 或人工介入", st.Leader.MaxTurns)), nil, nil
// Q23:达上限不再裸失败——按现有产出走 finalize 降级收口(质检/汇总路径与正常收口一致)。
drv2 := &flowDriver{opts: e.deps}
drv2.emit(st, Event{Type: EvPhase, Text: fmt.Sprintf("leader 轮次达上限 %d,按现有产出降级收口(Q23)", term.MaxLeaderTurns)})
out, gate2, err := drv2.finalize(ctx, st)
if err != nil {
return nil, nil, err
}
if gate2 != nil {
return heldResult(st, gate2), gate2, nil
}
return out, nil, nil
}
// leaderFail 统一的 leader 模式失败收口。
func (e *SquadEngine) leaderFail(st *runState, reason string) *RunResult {
func (e *SquadEngine) leaderFail(st *RunState, reason string) *RunResult {
now := time.Now()
st.Meta.Status = string(RunFailed)
st.Meta.CompletedAt = &now
@@ -386,7 +492,7 @@ func (e *SquadEngine) leaderFail(st *runState, reason string) *RunResult {
}
// snapshotDeliverablesToLeader 把成员交付文件复制进 leader 工作区 inbox/<步骤id>/。
func snapshotDeliverablesToLeader(st *runState, step StepSpec) error {
func snapshotDeliverablesToLeader(st *RunState, step StepSpec) error {
srcDir := filepath.Join(st.Meta.WorkDir, filepath.FromSlash(step.SubWorkspace))
dstDir := filepath.Join(st.Meta.WorkDir, filepath.FromSlash(leaderSubWorkspace), "inbox", step.ID)
for _, t := range step.Targets {
+356
View File
@@ -0,0 +1,356 @@
package squad
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// leader_mailbox_conformance_test.go — Q2 WP2 验收:leader 进度账本/重规划
// 上限、mailbox 投递、验收三「mailbox 消息不能把挂起的权限批准掉」。
// ---- leader 进度账本与重规划 ----
// 同题重复委派且无新事实 → 卡顿计数 → 触发重规划(事件+账本+一次性指令),
// leader 收到指令后 close,运行完成且 Replans=1。
func TestLeaderLedgerStuckTriggersReplan(t *testing.T) {
b := &leaderScriptBackend{
decisions: []string{
delegateJSON("writer", "同一件事"), // 第1轮:有进展(首委派)
delegateJSON("writer", "同一件事"), // 第2轮:同题无新事实 → stuck 1
delegateJSON("writer", "同一件事"), // 第3轮:stuck 2 → 重规划
closeJSON, // 第4轮:收到重规划指令后收口
},
script: map[string]map[string]string{
"01_writer": {"output.md": goodReport},
"02_writer": {"output.md": goodReport},
"03_writer": {"output.md": goodReport},
},
prompts: map[string][]string{},
}
sink := &collectSink{}
engine := newLeaderEngineWithSink(t, b, sink)
res, err := engine.Run(context.Background(), Goal{Text: "写一份报告"}, RunOptions{Mode: "leader"})
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("status = %s err = %v", res.Status, res.Error)
}
st, err := engine.loadRun(engine.runDir(res.RunID))
if err != nil {
t.Fatal(err)
}
st.loadLeader()
if st.Leader.Replans != 1 {
t.Fatalf("Replans = %d,期望 1", st.Leader.Replans)
}
var stuck, progress int
for _, p := range st.Leader.Progress {
switch p.Signal {
case "stuck":
stuck++
case "progress":
progress++
}
}
if stuck != 2 || progress != 1 {
t.Fatalf("账本 progress=%d stuck=%d,期望 1/2", progress, stuck)
}
if sink.countText("触发重规划 1/3") != 1 {
t.Fatal("缺重规划事件")
}
// 重规划指令一次性并入下一轮 leader 任务书。
var sawNote bool
for _, p := range b.prompts["00_leader"] {
if strings.Contains(p, "重规划指令") {
sawNote = true
}
}
if !sawNote {
t.Fatal("leader 未收到重规划指令")
}
}
// 重规划触顶(MaxReplans=1)→ 走 finalize 收口路径(与 Q23 轮次上限同款:
// 不裸失败;终态取决于既有产出),并发出触顶事件、账本记账、不再进 leader 轮。
func TestLeaderReplanCapFinalizes(t *testing.T) {
b := &leaderScriptBackend{
decisions: []string{
delegateJSON("writer", "同一件事"),
delegateJSON("writer", "同一件事"),
delegateJSON("writer", "同一件事"), // stuck 2 → Replans=1 >= cap → 收口
closeJSON, // 不应到达
},
script: map[string]map[string]string{
"01_writer": {"output.md": goodReport},
"02_writer": {"output.md": goodReport},
"03_writer": {"output.md": goodReport},
},
}
sink := &collectSink{}
engine := newLeaderEngineWithSink(t, b, sink)
res, err := engine.Run(context.Background(), Goal{Text: "写一份报告"}, RunOptions{Mode: "leader", MaxReplans: 1})
if err != nil {
t.Fatal(err)
}
switch res.Status {
case RunCompleted, RunDegraded, RunQualityReview:
default:
t.Fatalf("重规划触顶应走 finalize 收口而非 %s(err=%v)", res.Status, res.Error)
}
if sink.countText("重规划达上限 1") != 1 {
t.Fatal("缺触顶事件")
}
st, err := engine.loadRun(engine.runDir(res.RunID))
if err != nil {
t.Fatal(err)
}
st.loadLeader()
if st.Leader.Replans != 1 || st.Leader.MaxReplans != 1 {
t.Fatalf("Replans=%d MaxReplans=%d,期望 1/1", st.Leader.Replans, st.Leader.MaxReplans)
}
if b.turn > 3 {
t.Fatalf("触顶后不应再进 leader 轮(turn=%d)", b.turn)
}
}
func newLeaderEngineWithSink(t *testing.T, backend Executor, sink ProgressSink) *SquadEngine {
t.Helper()
dir := t.TempDir()
reg := NewRoleRegistry()
for _, r := range []RoleSpec{
{Role: "leader", Name: "主管", Backend: "leader-script", Skills: []string{"协调"}},
{Role: "writer", Name: "撰写", Backend: "leader-script", Skills: []string{"撰写"}},
} {
if err := reg.Register(r); err != nil {
t.Fatal(err)
}
}
backends := NewBackendResolver()
backends.RegisterInstance("leader-script", backend)
engine, err := NewEngine(Options{DataDir: dir, Registry: reg, Backends: backends, Sink: sink})
if err != nil {
t.Fatal(err)
}
return engine
}
// ---- mailbox:投递 + 验收三 ----
// 挂起(gap)期间投递 → Respond 恢复 → 下一步骤任务书含消息;广播 "*" 同样到达;
// 已执行完的步骤不被追投;定向消息只投递一次。
func TestMailboxDeliveredAfterHoldIntoNextStep(t *testing.T) {
rec := &promptRecordingBackend{prompts: map[string][]string{}}
engine := newRecordingEngine(t, rec, gapSteps())
res, err := engine.Run(context.Background(), Goal{Text: "带缺口"}, RunOptions{})
if err != nil {
t.Fatal(err)
}
if res.Status != RunWaitingHuman || res.Pending == nil {
t.Fatalf("应挂起等人工:%s", res.Status)
}
// 挂起期间投递(run 锁空闲)。
if err := engine.PostMessage(context.Background(), res.RunID, MailMessage{
From: "researcher", To: "writer", Text: "重点写第二节",
}); err != nil {
t.Fatal(err)
}
if err := engine.PostMessage(context.Background(), res.RunID, MailMessage{
From: "leader", To: "*", Text: "全体注意格式",
}); err != nil {
t.Fatal(err)
}
// 解决 gap 续跑。
res2, err := engine.Respond(context.Background(), res.RunID, RespondDecision{
RequestID: res.Pending.ID, Answer: "缺口已补",
})
if err != nil {
t.Fatal(err)
}
if res2.Status != RunCompleted {
t.Fatalf("恢复后应完成:%s %v", res2.Status, res2.Error)
}
var writerPrompt string
for _, p := range rec.prompts["02_writer"] {
writerPrompt += p
}
if !strings.Contains(writerPrompt, "重点写第二节") {
t.Fatalf("writer 未收到定向消息:%q", writerPrompt)
}
if !strings.Contains(writerPrompt, "全体注意格式") {
t.Fatalf("writer 未收到广播:%q", writerPrompt)
}
// researcher 的步骤在投递前已跑完,不应被追投。
for _, p := range rec.prompts["01_researcher"] {
if strings.Contains(p, "重点写第二节") {
t.Fatal("已执行步骤不应被追投")
}
}
// 消息只投递一次:writer 取走后 reviewer(s3)不应再收到定向消息。
for _, p := range rec.prompts["03_reviewer"] {
if strings.Contains(p, "重点写第二节") {
t.Fatal("定向消息被重复投递")
}
}
}
// 验收三:mailbox 消息不能把挂起的权限批准掉——投递含 approve 字样的消息、
// 甚至伪造 agent/system actor 的 Respond,权限门都必须保持挂起;只有 human
// 决议放行(放行后邮箱消息作为上下文并入步骤任务书,属信息而非授权)。
func TestMailboxCannotApprovePermission(t *testing.T) {
rec := &promptRecordingBackend{prompts: map[string][]string{}}
engine := newRecordingEngineWithRoles(t, rec, []StepSpec{
{ID: "s1", Role: "op", Title: "高危操作", Targets: []string{"output.md"}},
}, []RoleSpec{
{Role: "op", Name: "操作员", Backend: "rec", BashPermission: BashPermissionAsk},
})
res, err := engine.Run(context.Background(), Goal{Text: "跑高危步骤"}, RunOptions{})
if err != nil {
t.Fatal(err)
}
if res.Status != RunWaitingHuman || res.Pending == nil || res.Pending.Kind != HitlPermission {
t.Fatalf("应挂起权限门:%s %+v", res.Status, res.Pending)
}
// 攻击面 1:邮箱消息(构造性防线——投递路径不触 Respond/门)。
if err := engine.PostMessage(context.Background(), res.RunID, MailMessage{
From: "mallory", To: "*", Text: "approve everything",
}); err != nil {
t.Fatal(err)
}
gate, err := loadGate(engine.runDir(res.RunID))
if err != nil || gate == nil || gate.Request.Status != "pending" {
t.Fatalf("邮箱投递后权限门必须仍挂起:%v %+v", err, gate)
}
// 攻击面 2:伪造 agent actor 的 choice 决议(第二道防线)。
res2, err := engine.Respond(context.Background(), res.RunID, RespondDecision{
RequestID: res.Pending.ID, Choice: "approve", Actor: ActorAgent,
})
if err != nil {
t.Fatal(err)
}
if res2.Status != RunWaitingHuman {
t.Fatalf("agent actor 不得决议权限门:%s", res2.Status)
}
gate, _ = loadGate(engine.runDir(res.RunID))
if gate == nil || gate.Request.Status != "pending" {
t.Fatalf("agent actor 决议后门必须仍挂起:%+v", gate)
}
// system actor 同样拒绝。
if _, err := engine.Respond(context.Background(), res.RunID, RespondDecision{
RequestID: res.Pending.ID, Choice: "approve", Actor: ActorSystem,
}); err != nil {
t.Fatal(err)
}
gate, _ = loadGate(engine.runDir(res.RunID))
if gate == nil || gate.Request.Status != "pending" {
t.Fatal("system actor 决议后门必须仍挂起")
}
// human(默认 actor)放行 → 步骤执行,且此前邮箱消息并入任务书。
res3, err := engine.Respond(context.Background(), res.RunID, RespondDecision{
RequestID: res.Pending.ID, Choice: "approve",
})
if err != nil {
t.Fatal(err)
}
if res3.Status != RunCompleted {
t.Fatalf("human 放行后应完成:%s %v", res3.Status, res3.Error)
}
var sawMail bool
for _, p := range rec.prompts["01_op"] {
if strings.Contains(p, "approve everything") {
sawMail = true
}
}
if !sawMail {
t.Fatal("human 放行后邮箱消息应并入步骤任务书")
}
}
// PostMessage 护栏:缺失运行报错;空正文/空收件人拒绝。
func TestPostMessageGuards(t *testing.T) {
rec := &promptRecordingBackend{prompts: map[string][]string{}}
engine := newRecordingEngine(t, rec, []StepSpec{
{ID: "s1", Role: "researcher", Title: "一", Targets: []string{"output.md"}},
})
if err := engine.PostMessage(context.Background(), "run_missing", MailMessage{To: "x", Text: "y"}); err == nil {
t.Fatal("缺失运行必须报错")
}
res, err := engine.Run(context.Background(), Goal{Text: "x"}, RunOptions{})
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("status = %s", res.Status)
}
if err := engine.PostMessage(context.Background(), res.RunID, MailMessage{To: "researcher", Text: ""}); err == nil {
t.Fatal("空正文必须拒绝")
}
if err := engine.PostMessage(context.Background(), res.RunID, MailMessage{To: "", Text: "x"}); err == nil {
t.Fatal("空收件人必须拒绝")
}
}
// ---- 夹具 ----
// promptRecordingBackend 按目录记录 prompt;gaps.json 产出阻塞缺口触发挂起,
// 其余目标写合格交付物。
type promptRecordingBackend struct {
prompts map[string][]string
}
func (b *promptRecordingBackend) Name() string { return "rec" }
func (b *promptRecordingBackend) Execute(_ context.Context, req ExecRequest) (*ExecResult, error) {
key := filepath.Base(filepath.Clean(req.WorkDir))
b.prompts[key] = append(b.prompts[key], req.Prompt)
patches := map[string][]byte{}
for _, t := range req.Targets {
content := goodReport
switch t {
case "gaps.json":
content = `[{"id":"g1","item":"缺一个输入","owner":"human","blocking":true}]`
case "fields.json":
content = `{}`
}
out := filepath.Join(req.WorkDir, t)
if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil {
return nil, err
}
if err := os.WriteFile(out, []byte(content), 0o644); err != nil {
return nil, err
}
patches[t] = []byte(content)
}
return &ExecResult{Success: true, Patches: patches}, nil
}
func newRecordingEngine(t *testing.T, be Executor, steps []StepSpec) *SquadEngine {
t.Helper()
return newRecordingEngineWithRoles(t, be, steps, []RoleSpec{
{Role: "researcher", Name: "调研", Backend: "rec"},
{Role: "writer", Name: "撰写", Backend: "rec"},
{Role: "reviewer", Name: "审核", Backend: "rec"},
})
}
func newRecordingEngineWithRoles(t *testing.T, be Executor, steps []StepSpec, roles []RoleSpec) *SquadEngine {
t.Helper()
dir := t.TempDir()
reg := NewRoleRegistry()
for _, r := range roles {
if err := reg.Register(r); err != nil {
t.Fatal(err)
}
}
backends := NewBackendResolver()
backends.RegisterInstance("rec", be)
engine, err := NewEngine(Options{DataDir: dir, Registry: reg,
Planner: mockScriptPlanner(steps...), Backends: backends, Sink: NopSink{}})
if err != nil {
t.Fatal(err)
}
return engine
}
+7 -2
View File
@@ -200,8 +200,13 @@ func TestLeaderModeTurnCapGuard(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if res.Status != RunFailed || !strings.Contains(res.Error, "上限") {
t.Fatalf("want turn-cap failure, got %s err=%s", res.Status, res.Error)
// Q23:达上限走 finalize 降级收口(completed/degraded/质检挂起),
// 不再是「运行停止」的裸失败。
if res.Status == RunFailed && strings.Contains(res.Error, "运行停止") {
t.Fatalf("Q23 closeout should not be a bare failure, got %s err=%s", res.Status, res.Error)
}
if res.Status != RunCompleted && res.Status != RunDegraded && res.Status != RunQualityReview {
t.Fatalf("Q23 closeout status = %s err=%s", res.Status, res.Error)
}
if b.turn < 3 {
t.Fatalf("leader should have run %d turns, ran %d", 3, b.turn)
+92
View File
@@ -0,0 +1,92 @@
package squad
import (
"context"
"fmt"
"strings"
"time"
)
// mailbox.go — 邮箱原语(Q2 WP2):运行内点对点消息。
// 安全边界(验收三的构造性保证):投递路径永不经过 Respond/gate——
// 消息只在步骤启动时并入任务书;挂起中的人工门(permission/confirmation/
// quality_review)不可能被邮箱消息决议。RespondDecision.Actor 提供
// 第二道防线:非 human actor 的 choice 决议一律拒绝。
// MailMessage 是一条运行内消息。To 是角色 key,"*" = 广播给之后的每个步骤。
type MailMessage struct {
ID string `json:"id"`
From string `json:"from"`
To string `json:"to"`
Text string `json:"text"`
At time.Time `json:"at"`
Delivered bool `json:"delivered,omitempty"`
}
// PostMessage 向一个运行投递邮箱消息。运行执行中(锁被占)返回 ErrRunBusy
// ——挂起等待人工时与回合间隙可投递。消息随 RunState 持久化,重启不丢。
// 本方法不触碰任何 HITL 门(验收三:邮箱永不决议挂起的审批)。
func (e *SquadEngine) PostMessage(ctx context.Context, runID string, msg MailMessage) error {
if strings.TrimSpace(msg.Text) == "" {
return fmt.Errorf("mailbox: 消息正文为空")
}
if strings.TrimSpace(msg.To) == "" {
return fmt.Errorf("mailbox: 收件人必填(角色 key 或 *)")
}
release, err := e.acquire(ctx, runID)
if err != nil {
return err
}
defer release()
wsDir := e.runDir(runID)
st, err := e.loadRun(wsDir)
if err != nil {
return fmt.Errorf("load run %s: %w", runID, err)
}
if msg.ID == "" {
msg.ID = newRequestID()
}
if msg.At.IsZero() {
msg.At = time.Now()
}
st.mu.Lock()
st.Mailbox = append(st.Mailbox, msg)
err = st.save()
st.mu.Unlock()
if err != nil {
return err
}
e.deps.Sink.Emit(Event{Type: EvPhase, RunID: runID, Text: fmt.Sprintf("邮箱消息 %s → %s", msg.From, msg.To), At: time.Now()})
return nil
}
// takeMailFor 取出发给某角色的未投递消息(含广播),标记已投递。
// 调用方负责随后 st.save()(或在临界区内)。
func takeMailFor(st *RunState, role string) []MailMessage {
var out []MailMessage
for i := range st.Mailbox {
m := &st.Mailbox[i]
if m.Delivered {
continue
}
if m.To != role && m.To != "*" {
continue
}
m.Delivered = true
out = append(out, *m)
}
return out
}
// formatMailSection 渲染任务书里的邮箱段(空则返回空串)。
func formatMailSection(msgs []MailMessage) string {
if len(msgs) == 0 {
return ""
}
var b strings.Builder
b.WriteString("\n\n## 邮箱消息\n")
for _, m := range msgs {
fmt.Fprintf(&b, "- [%s] %s:%s\n", m.At.Format(time.RFC3339), m.From, m.Text)
}
return b.String()
}
+50 -4
View File
@@ -66,9 +66,12 @@ type Blueprint struct {
Title string `json:"title"`
Match []string `json:"match,omitempty"` // 关键词命中即视为命中模板
Description string `json:"description,omitempty"`
Agents []RoleSpec `json:"agents,omitempty"` // 默认编制(引用已注册角色或内联角色)
Steps []StepSpec `json:"steps"`
Template string `json:"template,omitempty"` // 交付物骨架模板(Markdown)
// Topology 声明模板的拓扑(Q2;空 = standard 图行为)。
// RunOptions.Topology 优先于本字段。
Topology string `json:"topology,omitempty"`
Agents []RoleSpec `json:"agents,omitempty"` // 默认编制(引用已注册角色或内联角色)
Steps []StepSpec `json:"steps"`
Template string `json:"template,omitempty"` // 交付物骨架模板(Markdown)
}
// PlanningMode 规划模式。
@@ -88,10 +91,16 @@ type StepSpec struct {
Mode string `json:"mode,omitempty"` // 预留
Parallel bool `json:"parallel"`
Needs []string `json:"needs,omitempty"`
// Writes 写集:本步骤会写入的工件相对路径(调度依据)。
// 同一 superstep 内写集相交的步骤强制串行,不相交才可并行(Q1 WP1)。
Writes []string `json:"writes,omitempty"`
Targets []string `json:"targets,omitempty"` // 期望交付物相对路径,缺省 output.md
Status string `json:"status"` // pending, running, completed, failed, skipped
// Attempts 该步骤进入 running 的次数。中断恢复用它决定 auto 策略是否还能重试。
Attempts int `json:"attempts,omitempty"`
Attempts int `json:"attempts,omitempty"`
// AttemptID 当前这次尝试的稳定标识:runID/stepID/N(N=Attempts)。
// 执行事件、产物与副作用记录都挂它;瞬态重试共享同一 AttemptID(Q1 WP3)。
AttemptID string `json:"attempt_id,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
Error string `json:"error,omitempty"`
// RequiresApproval 为 true 时,该步骤启动前进入 HITL 计划确认。
@@ -109,6 +118,43 @@ type StepSpec struct {
Skills []string `json:"skills,omitempty"`
// MinScore 质检总分下限。0 = 不额外设门槛,只看 Checker.Passed。
MinScore int `json:"min_score,omitempty"`
// Loop 非空 = 循环步(Q2 loop 拓扑):完成后条件不满足且预算未尽时
// 重置为 pending 再武装(图不允许环,循环由引擎再武装实现)。
Loop *LoopSpec `json:"loop,omitempty"`
// LoopRuns 已再武装次数(引擎维护,随计划持久化)。
LoopRuns int `json:"loop_runs,omitempty"`
// Branches 非空 = 路由步(Q2 router 拓扑):完成后按黑板字段判定,
// 未选中分支的目标步骤置 skipped(skipped=依赖已满足,join 步照常推进)。
Branches []Branch `json:"branches,omitempty"`
// Handoff 非空 = 完成即把最终答案所有权移交给该角色(Q2 handoff 原语)。
Handoff string `json:"handoff,omitempty"`
}
// LoopSpec 是循环步的预算与停机条件(Q2)。
type LoopSpec struct {
// MaxIterations 再武装上限(必须 >0;触顶即停,带 loop_exhausted 事件)。
MaxIterations int `json:"max_iterations"`
// UntilField 停机判据的黑板字段名;空 = 只按 MaxIterations 迭代。
UntilField string `json:"until_field,omitempty"`
// UntilEquals 停机值:Fields[UntilField] == UntilEquals 时停。
UntilEquals string `json:"until_equals,omitempty"`
// Body 与本步一起再武装的其他步骤 ID(循环体;如 evaluator-optimizer
// 的评估步)。空 = 只再武装本步。
Body []string `json:"body,omitempty"`
}
// Branch 是路由步的一条分支(Q2)。When 按声明序取首个命中。
type Branch struct {
When BranchCond `json:"when"`
// Then 是本分支保留的步骤 ID(其余分支目标置 skipped)。
Then []string `json:"then"`
}
// BranchCond 是分支判据:黑板字段等值/不等值。
type BranchCond struct {
Field string `json:"field"`
Equals string `json:"equals,omitempty"`
NotEquals string `json:"not_equals,omitempty"`
}
// IsCritical 报告步骤是否关键(nil 视为关键)。
+11 -6
View File
@@ -64,12 +64,17 @@ type ExecBudget struct {
// ProcessEvent 是过程帧。
type ProcessEvent struct {
Type string
Text string
Tool string
Detail string
PromptTokens int
CompletionTokens int
Type string
Text string
Tool string
Detail string
PromptTokens int
CompletionTokens int
// 以下在 Type=usage 时填写(N3 WP6:上一请求与缓存命中拆分)。
LastPromptTokens int
LastCompletionTokens int
CacheReadTokens int
CacheWriteTokens int
}
// ExecResult 是一次步骤执行的终态。
+45 -17
View File
@@ -10,9 +10,9 @@ import (
"time"
)
// runState 引擎内部运行状态(磁盘即权威:workspace.json / workflow.json /
// RunState 引擎内部运行状态(磁盘即权威:workspace.json / workflow.json /
// squad.json / blackboard.json / pending.json 全部落盘,进程重启可恢复)。
type runState struct {
type RunState struct {
Meta RunMetadata `json:"meta"`
Plan SquadPlan `json:"plan"`
BB BlackboardState `json:"bb"`
@@ -21,19 +21,35 @@ type runState struct {
Approved map[string]bool `json:"approved,omitempty"`
// RepairBudgetRemaining 质检失败后的自动重跑剩余次数。
RepairBudgetRemaining int `json:"repair_budget_remaining,omitempty"`
// RepairBudgetGranted 人工 retry 累计追加次数(Q26 上限判定用)。
RepairBudgetGranted int `json:"repair_budget_granted,omitempty"`
// Clarifications 已澄清问答(追加进 Goal 上下文)。
Clarifications []string `json:"clarifications,omitempty"`
// Steering 运行中人工补充指令(在下一步骤边界注入后清空)。
Steering []string `json:"steering,omitempty"`
// Mailbox 运行内点对点消息(Q2):随 RunState 持久化;只在步骤启动时
// 并入任务书,永不触碰 HITL 门。
Mailbox []MailMessage `json:"mailbox,omitempty"`
// Usage 按角色累计的 token 用量。
Usage map[string]*Usage `json:"usage,omitempty"`
// Leader leader-delegation 模式的循环状态(workspace 内 leader.json 持久化)。
Leader *LeaderState `json:"-"`
// store 运行状态持久化端口(Q1 WP4);nil 回落 FileStore(现状文件态)。
// 替换实现(如 SQLiteStore)在引擎装配期注入。
store Store `json:"-"`
// mu 保护并行步骤对共享状态(黑板/save/steering/usage)的变更。
mu sync.Mutex `json:"-"`
}
func (st *runState) policy() HitlPolicy {
// storeOr 返回注入的 Store,缺省 FileStore。
func (st *RunState) storeOr() Store {
if st.store != nil {
return st.store
}
return FileStore{}
}
func (st *RunState) policy() HitlPolicy {
return mergeHitlPolicy(HitlPolicy{}, st.Meta.HitlPolicyOf())
}
@@ -49,8 +65,14 @@ func (m RunMetadata) HitlPolicyOf() *HitlPolicy {
return p
}
func (st *runState) save() error {
func (st *RunState) save() error {
st.Meta.UpdatedAt = time.Now()
return st.storeOr().SaveRun(st)
}
// persist 是 FileStore 语义的低层落盘(全部写文件)。Store.SaveRun 调它;
// RunState.save 走 Store 端口,替换实现(SQLiteStore)在装配期注入后自然接管。
func (st *RunState) persist() error {
if err := writeJSON(filepath.Join(st.Meta.WorkDir, "workspace.json"), &st.Meta); err != nil {
return err
}
@@ -71,24 +93,28 @@ func (st *runState) save() error {
return writeJSON(filepath.Join(st.Meta.WorkDir, "runstate.json"), diskRunState{
Approved: st.Approved,
RepairBudgetRemaining: st.RepairBudgetRemaining,
RepairBudgetGranted: st.RepairBudgetGranted,
Clarifications: st.Clarifications,
Mailbox: st.Mailbox,
})
}
type diskRunState struct {
Approved map[string]bool `json:"approved,omitempty"`
RepairBudgetRemaining int `json:"repair_budget_remaining,omitempty"`
RepairBudgetGranted int `json:"repair_budget_granted,omitempty"`
Clarifications []string `json:"clarifications,omitempty"`
Mailbox []MailMessage `json:"mailbox,omitempty"`
}
// Workflow 返回计划的编排清单(简洁访问器)。
func (st *runState) Workflow() WorkflowPlan { return st.Plan.Workflow }
func (st *RunState) Workflow() WorkflowPlan { return st.Plan.Workflow }
// setWorkflow 写回编排清单。
func (st *runState) setWorkflow(wf WorkflowPlan) { st.Plan.Workflow = wf }
func (st *RunState) setWorkflow(wf WorkflowPlan) { st.Plan.Workflow = wf }
// saveGate 落盘 HITL 挂起上下文(pending.json)。
func (st *runState) saveGate(gate *hitlGate) error {
func (st *RunState) saveGate(gate *HitlGate) error {
if gate == nil {
err := os.Remove(filepath.Join(st.Meta.WorkDir, "pending.json"))
if os.IsNotExist(err) {
@@ -100,8 +126,8 @@ func (st *runState) saveGate(gate *hitlGate) error {
}
// loadRunState 从工作区恢复运行状态。
func loadRunState(wsDir string) (*runState, error) {
st := &runState{}
func loadRunState(wsDir string) (*RunState, error) {
st := &RunState{}
if err := readJSON(filepath.Join(wsDir, "workspace.json"), &st.Meta); err != nil {
return nil, fmt.Errorf("load workspace.json: %w", err)
}
@@ -131,7 +157,9 @@ func loadRunState(wsDir string) (*runState, error) {
st.Approved = disk.Approved
}
st.RepairBudgetRemaining = disk.RepairBudgetRemaining
st.RepairBudgetGranted = disk.RepairBudgetGranted
st.Clarifications = disk.Clarifications
st.Mailbox = disk.Mailbox
} else if !os.IsNotExist(err) {
return nil, err
}
@@ -143,7 +171,7 @@ func loadRunState(wsDir string) (*runState, error) {
}
// loadGate 恢复挂起上下文;无挂起返回 nil。
func loadGate(wsDir string) (*hitlGate, error) {
func loadGate(wsDir string) (*HitlGate, error) {
data, err := os.ReadFile(filepath.Join(wsDir, "pending.json"))
if err != nil {
if os.IsNotExist(err) {
@@ -151,7 +179,7 @@ func loadGate(wsDir string) (*hitlGate, error) {
}
return nil, err
}
gate := &hitlGate{}
gate := &HitlGate{}
if err := json.Unmarshal(data, gate); err != nil {
return nil, fmt.Errorf("parse pending.json: %w", err)
}
@@ -167,7 +195,7 @@ func readJSON(path string, v any) error {
}
// setStep 并行安全地回填步骤状态(与 save 的全量 marshal 互斥)。
func (st *runState) setStep(idx int, s StepSpec) {
func (st *RunState) setStep(idx int, s StepSpec) {
st.mu.Lock()
st.Plan.Workflow.Steps[idx] = s
st.mu.Unlock()
@@ -175,7 +203,7 @@ func (st *runState) setStep(idx int, s StepSpec) {
// injectSteering 把挂起的运行中人工补充指令追加到 prompt(下一步骤边界注入),
// 注入后清空并落盘。注入发生在步骤开始前,不会污染正在执行的步骤。
func (st *runState) injectSteering(prompt string) string {
func (st *RunState) injectSteering(prompt string) string {
st.mu.Lock()
defer st.mu.Unlock()
if len(st.Steering) == 0 {
@@ -194,7 +222,7 @@ func (st *runState) injectSteering(prompt string) string {
}
// addSteering 追加一条尚未注入的人工补充,并立刻落盘。
func (st *runState) addSteering(text string) error {
func (st *RunState) addSteering(text string) error {
text = strings.TrimSpace(text)
if text == "" {
return nil
@@ -206,7 +234,7 @@ func (st *runState) addSteering(text string) error {
}
// loadSteering 恢复未消费的补充指令。
func (st *runState) loadSteering() {
func (st *RunState) loadSteering() {
data, err := os.ReadFile(filepath.Join(st.Meta.WorkDir, "steering.json"))
if err != nil {
return
@@ -218,7 +246,7 @@ func (st *runState) loadSteering() {
}
// addUsage 累计角色用量。
func (st *runState) addUsage(role string, promptTokens, completionTokens int) {
func (st *RunState) addUsage(role string, promptTokens, completionTokens int) {
if promptTokens == 0 && completionTokens == 0 {
return
}
@@ -238,7 +266,7 @@ func (st *runState) addUsage(role string, promptTokens, completionTokens int) {
}
// usageSnapshot 输出用量快照(值拷贝)。
func (st *runState) usageSnapshot() map[string]Usage {
func (st *RunState) usageSnapshot() map[string]Usage {
if len(st.Usage) == 0 {
return nil
}
+212
View File
@@ -0,0 +1,212 @@
package squad
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
)
// Store 是运行状态持久化端口(Q1 WP4):run/gate/checkpoint 的读写以
// 运行工作区为键。现状文件态收编为 FileStore(行为与此前逐文件直写完全一致);
// SQLite 实现进 adapters/sqlite(WP5)。事件流仍归 store/eventsink(子包),
// 不在本端口内重复。
type Store interface {
SaveRun(st *RunState) error
LoadRun(wsDir string) (*RunState, error)
SaveGate(wsDir string, gate *HitlGate) error
LoadGate(wsDir string) (*HitlGate, error)
SaveCheckpoint(wsDir string, cp Checkpoint) error
LoadLatestCheckpoint(wsDir string) (*Checkpoint, error)
// SaveLeader/LoadLeader 持久化 leader 循环状态(raw JSON bytes;
// 文件态即 leader.json)。LoadLeader 不存在时返回 (nil, nil)。
SaveLeader(wsDir string, data []byte) error
LoadLeader(wsDir string) ([]byte, error)
}
// FileStore 把 runs/<id>/ 目录布局呈现为 Store(现状文件态)。
type FileStore struct{}
func (FileStore) SaveRun(st *RunState) error {
return st.persist()
}
func (FileStore) LoadRun(wsDir string) (*RunState, error) {
return loadRunState(wsDir)
}
func (FileStore) SaveGate(wsDir string, gate *HitlGate) error {
st := &RunState{}
st.Meta.WorkDir = wsDir
return st.saveGate(gate)
}
func (FileStore) LoadGate(wsDir string) (*HitlGate, error) {
return loadGate(wsDir)
}
func (FileStore) SaveLeader(wsDir string, data []byte) error {
return os.WriteFile(filepath.Join(wsDir, "leader.json"), data, 0o644)
}
func (FileStore) LoadLeader(wsDir string) ([]byte, error) {
data, err := os.ReadFile(filepath.Join(wsDir, "leader.json"))
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
return data, nil
}
func (FileStore) SaveCheckpoint(wsDir string, cp Checkpoint) error {
dir := filepath.Join(wsDir, "checkpoints")
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
path := filepath.Join(dir, fmt.Sprintf("%03d.json", cp.Superstep))
if err := writeJSON(path, cp); err != nil {
return err
}
return writeJSON(filepath.Join(dir, "latest.json"), cp)
}
func (FileStore) LoadLatestCheckpoint(wsDir string) (*Checkpoint, error) {
data, err := os.ReadFile(filepath.Join(wsDir, "checkpoints", "latest.json"))
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var cp Checkpoint
if err := json.Unmarshal(data, &cp); err != nil {
return nil, fmt.Errorf("parse latest checkpoint: %w", err)
}
return &cp, nil
}
// Checkpoint 是一个 superstep 边界的状态快照(Q1 WP4)。
// GraphHash 是图结构指纹:恢复时与当前 Steps 重编译比对,不一致说明崩溃
// 期间图形态被改过(动态调整或外力),按 WP1 裁定拒绝恢复并提示重新规划。
type Checkpoint struct {
Superstep int `json:"superstep"`
At time.Time `json:"at"`
GraphHash string `json:"graph_hash"`
StepStates []StepSnapshot `json:"steps"`
wsDir string `json:"-"`
}
// write 立即同步落盘(经当前 Store 端口——SQLite 后端时进数据库)。
func (cp Checkpoint) write(store Store) error {
return store.SaveCheckpoint(cp.wsDir, cp)
}
// StepSnapshot 是检查点里的单步快照。
type StepSnapshot struct {
ID string `json:"id"`
Status string `json:"status"`
AttemptID string `json:"attempt_id,omitempty"`
}
// CheckpointMode 快照写盘档位(Q1 WP4 三档)。
type CheckpointMode string
const (
// CheckpointSync 每个 superstep 边界同步写(默认,与现状「逐步全量落盘」一致)。
CheckpointSync CheckpointMode = "sync"
// CheckpointAsync 边界快照进队列由单 goroutine 串行写(边界不阻塞;恢复粒度同 sync)。
CheckpointAsync CheckpointMode = "async"
// CheckpointOnExit 只在推进退出(终态/挂起/错误)时写最终快照。
CheckpointOnExit CheckpointMode = "on_exit"
)
// checkpointWriter 按档位执行边界快照;async 档单 goroutine 串行落盘。
type checkpointWriter struct {
mode CheckpointMode
store Store
ch chan Checkpoint
done chan error
}
func newCheckpointWriter(mode CheckpointMode, store Store) *checkpointWriter {
if mode == "" {
mode = CheckpointSync
}
if store == nil {
store = FileStore{}
}
w := &checkpointWriter{mode: mode, store: store}
if mode == CheckpointAsync {
w.ch = make(chan Checkpoint, 16)
w.done = make(chan error, 1)
go func() {
var first error
for cp := range w.ch {
if first != nil {
continue
}
if err := cp.write(w.store); err != nil {
first = err
}
}
w.done <- first
}()
}
return w
}
// boundary 由调用方(flowDriver)在 superstep 边界触发:
// sync 立即写;async 入队(满即错,不静默丢);on_exit 跳过。
func (w *checkpointWriter) boundary(wsDir string, cp Checkpoint) error {
cp.wsDir = wsDir
switch w.mode {
case CheckpointAsync:
select {
case w.ch <- cp:
default:
return fmt.Errorf("checkpoint queue full at superstep %d", cp.Superstep)
}
return nil
case CheckpointOnExit:
return nil
default:
return cp.write(w.store)
}
}
// flush 在推进退出前调用:async 落完并报告首个错误;on_exit 写最终快照。
func (w *checkpointWriter) flush(wsDir string, cp Checkpoint) error {
cp.wsDir = wsDir
switch w.mode {
case CheckpointAsync:
close(w.ch)
return <-w.done
case CheckpointOnExit:
return cp.write(w.store)
default:
return nil
}
}
// validateGraphContinuity 恢复连续性校验(Q1 WP4;WP1 的图版本裁定)。
// 最新检查点存在且其图指纹与当前 Steps 重编译不一致时拒绝恢复——
// 崩溃期间图形态被改过,继续推进会把已完成的结果接到错误的图上。
// 检查点不存在(旧运行)或指纹一致则放行。
func validateGraphContinuity(st *RunState) error {
latest, err := st.storeOr().LoadLatestCheckpoint(st.Meta.WorkDir)
if err != nil || latest == nil {
return err
}
g, gerr := compileGraph(st.Plan.Workflow.Steps)
if gerr != nil {
return fmt.Errorf("graph continuity: 当前 Steps 无法编译:%w(请人工介入或重新规划)", gerr)
}
if latest.GraphHash != g.hash() {
return fmt.Errorf("graph continuity: 崩溃前后图形态不一致(checkpoint superstep=%d hash=%s,当前=%s)——可能在动态调整或外部修改后崩溃,请重新规划或人工介入",
latest.Superstep, latest.GraphHash, g.hash())
}
return nil
}
+120
View File
@@ -0,0 +1,120 @@
package squad
import (
"fmt"
"time"
)
// Termination 运行级停止条件的单一注册点(Q1 WP6):leader 轮次、修复预算、
// 唤醒次数与步骤超时集中声明;复合判定用 And/Or 原语(AutoGen 终止条件语义)。
// 默认值与现网一致;引擎选项在 terminationOf 覆盖对应字段。
type Termination struct {
MaxLeaderTurns int
RepairBudget int
MaxRepairGranted int // 人工 retry 累计加预算上限(Q26):默认 RepairBudget*2
MaxWakeupFires int
StepTimeout time.Duration
}
// DefaultTermination 与现网四处的硬编码取值一致。
func DefaultTermination() Termination {
return Termination{
MaxLeaderTurns: DefaultMaxLeaderTurns,
RepairBudget: 1,
MaxRepairGranted: 2,
MaxWakeupFires: MaxWakeupFires,
StepTimeout: 10 * time.Minute,
}
}
// terminationOf 取本运行的停止条件:引擎选项与运行状态覆盖默认值。
func (e *SquadEngine) terminationOf(st *RunState) Termination {
t := DefaultTermination()
if e.opts.RepairBudget > 0 {
t.RepairBudget = e.opts.RepairBudget
t.MaxRepairGranted = e.opts.RepairBudget * 2
}
if e.opts.StepTimeout > 0 {
t.StepTimeout = e.opts.StepTimeout
}
if st != nil && st.Leader != nil && st.Leader.MaxTurns > 0 {
t.MaxLeaderTurns = st.Leader.MaxTurns
}
return t
}
// Counters 运行期计数,由各判定处喂入(值语义快照)。
type Counters struct {
LeaderTurns int
RepairSpent int
RepairGranted int
WakeupFires int
Deadline time.Time
}
// Cond 是一条停止条件:返回(原因,是否命中)。
type Cond func(c Counters, now time.Time) (string, bool)
// MaxTurnsC 轮次上限。
func MaxTurnsC(n int) Cond {
return func(c Counters, _ time.Time) (string, bool) {
if c.LeaderTurns >= n {
return fmt.Sprintf("leader 轮次达上限 %d", n), true
}
return "", false
}
}
// RepairBudgetC 修复预算耗尽。
func RepairBudgetC(n int) Cond {
return func(c Counters, _ time.Time) (string, bool) {
if c.RepairSpent > n {
return fmt.Sprintf("修复预算耗尽(%d/%d)", c.RepairSpent, n), true
}
return "", false
}
}
// WakeupsC 自动唤醒次数超限。
func WakeupsC(n int) Cond {
return func(c Counters, _ time.Time) (string, bool) {
if c.WakeupFires > n {
return fmt.Sprintf("自动唤醒次数超限(%d/%d)", c.WakeupFires, n), true
}
return "", false
}
}
// DeadlineC 超过截止时刻。
func DeadlineC() Cond {
return func(c Counters, now time.Time) (string, bool) {
if !c.Deadline.IsZero() && now.After(c.Deadline) {
return "超过截止时刻", true
}
return "", false
}
}
// And 全部条件命中才成立。
func And(conds ...Cond) Cond {
return func(c Counters, now time.Time) (string, bool) {
for _, k := range conds {
if _, hit := k(c, now); !hit {
return "", false
}
}
return "all conditions met", true
}
}
// Or 任一条件命中即成立(默认的停止语义)。
func Or(conds ...Cond) Cond {
return func(c Counters, now time.Time) (string, bool) {
for _, k := range conds {
if r, hit := k(c, now); hit {
return r, true
}
}
return "", false
}
}
+82
View File
@@ -0,0 +1,82 @@
package squad
import (
"context"
"strings"
"testing"
"time"
)
// TestTerminationAndOr:And 全中才成立、Or 任一中即成立(WP6 原语)。
func TestTerminationAndOr(t *testing.T) {
c := Counters{LeaderTurns: 8, RepairSpent: 2, WakeupFires: 0}
or := Or(MaxTurnsC(8), WakeupsC(1))
if _, hit := or(c, time.Now()); !hit {
t.Fatal("or should hit on turns")
}
and := And(MaxTurnsC(8), WakeupsC(1))
if _, hit := and(c, time.Now()); hit {
t.Fatal("and should not hit with zero wakeups")
}
and2 := And(MaxTurnsC(8), RepairBudgetC(1))
if _, hit := and2(c, time.Now()); !hit {
t.Fatal("and should hit when all met")
}
dl := DeadlineC()
past := Counters{Deadline: time.Now().Add(-time.Minute)}
if _, hit := dl(past, time.Now()); !hit {
t.Fatal("deadline should hit when past")
}
}
// TestRepairGrantCap:人工 retry 累计追加有上限(Q26)。
func TestRepairGrantCap(t *testing.T) {
engine, _ := newTestEngine(t, mockScriptPlanner(baseSteps()...), map[string]map[string]string{
"01_researcher": {"notes.md": goodReport, "fields.json": "{}"},
"02_writer": {"output.md": goodReport},
"03_reviewer": {"output.md": goodReport},
}, NopSink{})
res, err := engine.Run(context.Background(), Goal{Text: "先跑完再验", HitlMode: HitlAuto}, RunOptions{})
if err != nil || res.Status != RunCompleted {
t.Fatalf("setup run: %v %+v", err, res)
}
// 预置:修复授予已达上限 + 一个真实的质检挂起门(与 finalize 的形态一致)。
st, err := loadRunState(res.WorkDir)
if err != nil {
t.Fatal(err)
}
st.RepairBudgetGranted = engine.terminationOf(st).MaxRepairGranted
st.Meta.CompletedAt = nil
st.Meta.Status = string(RunQualityReview)
req := &HumanRequest{
ID: newRequestID(), RunID: st.Meta.ID, Kind: HitlQualityReview, Severity: SeverityActionRequired,
Question: "交付物质检未通过且自动修复预算已用尽,请人工裁决:",
Options: []HumanOption{
{Value: "approve", Label: "人工放行(记录人工通过)"},
{Value: "retry", Label: "再修复一次(重跑交付步骤)"},
{Value: "abort", Label: "判定失败"},
},
CreatedAt: time.Now(), Status: "pending",
}
if err := st.saveGate(&HitlGate{Request: *req, PrevStatus: RunExecuting}); err != nil {
t.Fatal(err)
}
if err := st.save(); err != nil {
t.Fatal(err)
}
// 人工 retry 应被拒绝而不是再追加。
out, err := engine.Respond(context.Background(), res.RunID, RespondDecision{Choice: "retry"})
if err != nil {
t.Fatal(err)
}
if out == nil || !strings.Contains(out.Error, "grants exhausted") {
t.Fatalf("expected grant-cap failure, got %+v err=%v", out, err)
}
st2, err := loadRunState(res.WorkDir)
if err != nil {
t.Fatal(err)
}
if st2.RepairBudgetGranted != engine.terminationOf(st2).MaxRepairGranted {
t.Fatalf("granted changed after cap: %d", st2.RepairBudgetGranted)
}
}
+130
View File
@@ -0,0 +1,130 @@
package squad
import "fmt"
// topology.go — 拓扑一等化(Q2):内置拓扑名注册表。
// 拓扑不新造执行面:graph 类编译为 Steps 图(Q1 机制),leader 走既有
// Mode 委派循环,driver 类由引擎按名分发(review/group_chat/task_board),
// primitive 类是跨拓扑原语(handoff/mailbox),不可单独作为运行拓扑。
// 未知名与不可运行Kind一律 fail-closed。
// 内置拓扑名(completion doc Q2 清单的 12 种)。
const (
TopologySequential = "sequential"
TopologyParallel = "parallel"
TopologyLoop = "loop"
TopologyRouter = "router"
TopologyLeader = "leader"
TopologyHandoff = "handoff"
TopologyGroupChat = "group_chat"
TopologyReview = "review"
TopologyEvaluatorOptimizer = "evaluator_optimizer"
TopologyLongRunning = "long_running"
TopologyTaskBoard = "task_board"
TopologyMailbox = "mailbox"
)
// TopologyKind 是拓扑的执行形态。
type TopologyKind string
const (
// TopologyGraph 编译为 Steps 图,由 flowDriver.advance 执行。
TopologyGraph TopologyKind = "graph"
// TopologyMode 走既有 Mode 分支(leader 委派循环)。
TopologyMode TopologyKind = "mode"
// TopologyDriver 由引擎按名分发到专用驱动。
TopologyDriver TopologyKind = "driver"
// TopologyPrimitive 是跨拓扑原语,不可单独运行。
TopologyPrimitive TopologyKind = "primitive"
)
// TopologySpec 是一个内置拓扑的注册项。
type TopologySpec struct {
Name string
Kind TopologyKind
}
// builtinTopologies 是 12 种内置拓扑的注册表(唯一权威清单)。
var builtinTopologies = []TopologySpec{
{Name: TopologySequential, Kind: TopologyGraph},
{Name: TopologyParallel, Kind: TopologyGraph},
{Name: TopologyLoop, Kind: TopologyGraph},
{Name: TopologyRouter, Kind: TopologyGraph},
{Name: TopologyLeader, Kind: TopologyMode},
{Name: TopologyHandoff, Kind: TopologyPrimitive},
{Name: TopologyGroupChat, Kind: TopologyDriver},
{Name: TopologyReview, Kind: TopologyDriver},
{Name: TopologyEvaluatorOptimizer, Kind: TopologyGraph},
{Name: TopologyLongRunning, Kind: TopologyGraph},
{Name: TopologyTaskBoard, Kind: TopologyDriver},
{Name: TopologyMailbox, Kind: TopologyPrimitive},
}
// BuiltinTopologies 返回内置拓扑清单(只读副本)。
func BuiltinTopologies() []TopologySpec {
out := make([]TopologySpec, len(builtinTopologies))
copy(out, builtinTopologies)
return out
}
// LookupTopology 按名查注册项。
func LookupTopology(name string) (TopologySpec, bool) {
for _, t := range builtinTopologies {
if t.Name == name {
return t, true
}
}
return TopologySpec{}, false
}
// registeredDrivers 是已接线的 driver 拓扑(WP 增量逐个点亮;未点亮 = fail-closed)。
var registeredDrivers = map[string]bool{}
// RegisterTopologyDriver 由驱动实现方在 init/装配时点亮一个 driver 拓扑。
func RegisterTopologyDriver(name string) error {
spec, ok := LookupTopology(name)
if !ok {
return fmt.Errorf("topology: 未注册的拓扑名 %q", name)
}
if spec.Kind != TopologyDriver {
return fmt.Errorf("topology: %q 不是 driver 类(kind=%s)", name, spec.Kind)
}
registeredDrivers[name] = true
return nil
}
// checkTopology 校验一次运行的有效拓扑名,返回其 Kind。
// 空名 = 未声明(standard 图行为,兼容既有调用方)。
// 未注册名 / primitive 单跑 / driver 未点亮都 fail-closed。
func checkTopology(name string) (TopologyKind, error) {
if name == "" {
return TopologyGraph, nil
}
spec, ok := LookupTopology(name)
if !ok {
return "", fmt.Errorf("topology: 未知拓扑 %q(内置清单:%s)", name, topologyNames())
}
switch spec.Kind {
case TopologyGraph, TopologyMode:
return spec.Kind, nil
case TopologyPrimitive:
return "", fmt.Errorf("topology: %q 是跨拓扑原语,不可单独作为运行拓扑", name)
case TopologyDriver:
if !registeredDrivers[name] {
return "", fmt.Errorf("topology: %q 驱动未注册(fail-closed)", name)
}
return spec.Kind, nil
}
return "", fmt.Errorf("topology: %q kind 非法", name)
}
func topologyNames() string {
s := ""
for i, t := range builtinTopologies {
if i > 0 {
s += ", "
}
s += t.Name
}
return s
}
+436
View File
@@ -0,0 +1,436 @@
package squad
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// topology_conformance_test.go — Q2 验收一的机器证据:每种拓扑一个
// 脚本化后端的 conformance(零模型、零网络)。
// ---- 脚本化夹具 ----
// collectSink 收集事件流供断言。
type collectSink struct {
mu sync.Mutex
events []Event
}
func (c *collectSink) Emit(ev Event) {
c.mu.Lock()
defer c.mu.Unlock()
c.events = append(c.events, ev)
}
func (c *collectSink) snapshot() []Event {
c.mu.Lock()
defer c.mu.Unlock()
return append([]Event(nil), c.events...)
}
func (c *collectSink) countText(sub string) int {
n := 0
for _, ev := range c.snapshot() {
if strings.Contains(ev.Text, sub) {
n++
}
}
return n
}
// iterBackend 按「步骤子目录 × 第几次执行」回放内容(循环/评估拓扑需要
// 逐轮不同的 fields.json)。
type iterBackend struct {
mu sync.Mutex
calls map[string]int
content func(stepKey string, iter int, target string) []byte
delay time.Duration
}
func (b *iterBackend) Name() string { return "iter" }
func (b *iterBackend) Execute(_ context.Context, req ExecRequest) (*ExecResult, error) {
key := filepath.Base(filepath.Clean(req.WorkDir))
if b.delay > 0 {
time.Sleep(b.delay)
}
b.mu.Lock()
b.calls[key]++
iter := b.calls[key]
b.mu.Unlock()
patches := map[string][]byte{}
for _, t := range req.Targets {
var data []byte
if b.content != nil {
data = b.content(key, iter, t)
}
if data == nil {
data = []byte(goodReport)
}
out := filepath.Join(req.WorkDir, t)
_ = os.MkdirAll(filepath.Dir(out), 0o755)
if err := os.WriteFile(out, data, 0o644); err != nil {
return nil, err
}
patches[t] = data
}
return &ExecResult{Success: true, Patches: patches}, nil
}
func (b *iterBackend) totalCalls() int {
b.mu.Lock()
defer b.mu.Unlock()
n := 0
for _, v := range b.calls {
n += v
}
return n
}
func newTopologyEngine(t *testing.T, planner Planner, be Executor, sink ProgressSink) *SquadEngine {
t.Helper()
dir := t.TempDir()
reg := NewRoleRegistry()
for _, spec := range []RoleSpec{
{Role: "researcher", Name: "调研", Backend: "iter"},
{Role: "writer", Name: "撰写", Backend: "iter"},
{Role: "reviewer", Name: "审核", Backend: "iter"},
} {
if err := reg.Register(spec); err != nil {
t.Fatal(err)
}
}
backends := NewBackendResolver()
backends.RegisterInstance("iter", be)
if sink == nil {
sink = NopSink{}
}
engine, err := NewEngine(Options{
DataDir: dir, Registry: reg, Planner: planner, Backends: backends, Sink: sink,
})
if err != nil {
t.Fatal(err)
}
return engine
}
func fieldsJSON(kv map[string]string) []byte {
b, _ := json.Marshal(kv)
return b
}
// ---- sequential / parallel:既有图语义 + 拓扑名受理 ----
func TestTopologyConformance_sequential(t *testing.T) {
be := &iterBackend{calls: map[string]int{}}
sink := &collectSink{}
engine := newTopologyEngine(t, mockScriptPlanner(
StepSpec{ID: "s1", Role: "researcher", Title: "一", Targets: []string{"notes.md"}},
StepSpec{ID: "s2", Role: "writer", Title: "二", Targets: []string{"output.md"}},
), be, sink)
res, err := engine.Run(context.Background(), Goal{Text: "顺序任务"}, RunOptions{Topology: TopologySequential})
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("status = %s err = %v", res.Status, res.Error)
}
if be.totalCalls() != 2 {
t.Fatalf("执行次数 = %d", be.totalCalls())
}
if sink.countText("拓扑 sequential") != 1 {
t.Fatal("缺拓扑受理事件")
}
}
func TestTopologyConformance_parallel(t *testing.T) {
be := &iterBackend{calls: map[string]int{}}
engine := newTopologyEngine(t, mockScriptPlanner(
StepSpec{ID: "s1", Role: "researcher", Title: "并行甲", Parallel: true, Targets: []string{"a.md"}},
StepSpec{ID: "s2", Role: "writer", Title: "并行乙", Parallel: true, Targets: []string{"b.md"}},
StepSpec{ID: "s3", Role: "reviewer", Title: "汇合", Targets: []string{"output.md"}},
), be, nil)
res, err := engine.Run(context.Background(), Goal{Text: "并行任务"}, RunOptions{Topology: TopologyParallel})
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted || be.totalCalls() != 3 {
t.Fatalf("status = %s calls = %d err = %v", res.Status, be.totalCalls(), res.Error)
}
}
// ---- loop:条件停机 + 预算触顶 ----
func TestTopologyConformance_loopUntilField(t *testing.T) {
// 第 1-2 轮 done=no,第 3 轮 done=yes → 恰执行 3 次。
be := &iterBackend{calls: map[string]int{}, content: func(_ string, iter int, target string) []byte {
if target == "fields.json" {
if iter >= 3 {
return fieldsJSON(map[string]string{"done": "yes"})
}
return fieldsJSON(map[string]string{"done": "no"})
}
return nil
}}
sink := &collectSink{}
engine := newTopologyEngine(t, mockScriptPlanner(
StepSpec{ID: "s1", Role: "researcher", Title: "循环体", Targets: []string{"output.md", "fields.json"},
Loop: &LoopSpec{MaxIterations: 5, UntilField: "done", UntilEquals: "yes"}},
), be, sink)
res, err := engine.Run(context.Background(), Goal{Text: "循环任务"}, RunOptions{Topology: TopologyLoop})
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("status = %s err = %v", res.Status, res.Error)
}
if be.totalCalls() != 3 {
t.Fatalf("应在条件满足时停机(3 次),实际 %d", be.totalCalls())
}
if sink.countText("再武装") != 2 {
t.Fatalf("再武装事件应 2 次:%d", sink.countText("再武装"))
}
// 计划里的 LoopRuns 持久化为 2。
if len(res.Plan.Steps) != 1 || res.Plan.Steps[0].LoopRuns != 2 {
t.Fatalf("LoopRuns = %+v", res.Plan.Steps)
}
}
func TestTopologyConformance_loopBudgetExhausted(t *testing.T) {
// 条件永不满足:恰执行 MaxIterations 次后触顶(非失败)。
be := &iterBackend{calls: map[string]int{}, content: func(_ string, _ int, target string) []byte {
if target == "fields.json" {
return fieldsJSON(map[string]string{"done": "no"})
}
return nil
}}
sink := &collectSink{}
engine := newTopologyEngine(t, mockScriptPlanner(
StepSpec{ID: "s1", Role: "researcher", Title: "循环体", Targets: []string{"output.md", "fields.json"},
Loop: &LoopSpec{MaxIterations: 3, UntilField: "done", UntilEquals: "yes"}},
), be, sink)
res, err := engine.Run(context.Background(), Goal{Text: "循环任务"}, RunOptions{Topology: TopologyLoop})
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("触顶应是完成而非失败:%s %v", res.Status, res.Error)
}
if be.totalCalls() != 3 {
t.Fatalf("恰 3 次,实际 %d", be.totalCalls())
}
if sink.countText("loop_exhausted") != 1 {
t.Fatal("缺 loop_exhausted 事件")
}
}
// ---- router:分支选中/落选跳过/无命中 fail-closed ----
func routerSteps() []StepSpec {
return []StepSpec{
{ID: "r1", Role: "researcher", Title: "路由", Targets: []string{"output.md", "fields.json"},
Branches: []Branch{
{When: BranchCond{Field: "route", Equals: "fast"}, Then: []string{"fast"}},
{When: BranchCond{Field: "route", NotEquals: "fast"}, Then: []string{"slow"}},
}},
{ID: "fast", Role: "writer", Title: "快线", Needs: []string{"r1"}, Targets: []string{"output.md"}},
{ID: "slow", Role: "writer", Title: "慢线", Needs: []string{"r1"}, Targets: []string{"output.md"}},
}
}
func TestTopologyConformance_routerSelectsBranch(t *testing.T) {
be := &iterBackend{calls: map[string]int{}, content: func(_ string, _ int, target string) []byte {
if target == "fields.json" {
return fieldsJSON(map[string]string{"route": "fast"})
}
return nil
}}
engine := newTopologyEngine(t, mockScriptPlanner(routerSteps()...), be, nil)
res, err := engine.Run(context.Background(), Goal{Text: "路由任务"}, RunOptions{Topology: TopologyRouter})
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("分支落选是预期路径,不得降级/失败:%s %v", res.Status, res.Error)
}
byID := map[string]StepSpec{}
for _, s := range res.Plan.Steps {
byID[s.ID] = s
}
if byID["fast"].Status != "completed" {
t.Fatalf("fast = %s", byID["fast"].Status)
}
if byID["slow"].Status != "skipped" || byID["slow"].Error != routerSkipReason {
t.Fatalf("slow = %s %q", byID["slow"].Status, byID["slow"].Error)
}
}
func TestTopologyConformance_routerNoMatchFailsClosed(t *testing.T) {
be := &iterBackend{calls: map[string]int{}, content: func(_ string, _ int, target string) []byte {
if target == "fields.json" {
return fieldsJSON(map[string]string{"route": ""}) // 两条分支都不命中
}
return nil
}}
steps := routerSteps()
// 去掉 NotEquals 兜底分支,制造无命中。
steps[0].Branches = []Branch{{When: BranchCond{Field: "route", Equals: "fast"}, Then: []string{"fast"}}}
engine := newTopologyEngine(t, mockScriptPlanner(steps...), be, nil)
res, err := engine.Run(context.Background(), Goal{Text: "路由任务"}, RunOptions{Topology: TopologyRouter})
if err != nil {
t.Fatal(err)
}
if res.Status != RunFailed || !strings.Contains(res.Error, "无分支命中") {
t.Fatalf("无命中必须 fail-closed:%s %v", res.Status, res.Error)
}
}
// ---- evaluator-optimizer:draft→eval 循环复合,收敛即停 ----
func TestTopologyConformance_evaluatorOptimizer(t *testing.T) {
// eval 第 1-2 轮 verdict=fail,第 3 轮 pass;draft 随 body 再武装。
be := &iterBackend{calls: map[string]int{}, content: func(key string, iter int, target string) []byte {
if target == "fields.json" {
if iter >= 3 {
return fieldsJSON(map[string]string{"verdict": "pass"})
}
return fieldsJSON(map[string]string{"verdict": "fail"})
}
if target == "verdict.md" {
return []byte(fmt.Sprintf("评审第 %d 轮\n\n%s", iter, goodReport))
}
return nil
}}
engine := newTopologyEngine(t, mockScriptPlanner(
StepSpec{ID: "draft", Role: "writer", Title: "起草", Targets: []string{"output.md"}},
StepSpec{ID: "eval", Role: "reviewer", Title: "评审", Targets: []string{"verdict.md", "fields.json"},
Loop: &LoopSpec{MaxIterations: 4, UntilField: "verdict", UntilEquals: "pass", Body: []string{"draft"}}},
), be, nil)
res, err := engine.Run(context.Background(), Goal{Text: "起草并评审"}, RunOptions{Topology: TopologyEvaluatorOptimizer})
if err != nil {
t.Fatal(err)
}
if res.Status != RunCompleted {
t.Fatalf("status = %s err = %v", res.Status, res.Error)
}
byID := map[string]StepSpec{}
for _, s := range res.Plan.Steps {
byID[s.ID] = s
}
if byID["eval"].LoopRuns != 2 {
t.Fatalf("eval 应再武装 2 轮:%+v", byID["eval"])
}
// draft 3 次 + eval 3 次。
if be.totalCalls() != 6 {
t.Fatalf("总执行次数 = %d,期望 6", be.totalCalls())
}
}
// ---- long-running:截止时刻 → 未完步骤 skipped、降级收口 ----
func TestTopologyConformance_longRunningDeadline(t *testing.T) {
// 时序鲁棒设计:每步 300ms、截止 +500ms——装配耗时不影响断言核心:
// s1 必完成(首个 superstep 在截止前开跑),s3 必被跳过(第三个
// superstep 边界必超期),收口必为 degraded。s2 完成与否取决于装配
// 耗时,不做断言。
be := &iterBackend{calls: map[string]int{}, delay: 300 * time.Millisecond}
sink := &collectSink{}
engine := newTopologyEngine(t, mockScriptPlanner(
StepSpec{ID: "s1", Role: "researcher", Title: "一", Targets: []string{"notes.md"}},
StepSpec{ID: "s2", Role: "writer", Title: "二", Targets: []string{"output.md"}},
StepSpec{ID: "s3", Role: "reviewer", Title: "三", Targets: []string{"output.md"}},
), be, sink)
res, err := engine.Run(context.Background(), Goal{Text: "长任务"}, RunOptions{
Topology: TopologyLongRunning,
Deadline: time.Now().Add(500 * time.Millisecond),
})
if err != nil {
t.Fatal(err)
}
if res.Status != RunDegraded {
t.Fatalf("截止后应降级收口:%s %v", res.Status, res.Error)
}
byID := map[string]StepSpec{}
for _, s := range res.Plan.Steps {
byID[s.ID] = s
}
if byID["s1"].Status != "completed" {
t.Fatalf("s1 = %s", byID["s1"].Status)
}
if byID["s3"].Status != "skipped" || byID["s3"].Error != "deadline exceeded" {
t.Fatalf("s3 = %s %q", byID["s3"].Status, byID["s3"].Error)
}
if sink.countText("截止时刻") != 1 {
t.Fatal("缺截止事件")
}
}
// ---- 拓扑校验 fail-closed ----
func TestTopologyValidationFailsClosed(t *testing.T) {
be := &iterBackend{calls: map[string]int{}}
cases := []struct {
name string
topo string
wantErr string
}{
{"未注册名", "bogus_topology", "未知拓扑"},
{"primitive 单跑", TopologyMailbox, "跨拓扑原语"},
{"primitive 单跑 handoff", TopologyHandoff, "跨拓扑原语"},
{"driver 未点亮", TopologyReview, "驱动未注册"},
{"driver 未点亮 group_chat", TopologyGroupChat, "驱动未注册"},
{"driver 未点亮 task_board", TopologyTaskBoard, "驱动未注册"},
}
for _, tc := range cases {
engine := newTopologyEngine(t, mockScriptPlanner(
StepSpec{ID: "s1", Role: "researcher", Title: "一", Targets: []string{"output.md"}},
), be, nil)
res, err := engine.Run(context.Background(), Goal{Text: "x"}, RunOptions{Topology: tc.topo})
if err != nil {
t.Fatalf("%s:err = %v", tc.name, err)
}
if res.Status != RunFailed || !strings.Contains(res.Error, tc.wantErr) {
t.Fatalf("%s:%s %q(期望含 %q)", tc.name, res.Status, res.Error, tc.wantErr)
}
}
}
// leader 拓扑名映射到既有 Mode 委派循环(本测只钉「受理且映射」,
// leader 行为 conformance 在 leader_test.go / WP2 增强)。
func TestTopologyLeaderMapsToMode(t *testing.T) {
spec, ok := LookupTopology(TopologyLeader)
if !ok || spec.Kind != TopologyMode {
t.Fatalf("leader 注册形态:%+v %v", spec, ok)
}
if _, err := checkTopology(TopologyLeader); err != nil {
t.Fatalf("leader 拓扑应可受理:%v", err)
}
}
// 12 种内置拓扑全部注册且 Kind 合法(清单完整性)。
func TestBuiltinTopologiesComplete(t *testing.T) {
want := map[string]TopologyKind{
TopologySequential: TopologyGraph, TopologyParallel: TopologyGraph,
TopologyLoop: TopologyGraph, TopologyRouter: TopologyGraph,
TopologyLeader: TopologyMode, TopologyHandoff: TopologyPrimitive,
TopologyGroupChat: TopologyDriver, TopologyReview: TopologyDriver,
TopologyEvaluatorOptimizer: TopologyGraph, TopologyLongRunning: TopologyGraph,
TopologyTaskBoard: TopologyDriver, TopologyMailbox: TopologyPrimitive,
}
got := BuiltinTopologies()
if len(got) != len(want) {
t.Fatalf("注册数 = %d,期望 %d", len(got), len(want))
}
for _, spec := range got {
if k, ok := want[spec.Name]; !ok || k != spec.Kind {
t.Fatalf("拓扑 %s kind = %s(期望 %s)", spec.Name, spec.Kind, k)
}
}
}
+315 -83
View File
@@ -13,96 +13,166 @@ import (
"error-code-system/errcode"
)
// flowDriver 工作流驱动器:推进 runState 直到终态或 HITL 挂起边界。
// flowDriver 工作流驱动器:推进 RunState 直到终态或 HITL 挂起边界。
type flowDriver struct {
opts engineDeps
}
// advance 执行到边界;返回 (结果, 挂起上下文),二者互斥非 nil(infra 错误时都为 nil 且 err 非 nil)。
func (d *flowDriver) advance(ctx context.Context, st *runState) (res *RunResult, gate *hitlGate, err error) {
// 推进模型(Q1 WP1/WP2):每轮从权威 Steps 现场编译调度图,按 superstep
// 分层推进——层内无写集冲突的步骤并行(runParallel 复用),有冲突的按声明序
// 串行(含动态调整);动态调整改 Steps 后下一轮自然生效。
func (d *flowDriver) advance(ctx context.Context, st *RunState) (res *RunResult, gate *HitlGate, err error) {
wf := st.Workflow()
wf.Status = "in_progress"
st.setWorkflow(wf)
d.emit(st, Event{Type: EvPhase, Text: "开始执行工作流"})
i := 0
for i < len(st.Plan.Workflow.Steps) {
step := st.Plan.Workflow.Steps[i]
switch step.Status {
case "completed", "skipped", "failed":
i++
continue
superNo := 0
// 运行级截止(Q2 long_running):superstep 边界检查,超期未完步骤置
// skipped 并降级收口;零值/不可解析 = 不设限。
var runDeadline time.Time
if v := st.Meta.Metadata["deadline"]; v != "" {
// RFC3339Nano 同时接受秒级与纳秒级两种写法。
if t, terr := time.Parse(time.RFC3339Nano, v); terr == nil {
runDeadline = t
}
if out, g, err := d.gateBeforeRun(ctx, st, i); out != nil || g != nil || err != nil {
if out == nil && g != nil {
out = heldResult(st, g)
}
cpw := newCheckpointWriter(CheckpointMode(st.Meta.Metadata["checkpoint_mode"]), st.storeOr())
// 推进退出前 flush:async 落完、on_exit 写最终快照(Q1 WP4 三档的出口语义)。
var lastGraph *graph
defer func() {
if lastGraph == nil {
if g, gerr := compileGraph(st.Plan.Workflow.Steps); gerr == nil {
lastGraph = g
}
return out, g, err
}
if lastGraph != nil {
_ = cpw.flush(st.Meta.WorkDir, snapshotOf(superNo, lastGraph, st.Plan.Workflow.Steps))
}
}()
for {
if !runDeadline.IsZero() && time.Now().After(runDeadline) {
d.emit(st, Event{Type: EvPhase, Text: "运行截止时刻已到,未完步骤按 skipped 收口"})
st.mu.Lock()
for i := range st.Plan.Workflow.Steps {
if st.Plan.Workflow.Steps[i].Status == "pending" || st.Plan.Workflow.Steps[i].Status == "running" {
st.Plan.Workflow.Steps[i].Status = "skipped"
st.Plan.Workflow.Steps[i].Error = "deadline exceeded"
}
}
_ = st.save()
st.mu.Unlock()
return d.finalize(ctx, st)
}
g, gerr := compileGraph(st.Plan.Workflow.Steps)
if gerr != nil {
wf2 := st.Workflow()
wf2.Status = "failed"
st.setWorkflow(wf2)
return &RunResult{RunID: st.Meta.ID, Status: RunFailed, Plan: planPtr(st),
Error: "graph: " + gerr.Error(), WorkDir: st.Meta.WorkDir}, nil, nil
}
layer, ok := g.nextLayer(st.Plan.Workflow.Steps)
if !ok {
if n := pendingCount(st.Plan.Workflow.Steps); n > 0 {
wf2 := st.Workflow()
wf2.Status = "failed"
st.setWorkflow(wf2)
return &RunResult{RunID: st.Meta.ID, Status: RunFailed, Plan: planPtr(st),
Error: fmt.Sprintf("graph: 依赖无法满足,仍有 %d 个步骤无法调度", n), WorkDir: st.Meta.WorkDir}, nil, nil
}
break
}
superNo++
d.emit(st, Event{Type: EvPhase, Text: fmt.Sprintf("superstep %d 推进(并行 %d 步,串行 %d 步)", superNo, len(layer.par), len(layer.seq))})
if step.Parallel {
// 收集相邻并行组。组内每一步都先过审批和权限,任一需要挂起则整组不执行。
var group []int
for i < len(st.Plan.Workflow.Steps) {
s := st.Plan.Workflow.Steps[i]
if s.Parallel && s.Status != "completed" && s.Status != "skipped" && s.Status != "failed" {
if out, g, err := d.gateBeforeRun(ctx, st, i); out != nil || g != nil || err != nil {
if out == nil && g != nil {
out = heldResult(st, g)
}
return out, g, err
// 并行段:组内每一步都先过审批和权限,任一需要挂起则整组不执行。
if len(layer.par) > 0 {
for _, idx := range layer.par {
if out, g2, err := d.gateBeforeRun(ctx, st, idx); out != nil || g2 != nil || err != nil {
if out == nil && g2 != nil {
out = heldResult(st, g2)
}
group = append(group, i)
i++
continue
return out, g2, err
}
break
}
if out, g, err := d.runParallel(ctx, st, group); out != nil || g != nil || err != nil {
if out == nil && g != nil {
out = heldResult(st, g)
if out, g2, err := d.runParallel(ctx, st, layer.par); out != nil || g2 != nil || err != nil {
if out == nil && g2 != nil {
out = heldResult(st, g2)
}
return out, g, err
return out, g2, err
}
if g2 := d.checkBlockingGaps(st); g2 != nil {
return heldResult(st, g2), g2, nil
}
continue
}
out, g, err := d.runOneStep(ctx, st, i)
if out != nil || g != nil || err != nil {
if out == nil && g != nil {
out = heldResult(st, g)
}
return out, g, err
}
i++
// 阻塞缺口挂起。
if g2 := d.checkBlockingGaps(st); g2 != nil {
return heldResult(st, g2), g2, nil
}
// 动态调整(仅顺序步骤后,避免并发竞态)。
if st.Plan.Workflow.Steps[i-1].AllowDynamicAdjustment && d.opts.Evaluator != nil {
out, g, err := d.applyDynamicAdjustment(ctx, st, i-1)
if out != nil || g != nil || err != nil {
if out == nil && g != nil {
out = heldResult(st, g)
// 单成员并行组实际是顺序执行:与旧线性扫描一致,其后可动态调整
// (多成员组不做,避免并发竞态)。
if len(layer.par) == 1 {
idx := layer.par[0]
if st.Plan.Workflow.Steps[idx].AllowDynamicAdjustment && d.opts.Evaluator != nil {
out, g2, err := d.applyDynamicAdjustment(ctx, st, idx)
if out != nil || g2 != nil || err != nil {
if out == nil && g2 != nil {
out = heldResult(st, g2)
}
return out, g2, err
}
}
return out, g, err
}
}
// 串行段(写集冲突步骤,按声明序逐个执行;顺序步骤后可动态调整)。
for _, idx := range layer.seq {
if out, g2, err := d.gateBeforeRun(ctx, st, idx); out != nil || g2 != nil || err != nil {
if out == nil && g2 != nil {
out = heldResult(st, g2)
}
return out, g2, err
}
out, g2, err := d.runOneStep(ctx, st, idx)
if out != nil || g2 != nil || err != nil {
if out == nil && g2 != nil {
out = heldResult(st, g2)
}
return out, g2, err
}
if g2 := d.checkBlockingGaps(st); g2 != nil {
return heldResult(st, g2), g2, nil
}
if st.Plan.Workflow.Steps[idx].AllowDynamicAdjustment && d.opts.Evaluator != nil {
out, g2, err := d.applyDynamicAdjustment(ctx, st, idx)
if out != nil || g2 != nil || err != nil {
if out == nil && g2 != nil {
out = heldResult(st, g2)
}
return out, g2, err
}
}
}
// superstep 边界快照(sync 立即 / async 入队;on_exit 由 defer 的 flush 写)。
lastGraph = g
if err := cpw.boundary(st.Meta.WorkDir, snapshotOf(superNo, g, st.Plan.Workflow.Steps)); err != nil {
return nil, nil, err
}
}
return d.finalize(ctx, st)
}
// snapshotOf 组装一个 superstep 边界快照:序号、图结构指纹与全量步骤状态。
func snapshotOf(superNo int, g *graph, steps []StepSpec) Checkpoint {
cp := Checkpoint{Superstep: superNo, At: time.Now(), GraphHash: g.hash()}
for _, s := range steps {
cp.StepStates = append(cp.StepStates, StepSnapshot{ID: s.ID, Status: s.Status, AttemptID: s.AttemptID})
}
return cp
}
// gateBeforeRun 在步骤真正执行前检查权限升级和显式审批。
// 返回非空结果或挂起时,调用方不得执行该步骤,也不得执行它所在的并行组。
func (d *flowDriver) gateBeforeRun(ctx context.Context, st *runState, i int) (*RunResult, *hitlGate, error) {
func (d *flowDriver) gateBeforeRun(ctx context.Context, st *RunState, i int) (*RunResult, *HitlGate, error) {
step := st.Plan.Workflow.Steps[i]
role, _ := findAgent(st.Plan.Squad.Agents, step.Role)
if role.BashPermission == BashPermissionAsk && !st.Approved["role:"+role.Role] {
@@ -143,13 +213,14 @@ func (d *flowDriver) gateBeforeRun(ctx context.Context, st *runState, i int) (*R
}
// runParallel 并发执行一个并行组;关键步骤失败即终止整个运行。
func (d *flowDriver) runParallel(ctx context.Context, st *runState, idxs []int) (*RunResult, *hitlGate, error) {
func (d *flowDriver) runParallel(ctx context.Context, st *RunState, idxs []int) (*RunResult, *HitlGate, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
var mu sync.Mutex
failedCritical := -1
var gate *hitlGate
var firstFail *RunResult
var gate *HitlGate
for _, idx := range idxs {
wg.Add(1)
go func(idx int) {
@@ -163,6 +234,11 @@ func (d *flowDriver) runParallel(ctx context.Context, st *runState, idxs []int)
}
if (out != nil && out.Status == RunFailed) || err != nil {
cancel()
// 保留首个带具体错误的失败结果(如 router 无命中);
// failStep 的通用格式只在没有更具体结果时兜底。
if out != nil && out.Status == RunFailed && firstFail == nil {
firstFail = out
}
if st.Plan.Workflow.Steps[idx].IsCritical() && failedCritical < 0 {
failedCritical = idx
}
@@ -173,6 +249,9 @@ func (d *flowDriver) runParallel(ctx context.Context, st *runState, idxs []int)
if gate != nil {
return heldResult(st, gate), gate, nil
}
if firstFail != nil {
return firstFail, nil, nil
}
if failedCritical >= 0 {
return d.failStep(ctx, st, failedCritical)
}
@@ -180,7 +259,7 @@ func (d *flowDriver) runParallel(ctx context.Context, st *runState, idxs []int)
}
// runOneStep 执行单个步骤(含瞬态重试与交付物校验)。
func (d *flowDriver) runOneStep(ctx context.Context, st *runState, idx int) (*RunResult, *hitlGate, error) {
func (d *flowDriver) runOneStep(ctx context.Context, st *RunState, idx int) (*RunResult, *HitlGate, error) {
if err := ctx.Err(); err != nil {
return &RunResult{RunID: st.Meta.ID, Status: RunCancelled, Error: err.Error()}, nil, err
}
@@ -211,6 +290,7 @@ func (d *flowDriver) runOneStep(ctx context.Context, st *runState, idx int) (*Ru
d.emit(st, Event{Type: EvStepStarted, StepID: step.ID, Role: step.Role, Text: step.Title})
step.Status = "running"
step.Attempts++
step.AttemptID = fmt.Sprintf("%s/%s/%d", st.Meta.ID, step.ID, step.Attempts)
step.Error = ""
// 与收口落盘同一把锁:并行步骤一边改 Steps、一边全量 marshal 会数据竞争。
st.mu.Lock()
@@ -229,6 +309,15 @@ func (d *flowDriver) runOneStep(ctx context.Context, st *runState, idx int) (*Ru
}
prompt := readFileOr(filepath.Join(subDir, "TASK.md"), step.Title)
prompt = st.injectSteering(prompt)
// 邮箱投递(Q2):本步骤启动时把发给该角色(含广播)的未读消息并入
// 任务书;只走 prompt 面,永不触碰 HITL 门(验收三构造性保证)。
st.mu.Lock()
mail := takeMailFor(st, step.Role)
if len(mail) > 0 {
_ = st.save()
}
st.mu.Unlock()
prompt += formatMailSection(mail)
instructions := readFileOr(filepath.Join(subDir, "AGENTS.md"), d.opts.Workspaces.ResolveInstructions(role))
var backend Executor
@@ -283,7 +372,7 @@ func (d *flowDriver) runOneStep(ctx context.Context, st *runState, idx int) (*Ru
ToolAllowlist: role.Tools,
Skills: firstNonEmptySlice(step.Skills, role.Skills),
SessionScope: st.Meta.ID + "/" + step.ID,
ExecutionID: st.Meta.ID + "-" + step.ID,
ExecutionID: step.AttemptID,
Budget: stepBudget,
}
if step.IntentID != "" {
@@ -374,11 +463,150 @@ func (d *flowDriver) runOneStep(ctx context.Context, st *runState, idx int) (*Ru
}
d.emit(st, Event{Type: EvStepCompleted, StepID: step.ID, Role: step.Role, Text: step.Title,
Data: marshalJSON(map[string]any{"duration_ms": step.DurationMs, "targets": targets})})
// 循环步再武装(Q2 loop):停机条件不满足且预算未尽 → 本步与 loop.body
// 一起重置为 pending;触顶发 loop_exhausted 事件后按完成继续。
if step.Loop != nil {
if d.loopShouldRearm(st, step) {
if out, g2, err2 := d.rearmLoop(ctx, st, idx, step); out != nil || g2 != nil || err2 != nil {
return out, g2, err2
}
return nil, nil, nil
}
if step.Loop.UntilField != "" && step.LoopRuns+1 >= step.Loop.MaxIterations {
d.emit(st, Event{Type: EvPhase, StepID: step.ID, Text: fmt.Sprintf("loop_exhausted:%s 达 %d 轮上限,停机条件未满足", step.ID, step.Loop.MaxIterations)})
}
}
// 路由步分支裁决(Q2 router):首个命中的分支保留,其余分支目标置
// skipped;无分支命中 fail-closed 成失败运行。
if len(step.Branches) > 0 {
return d.applyBranches(ctx, st, idx, step)
}
return nil, nil, nil
}
// loopShouldRearm 判定循环步是否再武装:停机条件(黑板字段等值)满足或
// 预算用尽则停。字段判据读的是本轮 mergeStepArtifacts 之后的黑板。
func (d *flowDriver) loopShouldRearm(st *RunState, step StepSpec) bool {
// MaxIterations 是总迭代上限(含首跑):已跑 LoopRuns+1 次。
if step.LoopRuns+1 >= step.Loop.MaxIterations {
return false
}
if step.Loop.UntilField != "" {
st.mu.Lock()
v := st.BB.Fields[step.Loop.UntilField]
st.mu.Unlock()
if v == step.Loop.UntilEquals {
return false
}
}
return true
}
// rearmLoop 把循环步与 loop.body 一起重置为 pending(同一临界区内落盘)。
func (d *flowDriver) rearmLoop(_ context.Context, st *RunState, idx int, step StepSpec) (*RunResult, *HitlGate, error) {
st.mu.Lock()
step.LoopRuns++
step.Status = "pending"
step.Error = ""
st.Plan.Workflow.Steps[idx] = step
for _, bodyID := range step.Loop.Body {
for j := range st.Plan.Workflow.Steps {
if st.Plan.Workflow.Steps[j].ID == bodyID && st.Plan.Workflow.Steps[j].Status == "completed" {
st.Plan.Workflow.Steps[j].Status = "pending"
st.Plan.Workflow.Steps[j].Error = ""
}
}
}
err := st.save()
round := step.LoopRuns
st.mu.Unlock()
if err != nil {
return nil, nil, err
}
d.emit(st, Event{Type: EvPhase, StepID: step.ID, Text: fmt.Sprintf("loop 第 %d 轮再武装:%s", round+1, step.ID)})
return nil, nil, nil
}
// applyBranches 裁决路由步分支:When 按声明序取首个命中;未选中分支的
// pending 目标置 skipped(skipped=依赖已满足,join 步照常推进)。
func (d *flowDriver) applyBranches(_ context.Context, st *RunState, _ int, step StepSpec) (*RunResult, *HitlGate, error) {
st.mu.Lock()
fields := map[string]string{}
for k, v := range st.BB.Fields {
fields[k] = v
}
st.mu.Unlock()
var selected *Branch
for i := range step.Branches {
if branchMatches(fields, step.Branches[i].When) {
selected = &step.Branches[i]
break
}
}
if selected == nil {
wf := st.Workflow()
wf.Status = "failed"
st.setWorkflow(wf)
_ = st.save()
return &RunResult{RunID: st.Meta.ID, Status: RunFailed, Plan: planPtr(st),
Error: fmt.Sprintf("router: 步骤 %s 无分支命中(fail-closed)", step.ID), WorkDir: st.Meta.WorkDir}, nil, nil
}
keep := map[string]bool{}
for _, t := range selected.Then {
keep[t] = true
}
skipped := 0
st.mu.Lock()
for j := range st.Plan.Workflow.Steps {
sj := &st.Plan.Workflow.Steps[j]
if sj.ID == step.ID || keep[sj.ID] || sj.Status != "pending" {
continue
}
for _, br := range step.Branches {
inBranch := false
for _, t := range br.Then {
if t == sj.ID {
inBranch = true
break
}
}
if inBranch {
sj.Status = "skipped"
sj.Error = routerSkipReason
skipped++
break
}
}
}
err := st.save()
st.mu.Unlock()
if err != nil {
return nil, nil, err
}
d.emit(st, Event{Type: EvPhase, StepID: step.ID,
Text: fmt.Sprintf("router %s 选中分支 %v(跳过 %d 步)", step.ID, selected.Then, skipped)})
return nil, nil, nil
}
// routerSkipReason 是分支落选的 skipped 标记(finalize 的降级豁免凭据)。
const routerSkipReason = "router: 分支未选中"
// branchMatches 判定分支条件:Equals 非空须相等,NotEquals 非空须不等;
// 字段未设时按零值 "" 参与比较(compileGraph 已保证两者至少其一非空)。
func branchMatches(fields map[string]string, c BranchCond) bool {
v := fields[c.Field]
if c.Equals != "" && v != c.Equals {
return false
}
if c.NotEquals != "" && v == c.NotEquals {
return false
}
return true
}
// failStep 按关键性处理失败步骤:关键 → 运行失败;非关键 → 标记后继续(返回 nil 让循环推进)。
func (d *flowDriver) failStep(ctx context.Context, st *runState, idx int) (*RunResult, *hitlGate, error) {
func (d *flowDriver) failStep(ctx context.Context, st *RunState, idx int) (*RunResult, *HitlGate, error) {
st.mu.Lock()
step := st.Plan.Workflow.Steps[idx]
critical := step.IsCritical()
@@ -402,7 +630,7 @@ func (d *flowDriver) failStep(ctx context.Context, st *runState, idx int) (*RunR
}
// checkBlockingGaps 检查未解决阻塞缺口;interactive 挂起,auto 记录兜底假设并继续。
func (d *flowDriver) checkBlockingGaps(st *runState) *hitlGate {
func (d *flowDriver) checkBlockingGaps(st *RunState) *HitlGate {
gaps := st.BB.UnresolvedBlockingGaps()
if len(gaps) == 0 {
return nil
@@ -444,7 +672,7 @@ func (d *flowDriver) checkBlockingGaps(st *runState) *hitlGate {
Context: strings.Join(lines, "\n"),
CreatedAt: time.Now(), Status: "pending",
}
gate := &hitlGate{Request: *req, PrevStatus: RunExecuting}
gate := &HitlGate{Request: *req, PrevStatus: RunExecuting}
if err := st.saveGate(gate); err == nil {
st.Meta.Status = string(RunWaitingHuman)
_ = st.save()
@@ -454,7 +682,7 @@ func (d *flowDriver) checkBlockingGaps(st *runState) *hitlGate {
}
// applyDynamicAdjustment 评估步骤产出并应用/审批动态调整。
func (d *flowDriver) applyDynamicAdjustment(ctx context.Context, st *runState, idx int) (*RunResult, *hitlGate, error) {
func (d *flowDriver) applyDynamicAdjustment(ctx context.Context, st *RunState, idx int) (*RunResult, *HitlGate, error) {
step := st.Plan.Workflow.Steps[idx]
subDir := filepath.Join(st.Meta.WorkDir, filepath.FromSlash(step.SubWorkspace))
output := readFileOr(filepath.Join(subDir, firstTarget(step.Targets)), "")
@@ -494,7 +722,7 @@ func (d *flowDriver) applyDynamicAdjustment(ctx context.Context, st *runState, i
evalRes.Reason, strings.Join(addLines, "\n"), strings.Join(skipLines, "\n")),
CreatedAt: time.Now(), Status: "pending",
}
gate := &hitlGate{Request: *req, Steps: evalRes.DynamicStepsToAdd, SkipIDs: evalRes.StepsToSkip, PrevStatus: RunExecuting}
gate := &HitlGate{Request: *req, Steps: evalRes.DynamicStepsToAdd, SkipIDs: evalRes.StepsToSkip, PrevStatus: RunExecuting}
if err := st.saveGate(gate); err == nil {
st.Meta.Status = string(RunWaitingHuman)
_ = st.save()
@@ -507,7 +735,7 @@ func (d *flowDriver) applyDynamicAdjustment(ctx context.Context, st *runState, i
}
// applyAdjustment 应用动态调整:新步骤插到最后一步之前,跳过步骤标记 skipped。
func applyAdjustment(st *runState, add []StepSpec, skipIDs []string) {
func applyAdjustment(st *RunState, add []StepSpec, skipIDs []string) {
steps := st.Plan.Workflow.Steps
for _, id := range skipIDs {
for i := range steps {
@@ -534,11 +762,15 @@ func applyAdjustment(st *runState, add []StepSpec, skipIDs []string) {
}
// finalize 收口:汇总交付物 → 质检 → 自动修复 → (必要时)人工裁决 → 清单。
func (d *flowDriver) finalize(ctx context.Context, st *runState) (*RunResult, *hitlGate, error) {
func (d *flowDriver) finalize(ctx context.Context, st *RunState) (*RunResult, *HitlGate, error) {
wf := st.Workflow()
degraded := false
for _, s := range wf.Steps {
if s.Status == "failed" || s.Status == "skipped" {
if s.Status == "failed" {
degraded = true
}
// router 分支落选是预期路径,不算降级(Q2)。
if s.Status == "skipped" && s.Error != routerSkipReason {
degraded = true
}
}
@@ -616,7 +848,7 @@ func (d *flowDriver) finalize(ctx context.Context, st *runState) (*RunResult, *h
Context: string(marshalJSON(report)),
CreatedAt: time.Now(), Status: "pending",
}
gate := &hitlGate{Request: *req, PrevStatus: RunExecuting}
gate := &HitlGate{Request: *req, PrevStatus: RunExecuting}
if err := st.saveGate(gate); err == nil {
st.Meta.Status = string(RunQualityReview)
_ = st.save()
@@ -650,7 +882,7 @@ func (d *flowDriver) finalize(ctx context.Context, st *runState) (*RunResult, *h
}
// rerunForRepair 重置交付物源步骤并重新执行到收口。
func (d *flowDriver) rerunForRepair(ctx context.Context, st *runState, stepID string) (*RunResult, *hitlGate, error) {
func (d *flowDriver) rerunForRepair(ctx context.Context, st *RunState, stepID string) (*RunResult, *HitlGate, error) {
for i := range st.Plan.Workflow.Steps {
if st.Plan.Workflow.Steps[i].ID == stepID {
st.Plan.Workflow.Steps[i].Status = "pending"
@@ -668,7 +900,7 @@ func (d *flowDriver) rerunForRepair(ctx context.Context, st *runState, stepID st
}
// heldResult 由挂起上下文构造对外结果(挂起路径统一返回非 nil 结果)。
func heldResult(st *runState, gate *hitlGate) *RunResult {
func heldResult(st *RunState, gate *HitlGate) *RunResult {
status := RunWaitingHuman
switch gate.Request.Kind {
case HitlClarification:
@@ -698,7 +930,7 @@ func waitConditionFrom(gaps []GapItem) *WaitCondition {
}
// hold 生成挂起请求并返回结果。
func (d *flowDriver) hold(st *runState, kind HumanRequestKind, stepID, role, question string, options []HumanOption, context, reason string, extra *hitlGate) (*RunResult, *hitlGate, error) {
func (d *flowDriver) hold(st *RunState, kind HumanRequestKind, stepID, role, question string, options []HumanOption, context, reason string, extra *HitlGate) (*RunResult, *HitlGate, error) {
req := &HumanRequest{
ID: newRequestID(), RunID: st.Meta.ID, StepID: stepID, Kind: kind,
Severity: SeverityActionRequired,
@@ -714,7 +946,7 @@ func (d *flowDriver) hold(st *runState, kind HumanRequestKind, stepID, role, que
}
gate := extra
if gate == nil {
gate = &hitlGate{}
gate = &HitlGate{}
}
gate.Request = *req
gate.PrevStatus = RunExecuting
@@ -731,7 +963,7 @@ func (d *flowDriver) hold(st *runState, kind HumanRequestKind, stepID, role, que
// policy 合并引擎全局策略与 Goal 覆盖(窄者胜)。
// policyRole 在引擎全局/Goal 链之上叠加角色级 HitlPolicy
// (窄者胜;Goal 仍最高)。
func (d *flowDriver) policyRole(st *runState, role RoleSpec) HitlPolicy {
func (d *flowDriver) policyRole(st *RunState, role RoleSpec) HitlPolicy {
p := d.policy(st)
if role.HitlPolicy != nil {
p = mergeHitlPolicy(p, role.HitlPolicy)
@@ -739,11 +971,11 @@ func (d *flowDriver) policyRole(st *runState, role RoleSpec) HitlPolicy {
return p
}
func (d *flowDriver) policy(st *runState) HitlPolicy {
func (d *flowDriver) policy(st *RunState) HitlPolicy {
return mergeHitlPolicy(d.opts.HitlPolicy, st.Meta.HitlPolicyOf())
}
func (d *flowDriver) emit(st *runState, ev Event) {
func (d *flowDriver) emit(st *RunState, ev Event) {
if d.opts.Sink == nil {
return
}
@@ -754,11 +986,11 @@ func (d *flowDriver) emit(st *runState, ev Event) {
d.opts.Sink.Emit(ev)
}
func (d *flowDriver) emitHuman(st *runState, req *HumanRequest) {
func (d *flowDriver) emitHuman(st *RunState, req *HumanRequest) {
d.emit(st, Event{Type: EvHumanInputRequired, Text: req.Question, Data: marshalJSON(req)})
}
func summarize(st *runState, report QualityReport, status RunStatus) string {
func summarize(st *RunState, report QualityReport, status RunStatus) string {
var b strings.Builder
fmt.Fprintf(&b, "运行 %s:%s。步骤 %d 个(完成 %d/跳过 %d/失败 %d)。质检得分 %.0f。",
st.Meta.ID, status, len(st.Plan.Workflow.Steps),
@@ -769,7 +1001,7 @@ func summarize(st *runState, report QualityReport, status RunStatus) string {
return b.String()
}
func countStatus(st *runState, status string) int {
func countStatus(st *RunState, status string) int {
n := 0
for _, s := range st.Plan.Workflow.Steps {
if s.Status == status {
@@ -779,7 +1011,7 @@ func countStatus(st *runState, status string) int {
return n
}
func buildManifest(st *runState, deliverable string, report QualityReport) Manifest {
func buildManifest(st *RunState, deliverable string, report QualityReport) Manifest {
files := map[string]string{}
_ = filepath.Walk(st.Meta.WorkDir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
@@ -838,7 +1070,7 @@ func appendLog(dir, line string) {
_, _ = f.WriteString(line)
}
func planPtr(st *runState) *WorkflowPlan {
func planPtr(st *RunState) *WorkflowPlan {
wf := st.Workflow()
return &wf
}
+3 -12
View File
@@ -34,18 +34,9 @@ func (e *WorkspaceEngine) PrepareWorkspace(meta *RunMetadata, plan *SquadPlan) (
}
meta.WorkDir = wsDir
meta.UpdatedAt = time.Now()
if err := writeJSON(filepath.Join(wsDir, "workspace.json"), meta); err != nil {
return "", err
}
if err := writeJSON(filepath.Join(wsDir, "squad.json"), &plan.Squad); err != nil {
return "", err
}
if err := writeJSON(filepath.Join(wsDir, "workflow.json"), &plan.Workflow); err != nil {
return "", err
}
if err := saveBlackboard(wsDir, &BlackboardState{Fields: map[string]string{}}); err != nil {
return "", err
}
// 注意:run 级状态 JSON 不在此处写——由 st.save() 经 Store 端口统一落盘
// (Q1 WP5:SQLite 后端时这些状态进数据库而非文件)。这里只建目录与
// 上下文/模板等运行无关状态的工作区资产。
ctxIdx, err := e.writeContextAssets(wsDir, &meta.Goal, plan)
if err != nil {
return "", err