pi-legion 3.1.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +382 -2
  2. package/CONTRIBUTING.md +4 -17
  3. package/README.md +127 -66
  4. package/agents/centurion.md +20 -16
  5. package/agents/scout.md +3 -1
  6. package/agents/worker.md +6 -8
  7. package/docs/contracts/declarative-phase-machine-v5.md +128 -0
  8. package/docs/contracts/display-liveness-v1.md +373 -0
  9. package/docs/contracts/drop-non-pi-kinds-v4.md +198 -0
  10. package/docs/contracts/esc-abort-v1.md +4 -4
  11. package/docs/contracts/esc-no-retire-v3.md +2 -2
  12. package/docs/contracts/launch-admission-queue-v1.md +839 -0
  13. package/docs/contracts/status-panel-v1.md +174 -0
  14. package/docs/contracts/subagent-renewal-v1.md +260 -0
  15. package/docs/headless-child-contract.md +6 -3
  16. package/docs/inprocess-supervisor.md +106 -27
  17. package/docs/legion-v2-contract.md +27 -2
  18. package/docs/performance-2026-10-19.md +199 -0
  19. package/docs/spawn-mode-visibility-v1.md +4 -1
  20. package/docs/vexillatio-contract.md +3 -1
  21. package/index.ts +1155 -120
  22. package/package.json +5 -3
  23. package/skills/pi-legion/SKILL.md +2 -3
  24. package/src/agents/agents.ts +310 -46
  25. package/src/agents/overrides.ts +3 -2
  26. package/src/agents/presets.ts +14 -40
  27. package/src/agents/settings.ts +32 -95
  28. package/src/agents/step-model.ts +7 -22
  29. package/src/api.ts +1 -35
  30. package/src/extension/child-guard.ts +25 -1
  31. package/src/extension/event-bus.ts +80 -8
  32. package/src/extension/legion-commands.ts +41 -17
  33. package/src/extension/legion-doctor.ts +1 -1
  34. package/src/extension/legion-stop.ts +39 -13
  35. package/src/extension/legion-tools.ts +87 -25
  36. package/src/extension/liveness.ts +200 -0
  37. package/src/extension/notify.ts +136 -4
  38. package/src/extension/playbook.ts +4 -4
  39. package/src/extension/recycle.ts +4 -0
  40. package/src/extension/runtime.ts +435 -16
  41. package/src/extension/slash.ts +0 -21
  42. package/src/extension/summary.ts +14 -5
  43. package/src/extension/timing.ts +8 -4
  44. package/src/legion/db.ts +165 -1
  45. package/src/legion/events.ts +81 -16
  46. package/src/legion/nodes.ts +13 -2
  47. package/src/legion/phase-conditions.ts +164 -0
  48. package/src/legion/phase-machine.ts +403 -0
  49. package/src/legion/rebuild.ts +7 -1
  50. package/src/legion/state-machine.ts +219 -115
  51. package/src/legion/usage.ts +58 -4
  52. package/src/runs/args.ts +32 -18
  53. package/src/runs/extension-inheritance.ts +220 -0
  54. package/src/runs/orchestrator.ts +1292 -96
  55. package/src/runs/progress-signal.ts +137 -0
  56. package/src/runs/store-lookup.ts +270 -0
  57. package/src/runs/worktree.ts +190 -21
  58. package/src/shared/ignored-kind.ts +57 -0
  59. package/src/shared/progress.ts +11 -0
  60. package/src/shared/session.ts +199 -19
  61. package/src/shared/types.ts +138 -69
  62. package/src/supervisor/admission-queue.ts +516 -0
  63. package/src/supervisor/child-context.ts +19 -0
  64. package/src/supervisor/inprocess-supervisor.ts +137 -38
  65. package/src/supervisor/proc-memory.ts +67 -0
  66. package/src/supervisor/routing-supervisor.ts +60 -2
  67. package/src/supervisor/rpc-supervisor.ts +2 -2
  68. package/src/tui/session-messages-file.ts +100 -0
  69. package/src/tui/status.ts +91 -18
  70. package/src/tui/tree-view.ts +84 -3
  71. package/src/tui/viz/layout.ts +54 -3
  72. package/src/tui/viz/model.ts +67 -14
  73. package/src/tui/viz/palette.ts +11 -3
  74. package/src/tui/viz/panels.ts +222 -8
  75. package/src/tui/viz/view.ts +110 -23
  76. package/agents/advisor.md +0 -110
  77. package/agents/designer.md +0 -87
  78. package/agents/planner.md +0 -53
  79. package/agents/prototype.md +0 -72
  80. package/agents/reviewer.md +0 -113
  81. package/src/backends/legacy/client.ts +0 -638
  82. package/src/backends/legacy/cursor-chat.ts +0 -348
  83. package/src/backends/legacy/runner.ts +0 -101
  84. package/src/backends/legacy/types.ts +0 -138
  85. package/src/runs/kind.ts +0 -260
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-legion",
3
- "version": "3.1.0",
4
- "description": "Pi Legion v2: recursive centurion trees on headless Pi RPC; shared SQLite WAL legion.db. Four-stage planning/implementing/reviewing/verifying state machine, parent/child/sibling legion_mail, three-layer /legion UI, upward MR trees, squad resume.",
3
+ "version": "5.0.0",
4
+ "description": "Pi Legion v2: recursive centurion teams on Pi. Children run in-process by default (rpc only for a worktree-owning centurion); shared SQLite WAL legion.db. Declarative per-team phase machine (built-in default: planning/implementing/reviewing/verifying), parent/child/sibling legion_mail, three-layer /legion UI, upward MR trees, squad resume.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -54,9 +54,11 @@
54
54
  "test:integration": "env -u PI_SUBAGENT_ROLE -u PI_SUBAGENT_ACCEPTANCE_ROLE -u PI_SUBAGENT_ALLOW_NESTED -u PI_SUBAGENT_CHILD -u PI_SUBAGENT_UTILITY_CHILD -u PI_SUBAGENT_MAX_DEPTH -u PI_SUBAGENT_PARENT_PATH -u PI_LEGION_DB -u PI_LEGION_NODE_ID node --experimental-strip-types --test test/integration/*.test.ts",
