@staix/agent-hub 0.35.0 → 0.36.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 (104) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +21 -4
  3. package/docs/agent-notes/README.md +60 -0
  4. package/docs/agent-notes/adapters.md +5 -2
  5. package/docs/agent-notes/bus.md +1 -0
  6. package/docs/agent-notes/daemon.md +5 -4
  7. package/docs/agent-notes/models.md +4 -3
  8. package/docs/agent-notes/tasks.md +8 -1
  9. package/docs/agent-notes/tests.md +1 -0
  10. package/docs/design/adapters.md +72 -0
  11. package/docs/design/agent-hub-architecture.md +1 -1
  12. package/docs/design/bus.md +8 -0
  13. package/docs/design/execution-reference.md +171 -11
  14. package/docs/design/guidance-experiments.md +438 -0
  15. package/docs/design/model-routes.md +628 -0
  16. package/docs/design/supervision.md +121 -0
  17. package/docs/design/task-board.md +111 -0
  18. package/docs/dogfood.md +15 -4
  19. package/docs/operations.md +291 -22
  20. package/docs/profiles.md +2 -2
  21. package/docs/quickstart.md +106 -1
  22. package/docs/research.md +4 -2
  23. package/docs/sdlc.md +108 -4
  24. package/docs/security.md +67 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +5 -4
  26. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  27. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  28. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  29. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  30. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  31. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  32. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  33. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  34. package/docs/verified.json +27 -27
  35. package/package.json +1 -1
  36. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  37. package/plugins/agent-hub/kimi-hook.js +1201 -368
  38. package/plugins/agent-hub/server.js +1682 -431
  39. package/src/adapters/claude-channel.ts +7 -4
  40. package/src/adapters/compat.ts +10 -10
  41. package/src/adapters/local-worker.ts +1 -1
  42. package/src/adapters/qwen-dual.ts +324 -44
  43. package/src/cli/guidance.ts +67 -0
  44. package/src/cli/help.ts +10 -3
  45. package/src/cli/identity.ts +10 -3
  46. package/src/cli/init-prompt.ts +15 -2
  47. package/src/cli/init-required-checks.ts +122 -0
  48. package/src/cli/init-settings.ts +10 -4
  49. package/src/cli/init.ts +39 -3
  50. package/src/cli/lineage.ts +78 -0
  51. package/src/cli/main.ts +111 -10
  52. package/src/cli/setup-research.ts +10 -0
  53. package/src/hub/autonomy-defaults.ts +20 -9
  54. package/src/hub/board.ts +346 -4
  55. package/src/hub/build-entry.ts +11 -0
  56. package/src/hub/bus.ts +12 -0
  57. package/src/hub/ci-watch.ts +4 -4
  58. package/src/hub/config-apply.ts +2 -1
  59. package/src/hub/config-trust.ts +1 -0
  60. package/src/hub/control-client.ts +1 -1
  61. package/src/hub/daemon.ts +342 -20
  62. package/src/hub/delivery-hints.ts +4 -2
  63. package/src/hub/delivery-journal.ts +50 -2
  64. package/src/hub/delivery-public.ts +51 -0
  65. package/src/hub/dogfood-profile.ts +8 -4
  66. package/src/hub/execution-lineage-owner.ts +272 -0
  67. package/src/hub/execution-lineage.ts +52 -8
  68. package/src/hub/execution-links.ts +85 -0
  69. package/src/hub/guidance-variants.ts +398 -0
  70. package/src/hub/handoff.ts +1 -0
  71. package/src/hub/hub-tools.ts +43 -2
  72. package/src/hub/manager.ts +44 -2
  73. package/src/hub/memory-policy.ts +2 -2
  74. package/src/hub/peers.ts +1 -1
  75. package/src/hub/planning.ts +1 -1
  76. package/src/hub/progress.ts +24 -7
  77. package/src/hub/restart.ts +13 -0
  78. package/src/hub/roles.ts +26 -0
  79. package/src/hub/routing.ts +4 -1
  80. package/src/hub/sdlc-merge.ts +39 -1
  81. package/src/hub/sdlc-release.ts +1 -1
  82. package/src/hub/sdlc.ts +62 -11
  83. package/src/hub/settings.ts +2 -0
  84. package/src/hub/supervision-proposals.ts +405 -0
  85. package/src/hub/supervision-rules.ts +388 -0
  86. package/src/hub/supervision.ts +2 -0
  87. package/src/hub/task-approval.ts +2 -2
  88. package/src/hub/task-repository.ts +5 -0
  89. package/src/hub/tasks.ts +603 -50
  90. package/src/memory/capture.ts +2 -2
  91. package/src/models/relay.ts +9 -2
  92. package/src/models/route/config.ts +27 -0
  93. package/src/models/route/decision.ts +87 -15
  94. package/src/models/route/relay-selector.ts +8 -7
  95. package/src/models/route/runtime.ts +22 -16
  96. package/src/models/route/stage-diagnostics.ts +22 -0
  97. package/src/models/route/stage-evidence.ts +55 -0
  98. package/src/models/route/stage-fallback.ts +58 -0
  99. package/src/models/route/stage-input.ts +155 -0
  100. package/src/models/route/stage.ts +5 -147
  101. package/src/ui/guidance-panel.ts +156 -0
  102. package/src/ui/guidance-view.ts +43 -0
  103. package/src/ui/lineage-view.ts +34 -0
  104. package/src/ui/plugin.ts +71 -7
