@staix/agent-hub 0.27.0 → 0.29.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 (106) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +11 -3
  3. package/docs/agent-notes/adapters.md +4 -2
  4. package/docs/agent-notes/bus.md +4 -4
  5. package/docs/agent-notes/daemon.md +9 -3
  6. package/docs/agent-notes/local-worker.md +3 -1
  7. package/docs/agent-notes/tasks.md +7 -0
  8. package/docs/agent-notes/tests.md +7 -5
  9. package/docs/design/adapters.md +76 -0
  10. package/docs/design/agent-hub-architecture.md +67 -0
  11. package/docs/design/agent-hub.md +52 -0
  12. package/docs/design/bus.md +48 -0
  13. package/docs/design/task-board.md +86 -0
  14. package/docs/dogfood.md +21 -3
  15. package/docs/operations.md +370 -12
  16. package/docs/profiles.md +1 -0
  17. package/docs/quickstart.md +19 -3
  18. package/docs/sdlc.md +2 -2
  19. package/docs/security.md +24 -4
  20. package/docs/smoke.md +2 -0
  21. package/docs/specs/2026-09-19-agent-hub-design.md +2 -0
  22. package/docs/verification/2026-10-31-codex-0166-reviewer-isolation.md +2 -0
  23. package/docs/verification/2026-11-02-0.28.0.md +54 -0
  24. package/docs/verification/2026-11-02-autonomy-t4.md +39 -0
  25. package/docs/verification/2026-11-02-codex-0166-reviewer-tool-call.md +53 -0
  26. package/docs/verification/2026-11-02-control-write-after.json +139 -0
  27. package/docs/verification/2026-11-02-control-write-baseline.json +127 -0
  28. package/docs/verification/2026-11-02-control-write-guarded.json +127 -0
  29. package/docs/verification/2026-11-02-control-write-outcomes.md +65 -0
  30. package/docs/verification/2026-11-02-orca-1.4.245-cli-contract.md +51 -0
  31. package/docs/verification/2026-11-03-0.29.0.md +59 -0
  32. package/docs/verification/2026-11-03-control-write-stall-windows.json +241 -0
  33. package/docs/verification/2026-11-03-control-write-stall-windows.md +20 -0
  34. package/docs/verification/2026-11-03-live-board-latency.json +556 -0
  35. package/docs/verification/2026-11-03-live-board-latency.md +64 -0
  36. package/docs/verified.json +14 -14
  37. package/package.json +2 -2
  38. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  39. package/plugins/agent-hub/server.js +857 -125
  40. package/src/adapters/claude-channel.ts +12 -2
  41. package/src/adapters/compat.ts +1 -1
  42. package/src/adapters/definitions/native-cli-claude-setup.ts +31 -9
  43. package/src/adapters/definitions/native-cli-entry-jcode.ts +33 -0
  44. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -2
  45. package/src/adapters/jcode.ts +37 -4
  46. package/src/adapters/qwen-dual.ts +3 -2
  47. package/src/cli/agents.ts +4 -2
  48. package/src/cli/bench.ts +4 -2
  49. package/src/cli/board-read.ts +25 -0
  50. package/src/cli/claude-homes.ts +2 -2
  51. package/src/cli/console-state.ts +8 -3
  52. package/src/cli/help.ts +6 -5
  53. package/src/cli/identity.ts +9 -1
  54. package/src/cli/init-prompt.ts +179 -0
  55. package/src/cli/init-settings.ts +229 -0
  56. package/src/cli/init.ts +102 -9
  57. package/src/cli/launch.ts +3 -1
  58. package/src/cli/main.ts +106 -35
  59. package/src/cli/output.ts +19 -0
  60. package/src/cli/recovery-package.ts +9 -0
  61. package/src/cli/setup-homes.ts +18 -3
  62. package/src/cli/specs.ts +150 -0
  63. package/src/cli/terminal-recovery.ts +35 -11
  64. package/src/hub/board.ts +59 -5
  65. package/src/hub/bus.ts +54 -7
  66. package/src/hub/child-process.ts +6 -4
  67. package/src/hub/config-apply.ts +4 -1
  68. package/src/hub/config-edit.ts +1 -1
  69. package/src/hub/config-tier.ts +1 -0
  70. package/src/hub/control-client.ts +43 -4
  71. package/src/hub/control-write-trace.ts +409 -0
  72. package/src/hub/cost-governance.ts +22 -6
  73. package/src/hub/crash.ts +20 -0
  74. package/src/hub/daemon.ts +470 -98
  75. package/src/hub/delivery-hints.ts +6 -3
  76. package/src/hub/delivery-journal.ts +14 -3
  77. package/src/hub/hub-tools.ts +10 -6
  78. package/src/hub/peers.ts +1 -1
  79. package/src/hub/review-brief.ts +18 -0
  80. package/src/hub/routing.ts +14 -3
  81. package/src/hub/runtime-capture-prune.ts +4 -1
  82. package/src/hub/sdlc-release-authorization.ts +13 -4
  83. package/src/hub/sdlc-release.ts +23 -10
  84. package/src/hub/sdlc.ts +15 -2
  85. package/src/hub/settings.ts +2 -0
  86. package/src/hub/specs-config.ts +43 -0
  87. package/src/hub/specs-task.ts +108 -0
  88. package/src/hub/specs.ts +1008 -0
  89. package/src/hub/task-list-page.ts +75 -0
  90. package/src/hub/task-sweep.ts +10 -1
  91. package/src/hub/task-worktree.ts +331 -0
  92. package/src/hub/tasks.ts +606 -53
  93. package/src/hub/terminal-open.ts +10 -5
  94. package/src/hub/tool-request.ts +131 -0
  95. package/src/local/deny.ts +49 -0
  96. package/src/local/tools.ts +4 -2
  97. package/src/memory/brief.ts +5 -0
  98. package/src/memory/client.ts +5 -2
  99. package/src/ui/office-model.ts +17 -1
  100. package/src/ui/office-space.ts +1 -1
  101. package/templates/config.json +1 -0
  102. package/templates/profiles/dev.json +1 -0
  103. package/templates/profiles/general.json +1 -0
  104. package/templates/profiles/research.json +1 -0
  105. package/templates/profiles/writing.json +1 -0
  106. package/templates/specs.block.md +5 -0
@@ -3,7 +3,7 @@ import { KINDS, sanitize, type Kind } from "./envelope.ts";
3
3
  export const DELIVERY_RETRY_WARNING = sanitize("Hub redelivery warning: An earlier attempt of this delivery is uncertain; check for its effects before acting.");
4
4
  export interface HeldDeliveryHints {
5
5
  count: number;
6
- rows: { id: string; senders: string[]; kinds: Kind[]; createdAt: number }[];
6
+ rows: { id: string; revision?: number; senders: string[]; kinds: Kind[]; createdAt: number }[];
7
7
  truncated: boolean;
8
8
  }