55
55
  "test:live": "env -u PI_SUBAGENT_ROLE -u PI_SUBAGENT_ACCEPTANCE_ROLE -u PI_SUBAGENT_ALLOW_NESTED -u PI_SUBAGENT_CHILD -u PI_SUBAGENT_UTILITY_CHILD -u PI_SUBAGENT_MAX_DEPTH -u PI_SUBAGENT_PARENT_PATH -u PI_LEGION_DB -u PI_LEGION_NODE_ID node --experimental-strip-types --test test/live/*.test.ts",
56
56
  "test:all": "node --run typecheck && node --run test && node --run test:integration",
57
- "test:docker": "env -u PI_SUBAGENT_ROLE -u PI_SUBAGENT_ACCEPTANCE_ROLE -u PI_SUBAGENT_ALLOW_NESTED -u PI_SUBAGENT_CHILD -u PI_SUBAGENT_UTILITY_CHILD -u PI_SUBAGENT_MAX_DEPTH -u PI_SUBAGENT_PARENT_PATH sh -c 'echo \"RPC mainline Docker checks only; legacy Herdr workspace/kind/notification scenarios are archived under test/legacy/docker and require pi-legion v0.16.x\" && bash test/docker/verify-1-child-guard.sh && bash test/docker/verify-2-task-appendix.sh && bash test/docker/verify-3-readonly.sh && bash test/docker/verify-4-acceptance.sh && bash test/docker/verify-5-blocked.sh && bash test/docker/verify-6-cache.sh && bash test/docker/verify-7-budget.sh && bash test/docker/verify-8-verify-command.sh && bash test/docker/verify-9-worktree.sh && bash test/docker/verify-10-fallback.sh && bash test/docker/verify-11-nested-alias.sh'",
57
+ "test:docker": "env -u PI_SUBAGENT_ROLE -u PI_SUBAGENT_ACCEPTANCE_ROLE -u PI_SUBAGENT_ALLOW_NESTED -u PI_SUBAGENT_CHILD -u PI_SUBAGENT_UTILITY_CHILD -u PI_SUBAGENT_MAX_DEPTH -u PI_SUBAGENT_PARENT_PATH sh -c 'echo \"Docker mainline checks for the RPC path only\" && bash test/docker/verify-1-child-guard.sh && bash test/docker/verify-2-task-appendix.sh && bash test/docker/verify-3-readonly.sh && bash test/docker/verify-4-acceptance.sh && bash test/docker/verify-5-blocked.sh && bash test/docker/verify-6-cache.sh && bash test/docker/verify-7-budget.sh && bash test/docker/verify-8-verify-command.sh && bash test/docker/verify-9-worktree.sh && bash test/docker/verify-10-fallback.sh && bash test/docker/verify-11-nested-alias.sh'",
58
58
  "prepublishOnly": "node --run typecheck && node --run test && node --run test:integration",
59
59
  "mock-llm": "node --experimental-strip-types test/mock-llm/cli.ts",