package/src/hub/board.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { GUIDANCE_VARIANT_LIMITS, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_HASH_HEX_LENGTH, parseGuidanceVariantV1, parseGuidanceExperiment, parseGuidanceStoredRecord, validateGuidanceVariantV1, type GuidanceVariantV1, type GuidanceExperimentRecord, type GuidanceStoredRecord, type GuidanceWriteFence } from "./guidance-variants.ts";
2
+ import { ExecutionLinkError, EXECUTION_LINK_LIMITS, executionLinkActor, executionLinkInteger, executionLinkId, executionLinkReferences, executionReferenceDigest, parseExecutionLinkInput, parseExecutionLinkRecord, type ExecutionLinkInput, type ExecutionLinkRecord, type ExecutionLinkFence } from "./execution-links.ts";
3
+ import { executionReferenceKey, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
1
4
  import { parseAttemptReceipt, parseResearchRunners, verifyAttemptReceipt, type AttemptReceiptV1 } from "./research-runner.ts";
2
5
  import { canonicalJson } from "./packs.ts";
3
6
  import { parseEvidenceLink, evidenceLinkCanonical, MAX_EVIDENCE_RECORD_BYTES, type EvidenceLinkV1 } from "./research-evidence.ts";
@@ -17,7 +20,7 @@ import { controlWriteSpan } from "./control-write-trace.ts";
17
20
  import { planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
18
21
  import { HUB, USER, type PeerId } from "./envelope.ts";
19
22
  import type { SweepRecord } from "./task-sweep.ts";
20
- import type { SdlcReceipt } from "./sdlc.ts";
23
+ import type { SpecAcceptance, SdlcReceipt } from "./sdlc.ts";
21
24
  import { parseReviewFindings, type ReviewFindingSet } from "./review-findings.ts";
22
25
  import { parseDeliverableRecords, type DeliverableRecord } from "./deliverables.ts";
23
26
  import type { CostPlan, ReviewCost } from "./cost-governance.ts";
@@ -25,6 +28,19 @@ import type { SpecRef, SpecTaskReport } from "./specs-task.ts";
25
28
  export type { SpecAck, SpecRef, SpecTaskReport } from "./specs-task.ts";
26
29
  import { campaignHash, parseResearchCampaign, parseResearchHandoff, type ResearchCampaignContract, type ResearchCampaignStatus, type ResearchUnit, type ResearchHandoffV1, type ResearchHandoffRecord } from "./research-campaign.ts";
27
30
 
31
+ const GUIDANCE_VARIANT_SELECT = `SELECT CASE WHEN typeof(id)='text' AND length(CAST(id AS BLOB))<=${GUIDANCE_HASH_HEX_LENGTH} THEN id END AS id,CASE WHEN typeof(body)='text' AND length(CAST(body AS BLOB))<=? THEN body END AS body,
32
+ CASE WHEN typeof(body_sha256)='text' AND length(CAST(body_sha256 AS BLOB))<=${GUIDANCE_HASH_HEX_LENGTH} THEN body_sha256 END AS body_sha256,
33
+ CASE WHEN typeof(created_by)='text' AND length(CAST(created_by AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN created_by END AS created_by,CASE WHEN typeof(created_at)='integer' THEN created_at END AS created_at,
34
+ CASE WHEN withdrawn_by IS NULL OR typeof(withdrawn_by)='text' AND length(CAST(withdrawn_by AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN withdrawn_by END AS withdrawn_by,CASE WHEN withdrawn_at IS NULL OR typeof(withdrawn_at)='integer' THEN withdrawn_at END AS withdrawn_at,
35
+ CASE WHEN withdrawn_at IS NULL OR typeof(withdrawn_at)='integer' THEN 1 ELSE 0 END AS valid_withdrawn_at,
36
+ CASE WHEN withdrawn_by IS NULL OR typeof(withdrawn_by)='text' AND length(CAST(withdrawn_by AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN 1 ELSE 0 END AS valid_withdrawn_by`;
37
+
38
+ /** Internal host capability; never accepted from a control or tool argument. */
39
+ export const HOST_MERGE_ADOPTION = Symbol("host merge adoption");
40
+ /** Internal publication capability, independent of the person-only acceptance API. */
41
+ export const HOST_SPEC_ACCEPTANCE_CARRY = Symbol("host spec acceptance carry");
42
+ export interface SpecAcceptanceCommit { source: number; cancellationRevision: number; acceptance: SpecAcceptance; }
43
+
28
44
  export interface ResearchCampaignRecord {
29
45
  id: string;
30
46
  project: string;
@@ -94,6 +110,17 @@ function researchCampaignFromRow(row: ResearchCampaignRow): ResearchCampaignReco
94
110
  } catch { throw researchFailure(); }
95
111
  }
96
112
 
113
+ const EXECUTION_REFERENCE_SELECT = `SELECT
114
+ CASE WHEN length(CAST(id AS BLOB))=64 THEN id END AS id,
115
+ CASE WHEN length(CAST(project_id AS BLOB)) BETWEEN 1 AND 256 THEN project_id END AS project_id,
116
+ task_id,task_created,
117
+ CASE WHEN length(CAST(from_json AS BLOB))<=${EXECUTION_LINK_LIMITS.referenceBytes} THEN from_json END AS from_json,
118
+ CASE WHEN length(CAST(from_sha256 AS BLOB))=64 THEN from_sha256 END AS from_sha256,
119
+ CASE WHEN length(CAST(reference_json AS BLOB))<=${EXECUTION_LINK_LIMITS.referenceBytes} THEN reference_json END AS reference_json,
120
+ CASE WHEN length(CAST(reference_sha256 AS BLOB))=64 THEN reference_sha256 END AS reference_sha256,
121
+ CASE WHEN length(CAST(recorded_by AS BLOB)) BETWEEN 1 AND ${EXECUTION_LINK_LIMITS.actor} THEN recorded_by END AS recorded_by,
122
+ recorded_at FROM execution_reference_links`;
123
+
97
124
  export interface ExperimentComparisonPlanRecord {
98
125
  hash: string;
99
126
  project: string;
@@ -138,6 +165,17 @@ export type TaskState = "backlog" | "proposed" | "in_progress" | "in_review" | "
138
165
  export const isClosedTaskState = (state: string): boolean => state === "approved" || state === "cancelled";
139
166
  export interface TaskOffer { envelopeId: string; owner: PeerId; assignmentFlowRevision: number; pullOnly?: boolean }
140
167
  export interface TaskCancellation { reason: string; supersededBy?: string; flowRevision: number; withheld?: true }
168
+ /** Metadata only: source task text, plans and growing histories never enter a carry lookup. */
169
+ export interface SpecAcceptanceCandidate {
170
+ id: number; created: number; state: "cancelled"; refs: TaskRefs; signals: string[];
171
+ supersededBy: string; cancellationRevision: number; withheld: boolean;
172
+ repo: unknown; issue: unknown; acceptance: unknown;
173
+ }
174
+ // ponytail: one 32-source snapshot; larger sets need a bounded paginated lookup with a shared currentness proof.
175
+ const SPEC_ACCEPTANCE_SOURCE_LIMIT = 32;
176
+ const SPEC_ACCEPTANCE_FIELD_BYTES = 64 * 1024;
177
+ const SPEC_ACCEPTANCE_TOTAL_BYTES = 256 * 1024;
178
+
141
179
  export const TASK_STALL_CODES = ["tests", "spec", "network", "worktree", "roster", "pull-only", "not-attached", "excluded", "owner-admission", "offline", "paused", "failing", "pii", "policy", "cancelled", "unavailable", "no-writes", "queue-count", "queue-age", "queue-age-unknown"] as const;
142
180
  export type TaskStallCode = (typeof TASK_STALL_CODES)[number];
143
181
  export interface TaskStall { task: number; signature: string; replanRevision: number; cause: { kind: "reservation" | "no-eligible-peer" | "cancelled-dependency" | "no-writes"; peer?: string; dependency?: number; code: TaskStallCode; turns?: number; acceptance?: number; refusals?: { peer: string; code: TaskStallCode }[] }; at: number }
@@ -559,6 +597,21 @@ export class Board {
559
597
  this.db.run(`CREATE TABLE IF NOT EXISTS research_evidence_links (
560
598
  project TEXT NOT NULL, id TEXT NOT NULL, revision INTEGER NOT NULL, task_id INTEGER NOT NULL,
561
599
  body TEXT NOT NULL, body_sha256 TEXT NOT NULL, PRIMARY KEY(project,id,revision))`);
600
+ // Private snapshots stay outside Task and every SELECT * task reader.
601
+ this.db.run(`CREATE TABLE IF NOT EXISTS guidance_experiments (
602
+ project_id TEXT NOT NULL,task_id INTEGER NOT NULL,task_created INTEGER NOT NULL,experiment_id TEXT NOT NULL,baseline_json TEXT NOT NULL,
603
+ PRIMARY KEY(project_id,task_id,task_created,experiment_id))`);
604
+ this.db.run(`CREATE TABLE IF NOT EXISTS guidance_variants (
605
+ project_id TEXT NOT NULL,task_id INTEGER NOT NULL,task_created INTEGER NOT NULL,experiment_id TEXT NOT NULL,id TEXT NOT NULL,
606
+ body TEXT NOT NULL,body_sha256 TEXT NOT NULL,created_by TEXT NOT NULL,created_at INTEGER NOT NULL,withdrawn_by TEXT,withdrawn_at INTEGER,
607
+ PRIMARY KEY(project_id,task_id,task_created,experiment_id,id))`);
608
+ this.db.run(`CREATE TABLE IF NOT EXISTS execution_reference_links (
609
+ id TEXT PRIMARY KEY, project_id TEXT NOT NULL, task_id INTEGER NOT NULL, task_created INTEGER NOT NULL,
610
+ from_json TEXT NOT NULL, from_sha256 TEXT NOT NULL, reference_json TEXT NOT NULL, reference_sha256 TEXT NOT NULL,
611
+ recorded_by TEXT NOT NULL, recorded_at INTEGER NOT NULL,
612
+ UNIQUE(project_id,task_id,task_created,from_sha256,reference_sha256))`);
613
+ this.db.run("CREATE INDEX IF NOT EXISTS execution_reference_task_scope ON execution_reference_links(project_id,task_id,task_created,id)");
614
+ this.db.run("CREATE INDEX IF NOT EXISTS guidance_variant_task_id ON guidance_variants(project_id,task_id,task_created,id)");
562
615
  this.db.run(`CREATE TABLE IF NOT EXISTS review_comments (
563
616
  task_id INTEGER NOT NULL,task_created INTEGER NOT NULL,id TEXT NOT NULL,body TEXT NOT NULL,lifecycle TEXT NOT NULL,revision INTEGER NOT NULL,
564
617
  PRIMARY KEY(task_id,task_created,id))`);
@@ -1032,6 +1085,214 @@ export class Board {
1032
1085
  });
1033
1086
  }
1034
1087
 
1088
+ /** Fixed experiment scope; SQL bounds JSON before it reaches JavaScript. No caller may widen a page. */
1089
+ guidanceExperiment(projectKey: string, taskId: number, taskCreated: number, experimentId: string): GuidanceExperimentRecord | undefined {
1090
+ const row = this.db.query(`SELECT CASE WHEN typeof(baseline_json)='text' AND length(CAST(baseline_json AS BLOB))<=? THEN baseline_json END AS baseline
1091
+ FROM guidance_experiments WHERE project_id=? AND task_id=? AND task_created=? AND experiment_id=?`)
1092
+ .get(GUIDANCE_VARIANT_LIMITS.recordBytes, projectKey, taskId, taskCreated, experimentId) as { baseline: unknown } | null;
1093
+ if (!row) return undefined;
1094
+ if (typeof row.baseline !== "string") throw new Error("guidance experiment storage is invalid");
1095
+ const record = parseGuidanceExperiment({ projectKey, taskId, taskCreated, experimentId, baseline: JSON.parse(row.baseline) });
1096
+ if (JSON.stringify(record.baseline) !== row.baseline) throw new Error("guidance experiment storage is not canonical");
1097
+ return record;
1098
+ }
1099
+ guidanceVariants(projectKey: string, taskId: number, taskCreated: number, experimentId: string): GuidanceStoredRecord[] {
1100
+ const experiment = this.guidanceExperiment(projectKey, taskId, taskCreated, experimentId);
1101
+ const rows = this.db.query(`${GUIDANCE_VARIANT_SELECT} FROM guidance_variants
1102
+ WHERE project_id=? AND task_id=? AND task_created=? AND experiment_id=? ORDER BY guidance_variants.id LIMIT ?`)
1103
+ .all(GUIDANCE_VARIANT_LIMITS.recordBytes, projectKey, taskId, taskCreated, experimentId, GUIDANCE_VARIANT_LIMITS.variants + 1) as Record<string, unknown>[];
1104
+ if (rows.length > GUIDANCE_VARIANT_LIMITS.variants || rows.length && !experiment) throw new Error("guidance variant storage is invalid");
1105
+ return rows.map(row => this.guidanceVariantRow(row, experiment!));
1106
+ }
1107
+ private guidanceVariantRow(row: Record<string, unknown>, experiment: GuidanceExperimentRecord): GuidanceStoredRecord {
1108
+ if (row.valid_withdrawn_by !== 1 || row.valid_withdrawn_at !== 1 || typeof row.body !== "string" || createHash("sha256").update(row.body).digest("hex") !== row.body_sha256
1109
+ || (row.withdrawn_by === null) !== (row.withdrawn_at === null)) throw new Error("guidance variant storage is invalid");
1110
+ const record = parseGuidanceStoredRecord({ variant: JSON.parse(row.body), createdBy: row.created_by, createdAt: row.created_at,
1111
+ ...(row.withdrawn_by === null ? {} : { withdrawn: { by: row.withdrawn_by, at: row.withdrawn_at } }) });
1112
+ const value = record.variant;
1113
+ if (JSON.stringify(value) !== row.body || value.id !== row.id || value.projectKey !== experiment.projectKey || value.taskId !== experiment.taskId
1114
+ || value.taskCreated !== experiment.taskCreated || value.experimentId !== experiment.experimentId
1115
+ || JSON.stringify(value.baseline) !== JSON.stringify(experiment.baseline)) throw new Error("guidance variant binding is invalid");
1116
+ return record;
1117
+ }
1118
+ /** After Tasks admission only. The raw experiment id is never part of the public selector. */
1119
+ guidanceVariantLocation(projectKey: string, taskId: number, taskCreated: number, id: string): string | undefined {
1120
+ const rows = this.db.query(`SELECT CASE WHEN typeof(experiment_id)='text' AND length(CAST(experiment_id AS BLOB))<=? THEN experiment_id END AS experiment_id
1121
+ FROM guidance_variants INDEXED BY guidance_variant_task_id WHERE project_id=? AND task_id=? AND task_created=? AND id=? LIMIT 2`)
1122
+ .all(EXECUTION_REFERENCE_LIMITS.id, projectKey, taskId, taskCreated, id) as { experiment_id: unknown }[];
1123
+ if (rows.length > 1 || rows.some(row => typeof row.experiment_id !== "string")) throw new Error("guidance variant selection is ambiguous or unavailable");
1124
+ return rows[0]?.experiment_id as string | undefined;
1125
+ }
1126
+ /** One fixed keyset page: no OFFSET, task history, experiment-count cap or unbounded payload scan. */
1127
+ guidanceVariantPage(projectKey: string, taskId: number, taskCreated: number, after = ""): GuidanceStoredRecord[] {
1128
+ const rows = this.db.query(`${GUIDANCE_VARIANT_SELECT},CASE WHEN typeof(experiment_id)='text' AND length(CAST(experiment_id AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN experiment_id END AS experiment_id
1129
+ FROM guidance_variants INDEXED BY guidance_variant_task_id WHERE project_id=? AND task_id=? AND task_created=? AND guidance_variants.id>? ORDER BY guidance_variants.id LIMIT ?`)
1130
+ .all(GUIDANCE_VARIANT_LIMITS.recordBytes, projectKey, taskId, taskCreated, after, GUIDANCE_PAGE_MAX_RECORDS + 1) as Record<string, unknown>[];
1131
+ if (new Set(rows.map(row => row.id)).size !== rows.length) throw new Error("guidance variant selection is ambiguous");
1132
+ const experiments = new Map<string, GuidanceExperimentRecord>();
1133
+ return rows.map(row => {
1134
+ if (typeof row.experiment_id !== "string") throw new Error("guidance experiment scope is invalid");
1135
+ let experiment = experiments.get(row.experiment_id);
1136
+ if (!experiment) {
1137
+ experiment = this.guidanceExperiment(projectKey, taskId, taskCreated, row.experiment_id);
1138
+ if (!experiment) throw new Error("guidance experiment is unavailable");
1139
+ experiments.set(row.experiment_id, experiment);
1140
+ }
1141
+ return this.guidanceVariantRow(row, experiment);
1142
+ });
1143
+ }
1144
+
1145
+ private guidanceWriteTask(fence: GuidanceWriteFence): Task {
1146
+ const task = this.get(fence.taskId);
1147
+ if (!executionLinkActor(fence.by) || !executionLinkInteger(fence.at) || !task || task.created !== fence.taskCreated
1148
+ || task.history.length !== fence.flowRevision || task.owner !== fence.owner || task.state !== fence.state || task.role !== fence.roleId
1149
+ || task.state === "approved" || task.state === "cancelled" || fence.by !== USER && (task.owner !== fence.by || task.state === "in_review")
1150
+ || task.signals.includes("pii") || task.signals.includes("pii_path")) throw new Error("guidance task binding changed");
1151
+ return task;
1152
+ }
1153
+ /** Tasks alone supplies current runtime/privacy/catalog authority; persisted facts are checked again inside this transaction. */
1154
+ recordGuidanceVariant(value: GuidanceVariantV1, fence: GuidanceWriteFence): { record: GuidanceStoredRecord; already: boolean } {
1155
+ const variant = parseGuidanceVariantV1(value);
1156
+ return this.atomic(() => {
1157
+ this.guidanceWriteTask(fence);
1158
+ if (variant.author !== fence.by || variant.taskId !== fence.taskId || variant.taskCreated !== fence.taskCreated
1159
+ || variant.flowRevision !== fence.flowRevision || variant.baseline.roleId !== fence.roleId) throw new Error("guidance task binding changed");
1160
+ const original = this.guidanceExperiment(variant.projectKey, variant.taskId, variant.taskCreated, variant.experimentId);
1161
+ const records = this.guidanceVariants(variant.projectKey, variant.taskId, variant.taskCreated, variant.experimentId);
1162
+ validateGuidanceVariantV1(variant, { projectKey: variant.projectKey, taskId: variant.taskId, taskCreated: variant.taskCreated,
1163
+ experimentId: variant.experimentId, flowRevision: fence.flowRevision, actor: fence.by, baseline: original?.baseline ?? variant.baseline,
1164
+ currentBaseline: { id: variant.baseline.roleId, layer: variant.baseline.layer, hash: variant.baseline.sha256 }, variantIds: records.map(item => item.variant.id) });
1165
+ const known = records.find(item => item.variant.id === variant.id);
1166
+ if (known) {
1167
+ if (JSON.stringify(known.variant) !== JSON.stringify(variant)) throw new Error("guidance variant id has changed content");
1168
+ return { record: known, already: true };
1169
+ }
1170
+ const body = JSON.stringify(variant), stored = parseGuidanceStoredRecord({ variant, createdBy: fence.by, createdAt: fence.at });
1171
+ if (!original) this.taskWrite(() => this.db.query("INSERT INTO guidance_experiments(project_id,task_id,task_created,experiment_id,baseline_json) VALUES(?,?,?,?,?)")
1172
+ .run(variant.projectKey, variant.taskId, variant.taskCreated, variant.experimentId, JSON.stringify(variant.baseline)));
1173
+ this.taskWrite(() => this.db.query(`INSERT INTO guidance_variants(project_id,task_id,task_created,experiment_id,id,body,body_sha256,created_by,created_at) VALUES(?,?,?,?,?,?,?,?,?)`)
1174
+ .run(variant.projectKey, variant.taskId, variant.taskCreated, variant.experimentId, variant.id, body, createHash("sha256").update(body).digest("hex"), fence.by, fence.at));
1175
+ return { record: stored, already: false };
1176
+ });
1177
+ }
1178
+ withdrawGuidanceVariant(projectKey: string, experimentId: string, id: string, fence: GuidanceWriteFence): { record: GuidanceStoredRecord; already: boolean } {
1179
+ return this.atomic(() => {
1180
+ this.guidanceWriteTask(fence);
1181
+ const record = this.guidanceVariants(projectKey, fence.taskId, fence.taskCreated, experimentId).find(item => item.variant.id === id);
1182
+ if (!record) throw new Error("guidance variant is unavailable");
1183
+ if (record.withdrawn) return { record, already: true };
1184
+ const next = parseGuidanceStoredRecord({ ...record, withdrawn: { by: fence.by, at: fence.at } });
1185
+ const result = this.taskWrite(() => this.db.query(`UPDATE guidance_variants SET withdrawn_by=?,withdrawn_at=?
1186
+ WHERE project_id=? AND task_id=? AND task_created=? AND experiment_id=? AND id=? AND withdrawn_by IS NULL AND withdrawn_at IS NULL`)
1187
+ .run(fence.by, fence.at, projectKey, fence.taskId, fence.taskCreated, experimentId, id));
1188
+ if (result.changes !== 1) throw new Error("guidance withdrawal binding changed");
1189
+ return { record: next, already: false };
1190
+ });
1191
+ }
1192
+ hasGuidanceVariants(): boolean {
1193
+ return (this.db.query("SELECT EXISTS(SELECT 1 FROM guidance_experiments) OR EXISTS(SELECT 1 FROM guidance_variants) AS present").get() as { present: number }).present === 1;
1194
+ }
1195
+ /** Recovery only. Normal reads always address one indexed experiment. */
1196
+ guidanceVariantsIntegrity(): { experiments: number; variants: number; digest: string } {
1197
+ try { return this.db.transaction(() => {
1198
+ const digest = createHash("sha256").update("agent-hub.guidance-variants/v1\n"); let experiments = 0, variants = 0;
1199
+ // ponytail: recovery streams O(historical experiments), with bounded row/page memory. If measured recovery cost warrants it,
1200
+ // upgrade to keyset pages plus a verification budget; a partial scan must never certify complete integrity.
1201
+ const statement = this.db.prepare(`SELECT CASE WHEN typeof(project_id)='text' AND length(CAST(project_id AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.projectKey} THEN project_id END AS project_id,CASE WHEN typeof(task_id)='integer' THEN task_id END AS task_id,CASE WHEN typeof(task_created)='integer' THEN task_created END AS task_created,
1202
+ CASE WHEN typeof(experiment_id)='text' AND length(CAST(experiment_id AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN experiment_id END AS experiment_id FROM guidance_experiments ORDER BY project_id,task_id,task_created,experiment_id`);
1203
+ try {
1204
+ for (const row of statement.iterate() as Iterable<{ project_id: string; task_id: number; task_created: number; experiment_id: string }>) {
1205
+ if (typeof row.project_id !== "string" || typeof row.experiment_id !== "string" || !executionLinkInteger(row.task_id, 1) || !executionLinkInteger(row.task_created)) throw new Error("guidance experiment scope is invalid");
1206
+ const experiment = this.guidanceExperiment(row.project_id, row.task_id, row.task_created, row.experiment_id)!;
1207
+ const records = this.guidanceVariants(row.project_id, row.task_id, row.task_created, row.experiment_id);
1208
+ if (!records.length) throw new Error("guidance experiment is empty");
1209
+ digest.update(JSON.stringify(experiment)).update("\n"); experiments++;
1210
+ for (const record of records) { digest.update(JSON.stringify(record)).update("\n"); variants++; }
1211
+ }
1212
+ } finally { statement.finalize(); }
1213
+ const orphan = this.db.query(`SELECT EXISTS(SELECT 1 FROM guidance_variants AS v WHERE NOT EXISTS(SELECT 1 FROM guidance_experiments AS e
1214
+ WHERE e.project_id=v.project_id AND e.task_id=v.task_id AND e.task_created=v.task_created AND e.experiment_id=v.experiment_id)) AS present`).get() as { present: number };
1215
+ if (orphan.present) throw new Error("guidance variant experiment is unavailable");
1216
+ return { experiments, variants, digest: digest.digest("hex") };
1217
+ })(); }
1218
+ catch { throw new Error("guidance variant integrity is unavailable; inspect retained project state before retrying"); }
1219
+ }
1220
+
1221
+ private executionReferenceRow(row: Record<string, unknown>): ExecutionLinkRecord {
1222
+ try {
1223
+ if (typeof row.from_json !== "string" || typeof row.reference_json !== "string") throw new Error();
1224
+ const record = parseExecutionLinkRecord({ id: row.id, projectKey: row.project_id, taskId: row.task_id, taskCreated: row.task_created,
1225
+ from: JSON.parse(row.from_json), reference: JSON.parse(row.reference_json), strength: "declared", recordedBy: row.recorded_by, recordedAt: row.recorded_at });
1226
+ if (executionReferenceKey(record.from) !== row.from_json || executionReferenceKey(record.reference) !== row.reference_json
1227
+ || executionReferenceDigest(record.from) !== row.from_sha256 || executionReferenceDigest(record.reference) !== row.reference_sha256) throw new Error();
1228
+ return record;
1229
+ } catch { throw new ExecutionLinkError("corrupt"); }
1230
+ }
1231
+ /** Tasks is the only writer; it additionally fences current private/observer/read-only context and exact from membership. */
1232
+ recordExecutionReference(projectKey: string, value: ExecutionLinkInput, fence: ExecutionLinkFence): { record: ExecutionLinkRecord; already: boolean } {
1233
+ const input = parseExecutionLinkInput(value), refs = executionLinkReferences(projectKey, input), id = executionLinkId(projectKey, input);
1234
+ if (!executionLinkActor(fence.by) || !executionLinkInteger(fence.at)) throw new ExecutionLinkError("invalid");
1235
+ try {
1236
+ return this.atomic(() => {
1237
+ const task = this.get(input.taskId);
1238
+ if (!task || task.created !== input.taskCreated || task.history.length !== input.flowRevision
1239
+ || fence.by !== USER && task.owner !== fence.by && task.reviewer !== fence.by
1240
+ || task.signals.includes("pii") || task.signals.includes("pii_path")) throw new ExecutionLinkError("changed");
1241
+ // Fence precedes dedup: a private, stale or removed actor cannot replay an old authorization.
1242
+ const known = this.db.query(`${EXECUTION_REFERENCE_SELECT} WHERE id=?`).get(id) as Record<string, unknown> | null;
1243
+ if (known) {
1244
+ const record = this.executionReferenceRow(known);
1245
+ if (record.projectKey !== projectKey || record.taskId !== input.taskId || record.taskCreated !== input.taskCreated
1246
+ || executionReferenceKey(record.from) !== executionReferenceKey(refs.from) || executionReferenceKey(record.reference) !== executionReferenceKey(refs.reference)) throw new ExecutionLinkError("corrupt");
1247
+ return { record, already: true };
1248
+ }
1249
+ const count = this.db.query("SELECT COUNT(*) AS n FROM (SELECT 1 FROM execution_reference_links WHERE project_id=? AND task_id=? AND task_created=? LIMIT ?)")
1250
+ .get(projectKey, input.taskId, input.taskCreated, EXECUTION_LINK_LIMITS.read) as { n: number };
1251
+ if (count.n >= EXECUTION_LINK_LIMITS.perTask) throw new ExecutionLinkError("limit");
1252
+ this.taskWrite(() => this.db.query(`INSERT INTO execution_reference_links
1253
+ (id,project_id,task_id,task_created,from_json,from_sha256,reference_json,reference_sha256,recorded_by,recorded_at) VALUES(?,?,?,?,?,?,?,?,?,?)`)
1254
+ .run(id, projectKey, input.taskId, input.taskCreated, executionReferenceKey(refs.from), executionReferenceDigest(refs.from),
1255
+ executionReferenceKey(refs.reference), executionReferenceDigest(refs.reference), fence.by, fence.at));
1256
+ return { record: parseExecutionLinkRecord({ id, projectKey, taskId: input.taskId, taskCreated: input.taskCreated,
1257
+ ...refs, strength: "declared", recordedBy: fence.by, recordedAt: fence.at }), already: false };
1258
+ });
1259
+ } catch (error) { if (error instanceof ExecutionLinkError) throw error; throw new ExecutionLinkError("corrupt"); }
1260
+ }
1261
+ /** Metadata only, after Tasks source authorization. 65 is an overflow sentinel, never a truncated complete neighborhood. */
1262
+ executionReferences(projectKey: string, taskId: number, taskCreated: number, limit: number = EXECUTION_LINK_LIMITS.read): ExecutionLinkRecord[] {
1263
+ // Reuse the address boundary without looking up any source, task body or foreign producer.
1264
+ executionLinkReferences(projectKey, { taskId, taskCreated, flowRevision: 0, reference: { v: 1, tool: "ahub", projectKey, kind: "task", id: `${taskId}:${taskCreated}` } });
1265
+ if (!executionLinkInteger(limit, 1) || limit > EXECUTION_LINK_LIMITS.read) throw new ExecutionLinkError("invalid");
1266
+ try {
1267
+ return (this.db.query(`${EXECUTION_REFERENCE_SELECT} WHERE project_id=? AND task_id=? AND task_created=? ORDER BY id LIMIT ?`)
1268
+ .all(projectKey, taskId, taskCreated, limit) as Record<string, unknown>[]).map(row => this.executionReferenceRow(row));
1269
+ } catch { throw new ExecutionLinkError("corrupt"); }
1270
+ }
1271
+ hasExecutionReferences(): boolean {
1272
+ try { return (this.db.query("SELECT EXISTS(SELECT 1 FROM execution_reference_links) AS present").get() as { present: number }).present === 1; }
1273
+ catch { throw new ExecutionLinkError("corrupt"); }
1274
+ }
1275
+ /** Every persisted field, streamed without retaining all rows; reads never resolve references or mutate state. */
1276
+ executionReferencesIntegrity(): { count: number; digest: string } {
1277
+ try {
1278
+ return this.db.transaction(() => {
1279
+ const statement = this.db.prepare(`${EXECUTION_REFERENCE_SELECT} ORDER BY project_id,task_id,task_created,id`);
1280
+ const digest = createHash("sha256").update("agent-hub.execution-reference-links/v1\n");
1281
+ let count = 0, perTask = 0, priorScope: string | undefined;
1282
+ try {
1283
+ for (const row of statement.iterate() as Iterable<Record<string, unknown>>) {
1284
+ const record = this.executionReferenceRow(row), scope = JSON.stringify([record.projectKey, record.taskId, record.taskCreated]);
1285
+ if (scope !== priorScope) { priorScope = scope; perTask = 0; }
1286
+ if (++perTask > EXECUTION_LINK_LIMITS.perTask) throw new ExecutionLinkError("corrupt");
1287
+ const canonical = JSON.stringify(record);
1288
+ digest.update(String(Buffer.byteLength(canonical))).update(":").update(canonical).update("\n"); count++;
1289
+ }
1290
+ } finally { statement.finalize(); }
1291
+ return { count, digest: digest.digest("hex") };
1292
+ })();
1293
+ } catch { throw new ExecutionLinkError("corrupt"); }
1294
+ }
1295
+
1035
1296
  hasResearchEvidenceState(): boolean {
1036
1297
  return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_evidence_links) AS present").get() as { present: number }).present === 1;
1037
1298
  }