9
9
  export function heldDeliveryHints(rows: readonly HeldDeliveryHints["rows"][number][], count = rows.length): HeldDeliveryHints {
@@ -23,8 +23,11 @@ export function renderHeldHint(value: unknown, now = Date.now(), recipientRetry
23
23
  if (!Number.isSafeInteger(held.count) || held.count < 1 || !Array.isArray(held.rows) || held.rows.length > 32 || held.rows.length > held.count || typeof held.truncated !== "boolean" || Buffer.byteLength(JSON.stringify(held), "utf8") > 4096) return "";
24
24
  if (held.rows.some(row => !row || typeof row !== "object" || typeof row.id !== "string" || !row.id.length || row.id.length > 256 || !Number.isFinite(row.createdAt) || !Array.isArray(row.senders) || !Array.isArray(row.kinds) || row.senders.some(sender => typeof sender !== "string" || sender.length > 256) || row.kinds.some(kind => !kinds.has(kind)))) return "";
25
25
  } catch { return ""; }
26
- const rows = held.rows.map(row => `${sanitize(row.id)} from ${row.senders.map(sanitize).join(",")} kind ${row.kinds.join(",")} age ${Math.max(0, Math.floor((now - row.createdAt) / 1000))}s`);
27
- const action = recipientRetry ? "Use hub_delivery_retry {delivery_id} for one retry of your own uncertain row; check for earlier effects. A repeated uncertain retry needs the person." : "Ask the person to resolve these held deliveries; this delivery-only peer cannot initiate recipient retry.";
26
+ const rows = held.rows.map(row => `${sanitize(row.id)}${Number.isSafeInteger(row.revision) && row.revision! >= 0 ? ` revision ${row.revision}` : ""} from ${row.senders.map(sanitize).join(",")} kind ${row.kinds.join(",")} age ${Math.max(0, Math.floor((now - row.createdAt) / 1000))}s`);
27
+ const resolvable = held.rows.some(row => Number.isSafeInteger(row.revision) && row.revision! >= 0);
28
+ const action = resolvable
29
+ ? `Use hub_delivery_resolve {delivery_id, revision, action, reason} to confirm completion or discard your own held row. ${recipientRetry ? "Use hub_delivery_retry only to request its one uncertain redelivery; check for earlier effects." : "Retry remains person-only for this delivery mode."}`
30
+ : `Ask the person to resolve these held deliveries because this hint has no usable revision. ${recipientRetry ? "A retry may be requested with hub_delivery_retry {delivery_id}; check for earlier effects." : "Retry remains person-only for this delivery mode."}`;
28
31
  const out = `Held hub deliveries: ${held.count}${held.truncated ? " (metadata truncated)" : ""}\n${rows.join("\n")}\n${action}`;
29
32
  return Buffer.byteLength(out, "utf8") <= 4096 ? out : `Held hub deliveries: ${held.count} (metadata truncated; ask the person to inspect the queue).`;
30
33
  }
