@staix/agent-hub 0.45.0 → 0.46.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 (107) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +10 -4
  3. package/docs/adding-an-ai-tool.md +1 -0
  4. package/docs/agent-notes/adapters.md +33 -4
  5. package/docs/agent-notes/budget.md +2 -1
  6. package/docs/agent-notes/daemon.md +5 -1
  7. package/docs/agent-notes/security-review.md +3 -2
  8. package/docs/agent-notes/tasks.md +3 -1
  9. package/docs/agent-notes/tests.md +1 -1
  10. package/docs/design/adapters.md +16 -0
  11. package/docs/design/agent-hub-architecture.md +12 -0
  12. package/docs/design/cli-output.md +2 -0
  13. package/docs/design/roadmap.md +86 -5
  14. package/docs/design/task-board.md +2 -2
  15. package/docs/dogfood.md +15 -0
  16. package/docs/events.md +2 -2
  17. package/docs/operations.md +102 -20
  18. package/docs/quickstart.md +9 -3
  19. package/docs/security.md +7 -5
  20. package/docs/smoke.md +1 -1
  21. package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -0
  22. package/docs/verification/2026-11-22-agy-1.5.14.md +27 -0
  23. package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
  24. package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
  25. package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
  26. package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
  27. package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
  28. package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
  29. package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
  30. package/docs/verification/2026-11-23-0.46.0.md +44 -0
  31. package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
  32. package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
  33. package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
  34. package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
  35. package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
  36. package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
  37. package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
  38. package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
  39. package/docs/verified.json +23 -23
  40. package/package.json +3 -2
  41. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  42. package/plugins/agent-hub/kimi-hook.js +5951 -5499
  43. package/plugins/agent-hub/server.js +1136 -1015
  44. package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
  45. package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
  46. package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
  47. package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
  48. package/src/adapters/claude-channel.ts +2 -1
  49. package/src/adapters/compat.ts +12 -11
  50. package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
  51. package/src/adapters/definitions/native-cli-doctor.ts +8 -5
  52. package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
  53. package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
  54. package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
  55. package/src/adapters/definitions/native-cli-skills.ts +29 -0
  56. package/src/cli/claude-profile-hook.ts +40 -3
  57. package/src/cli/console-state.ts +55 -26
  58. package/src/cli/console-usage.ts +5 -3
  59. package/src/cli/console.ts +35 -4
  60. package/src/cli/help.ts +15 -10
  61. package/src/cli/identity.ts +2 -1
  62. package/src/cli/instruction-hook.ts +28 -0
  63. package/src/cli/jcode-mcp.ts +2 -1
  64. package/src/cli/main.js +8 -0
  65. package/src/cli/main.ts +138 -18
  66. package/src/cli/output-standard.ts +3 -55
  67. package/src/cli/output.ts +8 -2
  68. package/src/cli/recovery-package.ts +47 -11
  69. package/src/cli/roadmap.ts +37 -3
  70. package/src/cli/setup-homes.ts +1 -0
  71. package/src/cli/setup.ts +1 -1
  72. package/src/cli/skills-install.ts +463 -0
  73. package/src/cli/task-output.ts +1 -1
  74. package/src/cli/upgrade-presentation-flags.ts +1 -1
  75. package/src/hub/board.ts +42 -4
  76. package/src/hub/budget-projection.ts +99 -0
  77. package/src/hub/claude-launch-proof.ts +5 -1
  78. package/src/hub/conductor.ts +8 -3
  79. package/src/hub/config-apply.ts +3 -2
  80. package/src/hub/config-tier.ts +1 -1
  81. package/src/hub/config-trust.ts +1 -1
  82. package/src/hub/control-client.ts +9 -2
  83. package/src/hub/daemon.ts +457 -26
  84. package/src/hub/events.ts +1 -1
  85. package/src/hub/execution-budget.ts +29 -8
  86. package/src/hub/hub-tools.ts +2 -2
  87. package/src/hub/inference.ts +1 -1
  88. package/src/hub/instances.ts +10 -1
  89. package/src/hub/instructed-exact.ts +95 -0
  90. package/src/hub/instructed-intent.ts +64 -0
  91. package/src/hub/instructed-ipc.ts +33 -0
  92. package/src/hub/instructed-runtime.ts +19 -0
  93. package/src/hub/instruction-receipt.ts +218 -0
  94. package/src/hub/manager.ts +46 -3
  95. package/src/hub/registry.ts +1 -1
  96. package/src/hub/roadmap-decompose.ts +60 -1
  97. package/src/hub/roadmap-sync.ts +2 -2
  98. package/src/hub/roadmap.ts +19 -1
  99. package/src/hub/routing.ts +18 -1
  100. package/src/hub/runtime-capture-prune.ts +2 -1
  101. package/src/hub/settings.ts +2 -1
  102. package/src/hub/tasks.ts +194 -12
  103. package/src/hub/ui.ts +6 -2
  104. package/src/hub/usage-rollup.ts +42 -2
  105. package/src/ui/index.html +342 -8
  106. package/src/ui/plugin.ts +6 -2
  107. package/src/ui/roadmap-model.ts +70 -0
package/src/hub/events.ts CHANGED
@@ -99,7 +99,7 @@ export type HubEvent =
99
99
  | ({ type: "turn_end"; peer: string; turn: string; ms: number; tokens?: number; files?: number; snapshotMs?: number; preparedRoles?: RoleIdentity[] | null; model?: string; modelEvidence?: ModelEvidence; edits?: TurnEdits } & Partial<TaskAttribution>)
100
100
  | { type: "native_turn_end"; peer: string; id?: string; reason?: "user_canceled" | "error" | "max_invocations" | "max_forced_invocations" | "max_token_budget_exceeded" | "terminal_step_type" | "terminal_custom_hook" }
101
101
  | { type: "conduct"; peer: string; action: string; task?: number; target?: string }
102
- | ({ type: "agent_cli"; peer: string; command: string; refused: boolean; delegated?: true; instructed?: true } & Partial<TaskAttribution>)
102
+ | ({ type: "agent_cli"; peer: string; command: string; refused: boolean; delegated?: true; instructed?: true; instructionReceipt?: string } & Partial<TaskAttribution>)
103
103
  | ({ type: "permission"; id: string; peer: string; event: "requested" | "answered" | "expired" | "cancelled"; latencyMs?: number; surface?: "console" | "dashboard" | "terminal"; option?: "allow_once" | "allow_always" | "reject_once" | "reject_always" } & Partial<TaskAttribution>)
104
104
  /** #1053: one question a peer asked the person, and how it ended. Counts, ids and a closed reason only: never a prompt, an option, an answer or other text. */
105
105
  | ({ type: "question"; set: string; peer: string; event: "asked" | "answered" | "pending" | "superseded" | "cancelled" | "expired" | "unavailable"; latencyMs?: number; surface?: "terminal" | "console" | "dashboard" | "acon" | "conductor"; person?: string; reason?: "superseded" | "stopped" | "turn_aborted" | "session_changed" | "expired" | "unattended"; questions?: number; private?: boolean } & Partial<TaskAttribution>)