@@ -1725,6 +1986,57 @@ export class Board {
1725
1986
  return (rows as Record<string, unknown>[]).map(parse);
1726
1987
  }
1727
1988
 
1989
+ /** A bounded, read-only source projection. Unknown/capped results never authorize carry. */
1990
+ specAcceptanceCandidates(destination: number): { rows: SpecAcceptanceCandidate[]; complete: boolean } {
1991
+ const unavailable = { rows: [], complete: false };
1992
+ if (!Number.isSafeInteger(destination) || destination <= 0) return unavailable;
1993
+ const object = (column: string) => `CASE WHEN length(CAST(${column} AS BLOB)) <= ${SPEC_ACCEPTANCE_FIELD_BYTES} THEN CASE WHEN json_valid(${column}) THEN json_type(${column})='object' ELSE 0 END ELSE 0 END`;
1994
+ const cancel = object("cancelled"), receipt = object("sdlc");
1995
+ try {
1996
+ const found = this.db.query(`WITH candidates AS (
1997
+ SELECT id,created,
1998
+ CASE WHEN length(CAST(refs AS BLOB)) <= ${SPEC_ACCEPTANCE_FIELD_BYTES} THEN refs END AS refs,
1999
+ CASE WHEN length(CAST(signals AS BLOB)) <= ${SPEC_ACCEPTANCE_FIELD_BYTES} THEN signals END AS signals,
2000
+ CASE WHEN ${cancel} THEN json_extract(cancelled,'$.supersededBy') END AS superseded_by,
2001
+ CASE WHEN ${cancel} THEN json_extract(cancelled,'$.flowRevision') END AS cancellation_revision,
2002
+ CASE WHEN ${cancel} THEN json_extract(cancelled,'$.withheld') END AS withheld,
2003
+ CASE WHEN sdlc IS NULL THEN 1 WHEN ${receipt} THEN 1 ELSE 0 END AS receipt_valid,
2004
+ CASE WHEN ${receipt} THEN json_extract(sdlc,'$.repo') END AS repo,
2005
+ CASE WHEN ${receipt} THEN json_extract(sdlc,'$.issue') END AS issue,
2006
+ CASE WHEN ${receipt} THEN CAST(json_extract(sdlc,'$.acceptance') AS TEXT) END AS acceptance
2007
+ FROM tasks WHERE state='cancelled' AND id < ? AND
2008
+ CASE WHEN ${cancel} THEN json_extract(cancelled,'$.supersededBy') IN (?,?,?) ELSE 0 END
2009
+ ORDER BY id DESC LIMIT ?
2010
+ ), projections AS (
2011
+ SELECT id,json_object('id',id,'created',created,'refs',refs,'signals',signals,'superseded_by',superseded_by,
2012
+ 'cancellation_revision',cancellation_revision,'withheld',withheld,'repo',repo,'issue',issue,'acceptance',acceptance) AS payload,
2013
+ receipt_valid AND refs IS NOT NULL AND signals IS NOT NULL AS valid FROM candidates
2014
+ ), budget AS (
2015
+ SELECT COUNT(*) <= ${SPEC_ACCEPTANCE_SOURCE_LIMIT} AND MIN(valid)
2016
+ AND SUM(length(CAST(payload AS BLOB))) <= ${SPEC_ACCEPTANCE_TOTAL_BYTES} AS complete FROM projections
2017
+ ) SELECT budget.complete, CASE WHEN budget.complete THEN projections.payload END AS payload FROM projections,budget ORDER BY projections.id DESC`)
2018
+ .all(destination, `task #${destination}`, `#${destination}`, String(destination), SPEC_ACCEPTANCE_SOURCE_LIMIT + 1) as { complete: number; payload: string | null }[];
2019
+ if (found.some(row => row.complete !== 1 || row.payload === null)) return unavailable;
2020
+ const rows: SpecAcceptanceCandidate[] = [];
2021
+ for (const projected of found) {
2022
+ const row = JSON.parse(projected.payload!) as Record<string, unknown>;
2023
+ if (typeof row.refs !== "string" || typeof row.signals !== "string") return unavailable;
2024
+ const refs = JSON.parse(row.refs), signals = JSON.parse(row.signals);
2025
+ if (!refs || typeof refs !== "object" || Array.isArray(refs) || refs.repo !== undefined && typeof refs.repo !== "string"
2026
+ || refs.paths !== undefined && (!Array.isArray(refs.paths) || refs.paths.some((value: unknown) => typeof value !== "string"))
2027
+ || !Array.isArray(signals) || signals.some((value: unknown) => typeof value !== "string")
2028
+ || !Number.isSafeInteger(row.id) || typeof row.created !== "number" || !Number.isFinite(row.created)
2029
+ || typeof row.superseded_by !== "string" || !Number.isSafeInteger(row.cancellation_revision) || Number(row.cancellation_revision) <= 0
2030
+ || ![null, 0, 1].includes(row.withheld as null | number)) return unavailable;
2031
+ const acceptance = row.acceptance == null ? undefined : JSON.parse(String(row.acceptance));
2032
+ rows.push({ id: row.id as number, created: row.created, state: "cancelled", refs, signals,
2033
+ supersededBy: row.superseded_by, cancellationRevision: row.cancellation_revision as number, withheld: row.withheld === 1,
2034
+ repo: row.repo, issue: row.issue, acceptance });
2035
+ }
2036
+ return { rows, complete: true };
2037
+ } catch { return unavailable; }
2038
+ }
2039
+
1728
2040
  /** Structural status facts only; avoid decoding text, plans and growing history on each status write. */