60
+ "test:perf": "env -u PI_SUBAGENT_ROLE -u PI_SUBAGENT_ACCEPTANCE_ROLE -u PI_SUBAGENT_ALLOW_NESTED -u PI_SUBAGENT_CHILD -u PI_SUBAGENT_UTILITY_CHILD -u PI_SUBAGENT_MAX_DEPTH -u PI_SUBAGENT_PARENT_PATH -u PI_LEGION_DB -u PI_LEGION_NODE_ID node --experimental-strip-types --test test/perf/*.test.ts",
61
+ "test:wal-stress": "node --experimental-strip-types test/stress/wal-stress.ts",
60
62
  "test:mock-llm": "env -u PI_SUBAGENT_ROLE -u PI_SUBAGENT_ACCEPTANCE_ROLE -u PI_SUBAGENT_ALLOW_NESTED -u PI_SUBAGENT_CHILD -u PI_SUBAGENT_UTILITY_CHILD -u PI_SUBAGENT_MAX_DEPTH -u PI_SUBAGENT_PARENT_PATH -u PI_LEGION_DB -u PI_LEGION_NODE_ID node --experimental-strip-types --test test/unit/mock-llm*.test.ts test/integration/mock-llm*.test.ts test/integration/railway-mock-e2e.test.ts",
61
63
  "test:tui-visual": "docker build -q -f test/docker/Dockerfile.tui-sandbox -t ghcr.io/zzjcool/pi-legion/tui-sandbox:latest . >/dev/null && docker run --rm -v $(pwd):/plugin -w /plugin ghcr.io/zzjcool/pi-legion/tui-sandbox:latest bash test/docker/verify-tui-visual.sh"
62
64
  },
@@ -82,9 +82,8 @@ Keep the run/session records while the squad may need to resume. The
82
82
 
83
83
  A Git worktree is workspace separation, not a security sandbox. Read-only
84
84
  checks remain guardrails rather than a process boundary; never rely on them to
85
- protect against intentional writes. Pi Legion v2 supports `kind: pi`; for a
86
- role that requires a non-Pi CLI, use the Herdr-era 0.16.x release line rather
87
- than expecting v2 to launch it.
85
+ protect against intentional writes. Pi Legion runs `kind: pi` roles only; the
86
+ `kind` frontmatter key is still legal but `pi` is the only accepted value.
88
87
 
89
88
  ## Later control
90
89
 