@@ -11,11 +11,19 @@ export interface ExecutionBudgetConfig {
11
11
  peers: string[];
12
12
  limits: ExecutionBudgetLimits;
13
13
  }
14
+ /** #1513 AC3: a person's reason for reconfiguring a budget, kept with who gave it and when. */
15
+ export interface ExecutionOverride {
16
+ reason: string;
17
+ by: string;
18
+ at: number;
19
+ }
14
20
  export interface ExecutionBudgetStatus extends ExecutionBudgetConfig {
15
21
  used: Partial<Record<ExecutionUnit, number>>;
16
22
  units: Partial<Record<ExecutionUnit, { used: number; limit: number; remaining: number; reason?: "exhausted" | "unknown_usage" }>>;
17
23
  createdAt: number;
18
24
  updatedAt: number;
25
+ /** The last reasoned override. A configure without a reason leaves it as it was. */
26
+ override?: ExecutionOverride;
19
27
  }
20
28
  export interface ExecutionBudgetDecision {
21
29
  allowed: boolean;
@@ -48,9 +56,16 @@ export class ExecutionBudget {
48
56
  this.db.run(`CREATE TABLE IF NOT EXISTS execution_budgets (
49
57
  id TEXT PRIMARY KEY, kind TEXT NOT NULL, task_id INTEGER, peers TEXT NOT NULL,
50
58
  limits TEXT NOT NULL, used TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`);
59
+ // #1513: a table created before the override column exists still opens, and keeps its rows.
60
+ const columns = this.db.query("PRAGMA table_info(execution_budgets)").all() as { name: string }[];
61
+ if (!columns.some(column => column.name === "last_override")) this.db.run("ALTER TABLE execution_budgets ADD COLUMN last_override TEXT");
51
62
  }
52
63
 
53
- configure(input: ExecutionBudgetConfig): ExecutionBudgetStatus {
64
+ /**
65
+ * A configure with a reason records it with the actor and the time, and the caller's `by` is only ever
66
+ * `person`: the console is the one writer of an execution budget.
67
+ */
68
+ configure(input: ExecutionBudgetConfig, meta: { reason?: string; by?: string } = {}): ExecutionBudgetStatus {
54
69
  if (!input.id || input.id.length > 200) throw new Error("execution budget id is invalid");
55
70
  if (input.kind !== "task" && input.kind !== "run") throw new Error("execution budget kind must be task or run");
56
71
  if (input.kind === "task" && (!Number.isSafeInteger(input.taskId) || input.taskId! < 1)) throw new Error("task budget requires a positive task id");
@@ -60,13 +75,17 @@ export class ExecutionBudget {
60
75
  if (unsupported.length) throw new Error(`execution budgets require instrumented peers (pi, local); unsupported: ${unsupported.join(", ")}`);
61
76
  const limits = validLimits(input.limits ?? {});
62
77
  if (!Object.keys(limits).length) throw new Error("execution budget requires at least one supported limit");
78
+ const reason = meta.reason === undefined ? undefined : String(meta.reason).trim();
79
+ if (reason !== undefined && reason.length > 280) throw new Error("execution budget reason is at most 280 characters");
63
80
  const now = Date.now();
64
- const existing = this.db.query("SELECT kind,task_id FROM execution_budgets WHERE id=?").get(input.id) as { kind: string; task_id: number | null } | undefined;
81
+ const existing = this.db.query("SELECT kind,task_id,last_override FROM execution_budgets WHERE id=?").get(input.id) as { kind: string; task_id: number | null; last_override: string | null } | undefined;
65
82
  if (existing && (existing.kind !== input.kind || existing.task_id !== (input.taskId ?? null))) throw new Error("execution budget id is already bound to another scope");
66
- this.db.query(`INSERT INTO execution_budgets (id,kind,task_id,peers,limits,used,created_at,updated_at)
67
- VALUES (?,?,?,?,?,'{}',?,?) ON CONFLICT(id) DO UPDATE SET kind=excluded.kind,task_id=excluded.task_id,
68
- peers=excluded.peers,limits=excluded.limits,updated_at=excluded.updated_at`).run(
69
- input.id, input.kind, input.taskId ?? null, JSON.stringify(peers), JSON.stringify(limits), now, now,
83
+ // A configure without a reason keeps the last one: the row answers "why is this limit what it is", not "what did the last call say".
84
+ const lastOverride = reason ? JSON.stringify({ reason, by: meta.by ?? "person", at: now }) : existing?.last_override ?? null;
85
+ this.db.query(`INSERT INTO execution_budgets (id,kind,task_id,peers,limits,used,created_at,updated_at,last_override)
86
+ VALUES (?,?,?,?,?,'{}',?,?,?) ON CONFLICT(id) DO UPDATE SET kind=excluded.kind,task_id=excluded.task_id,
87
+ peers=excluded.peers,limits=excluded.limits,updated_at=excluded.updated_at,last_override=excluded.last_override`).run(
88
+ input.id, input.kind, input.taskId ?? null, JSON.stringify(peers), JSON.stringify(limits), now, now, lastOverride,
70
89
  );
71
90
  return this.status(input.id) as ExecutionBudgetStatus;
72
91
  }
@@ -147,7 +166,7 @@ export class ExecutionBudget {
147
166
  close(): void { this.db.close(); }
148
167
  }
149
168
 
150
- interface BudgetRow { id: string; kind: "task"|"run"; task_id: number | null; peers: string; limits: string; used: string; created_at: number; updated_at: number }
169
+ interface BudgetRow { id: string; kind: "task"|"run"; task_id: number | null; peers: string; limits: string; used: string; created_at: number; updated_at: number; last_override?: string | null }
151
170
  function fromRow(row: BudgetRow): ExecutionBudgetStatus {
152
171
  const limits = JSON.parse(row.limits) as ExecutionBudgetLimits;
153
172
  const used = JSON.parse(row.used) as Partial<Record<ExecutionUnit, number>>;
@@ -157,5 +176,7 @@ function fromRow(row: BudgetRow): ExecutionBudgetStatus {
157
176
  const current = used[unit] ?? 0, remaining = Math.max(0, limit - current);
158
177
  units[unit] = { used: current, limit, remaining, ...((unit === "tokens" && remaining > 0) ? { reason: "unknown_usage" as const } : (remaining === 0 ? { reason: "exhausted" as const } : {})) };
159
178
  }
160
- return { id: row.id, kind: row.kind, ...(row.task_id === null ? {} : { taskId: row.task_id }), peers: JSON.parse(row.peers), limits, used, units, createdAt: row.created_at, updatedAt: row.updated_at };
179
+ const override = row.last_override ? JSON.parse(row.last_override) as ExecutionOverride : undefined;
180
+ return { id: row.id, kind: row.kind, ...(row.task_id === null ? {} : { taskId: row.task_id }), peers: JSON.parse(row.peers), limits, used, units, createdAt: row.created_at, updatedAt: row.updated_at,
181
+ ...(override && typeof override.reason === "string" && typeof override.by === "string" && typeof override.at === "number" ? { override } : {}) };
161
182
  }
@@ -241,7 +241,7 @@ export const TASK_TOOLS: HubTool[] = [
241
241
  tool("hub_roadmap_check", "Read roadmap drift findings and unknown evidence. Private tasks stay withheld; no writes are made.", {}),
242
242
  tool("hub_roadmap_unplaced", "Read the open GitHub issues, open board tasks and active/draft specs that no live milestone places, each with why. Private tasks are a count only. partial: true means the GitHub read stopped early or a list was cut, so the lists are a lower bound; unavailable names evidence that could not be read. Read only: no write, no model call. Optional repo is owner/name.", { repo: { type: "string", maxLength: MILESTONE_LIMITS.issue } }),
243
243
  tool("hub_roadmap_triage", "Ask the hub's model to suggest a milestone (or a new one) for unplaced work. Each suggestion cites the milestone and item words it matched and is saved as a pending model answer; nothing is linked until hub_roadmap_edit accept. Configured planner or unique conductor only. list: true reads the pending public suggestions without a model call and is open to any agent.", { repo: { type: "string", maxLength: MILESTONE_LIMITS.issue }, list: { type: "boolean" } }),
244
- tool("hub_roadmap_decompose", "Ask the hub's model to decompose one milestone into parts, from its outcome, the specs it links and the issues it links. Each part cites linked ids and says whether it needs a spec issue or goes straight to a task; the answer is saved as a pending model answer and nothing is linked, intaken or published. Pass accept with one part's number to hold that part as an intake draft instead: it is linked to the milestone, carries the part's spec-issue or task kind, and is offered to nobody until the person releases it with ahub intake approve. Configured planner or unique conductor only. On refusal inspect hub_roadmap_show and correct the named input.", { id: { type: "integer", minimum: 1 }, accept: { type: "integer", minimum: 1 } }, ["id"]),
244
+ tool("hub_roadmap_decompose", "Ask the hub's model to decompose one milestone into parts, from its outcome, the specs it links and the issues it links. Each part cites linked ids and says whether it needs a spec issue or goes straight to a task; the answer is saved as a pending model answer and nothing is linked, intaken or published. Pass accept with one part's number to hold that part as an intake draft instead: it is linked to the milestone, carries the part's spec-issue or task kind, and is offered to nobody until the person releases it with ahub intake approve. Pass publish true to preview the GitHub issues the milestone's held drafts would create (one per held spec part; a task part is its own held task, a released draft is skipped and a private part is only counted) without writing anything; publish true with apply true and the preview's confirm creates them behind roadmap.github_write and links each to the milestone, so a person or the configured conductor with that gate is required. Configured planner or unique conductor only. On refusal inspect hub_roadmap_show and correct the named input.", { id: { type: "integer", minimum: 1 }, accept: { type: "integer", minimum: 1 }, publish: { type: "boolean" }, apply: { type: "boolean" }, confirm: { type: "string", description: "the fingerprint the publish preview printed; required with apply" } }, ["id"]),
245
245
  tool("hub_roadmap_edit", "Create or change a milestone. Configured planner or unique conductor only; done/dropped are person-only. new/edit take fields; edit also needs the current revision. Link kinds are spec/issue/task/release; issue refs are owner/repo#N. accept applies exactly one pending triage suggestion through link (creating its proposed milestone first); reject drops it. No GitHub write, task assignment or model call. On refusal inspect hub_roadmap_show and correct the named input.", {
246
246
  op: { type: "string", enum: ["new", "edit", "link", "unlink", "order", "state", "accept", "reject"] }, id: { type: "integer", minimum: 1 }, revision: { type: "integer", minimum: 0 }, suggestion: { type: "integer", minimum: 1, description: "accept or reject: a pending suggestion id from hub_roadmap_triage" },
247
247
  fields: { type: "object", additionalProperties: false, properties: {
@@ -286,7 +286,7 @@ export const TASK_TOOLS: HubTool[] = [
286
286
  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"]),
287
287
  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"]),
288
288
  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. The configured conductor may also cancel a task another project handed this one that nobody has accepted. 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"]),
289
- 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"]),
289
+ 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 whenever the reason is load: you are busy, at your WIP cap or running a job. You are then skipped until you next report idle, and the task goes back to its planner or the next peer. Leave capacity off only for \"I should never own this\".", { id, reason: str, capacity: { type: "boolean" } }, ["id"]),
290
290
  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, resolved: { type: "array", maxItems: 64, uniqueItems: true, items: str, description: "Sent person comment ids addressed by this admitted completion; this is an owner claim, not check or verdict proof" } }, ["id", "summary"]),
291
291
  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"]),
292
292
  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" } }),
@@ -214,7 +214,7 @@ export interface PiiScreenDeps {
214
214
  }
215
215
 
216
216
  /** With triage (8 s) and a brief (2 x 2 s), a proposal answers within 20 s, under the plugin's 30 s control timeout. */
217
- const SCREEN_TIMEOUT_MS = 8_000;
217
+ export const SCREEN_TIMEOUT_MS = 8_000;
218
218
  /** On campus, the share of the deadline the on-device model gets before the gateway takes over (a cold load, an error). */
219
219
  const DEVICE_SHARE = 0.6;
220
220
  /**
@@ -19,11 +19,13 @@ export interface InstanceConfig {
19
19
  readOnly?: boolean;
20
20
  /** Jcode instances (#685): their own native data home, and optional model selection. A headless Claude implementer also takes `model` (#844). Machine-local, never editable from settings. */
21
21
  jcode_home?: string;
22
+ /** Names of jcode MCP servers `ahub doctor` accepts for this instance; absent inherits the top-level list (#1621). */
23
+ jcode_mcp_allow?: string[];
22
24
  provider?: string;
23
25
  model?: string;
24
26
  provider_profile?: string;
25
27
  }
26
- const JCODE_FIELDS = ["jcode_home", "provider", "model", "provider_profile"] as const;
28
+ const JCODE_FIELDS = ["jcode_home", "jcode_mcp_allow", "provider", "model", "provider_profile"] as const;
27
29
  /** At most this many extra Jcode instances per project (#685). */
28
30
  export const MAX_JCODE_INSTANCES = 8;
29
31
  /** A flag value jcode takes as one argv word: bounded, printable, no spaces. */
@@ -58,6 +60,12 @@ function roles(value: unknown, field: string): string[] {
58
60
  return out;
59
61
  }
60
62
 
63
+ /** A jcode MCP allowlist (#1621): an array of nonempty, control-free names of at most 256 bytes, at most 64 of them. */
64
+ export function mcpAllowNames(value: unknown, field: string): string[] {
65
+ if (!Array.isArray(value) || value.length > 64 || value.some(name => typeof name !== "string" || !name.trim() || Buffer.byteLength(name) > 256 || /\p{Cc}/u.test(name))) return fail(field, "must be an array of at most 64 nonempty control-free server names");
66
+ return [...value] as string[];
67
+ }
68
+
61
69
  /** The Jcode-only fields of one declaration (#685). Only the validated values are copied; nothing is read twice. */
62
70
  function jcodeInstanceFields(entry: Record<string, PropertyDescriptor>, path: string): Partial<InstanceConfig> {
63
71
  const home: unknown = entry.jcode_home?.value;
@@ -70,6 +78,7 @@ function jcodeInstanceFields(entry: Record<string, PropertyDescriptor>, path: st
70
78
  if (!isNativeModelToken(word)) return fail(`${path}.${key}`, "must be one bounded printable word without spaces");
71
79
  out[key] = word;
72
80
  }
81
+ if (entry.jcode_mcp_allow) out.jcode_mcp_allow = mcpAllowNames(entry.jcode_mcp_allow.value, `${path}.jcode_mcp_allow`);
73
82
  if (entry.start_mode && entry.start_mode.value !== "headless") return fail(`${path}.start_mode`, "a Jcode instance starts headless");
74
83
  return out;
75
84
  }
@@ -0,0 +1,95 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { parseModelCommand } from "../cli/model.ts";
3
+ import { parseStudyArgs } from "../cli/study.ts";
4
+ import { SCREEN_TIMEOUT_MS } from "./inference.ts";
5
+
6
+ export const INSTRUCTION_CHILD_TIMEOUT_MS = 30_000;
7
+ export const INSTRUCTION_CONTROL_TIMEOUT_MS = INSTRUCTION_CHILD_TIMEOUT_MS + 3 * SCREEN_TIMEOUT_MS + 5_000;
8
+
9
+ /** Parse only the explicit skill's `run` form; no shell syntax or implicit quoting is accepted. */
10
+ export function parseExactInstruction(args: string): string[] | undefined {
11
+ if (!args.isWellFormed() || /[\p{Cc}\p{Cf}'"\\$`<>&]/u.test(args)) return;
12
+ const words = args.trim().split(/ +/u);
13
+ if (words[0] !== "run" || !words[1] || words[1]!.startsWith("-")) return;
14
+ return words.slice(1);
15
+ }
16
+
17
+ /** A missing machine-local setting uses intent mode; malformed values never enable it. */
18
+ export function instructedMode(value: unknown): "off" | "exact" | "intent" {
19
+ if (value === undefined) return "intent";
20
+ if (value === "off" || value === "exact" || value === "intent") return value;
21
+ throw new Error("instructed.mode must be off, exact or intent");
22
+ }
23
+
24
+ export interface ExactForm { argv: string[]; taskId?: number; targetPeer?: string; screen?: true; titleTarget?: true; study?: { id: string; revision: number } }
25
+
26
+ /** Closed, syntax-checked forms only. New and unclassified forms never inherit authority. */
27
+ export function exactForm(argv: readonly string[]): ExactForm | undefined {
28
+ if (argv.some(word => word === "--as-user" || word.startsWith("--as-user=") || word === "--project" || word.startsWith("--project=") || word === "--live-test")) return;
29
+ const [command, sub, ...tail] = argv;
30
+ if (command === "task" && sub === "claim") {
31
+ const [id, slot, verdict, ...extra] = tail;
32
+ if (!extra.length && id && slot && /^[1-9]\d*$/.test(id) && /^[1-9]\d*$/.test(slot)
33
+ && Number.isSafeInteger(Number(id)) && Number.isSafeInteger(Number(slot)) && ["supported", "unsupported", "unclear"].includes(verdict ?? "")) return { argv: [...argv], taskId: Number(id) };
34
+ return;
35
+ }
36
+ if (command === "task" && (sub === "assign" || sub === "unassign")) {
37
+ const positional: string[] = [], flags = new Map<string, string>();
38
+ for (let i = 0; i < tail.length; i++) {
39
+ const word = tail[i]!;
40
+ if (word.startsWith("--")) {
41
+ if (!["--role", "--revision"].includes(word) || flags.has(word) || !tail[i + 1]) return;
42
+ flags.set(word, tail[++i]!);
43
+ } else positional.push(word);
44
+ }
45
+ if (positional.length !== (sub === "assign" ? 2 : 1) || !/^[1-9]\d*$/.test(positional[0]!) || !Number.isSafeInteger(Number(positional[0]))) return;
46
+ if (sub === "assign" && !/^[a-z][a-z0-9-]*$/.test(positional[1]!)) return;
47
+ const role = flags.get("--role");
48
+ if (role && !(sub === "assign" ? ["owner", "reviewer", "planner"] : ["owner", "reviewer"]).includes(role)) return;
49
+ const revision = flags.get("--revision");
50
+ if (revision !== undefined && (!/^\d+$/.test(revision) || !Number.isSafeInteger(Number(revision)))) return;
51
+ return { argv: [...argv], taskId: Number(positional[0]) };
52
+ }
53
+ if (command === "backlog" && (sub === "pull" || sub === "return") && tail.length === 1 && /^[1-9]\d*$/.test(tail[0]!) && Number.isSafeInteger(Number(tail[0]))) return { argv: [...argv], taskId: Number(tail[0]) };
54
+ if (command === "backlog" && (sub === "pin" || sub === "pull-ready")) {
55
+ const [id, revision, ...rest] = tail;
56
+ if (!id || !/^[1-9]\d*$/.test(id) || !Number.isSafeInteger(Number(id)) || !revision || !/^\d+$/.test(revision) || !Number.isSafeInteger(Number(revision))) return;
57
+ const reason = sub === "pin" ? rest.slice(1) : rest;
58
+ if (sub === "pin" && !["true", "false"].includes(rest[0] ?? "")) return;
59
+ if (!reason.length || reason.some(word => !word || word.startsWith("--"))) return;
60
+ return { argv: [...argv], taskId: Number(id), screen: true };
61
+ }
62
+ if (command === "backlog" && sub === "add") {
63
+ const [taskClass, ...title] = tail;
64
+ if (taskClass && /^[a-z][a-z0-9_-]*$/.test(taskClass) && title.length && title.every(word => word && !word.startsWith("--"))) return { argv: [...argv], screen: true };
65
+ return;
66
+ }
67
+ if (command === "roadmap" && sub === "state") {
68
+ const [id, state, ...extra] = tail;
69
+ if (!extra.length && id && /^[1-9]\d*$/.test(id) && Number.isSafeInteger(Number(id)) && (state === "done" || state === "dropped")) return { argv: [...argv] };
70
+ return;
71
+ }
72
+ if (command === "study" && sub === "approve") {
73
+ const parsed = parseStudyArgs(argv.slice(1));
74
+ if (!("usage" in parsed) && parsed.op === "approve") return { argv: [...argv], screen: true, study: { id: parsed.id, revision: parsed.revision } };
75
+ return;
76
+ }
77
+ if (command === "title" && sub && /^[a-z][a-z0-9-]*$/.test(sub) && tail.length && tail.every(word => word && !word.startsWith("--"))) return { argv: [...argv], targetPeer: sub, screen: true, titleTarget: true };
78
+ if (command === "model") {
79
+ try { const model = parseModelCommand(argv.slice(1)); if ((model.op === "set" || model.op === "clear") && model.peer) return { argv: [...argv], targetPeer: model.peer }; } catch { return; }
80
+ }
81
+ if (["stop", "pause", "resume"].includes(command ?? "") && argv.length === 2 && sub && /^[a-z][a-z0-9-]*$/.test(sub)) return { argv: [...argv], targetPeer: sub };
82
+ if (command === "settings" && sub === "set" && tail.length >= 2 && tail.length <= 3) {
83
+ const [key, value, flag] = tail;
84
+ if (key && value && (key === "tasks.auto_pull" || /^tasks\.wip_limits\.[a-z][a-z0-9-]*$/.test(key) || key === "tasks.queue_backpressure.max_queued" || key === "tasks.queue_backpressure.max_oldest_s") && (flag === undefined || flag === "--yes")) return { argv: [...argv] };
85
+ }
86
+ return;
87
+ }
88
+
89
+ export interface InstructedExecution { peer: string; receipt: string; taskId?: number; active: boolean; current(): void; beginStudy?(): void }
90
+ /** Host-only provenance follows the actual control request into board writes. */
91
+ export const instructedExecution = new AsyncLocalStorage<InstructedExecution>();
92
+ export function instructedHistory(by: string): { instructed: true; instructedPeer: string; instructionReceipt: string } | Record<string, never> {
93
+ const context = instructedExecution.getStore();
94
+ return by === "user" && context?.active ? { instructed: true, instructedPeer: context.peer, instructionReceipt: context.receipt } : {};
95
+ }
@@ -0,0 +1,64 @@
1
+ import { exactForm } from "./instructed-exact.ts";
2
+
3
+ export interface IntentForm { argv: string[]; taskId?: number; targetPeer?: string; verdictIds?: string[]; review?: true }
4
+
5
+ /** Each id must occur as its own literal token; repeated ids need separate occurrences. */
6
+ export function literalInstructionIds(prompt: string, ids: readonly string[]): boolean {
7
+ const used: { start: number; end: number }[] = [];
8
+ for (const id of ids) {
9
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(id)) return false;
10
+ let at = prompt.indexOf(id), found = false;
11
+ while (at >= 0) {
12
+ const before = prompt[at - 1], after = prompt[at + id.length];
13
+ if ((!before || !/[\p{L}\p{N}_-]/u.test(before)) && (!after || !/[\p{L}\p{N}_-]/u.test(after)) && !used.some(span => at < span.end && at + id.length > span.start)) {
14
+ used.push({ start: at, end: at + id.length }); found = true; break;
15
+ }
16
+ at = prompt.indexOf(id, at + 1);
17
+ }
18
+ if (!found) return false;
19
+ }
20
+ return true;
21
+ }
22
+
23
+ /** Closed intent forms; child argv is passed directly, never to a shell. */
24
+ export function intentForm(argv: readonly string[]): IntentForm | undefined {
25
+ if (!argv.length || argv.some(word => typeof word !== "string" || !word.isWellFormed() || /[\p{Cc}\p{Cf}]/u.test(word))) return;
26
+ if (argv.some(word => word === "--as-user" || word.startsWith("--as-user=") || word === "--live-test" || word.startsWith("--live-test=") || word === "--project" || word.startsWith("--project="))) return;
27
+ const [command, sub, ...tail] = argv;
28
+ const exact = exactForm(argv);
29
+ if (exact && (command === "task" && sub === "assign" || command === "backlog" && (sub === "pull" || sub === "return") || command === "model" || command === "stop")) return exact;
30
+ const integer = (value: string | undefined) => !!value && /^[1-9]\d*$/.test(value) && Number.isSafeInteger(Number(value));
31
+ if (command === "task" && sub === "claim") {
32
+ const [id, slot, verdict, ...extra] = tail;
33
+ if (!extra.length && integer(id) && integer(slot) && ["supported", "unsupported", "unclear"].includes(verdict ?? "")) return { argv: [...argv], taskId: Number(id), verdictIds: [id!, slot!] };
34
+ }
35
+ // #1622 family 4: a final milestone verdict. The milestone id must be written literally in the person's prompt; the history entry carries the instructed provenance.
36
+ if (command === "roadmap" && sub === "state") {
37
+ const [id, state, ...extra] = tail;
38
+ if (!extra.length && integer(id) && (state === "done" || state === "dropped")) return { argv: [...argv], verdictIds: [id!] };
39
+ return;
40
+ }
41
+ if (command === "results" && argv.slice(1).every(word => ["--unread", "--json", "--full", "--color=auto", "--color=always", "--color=never"].includes(word))) return { argv: [...argv] };
42
+ if (command === "capabilities" && argv.slice(1).every(word => ["--json", "--color=auto", "--color=always", "--color=never"].includes(word))) return { argv: [...argv] };
43
+ if (command === "learn" && sub === "list" && tail.every(word => ["--all", "--json", "--color=auto", "--color=always", "--color=never"].includes(word))) return { argv: [...argv] };
44
+ if (command === "learn" && ["accept", "reject"].includes(sub ?? "") && tail.length === 1 && integer(tail[0])) return { argv: [...argv], taskId: Number(tail[0]), verdictIds: [tail[0]!] };
45
+ if (command === "review" && integer(sub)) {
46
+ const [verdict, flag, head, ...extra] = tail;
47
+ if (["approved", "changes_requested"].includes(verdict ?? "") && !extra.length && (flag === undefined && head === undefined || flag === "--head" && !!head && /^[a-f0-9]{40}$/.test(head))) return { argv: [...argv], taskId: Number(sub), verdictIds: [sub!], review: true };
48
+ }
49
+ return;
50
+ }
51
+
52
+ /** A closed family gets an explanation without echoing its operands. */
53
+ export function intentRefusal(argv: readonly string[]): string {
54
+ const [command, sub] = argv;
55
+ if (command === "role") return "role changes are trust settings and stay person-only";
56
+ if (command === "task" && sub === "claim" && argv.includes("--manifest")) return "file-backed claim verdicts stay person-only";
57
+ if (command === "task" && sub === "handoff") return "cross-project handoff lacks an instruction revocation fence";
58
+ if (command === "backlog" && ["add", "split"].includes(sub ?? "")) return "task creation requires instruction-bound privacy screening";
59
+ if (command === "study" && sub === "approve") return "study approval requires instruction-bound privacy screening";
60
+ if (command === "roadmap" && sub === "state") return "only roadmap state done or dropped for one milestone id is admitted; other states stay with the person";
61
+ if (command === "title") return "titles contain free text, and an unnamed title cannot be restored";
62
+ if (command === "backlog" && ["plan", "pin", "pull-ready"].includes(sub ?? "") || command === "review") return "this form contains free text or unclassified options";
63
+ return "this form is not proven for instructed intent mode";
64
+ }
@@ -0,0 +1,33 @@
1
+ /** WebSocket-shaped adapter over the daemon-created Bun IPC channel, never a network socket. */
2
+ export class InstructedIpcSocket {
3
+ readyState: number = WebSocket.CONNECTING;
4
+ onopen: (() => void) | null = null;
5
+ onmessage: ((event: { data: string }) => void) | null = null;
6
+ onerror: (() => void) | null = null;
7
+ onclose: ((event: { code: number; reason: string }) => void) | null = null;
8
+ private readonly message = (value: unknown) => {
9
+ try {
10
+ const data = JSON.stringify(value);
11
+ if (typeof data !== "string" || Buffer.byteLength(data) > this.maxFrame) throw new Error("invalid inherited control frame");
12
+ this.onmessage?.({ data });
13
+ } catch { this.close(); }
14
+ };
15
+ private readonly disconnected = () => { this.readyState = WebSocket.CLOSED; this.onclose?.({ code: 1006, reason: "inherited control channel closed" }); };
16
+ constructor(private readonly maxFrame: number) {
17
+ if (typeof process.send !== "function") throw new Error("inherited control channel unavailable");
18
+ process.on("message", this.message);
19
+ process.once("disconnect", this.disconnected);
20
+ queueMicrotask(() => { if (this.readyState === WebSocket.CONNECTING) { this.readyState = WebSocket.OPEN; this.onopen?.(); } });
21
+ }
22
+ send(message: string): void {
23
+ if (this.readyState !== WebSocket.OPEN || Buffer.byteLength(message) > this.maxFrame || typeof process.send !== "function") throw new Error("invalid inherited control frame");
24
+ process.send(JSON.parse(message));
25
+ }
26
+ close(): void {
27
+ if (this.readyState === WebSocket.CLOSED) return;
28
+ this.readyState = WebSocket.CLOSED;
29
+ process.removeListener("message", this.message);
30
+ process.removeListener("disconnect", this.disconnected);
31
+ if (process.connected && typeof process.disconnect === "function") process.disconnect();
32
+ }
33
+ }
@@ -0,0 +1,19 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative } from "node:path";
3
+ import { realPath } from "./project.ts";
4
+
5
+ /** Runtime root is captured by the daemon once; unknown project or sandbox roots refuse. */
6
+ export function instructedRuntimeAllowed(runtimeRoot: string, projectRoots: readonly string[]): boolean {
7
+ if (!isAbsolute(runtimeRoot)) return false;
8
+ try {
9
+ for (const root of projectRoots) {
10
+ const rel = relative(realPath(root), runtimeRoot);
11
+ if (!rel || rel !== ".." && !rel.startsWith("../") && !isAbsolute(rel)) return false;
12
+ }
13
+ for (let current = runtimeRoot; ; current = dirname(current)) {
14
+ try { lstatSync(join(current, ".git")); return false; }
15
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false; }
16
+ if (dirname(current) === current) return true;
17
+ }
18
+ } catch { return false; }
19
+ }
@@ -0,0 +1,218 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { openHubDatabase, type Database } from "./db-schema.ts";
5
+ import { realPath } from "./project.ts";
6
+
7
+ export const INSTRUCTION_PROBED_VERSIONS = ["2.1.328", "2.1.329"] as const;
8
+ export const INSTRUCTION_PREFIX = "/agent-hub:ahub";
9
+ export const MAX_PROMPT_BYTES = 16 * 1024;
10
+ const MAX_TRANSCRIPT_TAIL = 1024 * 1024;
11
+ const MAX_AGE_MS = 10 * 60 * 1000;
12
+ const MAX_OPERATIONS = 10;
13
+ const MAX_RECEIPTS = 1024;
14
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15
+
16
+ /** Keep internal whitespace byte-for-byte; a transcript delimiter is not an argument. */
17
+ export function canonicalInstruction(prompt: unknown): string | undefined {
18
+ if (typeof prompt !== "string" || !prompt.isWellFormed() || Buffer.byteLength(prompt, "utf8") > MAX_PROMPT_BYTES || !prompt.startsWith(INSTRUCTION_PREFIX)) return;
19
+ const rest = prompt.slice(INSTRUCTION_PREFIX.length);
20
+ if (rest && !/^\s/u.test(rest)) return;
21
+ const args = rest.trim();
22
+ if (/[<>&]/u.test(args) || Buffer.from(args).includes(0)) return;
23
+ return args;
24
+ }
25
+ export function instructionHash(args: string): string {
26
+ return createHash("sha256").update(INSTRUCTION_PREFIX).update(Buffer.from([0])).update(args).digest("hex");
27
+ }
28
+ export interface PendingInstruction {
29
+ session: string; promptId: string; transcript: string; home: string; cwd: string; project: string; hash: string; peer?: string;
30
+ }
31
+ interface Row {
32
+ id: string; session: string; prompt_id: string; transcript: string; home: string; cwd: string; project: string; hash: string; peer: string | null; created: number; state: string; uses: number; record_uuid: string | null;
33
+ }
34
+ export interface ConfirmedInstruction { id: string; session: string; args: string; peer?: string }
35
+ /** Supplied by the daemon from its own session and managed-home inventory, never from a control message. */
36
+ export interface InstructionSessionEvidence { session: string; transcript: string; home: string; cwd: string; peer: string }
37
+ export type InstructionEvidence = (session: string, peer: string) => Promise<InstructionSessionEvidence | undefined>;
38
+
39
+ /** Session transcript must be its own file under this home's exact project directory. */
40
+ function transcriptTail(row: Row): string | undefined {
41
+ if (!UUID.test(row.session) || !isAbsolute(row.home) || !isAbsolute(row.cwd) || !isAbsolute(row.transcript)) return;
42
+ let fd: number | undefined;
43
+ try {
44
+ const home = realPath(row.home), cwd = realPath(row.cwd);
45
+ const slug = cwd.replace(/[^a-zA-Z0-9]/g, "-");
46
+ const expected = join(home, "projects", slug, `${row.session}.jsonl`);
47
+ if (row.transcript !== expected || realPath(expected) !== expected) return;
48
+ fd = openSync(expected, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
49
+ const stat = fstatSync(fd);
50
+ if (!stat.isFile() || stat.nlink !== 1) return;
51
+ const start = Math.max(0, stat.size - MAX_TRANSCRIPT_TAIL);
52
+ const bytes = Buffer.alloc(stat.size - start);
53
+ const n = readSync(fd, bytes, 0, bytes.length, start);
54
+ let data = bytes.subarray(0, n);
55
+ if (start) { const newline = data.indexOf(10); if (newline < 0) return; data = data.subarray(newline + 1); }
56
+ return new TextDecoder("utf-8", { fatal: true }).decode(data);
57
+ } catch { return; }
58
+ finally { if (fd !== undefined) closeSync(fd); }
59
+ }
60
+
61
+ function commandRecord(raw: unknown, row: Row, now: number): { uuid: string; args: string } | undefined {
62
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
63
+ const record = raw as Record<string, any>, message = record.message;
64
+ if (record.type !== "user" || (record.isMeta !== undefined && record.isMeta !== false) || record.isSidechain !== false || record.origin?.kind !== "human" || Object.hasOwn(record, "promptSource")
65
+ || record.sessionId !== row.session || record.cwd !== row.cwd || !INSTRUCTION_PROBED_VERSIONS.includes(record.version as typeof INSTRUCTION_PROBED_VERSIONS[number]) || record.promptId !== row.prompt_id || !UUID.test(record.uuid ?? "") || !message || message.role !== "user" || typeof message.content !== "string") return;
66
+ if (typeof record.timestamp !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(record.timestamp)) return;
67
+ const at = Date.parse(record.timestamp);
68
+ if (!Number.isFinite(at) || at < row.created || at > now) return;
69
+ const match = /^<command-message>agent-hub:ahub<\/command-message>\n<command-name>\/agent-hub:ahub<\/command-name>\n<command-args>([\s\S]*)<\/command-args>$/.exec(message.content);
70
+ if (!match) return;
71
+ const args = canonicalInstruction(`${INSTRUCTION_PREFIX} ${match[1]!}`);
72
+ if (args === undefined || instructionHash(args) !== row.hash) return;
73
+ return { uuid: record.uuid.toLowerCase(), args };
74
+ }
75
+
76
+ /** Private local state. No caller receives prompt text until host-only confirmation. */
77
+ export class InstructionReceipts {
78
+ private readonly db: Database;
79
+ private readonly exactLeases = new Map<string, { session: string; created: number }>();
80
+ constructor(path: string, private readonly evidence: InstructionEvidence, private readonly clock: () => number = Date.now) {
81
+ this.db = openHubDatabase(path, { create: true });
82
+ this.db.run(`CREATE TABLE IF NOT EXISTS instruction_receipts (
83
+ id TEXT PRIMARY KEY, session TEXT NOT NULL, prompt_id TEXT NOT NULL, transcript TEXT NOT NULL, home TEXT NOT NULL, cwd TEXT NOT NULL, project TEXT NOT NULL,
84
+ hash TEXT NOT NULL, peer TEXT, created INTEGER NOT NULL, state TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, record_uuid TEXT UNIQUE)`);
85
+ this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS instruction_prompt_id ON instruction_receipts(session, prompt_id)");
86
+ this.db.run("CREATE TABLE IF NOT EXISTS instructed_mode (id INTEGER PRIMARY KEY CHECK (id = 1), mode TEXT NOT NULL)");
87
+ }
88
+ close(): void { this.exactLeases.clear(); this.db.close(); }
89
+ /** A new witness inherits an off or exact display copy; a retained witness always wins. */
90
+ seedMode(display: () => "off" | "exact" | "intent" | undefined): void {
91
+ if (this.db.query("SELECT 1 FROM instructed_mode WHERE id = 1").get()) return;
92
+ const value = display();
93
+ if (value === "off" || value === "exact") this.db.query("INSERT OR IGNORE INTO instructed_mode(id, mode) VALUES(1, ?)").run(value);
94
+ }
95
+ /** Missing witness uses the shipped default; malformed retained state never enables the tier. */
96
+ mode(): "off" | "exact" | "intent" {
97
+ const row = this.db.query("SELECT mode FROM instructed_mode WHERE id = 1").get() as { mode: unknown } | null;
98
+ if (!row) return "intent";
99
+ if (row.mode !== "off" && row.mode !== "exact" && row.mode !== "intent") throw new Error("instructed mode witness is invalid");
100
+ return row.mode;
101
+ }
102
+ hasIntentWitness(): boolean {
103
+ const row = this.db.query("SELECT mode FROM instructed_mode WHERE id = 1").get() as { mode: unknown } | null;
104
+ if (!row) return false;
105
+ if (row.mode !== "off" && row.mode !== "exact" && row.mode !== "intent") throw new Error("instructed mode witness is invalid");
106
+ return row.mode === "intent";
107
+ }
108
+ setMode(value: "off" | "exact" | "intent"): void {
109
+ if (value !== "off" && value !== "exact" && value !== "intent") throw new Error("invalid instructed mode");
110
+ this.db.query("INSERT INTO instructed_mode(id, mode) VALUES(1, ?) ON CONFLICT(id) DO UPDATE SET mode = excluded.mode").run(value);
111
+ }
112
+ pending(value: PendingInstruction, now: number): boolean {
113
+ if (!UUID.test(value.session) || !UUID.test(value.promptId)
114
+ || !/^[0-9a-f]{64}$/.test(value.hash) || !Number.isSafeInteger(now) || now < 0 || !isAbsolute(value.home) || !isAbsolute(value.cwd) || !isAbsolute(value.project) || !isAbsolute(value.transcript)
115
+ || [value.home, value.cwd, value.project, value.transcript].some(path => path.length > 4096 || /[\p{Cc}\p{Cf}]/u.test(path))
116
+ || value.peer !== undefined && !/^[a-z][a-z0-9_-]{0,63}$/.test(value.peer)) return false;
117
+ return this.db.transaction(() => {
118
+ for (const [id, lease] of this.exactLeases) if (lease.created <= now - MAX_AGE_MS || lease.created > now) this.exactLeases.delete(id);
119
+ this.db.query("DELETE FROM instruction_receipts WHERE created <= ?").run(now - MAX_AGE_MS);
120
+ const count = this.db.query("SELECT COUNT(*) AS n FROM instruction_receipts").get() as { n: number };
121
+ if (count.n >= MAX_RECEIPTS) return false;
122
+ return this.db.query("INSERT OR IGNORE INTO instruction_receipts(id, session, prompt_id, transcript, home, cwd, project, hash, peer, created, state) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')")
123
+ .run(randomUUID(), value.session, value.promptId, value.transcript, value.home, value.cwd, value.project, value.hash, value.peer ?? null, now).changes === 1;
124
+ })();
125
+ }
126
+ forPeer(peer: string): { confirmReceipt(session: string, now: number): Promise<ConfirmedInstruction | undefined>; confirmIntent(session: string, now: number): Promise<ConfirmedInstruction | undefined> } {
127
+ return { confirmReceipt: (session, now) => this.confirmForPeer(session, now, peer).catch(() => undefined), confirmIntent: (session, now) => this.confirmForPeer(session, now, peer, true).catch(() => undefined) };
128
+ }
129
+ private async confirmForPeer(session: string, now: number, peer: string, reusable = false): Promise<ConfirmedInstruction | undefined> {
130
+ if (!UUID.test(session) || !Number.isSafeInteger(now) || !/^[a-z][a-z0-9_-]{0,63}$/.test(peer)) return;
131
+ const evidence = await this.evidence(session, peer);
132
+ if (!evidence || evidence.session !== session || evidence.peer !== peer) return;
133
+ this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE state != 'closed' AND (created <= ? OR created > ?)").run(now - MAX_AGE_MS, now);
134
+ let rows = this.db.query(reusable ? "SELECT * FROM instruction_receipts WHERE session = ? ORDER BY created DESC, id DESC" : "SELECT * FROM instruction_receipts WHERE session = ? AND state = 'pending' ORDER BY created, id").all(session) as Row[];
135
+ if (reusable && rows[0] && rows[1]?.created === rows[0].created) return; // Equal timestamps do not establish which instruction is current.
136
+ if (reusable) rows = rows.slice(0, 1);
137
+ if (rows.length === 0 || reusable && rows[0]!.state === "closed") return;
138
+ const boundEvidence = { ...rows[0], session, home: evidence.home, cwd: evidence.cwd, transcript: evidence.transcript } as Row;
139
+ const tail = transcriptTail(boundEvidence); if (tail === undefined) return;
140
+ const lines = tail.split("\n");
141
+ const byPrompt = new Map<string, unknown[]>();
142
+ for (const line of lines) {
143
+ let parsed: unknown; try { parsed = JSON.parse(line); } catch { continue; }
144
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
145
+ const id = (parsed as { promptId?: unknown }).promptId;
146
+ if (typeof id !== "string") continue;
147
+ const bucket = byPrompt.get(id) ?? []; bucket.push(parsed); byPrompt.set(id, bucket);
148
+ }
149
+ for (const row of rows) {
150
+ if (now < row.created || now - row.created >= MAX_AGE_MS || (row.peer !== null && row.peer !== peer) || row.transcript !== evidence.transcript) continue;
151
+ const bound = { ...row, home: evidence.home, cwd: evidence.cwd, transcript: evidence.transcript };
152
+ const candidates: { uuid: string; args: string; at: number }[] = [];
153
+ for (const parsed of byPrompt.get(row.prompt_id) ?? []) {
154
+ const record = commandRecord(parsed, bound, now); if (!record) continue;
155
+ candidates.push({ ...record, at: Date.parse((parsed as { timestamp: string }).timestamp) });
156
+ }
157
+ candidates.sort((a, b) => a.at - b.at || a.uuid.localeCompare(b.uuid));
158
+ for (const record of candidates) {
159
+ const current = await this.evidence(session, peer);
160
+ const checkedAt = this.clock();
161
+ if (!Number.isSafeInteger(checkedAt) || checkedAt < now || checkedAt - row.created >= MAX_AGE_MS) {
162
+ this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE id = ?").run(row.id);
163
+ return;
164
+ }
165
+ if (!current || current.session !== evidence.session || current.peer !== evidence.peer || current.home !== evidence.home || current.cwd !== evidence.cwd || current.transcript !== evidence.transcript) return;
166
+ const refreshed = transcriptTail(bound);
167
+ if (refreshed !== tail) return;
168
+ const finalAt = this.clock();
169
+ if (!Number.isSafeInteger(finalAt) || finalAt < checkedAt || finalAt - row.created >= MAX_AGE_MS) {
170
+ this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE id = ?").run(row.id);
171
+ return;
172
+ }
173
+ if (reusable && row.state === "confirmed" && row.peer === peer && row.record_uuid === record.uuid) {
174
+ const stillOpen = this.db.query("SELECT 1 FROM instruction_receipts WHERE id = ? AND state = 'confirmed' AND peer = ? AND record_uuid = ?").get(row.id, peer, record.uuid);
175
+ if (stillOpen) return { id: row.id, session, args: record.args, peer };
176
+ continue;
177
+ }
178
+ const changed = this.db.query("UPDATE instruction_receipts SET state = 'confirmed', record_uuid = ?, peer = ? WHERE id = ? AND state = 'pending' AND NOT EXISTS (SELECT 1 FROM instruction_receipts WHERE record_uuid = ?)")
179
+ .run(record.uuid, peer, row.id, record.uuid);
180
+ if (changed.changes === 1) return { id: row.id, session, args: record.args, ...(row.peer ? { peer: row.peer } : {}) };
181
+ }
182
+ }
183
+ }
184
+ consume(id: string, now: number): boolean {
185
+ if (!Number.isSafeInteger(now) || now < 0) return false;
186
+ this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE id = ? AND state != 'closed' AND (created <= ? OR created > ?)").run(id, now - MAX_AGE_MS, now);
187
+ return this.db.query("UPDATE instruction_receipts SET uses = uses + 1, state = CASE WHEN uses + 1 >= ? THEN 'closed' ELSE state END WHERE id = ? AND state = 'confirmed' AND created <= ? AND created > ? AND uses < ?")
188
+ .run(MAX_OPERATIONS, id, now, now - MAX_AGE_MS, MAX_OPERATIONS).changes === 1;
189
+ }
190
+ /** Exact mode closes the durable receipt before the effect; a host-only lease tracks an in-flight stop. */
191
+ consumeExact(id: string, now: number): boolean {
192
+ if (!Number.isSafeInteger(now) || now < 0) return false;
193
+ const row = this.db.query("UPDATE instruction_receipts SET uses = 1, state = 'closed' WHERE id = ? AND state = 'confirmed' AND uses = 0 AND created <= ? AND created > ? RETURNING session, created")
194
+ .get(id, now, now - MAX_AGE_MS) as { session: string; created: number } | null;
195
+ if (!row) return false;
196
+ this.exactLeases.set(id, row);
197
+ return true;
198
+ }
199
+ /** Serialize intent operations and retain a revocable lease even for the tenth use. */
200
+ consumeIntent(id: string, now: number): boolean {
201
+ if (!Number.isSafeInteger(now) || now < 0 || this.exactLeases.has(id)) return false;
202
+ const row = this.db.query("UPDATE instruction_receipts SET uses = uses + 1, state = CASE WHEN uses + 1 >= ? THEN 'closed' ELSE state END WHERE id = ? AND state = 'confirmed' AND created <= ? AND created > ? AND uses < ? RETURNING session, created")
203
+ .get(MAX_OPERATIONS, id, now, now - MAX_AGE_MS, MAX_OPERATIONS) as { session: string; created: number } | null;
204
+ if (!row) return false;
205
+ this.exactLeases.set(id, row);
206
+ return true;
207
+ }
208
+ exactCurrent(id: string, now: number): boolean {
209
+ const lease = this.exactLeases.get(id);
210
+ return !!lease && Number.isSafeInteger(now) && now >= lease.created && now - lease.created < MAX_AGE_MS;
211
+ }
212
+ finishExact(id: string): void { this.exactLeases.delete(id); }
213
+ stop(session: string, peer?: string): void {
214
+ if (!UUID.test(session)) return;
215
+ for (const [id, lease] of this.exactLeases) if (lease.session === session) this.exactLeases.delete(id);
216
+ this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE session = ? AND state != 'closed' AND (? IS NULL OR peer IS NULL OR peer = ?)").run(session, peer ?? null, peer ?? null);
217
+ }
218
+ }