1729
2041
  statusTasks(): Pick<Task, "id" | "state" | "owner" | "reviewer">[] {
1730
2042
  return this.db.query("SELECT id, state, owner, reviewer FROM tasks WHERE state NOT IN ('approved','cancelled') ORDER BY id").all() as Pick<Task, "id" | "state" | "owner" | "reviewer">[];
@@ -1864,13 +2176,43 @@ export class Board {
1864
2176
  return Object.fromEntries(rows.map((r) => [r.state, r.n]));
1865
2177
  }
1866
2178
 
2179
+ /** Tasks alone calls this after current actor, privacy, artifact and GitHub evidence fences. Generic MOVES stays unchanged. */
2180
+ adoptMerge(id: number, by: PeerId, receipt: SdlcReceipt, head: string, expectedFlowRevision: number, authority: typeof HOST_MERGE_ADOPTION): Task {
2181
+ if (authority !== HOST_MERGE_ADOPTION || !Number.isSafeInteger(expectedFlowRevision) || expectedFlowRevision < 0)
2182
+ throw new Error("merge adoption requires host authority and a current flow revision; retry through Tasks.adoptMerge");
2183
+ return this.update(id, by, "merged outside the hub", { state: "approved", rejections: 0, sdlc: receipt },
2184
+ `PR #${receipt.pr} merged outside the hub at ${head}`, undefined, expectedFlowRevision, undefined, authority);
2185
+ }
2186
+
2187
+ /** Consent and the admitted outer event publish together, including observer/status-generation rollback. */
2188
+ updateWithSpecAcceptance(carry: SpecAcceptanceCommit, authority: typeof HOST_SPEC_ACCEPTANCE_CARRY, ...args: Parameters<Board["update"]>): Task {
2189
+ const [id, by, event, patch, note, extra, revision, codeSymbolsAuthority, adoptionAuthority] = args;
2190
+ if (authority !== HOST_SPEC_ACCEPTANCE_CARRY || revision === undefined
2191
+ || !["accepted", "lifecycle", "done", "done (checking)", "integration requested", "integration unresolved", "integrated"].includes(event)) throw new Error("spec carry requires host admission authority; inspect the current task and invoke the action through Tasks");
2192
+ return this.atomic(() => {
2193
+ const task = this.get(id), acceptance = carry.acceptance, receipt = patch.sdlc ?? task?.sdlc;
2194
+ if (!task || task.sdlc?.acceptance || !Number.isSafeInteger(carry.source) || carry.source >= id || carry.source <= 0
2195
+ || !Number.isSafeInteger(carry.cancellationRevision) || carry.cancellationRevision <= 0
2196
+ || !receipt || receipt.repo !== acceptance.repo || receipt.issue !== acceptance.issue
2197
+ || task.sdlc?.repo !== acceptance.repo || task.sdlc.issue !== acceptance.issue) throw new Error("spec carry identity changed before publication; inspect the current task and held deliveries before repeating this action");
2198
+ const carried = this.update(id, HUB, "spec acceptance carried", { sdlc: { ...task.sdlc, acceptance } },
2199
+ `from task #${carry.source}; original person acceptance at ${acceptance.acceptedAt}; cancellation revision ${carry.cancellationRevision}`, {}, revision);
2200
+ return this.update(id, by, event, { ...patch, sdlc: { ...receipt, acceptance } }, note, extra, carried.history.length, codeSymbolsAuthority, adoptionAuthority);
2201
+ });
2202
+ }
2203
+
1867
2204
  /** The only way a task changes. Validates the move, records who did what, returns the new row. */
1868
2205
  /** A `plan` in the patch replaces the old one whole: a new plan is the owner's current intent, not an addition. */
1869
- update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS): Task {
1870
- if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority));
2206
+ update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2207
+ if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority, adoptionAuthority));
1871
2208
  const task = this.get(id);