@@ -895,8 +895,8 @@ export class DeliveryJournal {
895
895
  heldDeliveryHints(peer: string) {
896
896
  this.ensureOpen();
897
897
  const count = Number((this.db.query("SELECT COUNT(*) AS n FROM deliveries WHERE project_id = ? AND peer = ? AND state = 'needs_review'").get(this.projectId, peer) as { n: number }).n);
898
- const rows = this.db.query("SELECT d.id, d.created_at, (SELECT json_group_array(DISTINCT json_extract(env.value, '$.from')) FROM json_each(d.originals) env) AS senders, (SELECT json_group_array(DISTINCT json_extract(env.value, '$.kind')) FROM json_each(d.originals) env) AS kinds FROM deliveries d WHERE d.project_id = ? AND d.peer = ? AND d.state = 'needs_review' ORDER BY d.created_at, d.id LIMIT 33").all(this.projectId, peer) as { id: string; created_at: number; senders: string; kinds: string }[];
899
- return heldDeliveryHints(rows.map(row => ({ id: row.id, createdAt: row.created_at, senders: JSON.parse(row.senders) as string[], kinds: JSON.parse(row.kinds) as Kind[] })), count);
898
+ const rows = this.db.query("SELECT d.id, d.revision, d.created_at, (SELECT json_group_array(DISTINCT json_extract(env.value, '$.from')) FROM json_each(d.originals) env) AS senders, (SELECT json_group_array(DISTINCT json_extract(env.value, '$.kind')) FROM json_each(d.originals) env) AS kinds FROM deliveries d WHERE d.project_id = ? AND d.peer = ? AND d.state = 'needs_review' ORDER BY d.created_at, d.id LIMIT 33").all(this.projectId, peer) as { id: string; revision: number; created_at: number; senders: string; kinds: string }[];
899
+ return heldDeliveryHints(rows.map(row => ({ id: row.id, revision: row.revision, createdAt: row.created_at, senders: JSON.parse(row.senders) as string[], kinds: JSON.parse(row.kinds) as Kind[] })), count);
900
900
  }
901
901
  /** Explicit resolutions, not automatic safe failures, consume the immutable originals' retry lineage. */
902
902
  retryEvidence(peer: string, originals: readonly Envelope[]): "unused" | "used" | "unknown" {
@@ -993,7 +993,12 @@ export class DeliveryJournal {
993
993
  if (prior) return this.get(id)!;
994
994
  const current = this.get(id);
995
995
  if (!current) throw new Error(`unknown delivery ${id}`);
996
- if (actor.startsWith("peer:") && (action !== "retry" || current.peer !== actor.slice(5) || current.state !== "needs_review" || this.retryEvidence(current.peer, current.originals) !== "unused")) throw new Error("recipient retry unavailable; inspect the held delivery or ask the person");
996
+ if (actor.startsWith("peer:")) {
997
+ const peer = actor.slice(5);
998
+ const recipientRetry = action === "retry" && current.peer === peer && current.state === "needs_review" && this.retryEvidence(current.peer, current.originals) === "unused";
999
+ const ownerDisposition = (action === "completed" || action === "discard") && current.peer === peer && current.state === "needs_review";
1000
+ if (!recipientRetry && !ownerDisposition) throw new Error("recipient delivery resolution unavailable; inspect the held delivery or ask the person");
1001
+ }
997
1002
  if (current.revision !== revision)
998
1003
  throw new Error(`stale delivery revision for ${id}`);
999
1004
  if (
@@ -1037,6 +1042,12 @@ export class DeliveryJournal {
1037
1042
  return result;
1038
1043
  })();
1039
1044
  }
1045
+ /** #1096: the ids of every delivery an operator action (completed, retry, discard) already settled. One query, so a list of any length costs one read. */
1046
+ resolvedIds(): Set<string> {
1047
+ this.ensureOpen();
1048
+ const rows = this.db.query("SELECT DISTINCT delivery_id FROM resolution_history WHERE project_id=?").all(this.projectId) as { delivery_id: string }[];
1049
+ return new Set(rows.map(row => row.delivery_id));
1050
+ }
1040
1051
  resolution(id: string): { action: JournalResolution; reason: string; observedRevision: number; actor: string } | undefined {
1041
1052
  const row = this.db.query("SELECT action,reason,observed_revision,actor FROM resolution_history WHERE project_id=? AND delivery_id=? ORDER BY id DESC LIMIT 1").get(this.projectId, id) as { action: JournalResolution; reason: string; observed_revision: number; actor: string } | null;
1042
1053
  return row ? { action: row.action, reason: row.reason, observedRevision: row.observed_revision, actor: row.actor } : undefined;
@@ -8,7 +8,7 @@ import { NOTE_KINDS } from "./envelope.ts";
8
8
 
9
9
  /** Restricted to the fixed current-child tools server, never an ordinary peer tool. */
10
10
  /** The fixed MCP surface of a current owned implementer child; independent of broader project roles. */
11
- export const IMPLEMENTER_HUB_TOOL_NAMES: readonly string[] = Object.freeze(["hub_task_accept", "hub_task_decline", "hub_task_done", "hub_checkpoint", "hub_send", "hub_task_show", "hub_task_propose", "hub_remember", "hub_inbox", "hub_permission_request", "hub_study_show", "hub_experiment_show", "hub_experiment_record", "hub_study_handoff"]);
11
+ export const IMPLEMENTER_HUB_TOOL_NAMES: readonly string[] = Object.freeze(["hub_task_accept", "hub_task_decline", "hub_task_done", "hub_checkpoint", "hub_send", "hub_task_show", "hub_task_propose", "hub_remember", "hub_inbox", "hub_permission_request", "hub_study_show", "hub_experiment_show", "hub_experiment_record", "hub_study_handoff", "hub_specs", "hub_delivery_resolve"]);
12
12
 
13
13
  export const IMPLEMENTER_PERMISSION_TOOL = {
14
14
  name: "hub_permission_request",
@@ -21,6 +21,7 @@ export const ACTIONABLE_MESSAGE_INSTRUCTION = "Do not use [FYI] for PR ready, do
21
21
 
22
22
  const str = { type: "string" } as const;
23
23
  const id = { type: "integer", description: "task id" } as const;
24
+ const toolWriteRequestId = { type: "string", minLength: 1, maxLength: 256, pattern: "^v1/[A-Za-z0-9._-]{1,128}/[1-9][0-9]{0,15}/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$", description: "control-transport-only request_id returned by an outcome-unknown write; inspect first and retry with the same key and identical arguments only if absent. Direct in-process tool calls cannot use request_id" } as const;
24
25
  const refs = {
25
26
  type: "object",
26
27
  description: "where the work lives",
@@ -28,6 +29,7 @@ const refs = {
28
29
  additionalProperties: false,
29
30
  } as const;
30
31
  const list = (description: string) => ({ type: "array", items: str, description }) as const;
32
+ const specAck = { type: "array", maxItems: 20, items: { type: "object", properties: { id: { type: "string", minLength: 1, maxLength: 160 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, required: ["id", "reason"], additionalProperties: false } } as const;
31
33
  /** #509a: files a task delivered. The hub hashes them itself; there is no hash field, and one is refused. */
32
34
  const deliverablesSchema = {
33
35
  type: "array", minItems: 1, maxItems: 16,
@@ -78,7 +80,7 @@ export interface HubTool {
78
80
  const tool = (name: string, description: string, properties: Record<string, unknown>, required: string[] = []): HubTool => ({
79
81
  name,
80
82
  description,
81
- inputSchema: { type: "object", properties, required, additionalProperties: false },
83
+ inputSchema: { type: "object", properties: name === "hub_review" || name === "hub_task_propose" ? { ...properties, request_id: toolWriteRequestId } : properties, required, additionalProperties: false },
82
84
  });
83
85
 
84
86
  /** #601: a campaign's contract and handoff are model-written text about its sources. The write tools' arguments and every study result stay out of memory capture. */
@@ -95,6 +97,7 @@ export const TASK_TOOLS: HubTool[] = [
95
97
  tool("hub_check_result", "Read your current task-bound isolated check receipt. Stale ownership/generation refuses; output is policy screened.", { run: str }, ["run"]),
96
98
  tool("hub_check_cancel", "Cancel your task-bound isolated check; only its owner or the person may cancel.", { run: str }, ["run"]),
97
99
  tool("hub_delivery_retry", "Request one redelivery of your own needs_review delivery. An earlier attempt may have effects: inspect those effects before acting. Refuses another peer's row or any lineage already explicitly retried; a repeated uncertain row needs the person. Never completes/discards a delivery or changes task state.", { delivery_id: { type: "string", minLength: 1, maxLength: 256 } }, ["delivery_id"]),
100
+ tool("hub_delivery_resolve", "Confirm completion or discard your own needs_review delivery using the revision shown by hub_inbox. Requires a reason. Never replays the delivery or changes task state; another peer's row and stale revisions are refused.", { delivery_id: { type: "string", minLength: 1, maxLength: 256 }, revision: { type: "integer", minimum: 0 }, action: { type: "string", enum: ["completed", "discard"] }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["delivery_id", "revision", "action", "reason"]),
98
101
  tool("hub_backlog_list", "Read public backlog cards with planning revisions. Configured planners only; PII remains a stub.", {}),
99
102
  tool("hub_backlog_plan", "Plan an unpinned backlog item outside frozen releases with the revision you read and a bounded reason. Omit fields or give {} for a note-only revision. fields.sdlc accepts only repo/issue identity on unstarted backlog work; relinking clears old spec acceptance. A person's rank is retained. Actual dates cannot be set.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", maxLength: 1000 }, fields: { type: "object", properties: { sdlc: { type: "object", minProperties: 1, properties: { repo: { type: ["string", "null"], maxLength: 400 }, issue: { type: ["integer", "null"], minimum: 1 } }, additionalProperties: false }, rank: { type: ["integer", "null"], minimum: 0 }, priority: { type: ["integer", "null"], minimum: 0, maximum: 3 }, release: { type: ["integer", "null"], minimum: 1 }, plannedStart: { type: ["integer", "null"], minimum: 1 }, due: { type: ["integer", "null"], minimum: 1 }, deps: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, reserved: { type: ["string", "null"], minLength: 1, maxLength: 32 } }, additionalProperties: false } }, ["id", "revision", "reason"]),
100
103
  tool("hub_backlog_pull", "Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
@@ -115,13 +118,14 @@ export const TASK_TOOLS: HubTool[] = [
115
118
  tool("hub_release_cut", "Freeze an active release's approved scope after host resource admission and fresh peer quota checks. Unknown evidence defers; no publish, tag, upgrade or authorization.", { id, revision: { type: "integer", minimum: 0 } }, ["id", "revision"]),
116
119
  tool("hub_release_list", "Read public release scope and planned/actual dates for phased planning. Configured planners only.", {}),
117
120
 
118
- tool("hub_task_propose", "Put a piece of work on the shared task board. The hub assigns an owner by class (routing.toml) unless you name one. Classes: plan, implement, bulk_edit, test, review, summarize, triage. Name the class when you know it; without one the hub tries to pick it. Name yourself as owner to claim work nobody assigned you: it starts in progress. Put the paths the work touches in refs, set refs.repo for work in another repository, and when you claim work, a plan; the hub says when they overlap another open task.", { title: str, class: { type: "string", enum: ["plan", "implement", "bulk_edit", "test", "review", "summarize", "triage"] }, detail: str, role: { type: "string", description: "catalog role id for this task class; guidance only, no routing or authority change" }, refs, plan, owner: { type: "string", description: "peer id; yours to claim the work, omit to let the hub route it. With after, the owner is reserved: offered the task first once it is ready" }, after: { type: "array", items: { type: "integer" }, description: "ids of tasks that must be approved first; until then this one waits, offered to nobody, and cannot be claimed" }, backlog: { type: "boolean", description: "stage unoffered work; owner is only a reservation, even when naming yourself" }, urgent: { type: "boolean", description: "hand it over even when its owner is paused for quota only briefly" }, goal: { type: "string", description: "id of this project's long-term task (ahub goal list) the work is part of" } }, ["title"]),
121
+ tool("hub_task_propose", "Put a piece of work on the shared task board. The hub assigns an owner by class (routing.toml) unless you name one. Classes: plan, implement, bulk_edit, test, review, summarize, triage. Name the class when you know it; without one the hub tries to pick it. Name yourself as owner to claim work nobody assigned you: it starts in progress. Put the paths the work touches in refs, set refs.repo for work in another repository, and when you claim work, a plan; the hub says when they overlap another open task.", { title: str, class: { type: "string", enum: ["plan", "implement", "bulk_edit", "test", "review", "summarize", "triage"] }, detail: str, role: { type: "string", description: "catalog role id for this task class; guidance only, no routing or authority change" }, refs, plan, owner: { type: "string", description: "peer id; yours to claim the work, omit to let the hub route it. With after, the owner is reserved: offered the task first once it is ready" }, after: { type: "array", items: { type: "integer" }, description: "ids of tasks that must be approved first; until then this one waits, offered to nobody, and cannot be claimed" }, backlog: { type: "boolean", description: "stage unoffered work; owner is only a reservation, even when naming yourself" }, urgent: { type: "boolean", description: "hand it over even when its owner is paused for quota only briefly" }, needs_network: { type: "boolean", description: "the work needs the network (a package registry, git fetch or push, an API); it is never offered to a peer whose shell has none" }, needs_worktree: { type: "boolean", description: "the work needs its own git worktree on a task branch (the repository rule); it is never offered to a sandboxed peer, which cannot create one" }, goal: { type: "string", description: "id of this project's long-term task (ahub goal list) the work is part of" } }, ["title"]),
119
122
  tool("hub_task_accept", "Take a task that was assigned to you, with your plan for it. Set refs.repo for work in another repository; acceptance may correct only that repository metadata.", { id, plan: acceptPlan, refs: { ...refs, properties: { repo: refs.properties.repo } } }, ["id"]),
120
123
  tool("hub_task_cancel", "Cancel proposed/backlog work you proposed as its configured planner, including work an owner accepted and then declined while it has no execution, branch, commit or PR evidence; work with any such evidence is person-only. Keeps history and does not stop a native turn or delete files.", { id, reason: str, superseded_by: str, revision: { type: "integer", minimum: 0 } }, ["id", "reason"]),
121
124
  tool("hub_task_decline", "Pass on a task assigned to you; the hub offers it to the next peer. A plain decline is a lasting refusal: you are never offered this task again. Pass capacity: true when you only have no room right now: you are skipped for this move only, and a later reroute or planner pull may offer it to you again.", { id, reason: str, capacity: { type: "boolean" } }, ["id"]),
122
- tool("hub_task_done", "Mark your task finished. It goes to its reviewer with your summary and refs; no duplicate hub_send chat is needed. When the project configures a check for its class, the hub runs it first and the result comes as a task message: a failed check keeps the task with you.", { id, summary: { type: "string", description: "what changed, why, and the check you ran with its result" }, refs, deliverables: deliverablesSchema }, ["id", "summary"]),
125
+ tool("hub_task_done", "Mark your task finished. It goes to its reviewer with your summary and refs; no duplicate hub_send chat is needed. When re-filing work after review, set refs.commit to the new full SHA; summary text does not change the review head. If a covering spec is unchanged, update it or provide spec_ack with a public reason for each unchanged spec. When the project configures a check for its class, the hub runs it first and the result comes as a task message: a failed check keeps the task with you.", { id, summary: { type: "string", description: "what changed, why, and the check you ran with its result" }, refs, deliverables: deliverablesSchema, spec_ack: specAck }, ["id", "summary"]),
123
126
  tool("hub_sdlc_record", "Record artifact ids or claimed local checks on your task. This grants no authority or external-check evidence. Only its owner/reviewer or the person may record; only its reviewer/person may name a reviewed head or phase checklist. Phase evidence refs are content hashes, not external verification.", { id, receipt: { type: "object", properties: { deliverables: deliverablesSchema, stage: { type: "string", enum: ["spec", "plan", "implement", "review", "verify", "merge", "release"] }, repo: str, issue: id, pr: id, localHead: str, localResult: { type: "string", enum: ["passed", "failed", "unknown"] }, reviewedHead: str, phase: { type: "object", properties: { id: str, head: str, tasks: { type: "array", maxItems: 64, items: { type: "object", properties: { id, after: { type: "array", maxItems: 16, items: id } }, required: ["id", "after"], additionalProperties: false } }, criteria: { type: "array", maxItems: 32, items: { type: "object", properties: { id: str, required: { type: "boolean" }, result: { type: "string", enum: ["verified", "failed", "unverified"] }, refs: { type: "array", maxItems: 8, items: str } }, required: ["id", "required", "result", "refs"], additionalProperties: false } } }, required: ["id", "tasks", "criteria"], additionalProperties: false } }, additionalProperties: false } }, ["id", "receipt"]),
124
- tool("hub_task_list", "The task board. PII tasks show as [pii].", { state: { type: "string", enum: ["proposed", "in_progress", "in_review", "approved", "changes_requested", "cancelled"] }, ready: { type: "boolean", description: "only proposed tasks with nothing left to wait for" } }),
127
+ tool("hub_task_list", "The task board, newest updated first, 50 compact rows (id, state, owner, reviewer, title) per call. The reply is {tasks, total, next?}: pass next as cursor for the following page. Use ids for full rows of specific tasks, or detail: true for full rows of a page. PII tasks show as [pii].", { state: { type: "string", enum: ["proposed", "in_progress", "in_review", "approved", "changes_requested", "cancelled"] }, ready: { type: "boolean", description: "only proposed tasks with nothing left to wait for" }, limit: { type: "integer", minimum: 1, maximum: 200, description: "rows per page, default 50" }, cursor: { type: "string", description: "the next value from the previous reply, unchanged" }, ids: { type: "array", minItems: 1, maxItems: 200, items: { type: "integer", minimum: 1 }, description: "full rows for exactly these task numbers; no paging" }, detail: { type: "boolean", description: "full rows instead of compact rows" } }),
128
+ tool("hub_specs", "Read the project's design-spec checks or find specs covering repository-relative paths. Read-only; at most 20 result items are returned. Does not reveal private task data.", { action: { type: "string", enum: ["check", "covers"] }, paths: { type: "array", maxItems: 32, items: { type: "string", minLength: 1, maxLength: 2000 } } }, ["action"]),
125
129
  tool("hub_review", "Give your verdict on a task you were asked to review: map the changed signatures and call sites to the task's plan or detail, read the check result (hub_task_show has it, with the done summary), and list what is unmet. The verdict notifies the task owner; no duplicate hub_send chat is needed. Consecutive changes_requested verdicts (three by default, `tasks.escalate_after`) move the task to another peer.", { id, head: { type: "string", description: "full SHA actually reviewed; enforce binds approval to the current PR head" }, findings: reviewFindings, verdict: { type: "string", enum: ["approved", "changes_requested"] }, note: str, unmet: { type: "array", items: str, description: "each requirement of the plan or detail that the change does not meet; when the review request lists acceptance criteria, start an item with its id (\"AC1: what is missing\") so the verdict names it" }, coverage: { type: "object", description: "the review brief's reviewable paths you read (reviewed) and any you did not (skipped, each with a reason); in enforce an approval must account for every one", properties: { reviewed: { type: "array", items: str }, skipped: { type: "array", items: { type: "object", properties: { path: str, reason: str }, required: ["path", "reason"] } } } } }, ["id", "verdict"]),
126
130
  tool("hub_checkpoint", "Answer a checkpoint request from the hub (quota or context window pressure): what you were doing, what is half done, what whoever continues must know. Write the same to .agenthub/checkpoint.md first if you can.", { summary: str, request_id: { type: "string", description: "The request id supplied by a context checkpoint request; required for context checkpoints" } }, ["summary"]),
127
131
  tool("hub_source_read", "Read a registered source snapshot. Unicode character range, at most 32 KiB of sanitized UTF-8 text with next character offset. Private sources return only id, kind and private unless called by the on-prem worker inside a PII task. Excluded from capture.", { id: { type: "string", pattern: "^src:[0-9a-f]{16}$" }, range: { type: "object", properties: { offset: { type: "integer", minimum: 0 }, length: { type: "integer", minimum: 1 } }, required: ["offset", "length"], additionalProperties: false } }, ["id"]),
@@ -196,7 +200,7 @@ export function configuredToolContext(status: unknown, peer: string): ProjectToo
196
200
  return { startPeers, readOnly: readOnlyPeers.includes(peer) };
197
201
  }
198
202
 
199
- const READ_ONLY_PROJECT_TOOLS = Object.freeze(["hub_capabilities", "hub_send", "hub_inbox", "hub_delivery_done", "hub_review", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_status"]);
203
+ const READ_ONLY_PROJECT_TOOLS = Object.freeze(["hub_specs", "hub_capabilities", "hub_send", "hub_inbox", "hub_delivery_done", "hub_review", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_status"]);
200
204
  /** Publication restricts exposure only; server-side authority remains mandatory for every call. */
201
205
  export function projectToolList<T extends { name: string }>(tools: T[], readOnly = false): T[] {
202
206
  return readOnly ? tools.filter(tool => READ_ONLY_PROJECT_TOOLS.includes(tool.name)) : tools;
package/src/hub/peers.ts CHANGED
@@ -64,7 +64,7 @@ export interface PeerAdapter {
64
64
  /** Fixed-builtin native proof only; present undefined is unknown, not an absent proxy. */
65
65
  readonly frontendProxy?: FrontendProxyPort;
66
66
  /** Fixed operator notices from builtin native adapters, never provider text or native ids. */
67
- readonly statusNotice?: { code: "unidentified-cancellation" | "qwen-detached" | "qwen-stalled"; message: string };
67
+ readonly statusNotice?: { code: "unidentified-cancellation" | "qwen-detached" | "qwen-stalled" | "jcode-headless-after-recovery"; message: string };
68
68
  /** Fixed builtins with session.nativeRevert only. Native conversation effects remain in the adapter. */
69
69
  revertTurn?(nativeTurn: string): Promise<void>;
70
70
  /** #445 C1: what this peer's native source lists right now (a probed version only), or an empty manifest. Never throws for an unprobed version; a transport failure rejects. */
@@ -1,7 +1,9 @@
1
1
  import type { CodeFactResult, CodeSymbol } from "./code-facts.ts";
2
+ import { sanitize } from "./envelope.ts";
2
3
  import { childEnv } from "./child-process.ts";
3
4
  import { hubGitSync } from "./git.ts";
4
5
  import { symbolsOverlap } from "./symbol-normalizer.ts";
6
+ import type { SpecTaskReport } from "./board.ts";
5
7
 
6
8
  /**
7
9
  * #520: the review brief ahub builds itself, in place of `ocr delegate preview` and `rule`. Every reviewer gets the same
@@ -30,6 +32,22 @@ export interface ReviewBrief {
30
32
  /** Paths in the plain name list of the range that the brief does not list: read them directly. */
31
33
  unlisted: string[];
32
34
  }
35
+
36
+ /** A bounded, public summary of the design specs affected by one exact task head. */
37
+ export function renderSpecTaskReport(report: SpecTaskReport): string {
38
+ const head = /^[0-9a-f]{40}$/.test(report.head) ? report.head : "unknown";
39
+ const lines = [`Design specs at ${head}:`];
40
+ if (!report.complete) lines.push(`Spec inspection incomplete${report.reason ? `: ${report.reason}` : "; coverage is unknown"}.`);
41
+ if (report.errors > 0) lines.push(`spec errors: ${report.errors}; run ahub specs check.`);
42
+ for (const spec of report.unchanged.slice(0, 20)) {
43
+ const label = `${spec.id}${spec.path ? ` (${spec.path})` : ""}`;
44
+ lines.push(`spec not updated: ${label}${spec.reason ? `; acknowledged: ${spec.reason}` : ""}`);
45
+ }
46
+ for (const spec of report.changed.slice(0, 20)) lines.push(`spec updated: ${spec.id}${spec.path ? ` (${spec.path})` : ""}`);
47
+ if (report.truncated || report.unchanged.length > 20 || report.changed.length > 20) lines.push("Spec report truncated; run ahub specs check for the full report.");
48
+ if (report.complete && report.errors === 0 && report.unchanged.length === 0 && report.changed.length === 0) lines.push("No covering specs were found for the changed files.");
49
+ return sanitize(lines.join("\n"));
50
+ }
33
51
  export interface BriefPolicy { privatePath(path: string): boolean; nameable(text: string): boolean }
34
52
 
35
53
  const MAX_FILES = 500, RULE_BYTES = 32_000, MAX_RULE_FILES = 8;
@@ -7,7 +7,7 @@ import { join, resolve } from "node:path";
7
7
  import { CLASSES, type Task, type TaskClass } from "./board.ts";
8
8
  import { isGitHubRepository, specRefs } from "./spec-read.ts";
9
9
 
10
- export interface PeerCapabilities { tests: boolean; spec: boolean; testsReason?: string; specReason?: string; }
10
+ export interface PeerCapabilities { tests: boolean; spec: boolean; testsReason?: string; specReason?: string; /** #1081: the peer's shell can reach the network (through the egress proxy or directly). Absent means unknown, never refused. */ network?: boolean; networkReason?: string; /** #1081: the peer can have the task worktree made for it: it makes its own, or (a hub sandbox, #270) the hub makes it (#1115) where it can. Absent means unknown, never refused. */ worktree?: boolean; worktreeReason?: string; }
11
11
  import type { PeerId, PeerState } from "./envelope.ts";
12
12
 
13
13
  import { parseHubRoutes, type HubRoute } from "../models/route/config.ts";
@@ -289,7 +289,7 @@ export function currentRouting(cwd: string, log: (line: string) => void = () =>
289
289
  }
290
290
  }
291
291
 
292
- export type Signal = "pii" | "pii_path" | "long_context" | "urgent";
292
+ export type Signal = "pii" | "pii_path" | "long_context" | "urgent" | "needs_network" | "needs_worktree";
293
293
 
294
294
  /** What the policy can see in a task. Context length is estimated from the referenced files, 3 characters per token as elsewhere. */
295
295
  export function detectSignals(task: Pick<Task, "title" | "detail" | "refs">, routing: Routing, cwd: string): Signal[] {
@@ -310,7 +310,7 @@ export function detectSignals(task: Pick<Task, "title" | "detail" | "refs">, rou
310
310
  /** A peer's entry in a peer-indexed map: own keys only, so a peer named `constructor` is never an inherited Object member. */
311
311
  export const peerEntry = <T>(map: Readonly<Record<string, T>> | undefined, peer: string): T | undefined => (map && Object.hasOwn(map, peer) ? map[peer] : undefined);
312
312
 
313
- export type RoutingRefusalCode = QueueBackpressureCode | "context-headroom" | "instance" | "family" | "tests" | "spec" | "roster" | "pull-only" | "not-attached" | "excluded" | "owner-admission" | "offline" | "paused" | "failing" | "pii" | "policy";
313
+ export type RoutingRefusalCode = QueueBackpressureCode | "context-headroom" | "instance" | "family" | "tests" | "spec" | "network" | "worktree" | "roster" | "pull-only" | "not-attached" | "excluded" | "owner-admission" | "offline" | "paused" | "failing" | "pii" | "policy";
314
314
  export interface RoutingRefusal { peer: PeerId; role: "owner" | "reviewer"; code: RoutingRefusalCode; reason: string }
315
315
  export interface Assignment {
316
316
  reviewSelection?: ReviewerPoolSelection;
@@ -343,6 +343,12 @@ export function ownerRoleOfClass(cls: TaskClass): "planner" | "implementer" | "r
343
343
  return cls === "review" ? "reviewer" : cls === "plan" ? "planner" : "implementer";
344
344
  }
345
345
 
346
+ /**
347
+ * #1129: the classes whose owner changes the repository, so a hub-sandboxed owner needs the hub's task worktree and commit (#1115) whether or not the task declares
348
+ * `needs_worktree`. `test`, `summarize`, `triage`, `review` and `plan` read and report: they get none. One definition, so routing and `Tasks` cannot disagree.
349
+ */
350
+ export const writesRepository = (cls: TaskClass): boolean => cls === "implement" || cls === "bulk_edit";
351
+
346
352
  /** Why a planner was chosen: the person named it, rotation reached it, the task's recorded planner is kept, or there is none (PII, no holder). */
347
353
  export type PlannerReason = "rotation" | "named" | "kept" | "none";
348
354
 
@@ -490,6 +496,11 @@ export function assign(
490
496
  const caps = peerEntry(opts.capabilities, peer);
491
497
  if (needsTests && !caps?.tests) return deny("tests", `missing tests: ${caps?.testsReason ?? "capability unavailable"}`);
492
498
  if (needsSpec && !caps?.spec) return deny("spec", `missing spec: ${caps?.specReason ?? "capability unavailable"}`);
499
+ // #1081: work that declares it needs the network is never offered to a peer whose shell has none. Unknown (no `network` entry) is not a refusal.
500
+ if (task.signals.includes("needs_network") && caps?.network === false) return deny("network", `no network: ${caps.networkReason ?? "its shell cannot reach the network"}`);
501
+ // #1081: work that declares it needs a task worktree is never offered to a peer that cannot create one, so no branch ref is left behind by a refused accept.
502
+ // #1129: write-class work needs one whether or not it declares it, because a hub-sandboxed owner cannot commit and the hub commits in its worktree. Unknown capability is not a refusal.
503
+ if ((task.signals.includes("needs_worktree") || writesRepository(task.class)) && caps?.worktree === false) return deny("worktree", `no worktree: ${caps.worktreeReason ?? "it cannot create the task worktree"}`);
493
504
  }
494
505
  if (opts.offRoster?.includes(peer)) return deny("roster", "off roster");
495
506
  const named = role === "owner" ? opts.namedOwner ?? reserved : opts.namedReviewer;
@@ -246,7 +246,10 @@ function knownLayout(root: string, directories: readonly string[], files: readon
246
246
  }
247
247
  }
248
248
  function captureLayout(root: string): void {
249
- knownLayout(root, ["src", "plugins", "templates", ".claude-plugin"], ["package.json", "README.md", "LICENSE", "CHANGELOG.md"], ["node_modules"]);
249
+ knownLayout(root, ["src", "plugins", "templates", ".claude-plugin"], ["package.json", "README.md", "LICENSE", "CHANGELOG.md"], ["node_modules", "scripts"]);
250
+ // #1120: captures made before the release checker was carried have no scripts directory; when present it holds exactly the checker.
251
+ // The name is repeated here on purpose: a pruner copied into a capture runs beside that capture's own verifier and imports nothing but verifyPackage from it. test/runtime-capture-checker.test.ts pins this name to RELEASE_CHECKER.
252
+ if (optionalInfo(join(root, "scripts"))) knownLayout(join(root, "scripts"), [], ["check-docs.mjs"]);
250
253
  const modules = join(root, "node_modules");
251
254
  if (optionalInfo(modules)) {
252
255
  knownLayout(modules, ["@staix"], []); const scope = join(modules, "@staix"); knownLayout(scope, ["agent-mem"], []);
@@ -2,7 +2,7 @@ import { releaseTrackedClean } from "./release-worktree.ts";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { USER, type PeerId } from "./envelope.ts";
4
4
  import { hubGitEnv, hubGitSync } from "./git.ts";
5
- import { readDocEvidence, type DocEvidence, type ReleaseGit, type ReleaseReadiness } from "./sdlc-release.ts";
5
+ import { readDocEvidenceDetailed, type DocEvidence, type ReleaseGit, type ReleaseReadiness } from "./sdlc-release.ts";
6
6
  import type { SdlcGh } from "./sdlc.ts";
7
7
  import type { ReleaseGuardRequest, ReleasePushUpdate } from "../cli/sdlc-release-guard.ts";
8
8
 
@@ -17,6 +17,8 @@ export interface ReleaseAuthorization { schemaVersion: 1; id: string; by: PeerId
17
17
  export interface ReleaseAuthorizationPorts {
18
18
  git?: ReleaseGit;
19
19
  docs?: (root: string) => Promise<DocEvidence | undefined>;
20
+ /** Test seam: the checker program the default reader spawns (#1120). Never set from configuration. */
21
+ checker?: string;
20
22
  gh?: SdlcGh;
21
23
  now?: () => number;
22
24
  current?: () => boolean;
@@ -46,6 +48,13 @@ export class ReleaseAuthorizations {
46
48
  private latest?: Entry;
47
49
  constructor(private readonly root: string, private readonly ports: ReleaseAuthorizationPorts) {}
48
50
  private current(): void { if (this.ports.current?.() === false) throw new ReleaseAuthorizationError("release authorization unavailable during lifecycle transition"); }
51
+ /** #1120: a checker that is missing or failed is its own refusal; only evidence that is read and not fresh is "stale documentation". An injected reader keeps its undefined meaning (no evidence). */
52
+ private async docs(commit: string, version: string): Promise<ReleaseDocsVerdict | undefined> {
53
+ if (this.ports.docs) return docsVerdict(await this.ports.docs(this.root), commit, version);
54
+ const read = await readDocEvidenceDetailed(this.root, undefined, this.ports.checker);
55
+ if ("unavailable" in read) throw new ReleaseAuthorizationError(`release authorization needs the documentation checker: ${read.unavailable}`);
56
+ return docsVerdict(read.evidence, commit, version);
57
+ }
49
58
  private actor(by: PeerId): void {
50
59
  if (by !== USER && (typeof by !== "string" || !by.trim() || this.ports.conductor?.() !== by)) throw new ReleaseAuthorizationError("only the person or the configured conductor may authorize a release");
51
60
  }
@@ -95,8 +104,8 @@ export class ReleaseAuthorizations {
95
104
  this.current();
96
105
  const git = this.git(), commit = this.commit(git, "HEAD"), origin = this.origin(git);
97
106
  if (commit !== expectedCommit || this.version(git, commit) !== version) throw new ReleaseAuthorizationError("candidate commit or version differs from the person's request");
98
- const docs = docsVerdict(await (this.ports.docs ?? readDocEvidence)(this.root), commit, version);
99
- if (!docs) throw new ReleaseAuthorizationError("release authorization requires fresh committed documentation evidence");
107
+ const docs = await this.docs(commit, version);
108
+ if (!docs) throw new ReleaseAuthorizationError("release authorization requires fresh committed documentation evidence: run `node scripts/check-docs.mjs --committed` in the candidate checkout, restamp the stale documents in a committed change, then authorize again");
100
109
  this.current(); this.actor(by);
101
110
  if (this.commit(git, "HEAD") !== commit || this.version(git, commit) !== version || this.origin(git).hash !== origin.hash) throw new ReleaseAuthorizationError("release candidate changed during authorization");
102
111
  this.current(); this.actor(by);
@@ -127,7 +136,7 @@ export class ReleaseAuthorizations {
127
136
  if (!releaseTrackedClean(this.root, git)) throw new ReleaseAuthorizationError("npm publish requires a clean tracked worktree");
128
137
  const commit = this.commit(git, "HEAD"), version = this.version(git, commit);
129
138
  const receipt = this.matched(git, version, commit);
130
- const docs = docsVerdict(await (this.ports.docs ?? readDocEvidence)(this.root), commit, version);
139
+ const docs = await this.docs(commit, version);
131
140
  this.current();
132
141
  if (!docs || docs.digest !== receipt.docs.digest || this.commit(git, "HEAD") !== commit || !releaseTrackedClean(this.root, git)) throw new ReleaseAuthorizationError("publish checkout or documentation evidence changed");
133
142
  return { ok: true, receipts: [this.matched(git, version, commit)] };
@@ -1,6 +1,7 @@
1
1
  import type { Task } from "./board.ts";
2
2
  import type { Release } from "./planning.ts";
3
3
  import { spawn } from "node:child_process";
4
+ import { existsSync } from "node:fs";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { childEnv, stopOwnedProcess } from "./child-process.ts";
6
7
  import { hubGitSync } from "./git.ts";
@@ -23,7 +24,7 @@ const sdlcGh: SdlcGh = async (...args) => {
23
24
  export interface DocEvidence { schemaVersion: 1; head?: string; version?: string; documents: { path?: string; state: "fresh" | "stale" | "nonancestor" | "unknown"; verifiedAgainst?: string; commits?: number; dirty?: boolean }[]; errors: number; fresh: boolean; }
24
25
  export interface ReleaseReadiness { /** #481 AC12: interval, approval-to-release lead time and hotfix rate over shipped releases, filled by Tasks.releaseReadiness. */ releaseMetrics?: ReturnType<typeof releaseMetrics>; repo: string; head?: string; version?: string; tag?: string; tagCommit?: string; commits: string[]; mergedPrs: { pr: number; commit: string }[]; documents?: DocEvidence; liveIssues: { id: number; state: "open" | "closed" | "unknown" }[]; blockers: string[]; sourceReady: boolean; native: "unverified"; ready: false; }
25
26
  export type ReleaseGit = (args: string[]) => { code: number; stdout: string };
26
- export interface ReleaseReaders { gh?: SdlcGh; git?: ReleaseGit; docs?: (root: string, timeoutMs: number) => Promise<DocEvidence | undefined>; }
27
+ export interface ReleaseReaders { gh?: SdlcGh; git?: ReleaseGit; docs?: (root: string, timeoutMs: number) => Promise<DocEvidence | undefined>; /** Test seam (#1120): the checker program the default docs reader spawns. */ checker?: string; }
27
28
  const SHA = /^[0-9a-f]{40}$/;
28
29
  const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
29
30
  const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
@@ -34,21 +35,31 @@ function tagMatches(target: unknown, commit: string): boolean {
34
35
  return typeof oid === "string" && SHA.test(oid) && oid === commit;
35
36
  }
36
37
  /** Package-owned checker only; no caller-supplied program or document text is executed. */
37
- export function readDocEvidence(root: string, timeoutMs = 10_000): Promise<DocEvidence | undefined> {
38
+ /** #1120: why no evidence could be read, apart from evidence that says the documents are stale. */
39
+ export type DocEvidenceRead = { evidence: DocEvidence } | { unavailable: string };
40
+ const CHECKER_PATH = fileURLToPath(new URL("../../scripts/check-docs.mjs", import.meta.url));
41
+ const CHECKER_MISSING = "the documentation checker scripts/check-docs.mjs is missing from the running hub, which predates the fix that carries it into captured runtimes; record consent from a hub started from a checkout or a release that carries the checker (docs/sdlc.md, release preparation)";
42
+ const CHECKER_FAILED = "the documentation checker in the running hub did not finish with readable evidence (it timed out, crashed or printed unreadable output); run `node scripts/check-docs.mjs --json --committed` in the candidate checkout to see why, then retry";
43
+ export async function readDocEvidence(root: string, timeoutMs = 10_000): Promise<DocEvidence | undefined> {
44
+ const read = await readDocEvidenceDetailed(root, timeoutMs);
45
+ return "evidence" in read ? read.evidence : undefined;
46
+ }
47
+ export function readDocEvidenceDetailed(root: string, timeoutMs = 10_000, checker = CHECKER_PATH): Promise<DocEvidenceRead> {
48
+ if (!existsSync(checker)) return Promise.resolve({ unavailable: CHECKER_MISSING });
38
49
  return new Promise(resolve => {
39
- const child = spawn(process.execPath, [fileURLToPath(new URL("../../scripts/check-docs.mjs", import.meta.url)), root, "--json", "--committed"], { cwd: root, env: childEnv(), detached: true, stdio: ["ignore", "pipe", "ignore"] });
50
+ const child = spawn(process.execPath, [checker, root, "--json", "--committed"], { cwd: root, env: childEnv(), detached: true, stdio: ["ignore", "pipe", "ignore"] });
40
51
  let output = "", invalid = false;
41
52
  const stop = () => { invalid = true; void stopOwnedProcess(child, { group: true }).catch(() => {}); };
42
53
  const timer = setTimeout(stop, Math.max(1, Math.min(10_000, timeoutMs)));
43
54
  child.stdout?.setEncoding("utf8"); child.stdout?.on("data", chunk => { output += chunk; if (Buffer.byteLength(output) > 256 * 1024) { output = ""; stop(); } });
44
- child.once("error", () => { invalid = true; clearTimeout(timer); resolve(undefined); });
55
+ child.once("error", () => { invalid = true; clearTimeout(timer); resolve({ unavailable: CHECKER_FAILED }); });
45
56
  child.once("close", (code, signal) => {
46
- clearTimeout(timer); if (invalid || signal || (code !== 0 && code !== 1)) return resolve(undefined);
57
+ clearTimeout(timer); if (invalid || signal || (code !== 0 && code !== 1)) return resolve({ unavailable: CHECKER_FAILED });
47
58
  try {
48
59
  const data = JSON.parse(output);
49
- if (data.schemaVersion !== 1 || !Array.isArray(data.documents) || data.documents.length > 128 || !Number.isSafeInteger(data.errors) || data.errors < 0 || typeof data.fresh !== "boolean" || (data.head !== undefined && !SHA.test(data.head)) || (data.version !== undefined && !VERSION.test(data.version)) || data.documents.some((d: {state?:string}) => !["fresh","stale","nonancestor","unknown"].includes(d.state ?? ""))) return resolve(undefined);
50
- resolve(data);
51
- } catch { resolve(undefined); }
60
+ if (data.schemaVersion !== 1 || !Array.isArray(data.documents) || data.documents.length > 128 || !Number.isSafeInteger(data.errors) || data.errors < 0 || typeof data.fresh !== "boolean" || (data.head !== undefined && !SHA.test(data.head)) || (data.version !== undefined && !VERSION.test(data.version)) || data.documents.some((d: {state?:string}) => !["fresh","stale","nonancestor","unknown"].includes(d.state ?? ""))) return resolve({ unavailable: CHECKER_FAILED });
61
+ resolve({ evidence: data });
62
+ } catch { resolve({ unavailable: CHECKER_FAILED }); }
52
63
  });
53
64
  });
54
65
  }
@@ -101,8 +112,10 @@ export async function readReleaseReadiness(root: string, repo: string, liveIssue
101
112
  } catch { report.blockers.push("merged PR coverage unknown or truncated"); break; }
102
113
  }
103
114
  }
104
- const left = deadline - performance.now(); report.documents = left > 0 ? await (readers.docs ?? readDocEvidence)(root,Math.min(10_000,left)) : undefined;
105
- if (!report.documents || report.documents.head !== head || !report.documents.fresh || report.documents.errors || report.documents.documents.some(d => d.state !== "fresh")) report.blockers.push("documentation freshness or ancestry is unknown or stale");
115
+ const left = deadline - performance.now(); report.documents = left > 0 ? await (readers.docs ?? ((dir, ms) => readDocEvidenceDetailed(dir, ms, readers.checker).then(read => "evidence" in read ? read.evidence : undefined)))(root,Math.min(10_000,left)) : undefined;
116
+ const checkerMissing = !readers.docs && !existsSync(readers.checker ?? CHECKER_PATH); // #1120: a hub without the checker says so instead of calling the documents stale
117
+ if (checkerMissing) report.blockers.push("documentation checker unavailable in the running hub: " + CHECKER_MISSING);
118
+ else if (!report.documents || report.documents.head !== head || !report.documents.fresh || report.documents.errors || report.documents.documents.some(d => d.state !== "fresh")) report.blockers.push("documentation freshness or ancestry is unknown or stale");
106
119
  if (!liveIssues.length) report.blockers.push("native verification ledger unspecified");
107
120
  for (const id of liveIssues) {
108
121
  const reply = await gh(["issue","view",String(id),"--repo",repo,"--json","number,state"]); let state: "open"|"closed"|"unknown" = "unknown";
package/src/hub/sdlc.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { parseIssueLabels, parseRedFirst, testIntegrityBlockers, type RedFirstReceipt, type TestIntegrity } from "./test-integrity.ts";
2
2
  import { planConformanceBlockers, type PlanConformance } from "./plan-conformance.ts";
3
+ import { controlWriteSpan } from "./control-write-trace.ts";
3
4
  import { DEFAULT_MAX_NITS, findingsForHead, findingHead, findingTally, type ReviewFindingSet, type ReviewFindingTally } from "./review-findings.ts";
4
5
  import type { CostPlan } from "./cost-governance.ts";
5
6
  import { bandsConfig, type BandsConfig } from "./sdlc-metrics.ts";
@@ -427,7 +428,7 @@ export function touchingPrs(prs: { pr: number; paths: string[] }[]): { before: n
427
428
 
428
429
  export type SdlcGh = (args: string[], timeoutMs?: number, cwd?: string, maxOutputBytes?: number) => Promise<{ code: number; stdout: string }>;
429
430
  /** Fixed argv and bounded output and time; diagnostics never expose credentials or remote text. Reads, except the one guarded `gh pr merge` that `sdlc-merge.ts` builds (#786). */
430
- export const sdlcGh: SdlcGh = (args, timeoutMs = 10_000, cwd, maxOutputBytes = 256 * 1024) => new Promise((resolve) => {
431
+ export const sdlcGh: SdlcGh = (args, timeoutMs = 10_000, cwd, maxOutputBytes = 256 * 1024) => controlWriteSpan("external", () => new Promise<{ code: number; stdout: string }>((resolve) => {
431
432
  const outputLimit = Number.isSafeInteger(maxOutputBytes) ? Math.min(2 * 1024 * 1024, Math.max(1, maxOutputBytes)) : 256 * 1024;
432
433
  let child: ReturnType<typeof spawn>;
433
434
  try {
@@ -440,7 +441,7 @@ export const sdlcGh: SdlcGh = (args, timeoutMs = 10_000, cwd, maxOutputBytes = 2
440
441
  child.stdout?.on("data", chunk => { if (failed) return; stdout += chunk.toString(); if (Buffer.byteLength(stdout) > outputLimit) { stdout = ""; stop(); } });
441
442
  child.once("error", () => { failed = true; clearTimeout(timer); resolve({ code: 1, stdout: "" }); });
442
443
  child.once("close", code => { clearTimeout(timer); resolve({ code: failed ? 1 : code ?? 1, stdout: failed ? "" : stdout }); });
443
- });
444
+ }));
444
445
 
445
446
  /** Read-only, fixed argv: the issue's edit times, never its body. */
446
447
  export async function readSpecEdit(repoName: string, issue: number, run: SdlcGh = sdlcGh): Promise<SpecEdit | undefined> {
@@ -506,6 +507,18 @@ export async function readSdlcPr(receipt: SdlcReceipt, run: SdlcGh = sdlcGh, wit
506
507
  } catch { return undefined; }
507
508
  }
508
509
 
510
+ /** Read only the current PR head when broader PR evidence is unavailable. */
511
+ export async function readSdlcPrHead(receipt: SdlcReceipt, run: SdlcGh = sdlcGh): Promise<string | undefined> {
512
+ if (!repo(receipt.repo) || !id(receipt.pr)) return undefined;
513
+ try {
514
+ const result = await run(["pr", "view", String(receipt.pr), "--repo", receipt.repo, "--json", "headRefOid"], 10_000, undefined, 1024);
515
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 1024) return undefined;
516
+ const value: unknown = JSON.parse(result.stdout);
517
+ const head = (value as { headRefOid?: unknown } | null)?.headRefOid;
518
+ return sha(head) ? head : undefined;
519
+ } catch { return undefined; }
520
+ }
521
+
509
522
  export interface PlanIssueMetadata {
510
523
  repo: string;
511
524
  issue: number;
@@ -81,6 +81,8 @@ export const SETTINGS: readonly SettingDef[] = [
81
81
  { key: "routing.stay_switch", group: "Routing", label: "Stay or switch (hub/auto and stage routes)", type: "enum", values: ["off", "shadow", "enforce"], store: "routing", applies: "live", risk: "raises", path: ["stay_switch"] },
82
82
  ...CLASSES.flatMap(perClass),
83
83
  { key: "research.enabled", group: "Switches", label: "Research records", type: "boolean", store: "config", applies: "live", risk: "safe", path: ["research", "enabled"] },
84
+ { key: "specs.enabled", group: "Switches", label: "Design specs and freshness", type: "boolean", store: "config", applies: "live", risk: "safe", path: ["specs", "enabled"] },
85
+ { key: "specs.review", group: "Switches", label: "Covering spec review", type: "enum", values: ["off", "report", "require"], store: "config", applies: "live", risk: "safe", path: ["specs", "review"] },
84
86
  { key: "approvals.notify", group: "Switches", label: "Desktop notice for a waiting approval", type: "boolean", store: "config", applies: "live", risk: "safe", path: ["approvals", "notify"] },
85
87
  { key: "snapshots.enabled", group: "Switches", label: "Per-turn snapshots", type: "boolean", store: "config", applies: "live", risk: "safe", path: ["snapshots", "enabled"] },
86
88
  { key: "coordination", group: "Switches", label: "Coordination of overlapping owners", type: "enum", values: ["advisory", "turn-free"], store: "config", applies: "next use", risk: "safe", path: ["coordination"] },
@@ -0,0 +1,43 @@
1
+ export type SpecsReview = "off" | "report" | "require";
2
+
3
+ export interface SpecsConfig {
4
+ enabled: boolean;
5
+ review: SpecsReview;
6
+ roots: string[];
7
+ stamps_file: string;
8
+ }
9
+
10
+ export const DEFAULT_SPECS_CONFIG: Readonly<SpecsConfig> = Object.freeze({
11
+ enabled: true,
12
+ review: "report",
13
+ roots: [],
14
+ stamps_file: "",
15
+ });
16
+
17
+ function object(value: unknown): value is Record<string, unknown> {
18
+ return !!value && typeof value === "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
19
+ }
20
+
21
+ function safeRelative(value: unknown): value is string {
22
+ if (typeof value !== "string" || !value.length || value.length > 1024 || value.startsWith("/") || value.startsWith("-") || /^[A-Za-z]:/.test(value) || value.includes("\\") || value.includes(":") || /[\u0000-\u001f\u007f]/.test(value)) return false;
23
+ const normalized = value.endsWith("/") ? value.slice(0, -1) : value;
24
+ return !!normalized && !normalized.split("/").some(part => part === ".." || part === "." || part === "");
25
+ }
26
+
27
+ function invalid(message: string, nextSteps: string): never { throw new Error(`${message}; ${nextSteps}`); }
28
+
29
+ /** Filesystem-free parser shared by config loading and the specs engine. */
30
+ export function parseSpecsConfig(value: unknown): SpecsConfig {
31
+ if (value === undefined) return { ...DEFAULT_SPECS_CONFIG, roots: [] };
32
+ if (!object(value)) invalid("specs must be an object", "use an object with enabled, review, roots and stamps_file fields");
33
+ if (Object.keys(value).some(key => !["enabled", "review", "roots", "stamps_file"].includes(key))) invalid("specs has an unknown field", "use only enabled, review, roots and stamps_file");
34
+ const enabled = value.enabled === undefined ? DEFAULT_SPECS_CONFIG.enabled : value.enabled;
35
+ const review = value.review === undefined ? DEFAULT_SPECS_CONFIG.review : value.review;
36
+ const roots = value.roots === undefined ? DEFAULT_SPECS_CONFIG.roots : value.roots;
37
+ const stampsFile = value.stamps_file === undefined ? DEFAULT_SPECS_CONFIG.stamps_file : value.stamps_file;
38
+ if (typeof enabled !== "boolean") invalid("specs.enabled must be a boolean", "set it to true or false");
39
+ if (review !== "off" && review !== "report" && review !== "require") invalid("specs.review is invalid", "choose off, report or require");
40
+ if (!Array.isArray(roots) || roots.length > 1024 || roots.some(root => !safeRelative(root))) invalid("specs.roots is invalid", "use at most 1024 repository-relative directories without dot segments");
41
+ if (stampsFile !== "" && !safeRelative(stampsFile)) invalid("specs.stamps_file is invalid", "use an empty value or one repository-relative path without dot segments");
42
+ return { enabled, review, roots: [...roots] as string[], stamps_file: stampsFile as string };
43
+ }