@@ -19,7 +19,6 @@ import {
19
19
  type AcceptanceCriterion,
20
20
  type OnBlockedPolicy,
21
21
  type SpawnMode,
22
- SPAWN_MODES,
23
22
  type SystemPromptMode,
24
23
  type ToolBudgetConfig,
25
24
  type TurnBudgetConfig,
@@ -30,16 +29,20 @@ import {
30
29
  stripQuotes,
31
30
  } from "./frontmatter.ts";
32
31
  import { getAgentDir } from "./paths.ts";
32
+ import { ignoredKindMessage, reportIgnoredOnce } from "../shared/ignored-kind.ts";
33
+ import {
34
+ type PhaseDefinition,
35
+ type PhaseMachine,
36
+ type PhaseTransitionRule,
37
+ normalizePhaseMachine,
38
+ validatePhaseMachine,
39
+ } from "../legion/phase-machine.ts";
40
+ import type { PhaseCondition } from "../legion/phase-conditions.ts";
33
41
 
34
42
  export const BUILTIN_AGENT_NAMES = [
35
43
  "scout",
36
- "planner",
37
- "reviewer",
38
44
  "worker",
39
45
  "centurion",
40
- "advisor",
41
- "designer",
42
- "prototype",
43
46
  ] as const;
44
47
 
45
48
  /**
@@ -176,15 +179,6 @@ function int(value: unknown): number | undefined {
176
179
  return undefined;
177
180
  }
178
181
 
179
- function spawnModeOf(value: unknown, filePath: string): SpawnMode | undefined {
180
- if (value === undefined || value === null || value === "") return undefined;
181
- const raw = typeof value === "string" ? value.trim() : String(value);
182
- if ((SPAWN_MODES as readonly string[]).includes(raw)) return raw as SpawnMode;
183
- throw new Error(
184
- `Agent '${filePath}' has invalid spawnMode '${raw}'; expected one of: ${SPAWN_MODES.join(", ")}.`,
185
- );
186
- }
187
-
188
182
 
189
183
  /**
190
184
  * Accept `tools: read, bash`, `tools: [read, bash]`, and block-list spellings.
@@ -412,28 +406,281 @@ function parseCriteria(value: unknown): AcceptanceCriterion[] | undefined {
412
406
  return criteria.length > 0 ? criteria : undefined;
413
407
  }
414
408
 
415
- function parseBudget(value: unknown): ToolBudgetConfig | undefined {
416
- const raw = str(value);
417
- if (!raw) return undefined;
418
- try {
419
- const parsed = JSON.parse(raw) as Record<string, unknown>;
420
- const max = int(parsed.maxToolCalls);
421
- return max === undefined ? undefined : { maxToolCalls: max };
422
- } catch {
423
- return undefined;
409
+ /**
410
+ * Read an indented `phases:` block into the machine shape (#298).
411
+ *
412
+ * The shared frontmatter parser is flat — nested lists come back as raw text —
413
+ * so this walks the text itself. The grammar is deliberately tiny and matches
414
+ * only what a card can express:
415
+ *
416
+ * ```text
417
+ * - id: planning # a phase
418
+ * require: [contract_file] # inline condition list
419
+ * timeoutMs: 900000
420
+ * terminal: false
421
+ * next: # a list of transitions
422
+ * - to: implementing
423
+ * require: [contract_file]
424
+ * actorRole: centurion
425
+ * rework: true
426
+ * - to: failed
427
+ * ```
428
+ *
429
+ * Anything outside this shape is an error rather than a silent skip, because a
430
+ * half-read machine is worse than none: it would run with the transitions it
431
+ * happened to parse.
432
+ */
433
+ function parsePhaseBlock(text: string): PhaseMachine | undefined {
434
+ // `id` is filled from the `- id: ...` line; validatePhaseMachine rejects a
435
+ // machine where it is missing, so the assertion at the end is safe.
436
+ type PhaseDraft = Record<string, unknown> & { id: string; next?: Array<Record<string, unknown>> };
437
+ const phases: PhaseDraft[] = [];
438
+ let currentPhase: PhaseDraft | undefined;
439
+ let currentRule: Record<string, unknown> | undefined;
440
+ // Column where list items live. The first `- ` we see sets it, so the block may
441
+ // be indented by any amount relative to the document.
442
+ let itemIndent = -1;
443
+
444
+ const scalar = (value: string): unknown => {
445
+ const trimmed = value.trim();
446
+ if (trimmed === "true") return true;
447
+ if (trimmed === "false") return false;
448
+ if (/^-?\d+$/.test(trimmed)) return Number(trimmed);
449
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
450
+ const inner = trimmed.slice(1, -1).trim();
451
+ if (!inner) return [];
452
+ return inner.split(",").map((part) => part.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
453
+ }
454
+ return trimmed.replace(/^["']|["']$/g, "");
455
+ };
456
+
457
+ for (const rawLine of text.split("\n")) {
458
+ if (!rawLine.trim()) continue;
459
+ const indent = rawLine.length - rawLine.trimStart().length;
460
+ const line = rawLine.trim();
461
+
462
+ if (line.startsWith("- ")) {
463
+ if (itemIndent === -1) itemIndent = indent;
464
+ const body = line.slice(2).trim();
465
+ const entry: Record<string, unknown> = {};
466
+ const colon = body.indexOf(":");
467
+ if (colon > 0) entry[body.slice(0, colon).trim()] = scalar(body.slice(colon + 1));
468
+ // A `- ` at the item column opens a phase; deeper opens a transition.
469
+ if (indent <= itemIndent) {
470
+ currentPhase = entry as PhaseDraft;
471
+ currentPhase.next = [];
472
+ phases.push(currentPhase);
473
+ currentRule = undefined;
474
+ } else if (currentPhase) {
475
+ currentRule = entry;
476
+ currentPhase.next!.push(entry);
477
+ }
478
+ continue;
479
+ }
480
+
481
+ const colon = line.indexOf(":");
482
+ if (colon <= 0) continue;
483
+ const key = line.slice(0, colon).trim();
484
+ const value = line.slice(colon + 1).trim();
485
+ const target = currentRule ?? currentPhase;
486
+ if (!target) continue;
487
+ if (value === "") {
488
+ // `next:` with nothing after it — the transitions follow as `- to:` lines.
489
+ if (key === "next") target.next = target.next ?? [];
490
+ continue;
491
+ }
492
+ target[key] = scalar(value);
493
+ }
494
+
495
+ if (phases.length === 0) return undefined;
496
+ // Convert the walked drafts into the declared shape explicitly instead of
497
+ // asserting it. `validatePhaseMachine` runs right after this and rejects
498
+ // anything malformed, but doing the coercion here means the compiler — not just
499
+ // the validator — has seen every field.
500
+ const converted: PhaseDefinition[] = phases.map((draft) => {
501
+ const rules: PhaseTransitionRule[] = (draft.next ?? []).map((rule) => {
502
+ const out: PhaseTransitionRule = { to: String(rule.to ?? "") };
503
+ if (Array.isArray(rule.require)) out.require = rule.require.map(String) as PhaseCondition[];
504
+ if (typeof rule.actorRole === "string") out.actorRole = rule.actorRole;
505
+ if (rule.rework === true) out.rework = true;
506
+ if (rule.notifyParent === true) out.notifyParent = true;
507
+ return out;
508
+ });
509
+ const phase: PhaseDefinition = { id: String(draft.id ?? ""), next: rules };
510
+ if (Array.isArray(draft.require)) phase.require = draft.require.map(String) as PhaseCondition[];
511
+ if (typeof draft.timeoutMs === "number") phase.timeoutMs = draft.timeoutMs;
512
+ if (draft.terminal === true) phase.terminal = true;
513
+ return phase;
514
+ });
515
+ const machine: PhaseMachine = { phases: converted };
516
+ if (typeof (phases as unknown as { start?: unknown }).start === "string") {
517
+ machine.start = String((phases as unknown as { start: string }).start);
424
518
  }
519
+ return machine;
425
520
  }
426
521
 
427
- function parseTurnBudget(value: unknown): TurnBudgetConfig | undefined {
428
- const raw = str(value);
429
- if (!raw) return undefined;
430
- try {
431
- const parsed = JSON.parse(raw) as Record<string, unknown>;
432
- const max = int(parsed.maxTurns);
433
- return max === undefined ? undefined : { maxTurns: max };
434
- } catch {
435
- return undefined;
522
+ /**
523
+ * Parse a declared phase machine from `phases:` (#298).
524
+ *
525
+ * Accepts the YAML shape directly (a list of phase objects), or the same thing
526
+ * as a JSON string, matching how `toolBudget` is written.
527
+ *
528
+ * Validation happens HERE, at load, and every problem is reported at once. A
529
+ * machine that only fails mid-run would surface after a team had already spent
530
+ * tokens on a workflow that could never complete.
531
+ */
532
+ function parsePhaseMachine(value: unknown, filePath: string): PhaseMachine | undefined {
533
+ if (value === undefined || value === null) return undefined;
534
+ let raw: unknown = value;
535
+ if (typeof value === "string") {
536
+ const text = value.trim();
537
+ if (!text) return undefined;
538
+ // The frontmatter parser is FLAT, so a nested `phases:` block arrives here
539
+ // as raw text — exactly the situation `parseAcceptance` already handles.
540
+ // Two spellings are therefore accepted: an indented YAML block (what the
541
+ // card looks like) and a one-line JSON string (easier to generate).
542
+ let parsedText: unknown;
543
+ let wasJson = true;
544
+ try {
545
+ parsedText = JSON.parse(text);
546
+ } catch {
547
+ wasJson = false;
548
+ parsedText = parsePhaseBlock(text);
549
+ }
550
+ if (!wasJson && parsedText === undefined) {
551
+ throw new Error(
552
+ `Agent '${filePath}' has invalid phases: could not read the block. ` +
553
+ `Expected an indented list of " - id: <name>" entries, or a JSON string.`,
554
+ );
555
+ }
556
+ raw = parsedText;
557
+ }
558
+ // Accept both `[{...}]` and `{ phases: [...] }`.
559
+ const shaped = Array.isArray(raw)
560
+ ? ({ phases: raw } as unknown)
561
+ : raw;
562
+ if (shaped === null || typeof shaped !== "object") {
563
+ throw new Error(`Agent '${filePath}' has invalid phases: expected a list or an object with a 'phases' key.`);
436
564
  }
565
+ const machine = shaped as PhaseMachine;
566
+ if (!Array.isArray(machine.phases)) {
567
+ throw new Error(`Agent '${filePath}' has invalid phases: 'phases' must be a list.`);
568
+ }
569
+ // Inject the universal terminals before validating, so reachability is judged
570
+ // on the machine as it will actually run.
571
+ const normalized = normalizePhaseMachine(machine);
572
+ const errors = validatePhaseMachine(normalized);
573
+ if (errors.length > 0) {
574
+ const detail = errors.map((error) => ` - ${error.path}: ${error.message}`).join("\n");
575
+ throw new Error(`Agent '${filePath}' has an invalid phase machine:\n${detail}`);
576
+ }
577
+ return normalized;
578
+ }
579
+
580
+ /**
581
+ * Parse a child budget (`toolBudget` / `turnBudget`) strictly.
582
+ *
583
+ * These used to swallow every error and return `undefined`, so a typo became
584
+ * "no limit" -- the same silent-acceptance failure the frontmatter field check
585
+ * exists to prevent. Worse, a NEGATIVE number was accepted: `-3` reached the
586
+ * child, `toolCalls > -3` was true immediately, and the first tool call was
587
+ * blocked while the author believed they had set a limit of 3.
588
+ *
589
+ * `0` is meaningful here ("no calls allowed", per `extension/budget.ts`), so it
590
+ * must survive rather than decay into "unset". Anything that is not a
591
+ * non-negative integer is an error naming the file and the field.
592
+ */
593
+ function parseBudgets(fm: AgentFrontmatter, filePath: string): {
594
+ tool?: ToolBudgetConfig;
595
+ turn?: TurnBudgetConfig;
596
+ } {
597
+ const read = (
598
+ field: "toolBudget" | "turnBudget",
599
+ key: "maxToolCalls" | "maxTurns",
600
+ ): number | undefined => {
601
+ const raw = str(fm[field]);
602
+ if (!raw) return undefined;
603
+ let parsed: unknown;
604
+ try {
605
+ parsed = JSON.parse(raw);
606
+ } catch {
607
+ throw new Error(
608
+ `Agent '${filePath}' has invalid ${field}: expected a JSON object like '{"${key}": 10}', got '${raw}'.`,
609
+ );
610
+ }
611
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
612
+ throw new Error(
613
+ `Agent '${filePath}' has invalid ${field}: expected a JSON object with a '${key}' key.`,
614
+ );
615
+ }
616
+ const value = (parsed as Record<string, unknown>)[key];
617
+ if (value === undefined) return undefined;
618
+ if (typeof value !== "number" || !Number.isInteger(value)) {
619
+ throw new Error(
620
+ `Agent '${filePath}' has invalid ${field}.${key}: expected a non-negative integer, got ${JSON.stringify(value)}.`,
621
+ );
622
+ }
623
+ if (value < 0) {
624
+ throw new Error(
625
+ `Agent '${filePath}' has invalid ${field}.${key}: ${value} is negative. ` +
626
+ `0 means "none allowed"; omit the field for "no limit".`,
627
+ );
628
+ }
629
+ return value;
630
+ };
631
+ const toolMax = read("toolBudget", "maxToolCalls");
632
+ const turnMax = read("turnBudget", "maxTurns");
633
+ return {
634
+ ...(toolMax !== undefined ? { tool: { maxToolCalls: toolMax } } : {}),
635
+ ...(turnMax !== undefined ? { turn: { maxTurns: turnMax } } : {}),
636
+ };
637
+ }
638
+
639
+ /**
640
+ * Every frontmatter key a role card may declare.
641
+ *
642
+ * Kept next to the parser on purpose: an unknown key used to be silently
643
+ * ignored, so a typo (`maxSubagentdepth`, `inheritSkill`) produced a card that
644
+ * looked accepted but did nothing. That is the worst failure mode for a config
645
+ * file — the author believes the setting is in effect. Cards are now validated
646
+ * against this list and an unknown key is a hard error.
647
+ *
648
+ * When adding a field, add it here AND parse it; a name in this list that no
649
+ * parser reads is just as misleading as the reverse.
650
+ */
651
+ const AGENT_FRONTMATTER_FIELDS: ReadonlySet<string> = new Set([
652
+ // identity
653
+ "name", "description", "kind", "model", "thinking", "alias", "aliases",
654
+ "preset", "team", "output", "fallbackModels",
655
+ // prompt / context
656
+ "systemPromptMode", "inheritProjectContext", "inheritSkills", "inheritExtensions",
657
+ "excludeExtensions",
658
+ "phases",
659
+ "skillPath", "skills", "defaultReads",
660
+ // tools
661
+ "tools", "extensions", "subagentOnlyExtensions",
662
+ // budgets / guards / lifecycle
663
+ "defaultProgress", "async", "timeoutMs", "toolTimeoutMs", "completionGuard",
664
+ "maxSubagentDepth", "allowNestedSubagents", "renewable", "maxRenewals",
665
+ "utility", "disabled", "worktree", "steer", "onBlocked",
666
+ "acceptance", "toolBudget", "turnBudget",
667
+ ]);
668
+
669
+ /**
670
+ * Throw when a card declares a key this parser does not understand.
671
+ *
672
+ * Names are compared case-sensitively: YAML keys are case-sensitive, and a
673
+ * near-miss (`MaxRenewals`) is exactly the typo this is meant to catch.
674
+ */
675
+ function assertKnownFrontmatter(frontmatter: Record<string, unknown>, filePath: string): void {
676
+ const unknown = Object.keys(frontmatter).filter((key) => !AGENT_FRONTMATTER_FIELDS.has(key));
677
+ if (unknown.length === 0) return;
678
+ const known = [...AGENT_FRONTMATTER_FIELDS].sort().join(", ");
679
+ throw new Error(
680
+ `Agent '${filePath}' has unknown frontmatter ${unknown.length === 1 ? "field" : "fields"}: ` +
681
+ `${unknown.map((key) => `'${key}'`).join(", ")}. ` +
682
+ `Known fields: ${known}.`,
683
+ );
437
684
  }
438
685
 
439
686
  /**
@@ -447,6 +694,7 @@ export function parseAgentDocument(
447
694
  ): AgentConfig | null {
448
695
  const { frontmatter, body } = parseFrontmatter(content);
449
696
  const fm = frontmatter as AgentFrontmatter;
697
+ assertKnownFrontmatter(fm, filePath);
450
698
 
451
699
  const name = str(fm.name);
452
700
  const description = str(fm.description);
@@ -460,7 +708,7 @@ export function parseAgentDocument(
460
708
  inheritProjectContext: bool(fm.inheritProjectContext) ?? true,
461
709
  inheritSkills: bool(fm.inheritSkills) ?? false,
462
710
  ...(bool(fm.inheritExtensions) !== undefined ? { inheritExtensions: bool(fm.inheritExtensions) } : {}),
463
- kind: enumOr<AgentKind>(fm.kind, VALID_KINDS, "pi"),
711
+ kind: parseKind(fm.kind, name),
464
712
  systemPrompt: body,
465
713
  source,
466
714
  filePath,
@@ -496,17 +744,23 @@ function setIf<T extends object, K extends keyof T>(
496
744
  }
497
745
 
498
746
  /**
499
- * Pick a value only when it is a member of `allowed`.
500
- * An invalid enum degrades to the default rather than failing the whole file,
501
- * so a typo in one field cannot break discovery.
747
+ * Resolve the role's `kind`.
748
+ *
749
+ * v4 runs `pi` only. The key stays legal frontmatter (and `AgentConfig.kind`
750
+ * stays), but a value outside `AGENT_KINDS` is ignored: the role launches as
751
+ * `pi` and this is reported once, naming the role and the value it tried to
752
+ * set. Silently coercing would leave the user believing a non-pi CLI is in
753
+ * play, so an invalid/absent value is the only case that speaks up.
502
754
  */
503
- function enumOr<T extends string>(
504
- value: unknown,
505
- allowed: ReadonlySet<string>,
506
- fallback: T,
507
- ): T {
755
+ function parseKind(value: unknown, agentName: string): AgentKind {
508
756
  const raw = str(value);
509
- return raw && allowed.has(raw) ? (raw as T) : fallback;
757
+ if (raw === undefined || raw === "") return "pi";
758
+ if (VALID_KINDS.has(raw)) return raw as AgentKind;
759
+ reportIgnoredOnce(
760
+ `agent:${agentName}:${raw}`,
761
+ ignoredKindMessage({ origin: "agent", subject: `'${agentName}'`, value: raw }),
762
+ );
763
+ return "pi";
510
764
  }
511
765
 
512
766
  /** `systemPromptMode` is a closed set of two; anything else means `replace`. */
@@ -536,6 +790,7 @@ function applyCapabilityFields(
536
790
  setIf(config, "skills", listOrFalse(fm.skills));
537
791
  setIf(config, "skillPath", list(fm.skillPath));
538
792
  setIf(config, "extensions", list(fm.extensions));
793
+ if (list(fm.excludeExtensions)) config.excludeExtensions = list(fm.excludeExtensions);
539
794
  setIf(config, "subagentOnlyExtensions", list(fm.subagentOnlyExtensions));
540
795
  setIf(config, "alias", list(fm.alias) ?? list(fm.aliases));
541
796
  setIf(config, "output", str(fm.output));
@@ -551,14 +806,23 @@ function applyBehaviorFields(config: AgentConfig, fm: AgentFrontmatter): void {
551
806
  setIf(config, "completionGuard", bool(fm.completionGuard));
552
807
  setIf(config, "maxSubagentDepth", int(fm.maxSubagentDepth));
553
808
  setIf(config, "allowNestedSubagents", bool(fm.allowNestedSubagents));
809
+ // D5/D6: parsed verbatim and left absent when undeclared — the defaults live
810
+ // with the consumers (DEFAULT_RENEWABLE / DEFAULT_MAX_RENEWALS), so this
811
+ // layer never has to guess whether the role was explicit. `int()` returns 0
812
+ // for `maxRenewals: 0`, and `setIf` only skips `undefined`, so the
813
+ // "renewal disabled" spelling survives instead of decaying to the default.
814
+ setIf(config, "renewable", bool(fm.renewable));
815
+ setIf(config, "maxRenewals", int(fm.maxRenewals));
554
816
  setIf(config, "utility", bool(fm.utility));
555
817
  setIf(config, "disabled", bool(fm.disabled));
556
818
  setIf(config, "worktree", bool(fm.worktree));
557
819
  setIf(config, "steer", bool(fm.steer));
558
- setIf(config, "spawnMode", spawnModeOf(fm.spawnMode, config.filePath));
559
820
  setIf(config, "acceptance", parseAcceptance(fm.acceptance, config.name));
560
- setIf(config, "toolBudget", parseBudget(fm.toolBudget));
561
- setIf(config, "turnBudget", parseTurnBudget(fm.turnBudget));
821
+ const phases = parsePhaseMachine(fm.phases, config.filePath);
822
+ if (phases) config.phases = phases;
823
+ const budgets = parseBudgets(fm, config.filePath);
824
+ setIf(config, "toolBudget", budgets.tool);
825
+ setIf(config, "turnBudget", budgets.turn);
562
826
  // #214 / contract §9: only centurion holds worktree isolation. Writers no
563
827
  // longer auto-default to worktree:true — members work in-place; parallel
564
828
  // isolated writers are N root-dispatched centurions. Explicit worktree:true
@@ -24,7 +24,6 @@ export const OVERRIDE_FIELDS = [
24
24
  "preset",
25
25
  "thinking",
26
26
  "output",
27
- "kind",
28
27
  "onBlocked",
29
28
  "systemPromptMode",
30
29
  "systemPrompt",
@@ -32,19 +31,21 @@ export const OVERRIDE_FIELDS = [
32
31
  "inheritProjectContext",
33
32
  "inheritSkills",
34
33
  "inheritExtensions",
34
+ "excludeExtensions",
35
35
  "defaultProgress",
36
36
  "async",
37
37
  "completionGuard",
38
38
  "allowNestedSubagents",
39
+ "renewable",
39
40
  "utility",
40
41
  "disabled",
41
42
  "worktree",
42
43
  "steer",
43
- "spawnMode",
44
44
  // numbers
45
45
  "timeoutMs",
46
46
  "toolTimeoutMs",
47
47
  "maxSubagentDepth",
48
+ "maxRenewals",
48
49
  // arrays (a `false` value is meaningful for skills/extensions)
49
50
  "tools",
50
51
  "skills",
@@ -8,15 +8,15 @@
8
8
  *
9
9
  * Two invariants live here:
10
10
  *
11
- * 1. ATOMICITY — `kind` and `model` come from the same preset object.
12
- * `nativeModelFor("cursor", "cb/kimi-k3")` returns `undefined`, so a
13
- * mismatched pair would silently drop the model and start the child on
14
- * the CLI default. `assertKindModelCoherent` rejects that combination
15
- * at expansion time instead of letting the launch proceed.
11
+ * 1. ATOMICITY — `kind`, `model` and `thinking` come from the same preset
12
+ * object, so a preset can never ship half of one bundle and half another.
16
13
  *
17
14
  * 2. LOUD UNDEFINED — a referenced preset name with no matching entry is
18
15
  * an error that names the defined presets, never a silent fallback to
19
16
  * the dispatch model (mirrors `checkModelScope`'s out-of-scope error).
17
+ *
18
+ * v4 runs `kind: pi` only: a preset that names another kind is reported once
19
+ * and applied as `pi` (see `parsePreset`).
20
20
  */
21
21
 
22
22
  import {
@@ -27,7 +27,7 @@ import {
27
27
  type AgentKind,
28
28
  type PresetConfig,
29
29
  } from "../shared/types.ts";
30
- import { nativeModelFor } from "../runs/kind.ts";
30
+ import { ignoredKindMessage, reportIgnoredOnce } from "../shared/ignored-kind.ts";
31
31
 
32
32
  const VALID_KINDS: ReadonlySet<string> = new Set(AGENT_KINDS);
33
33
 
@@ -71,13 +71,17 @@ function parsePreset(
71
71
  const out: PresetConfig = {};
72
72
 
73
73
  if (input.kind !== undefined) {
74
+ // A non-`pi` kind is no longer a validation error (the field is still a
75
+ // legal key, it just only accepts one value). Report the ignored value once
76
+ // and apply the preset as `pi`, the single supported kind.
74
77
  if (typeof input.kind !== "string" || !VALID_KINDS.has(input.kind)) {
75
- throw new Error(
76
- `Subagent settings in '${filePath}' have invalid '${label}.kind'; ` +
77
- `expected one of: ${AGENT_KINDS.join(", ")}.`,
78
+ reportIgnoredOnce(
79
+ `preset:${name}`,
80
+ ignoredKindMessage({ origin: `preset '${name}'`, subject: `in ${filePath}`, value: input.kind }),
78
81
  );
82
+ } else {
83
+ out.kind = input.kind as AgentKind;
79
84
  }
80
- out.kind = input.kind as AgentKind;
81
85
  }
82
86
 
83
87
  if (input.model !== undefined) {
@@ -152,36 +156,6 @@ export function requirePreset(
152
156
  );
153
157
  }
154
158
 
155
- /**
156
- * Throw when `nativeModelFor(kind, model)` would silently drop the model.
157
- *
158
- * Reuses `nativeModelFor` rather than re-implementing the shape test, so the
159
- * guard can never disagree with the argv builder about what a kind accepts.
160
- *
161
- * `model` is the RESOLVED model — whichever precedence level actually won —
162
- * not the preset's own `model`, because a per-run tool `model`, `defaultModel`,
163
- * an override or the dispatch model can all beat or fill in for the preset.
164
- * The message therefore names the preset's KIND as the origin and reports
165
- * where the model came from, rather than implying the preset set it.
166
- */
167
- export function assertKindModelCoherent(
168
- kind: AgentKind,
169
- model: string | undefined,
170
- presetName: string,
171
- modelOrigin?: string,
172
- ): void {
173
- if (!model) return;
174
- if (nativeModelFor(kind, model) === undefined) {
175
- const origin = modelOrigin ? ` (from ${modelOrigin})` : "";
176
- throw new SubagentError(
177
- `Preset '${presetName}' selects kind '${kind}', but the resolved model '${model}'${origin} ` +
178
- `cannot be used with that kind and would be silently dropped at start. ` +
179
- `Fix the preset's kind or the model source.`,
180
- ErrorCodes.INVALID_PARAMS,
181
- );
182
- }
183
- }
184
-
185
159
  /**
186
160
  * Return a COPY of `agent` with kind/model/thinking from `preset`.
187
161
  *