1872
2209
  if (!task) throw new Error(`no task #${id}`);
1873
2210
  if (expectedFlowRevision !== undefined && (!Number.isSafeInteger(expectedFlowRevision) || expectedFlowRevision < 0 || task.history.length !== expectedFlowRevision)) throw new Error("task flow revision changed");
2211
+ const adoption = event === "merged outside the hub" && adoptionAuthority === HOST_MERGE_ADOPTION && expectedFlowRevision !== undefined
2212
+ && ["in_progress", "in_review", "changes_requested"].includes(task.state) && !task.draft
2213
+ && !task.signals.includes("pii") && !task.signals.includes("pii_path") && patch.state === "approved"
2214
+ && Object.keys(patch).every(key => ["state", "rejections", "sdlc"].includes(key));
2215
+ if (event === "merged outside the hub" && !adoption) throw new Error(`task #${id} in state ${task.state}: merge adoption requires a host-only eligible transition and current flow revision; retry through Tasks.adoptMerge`);
1874
2216
  const untouchedReturn = event === "backlog returned untouched" && patch.state === "backlog" && patch.owner === null && patch.reviewer === null
1875
2217
  && ["proposed", "in_progress"].includes(task.state) && expectedFlowRevision !== undefined && !!note?.trim() && !taskHasWorkEvidence(task);
1876
2218
  const returnPlanning: HistoryEntry["planning"] = untouchedReturn && Object.hasOwn(patch, "reserved")
@@ -1889,7 +2231,7 @@ export class Board {
1889
2231
  || event === "changes_requested" && patch.state === "changes_requested" && (by === task.reviewer || by === "user"));
1890
2232
  if (extra.reviewedHead !== undefined && (!/^[a-f0-9]{40}$/.test(extra.reviewedHead) || !["approved", "changes_requested"].includes(event))) throw new Error("invalid verdict head");
1891
2233
  if (task.draft && patch.state && patch.state !== "backlog" && patch.state !== "cancelled") throw new Error(`task #${id} is an intake draft; the person approves it first`);
1892
- if (patch.state && patch.state !== task.state && !MOVES[task.state].includes(patch.state) && !untouchedReturn && !reviewCheck && !approvalReopen) {
2234
+ if (patch.state && patch.state !== task.state && !MOVES[task.state].includes(patch.state) && !untouchedReturn && !reviewCheck && !approvalReopen && !adoption) {
1893
2235
  throw new Error(`task #${id} is ${task.state}: cannot move to ${patch.state}`);
1894
2236
  }
1895
2237
  const planner = Object.hasOwn(patch, "planner") ? plannerValue(patch.planner) : task.planner ?? null;
@@ -0,0 +1,11 @@
1
+ import type { Task } from "./board.ts";
2
+
3
+ /** Snapshot guidance only; live spec/plan readbacks remain the acceptance gates. */
4
+ export function buildEntryDiagnostic(task: Pick<Task, "id" | "sdlc">, planGap = task.sdlc?.planReview ? undefined : "plan not reviewed"): string | undefined {
5
+ const receipt = task.sdlc;
6
+ if (!receipt?.repo || !receipt.issue) return "spec issue not recorded (owner/planner: hub_sdlc_record)";
7
+ const accepted = receipt.acceptance;
8
+ if (!accepted || accepted.repo !== receipt.repo || accepted.issue !== receipt.issue) return `spec not accepted (person: ahub sdlc accept ${task.id} --issue ${receipt.issue})`;
9
+ if (planGap && !planGap.startsWith("plan not reviewed")) return `${planGap} (planner: hub_plan_review)`;
10
+ return planGap ? `plan not reviewed (planner: hub_plan_review)${planGap === "plan not reviewed" ? "" : `; ${planGap}`}` : undefined;
11
+ }
package/src/hub/bus.ts CHANGED
@@ -711,6 +711,18 @@ export class Bus {
711
711
  return this.storageError ? undefined : this.journal?.heldDeliveryHints(peer, canExposeAccepted);
712
712
  }
713
713
 
714
+ /** Read held originals without changing transport, retry or task evidence. */
715
+ heldInbox(peer: PeerId) {
716
+ if (this.closed || this.storageError || !this.journal) throw new Error("held inbox unavailable");
717
+ return this.journal.heldInbox(peer, this.peers.get(peer)?.acceptedSettlement === "explicit", this.opts.pullBudgetBytes?.() ?? PULL_BUDGET_BYTES);
718
+ }
719
+
720
+ hasHeldReviewScope(peer: PeerId): boolean {
721
+ if (this.closed || this.storageError) return true;
722
+ try { return this.journal?.hasHeldReviewScope(peer, this.peers.get(peer)?.acceptedSettlement === "explicit", this.opts.pullBudgetBytes?.() ?? PULL_BUDGET_BYTES) ?? false; }
723
+ catch { return true; } // Unknown provenance excludes observers without failing the caller.
724
+ }
725
+
714
726
  /** Whether timeout-originated holds still protect the recovery cause from supersession. */
715
727
  hasAcceptedTimeoutHolds(): boolean {
716
728
  if (this.closed || this.storageError || !this.journal) throw new Error("delivery timeout hold state unavailable");
@@ -1,4 +1,4 @@
1
- import { parsePrEvidence, type SdlcGh } from "./sdlc.ts";
1
+ import { requiredCheckNames, parsePrEvidence, type SdlcGh } from "./sdlc.ts";
2
2
 
3
3
  /**
4
4
  * #785 P1b: one bounded watcher per exact PR head. It starts when `hub_task_done` names a head whose CI was not green,
@@ -8,8 +8,6 @@ import { parsePrEvidence, type SdlcGh } from "./sdlc.ts";
8
8
  */
9
9
  export const CI_WATCH_DEADLINE_MS = 45 * 60_000;
10
10
  export const CI_WATCH_POLL_MS = 60_000;
11
- /** Same default set as `readReviewReadiness`, which is the authoritative read the review admission makes. */
12
- const DEFAULT_CHECKS = ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"];
13
11
  const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
14
12
  /** How many finished heads are remembered, so one head never tells the same outcome twice. */
15
13
  const SETTLED_CAP = 256;
@@ -25,6 +23,8 @@ type Entry = { watch: CiWatch; timer?: ReturnType<typeof setTimeout>; reported?:
25
23
  /** One read of the PR: the head, its state and the required checks of that head. A failed or unreadable read is `pending`; the deadline bounds the retries. */
26
24
  export async function pollCi(target: { repo: string; pr: number }, head: string, required: readonly string[], run: SdlcGh): Promise<CiPoll> {
27
25
  if (!REPO.test(target.repo) || !Number.isSafeInteger(target.pr) || target.pr < 1) return "closed";
26
+ const names = requiredCheckNames(target.repo, required);
27
+ if (!names.length) return "incomplete";
28
28
  try {
29
29
  const view = await run(["pr", "view", String(target.pr), "--repo", target.repo, "--json", "headRefOid,state,statusCheckRollup"], 10_000, undefined, 512 * 1024);
30
30
  if (view.code !== 0) return "pending";
@@ -33,7 +33,7 @@ export async function pollCi(target: { repo: string; pr: number }, head: string,
33
33
  if (body.state !== "OPEN") return "closed";
34
34
  // The same check-state mapping as every other PR read; files are not requested here.
35
35
  const evidence = parsePrEvidence({ ...body, files: [], changedFiles: 0 });
36
- const rows = (required.length ? required : DEFAULT_CHECKS).map(name => evidence.checks.filter(check => check.name === name));
36
+ const rows = names.map(name => evidence.checks.filter(check => check.name === name));
37
37
  if (rows.some(row => row.some(check => check.state === "failed"))) return "failed";
38
38
  if (rows.some(row => row.length === 0 || row.some(check => check.state === "pending"))) return "pending";
39
39
  return rows.every(row => row.length === 1 && row[0]!.state === "passed") ? "passed" : "incomplete";
@@ -207,6 +207,7 @@ const schema: Record<string, Check> = {
207
207
  conductor: block({ feed: words(["own", "all", "off"]), approval_wait_s: number(0, 2_147_483_647 / 1000) }),
208
208
  budget: block({ gate: number(0, 1), stale_min: timerMinutes, poll_min: timerMinutes, checkpoint_timeout_s: timerSeconds, kimi_tokens_5h: number(0), wait_max_min: number(0) }),
209
209
  context: block({ gate: number(0, 1), stale_min: timerMinutes, max_assignment_used: number(0, 1) }),
210
+ supervision: block({ mode: words(["off", "shadow", "advisory"]) }),
210
211
  bus: block({ max_attempts: operationalNumberCheck("bus.max_attempts"), digest_max: operationalNumberCheck("bus.digest_max"), pull_budget_bytes: operationalNumberCheck("bus.pull_budget_bytes"), notes_kept: operationalNumberCheck("bus.notes_kept"), terminal_history_limit: operationalNumberCheck("bus.terminal_history_limit"), accepted_settle_ms: operationalNumberCheck("bus.accepted_settle_ms") }),
211
212
  adapter_timing: block({ acp_tool_ceiling_min: operationalNumberCheck("adapter_timing.acp_tool_ceiling_min"), acp_activity_batch_ms: operationalNumberCheck("adapter_timing.acp_activity_batch_ms"), jcode_steer_timeout_s: operationalNumberCheck("adapter_timing.jcode_steer_timeout_s") }),
212
213
  model_relay: block({ cooldown_failures: operationalNumberCheck("model_relay.cooldown_failures"), cooldown_s: operationalNumberCheck("model_relay.cooldown_s"), cooldown_cap_s: operationalNumberCheck("model_relay.cooldown_cap_s"), terminal_history_limit: operationalNumberCheck("model_relay.terminal_history_limit") }),
@@ -277,7 +278,7 @@ const restart: Record<string, string> = {
277
278
  profile: "Session tool schemas and profile contracts are bound at startup", profile_overrides: "Session tool schemas and profile contracts are bound at startup",
278
279
  text_projection: "Converter and cache ownership are bound at startup", corpus: "The corpus index is bound to its roots at startup", terminal: "Terminal provider is supplied by the daemon lifecycle", bench: "Benchmark execution environment is selected before work starts",
279
280
  };
280
- const live = new Set(["visuals", "action_policy", "permission", "roster", "roles", "planner", "conductor", "protect_instruction_files", "task_sweep", "capabilities", "invocation", "research", "snapshots", "worktrees", "tasks.wip_limits", "tasks.escalate_after", "tasks.auto_pull", "tasks.queue_backpressure", "schedules", "approvals.notify", "questions", "pet", "specs"]);
281
+ const live = new Set(["visuals", "action_policy", "permission", "roster", "roles", "planner", "conductor", "protect_instruction_files", "task_sweep", "capabilities", "invocation", "research", "snapshots", "worktrees", "tasks.wip_limits", "tasks.escalate_after", "tasks.auto_pull", "tasks.queue_backpressure", "schedules", "approvals.notify", "questions", "pet", "specs", "supervision"]);
281
282
  const nextMemory = new Set(["memory.inject_tokens", "memory.brief_items", "memory.suggest_edges"]);
282
283
  /** Closed top-level schema; leaf overrides retain the existing session/runtime boundaries. */
283
284
  export function configApply(key: string, scopes: readonly ConfigIdentityScope[] = []): ApplyRule {
@@ -30,6 +30,7 @@ export const MACHINE_LOCAL = [
30
30
  "local.web_fetch", // #515b: lets a model request pages from listed hosts; a committed config may not choose where a model's requests go on someone else's machine
31
31
  "terminal.open", // the command a hub-made TUI start runs to open a terminal (#269)
32
32
  "tasks.auto_pull", // #785 P1c: lets the hub start work on its own; a committed config may not turn it on for someone else's machine
33
+ "supervision.mode", // #1221 T2: lets the hub propose existing actions to a person's console and agents; an opt-in only the person's own machine sets
33
34
  "folder_triggers", // #512c: entries make the hub read a folder and propose a task per new file; a committed config may not point the hub at a folder on someone else's machine
34
35
  "schedules", // #512: entries make the hub propose tasks on a timer; a committed config may not create work on someone else's machine
35
36
  "corpus.paths", // #510: folders the hub reads as evidence; a committed config may not point the hub at a folder on someone else's machine
@@ -21,7 +21,7 @@ export const PROTOCOL = 17;
21
21
  /** The descriptor's legacy protocol field remains this floor for previous published clients. */
22
22
  export const PROTOCOL_MIN = 16;
23
23
  // Literal metadata is read without executing a recovery target; consistency is pinned in tests.
24
- export const DAEMON_FEATURES = ["model_overrides", "visuals", "project_autonomy", "conductor_recovery", "encrypted_rooms", "external_adapter_instances", "external_adapter_modules", "configured_acp", "native_hook_launch", "task_cancel", "invocation", "recovery_deferred_hub", "peer_instances", "role_stages", "task_planners", "release_trains", "reviewer_pool", "native_tui_launch", "terminal_owner", "cli_audit_delegated", "action_policy_floor", "calendar_schedules", "research_records", "research_dispatch", "research_dropped_offers", "research_experiments", "research_comparisons", "research_runners", "task_handoff", "session_identity", "schema_guard", "design_specs", "queue_discard_states", "tool_write_idempotency", "research_evidence", "review_comments", "questions", "accepted_delivery_settlement", "completions", "review_observer_input_state", "task_handoff_key", "task_handoff_seq", "peer_takeover"] as const;
24
+ export const DAEMON_FEATURES = ["guidance_views", "guidance_variants", "execution_lineage", "model_overrides", "visuals", "project_autonomy", "conductor_recovery", "encrypted_rooms", "external_adapter_instances", "external_adapter_modules", "configured_acp", "native_hook_launch", "task_cancel", "invocation", "recovery_deferred_hub", "peer_instances", "role_stages", "task_planners", "release_trains", "reviewer_pool", "native_tui_launch", "terminal_owner", "cli_audit_delegated", "action_policy_floor", "calendar_schedules", "research_records", "research_dispatch", "research_dropped_offers", "research_experiments", "research_comparisons", "research_runners", "task_handoff", "session_identity", "schema_guard", "design_specs", "queue_discard_states", "tool_write_idempotency", "research_evidence", "review_comments", "questions", "accepted_delivery_settlement", "completions", "review_observer_input_state", "task_handoff_key", "task_handoff_seq", "peer_takeover"] as const;
25
25
  /** Protocols a current coordinator may authenticate while upgrading a running source. */
26
26
  export const RECOVERY_SOURCE_PROTOCOLS = [9, 10, 11, 12, 13, 14, 15, 16, PROTOCOL] as const;
27
27