@staix/agent-hub 0.34.1 → 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.
- package/CHANGELOG.md +73 -0
- package/README.md +53 -7
- package/docs/adding-an-ai-tool.md +2 -2
- package/docs/addons/claude-mem.md +4 -4
- package/docs/addons/open-code-review.md +1 -1
- package/docs/agent-notes/README.md +66 -0
- package/docs/agent-notes/adapters.md +14 -7
- package/docs/agent-notes/budget.md +1 -1
- package/docs/agent-notes/bus.md +2 -1
- package/docs/agent-notes/daemon.md +9 -7
- package/docs/agent-notes/local-worker.md +1 -1
- package/docs/agent-notes/models.md +5 -2
- package/docs/agent-notes/tasks.md +9 -2
- package/docs/agent-notes/tests.md +6 -0
- package/docs/design/adapters.md +182 -2
- package/docs/design/agent-hub-architecture.md +64 -2
- package/docs/design/agent-hub.md +6 -0
- package/docs/design/bus.md +26 -0
- package/docs/design/execution-reference.md +306 -0
- package/docs/design/guidance-experiments.md +438 -0
- package/docs/design/model-routes.md +628 -0
- package/docs/design/supervision.md +121 -0
- package/docs/design/task-board.md +121 -0
- package/docs/dogfood.md +45 -13
- package/docs/events.md +38 -20
- package/docs/memory.md +21 -7
- package/docs/operations.md +824 -40
- package/docs/profiles.md +2 -2
- package/docs/quickstart.md +117 -4
- package/docs/research.md +73 -13
- package/docs/roles.md +1 -1
- package/docs/sdlc.md +117 -11
- package/docs/security.md +153 -15
- package/docs/smoke.md +14 -0
- package/docs/specs/2026-09-19-agent-hub-design.md +13 -7
- package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
- package/docs/verification/2026-11-07-compat-python-startup-1248.md +51 -0
- package/docs/verification/2026-11-07-compat-receipt-harness-1248.md +105 -0
- package/docs/verification/2026-11-07-compat-receipt-producers-1248.md +96 -0
- package/docs/verification/2026-11-07-compat-workflow-1248.md +94 -0
- package/docs/verification/2026-11-07-daemon-startup-1232.md +169 -0
- package/docs/verification/2026-11-07-jcode-receipt-reconstruction-1248.md +118 -0
- package/docs/verification/2026-11-07-kimi-delayed-usage.md +34 -0
- package/docs/verification/2026-11-07-kimi-review-watch-1284.md +115 -0
- package/docs/verification/2026-11-08-agy-1.5.3.md +96 -0
- package/docs/verification/2026-11-08-agy-acp-t0.md +56 -0
- package/docs/verification/2026-11-08-hub-visual-1058.md +161 -0
- package/docs/verification/2026-11-08-jcode-0991-model-setter-1317.md +143 -0
- package/docs/verification/2026-11-08-kimi-252-model-setter-1317.md +137 -0
- package/docs/verification/2026-11-08-kimi-tui-completion-1282.md +45 -0
- package/docs/verification/2026-11-08-kimi-wire-yield-1283.md +31 -0
- package/docs/verification/2026-11-08-live-model-override-1317.md +250 -0
- package/docs/verification/2026-11-08-qwen-0269-acp.md +138 -0
- package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +91 -0
- package/docs/verification/2026-11-09-0.35.0.md +129 -0
- package/docs/verification/2026-11-09-headless-records-1320.md +157 -0
- package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
- package/docs/verification/2026-11-10-0.36.0.md +59 -0
- package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
- package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
- package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
- package/docs/verification/claude-permission-transport-native.py +10 -3
- package/docs/verification/claude-shell-wrapper-native.py +8 -8
- package/docs/verified.json +245 -15
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +21230 -0
- package/plugins/agent-hub/kimi-review-policy-worker.js +217 -0
- package/plugins/agent-hub/server.js +4359 -1071
- package/scripts/check-docs.mjs +12 -1
- package/src/adapters/acp-model-policy.ts +56 -0
- package/src/adapters/acp.ts +175 -5
- package/src/adapters/agy/entry.ts +8 -5
- package/src/adapters/agy/hooks.ts +65 -15
- package/src/adapters/channel-peer.ts +33 -1
- package/src/adapters/claude-channel.ts +7 -4
- package/src/adapters/claude-implementer.ts +16 -3
- package/src/adapters/codex-appserver.ts +118 -8
- package/src/adapters/codex-review-isolation.ts +3 -1
- package/src/adapters/compat.ts +18 -13
- package/src/adapters/definitions/builtin-metadata.ts +8 -1
- package/src/adapters/definitions/native-cli-entry-kimi.ts +76 -7
- package/src/adapters/definitions/native-cli-preview-common.ts +2 -2
- package/src/adapters/definitions/native-cli-preview-kimi.ts +9 -2
- package/src/adapters/definitions/reviewer-variants.ts +3 -1
- package/src/adapters/kimi-review-policy-worker.js +2 -0
- package/src/adapters/kimi-review-policy-worker.ts +85 -0
- package/src/adapters/kimi-review-policy.ts +68 -0
- package/src/adapters/kimi-review.ts +41 -41
- package/src/adapters/kimi-tui-facts.ts +153 -0
- package/src/adapters/kimi-wire-usage.ts +33 -8
- package/src/adapters/local-worker.ts +60 -21
- package/src/adapters/model-token.ts +3 -0
- package/src/adapters/pi.ts +27 -5
- package/src/adapters/qwen-dual.ts +324 -44
- package/src/adapters/registry-types.ts +34 -3
- package/src/adapters/registry.ts +1 -0
- package/src/adapters/reviewer-policy-watch.ts +86 -0
- package/src/adapters/reviewer-print.ts +80 -18
- package/src/cli/agents.ts +1 -1
- package/src/cli/facts-hook.ts +4 -2
- package/src/cli/guidance.ts +67 -0
- package/src/cli/help.ts +13 -5
- package/src/cli/identity.ts +13 -3
- package/src/cli/init-prompt.ts +15 -2
- package/src/cli/init-required-checks.ts +122 -0
- package/src/cli/init-settings.ts +10 -4
- package/src/cli/init.ts +39 -3
- package/src/cli/kimi-facts-hook.ts +11 -0
- package/src/cli/kimi-plugin.ts +157 -0
- package/src/cli/lineage.ts +78 -0
- package/src/cli/main.ts +159 -19
- package/src/cli/model.ts +52 -0
- package/src/cli/output.ts +23 -1
- package/src/cli/reset.ts +1 -1
- package/src/cli/setup-research.ts +10 -0
- package/src/cli/status-lines.ts +8 -4
- package/src/hub/autonomy-defaults.ts +20 -9
- package/src/hub/board.ts +346 -4
- package/src/hub/budget.ts +1 -1
- package/src/hub/build-entry.ts +11 -0
- package/src/hub/bus.ts +52 -2
- package/src/hub/ci-watch.ts +4 -4
- package/src/hub/code-facts.ts +10 -3
- package/src/hub/completions.ts +3 -1
- package/src/hub/config-apply.ts +3 -1
- package/src/hub/config-trust.ts +1 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +1387 -121
- package/src/hub/deliverable-files.ts +38 -5
- package/src/hub/delivery-hints.ts +4 -2
- package/src/hub/delivery-journal.ts +50 -2
- package/src/hub/delivery-public.ts +51 -0
- package/src/hub/dogfood-profile.ts +9 -5
- package/src/hub/envelope.ts +1 -1
- package/src/hub/events.ts +28 -18
- package/src/hub/execution-lineage-owner.ts +272 -0
- package/src/hub/execution-lineage.ts +164 -0
- package/src/hub/execution-links.ts +85 -0
- package/src/hub/execution-reference.ts +36 -0
- package/src/hub/guidance-variants.ts +398 -0
- package/src/hub/handoff.ts +1 -0
- package/src/hub/hub-tools.ts +62 -2
- package/src/hub/instances.ts +4 -3
- package/src/hub/kimi-events.ts +46 -0
- package/src/hub/kimi-usage.ts +132 -29
- package/src/hub/lifecycle.ts +31 -15
- package/src/hub/limits.ts +13 -4
- package/src/hub/manager.ts +58 -3
- package/src/hub/memory-policy.ts +4 -3
- package/src/hub/memory-sync-attestation.ts +54 -0
- package/src/hub/memory-sync-state.ts +20 -5
- package/src/hub/model-overrides.ts +115 -0
- package/src/hub/native-hook-launch.ts +12 -3
- package/src/hub/operational-view.ts +2 -2
- package/src/hub/peers.ts +28 -1
- package/src/hub/permission-mode.ts +1 -1
- package/src/hub/person-figures.ts +88 -0
- package/src/hub/planning.ts +1 -1
- package/src/hub/progress.ts +24 -7
- package/src/hub/report.ts +38 -4
- package/src/hub/research-dataset.ts +158 -0
- package/src/hub/research-memory.ts +68 -0
- package/src/hub/research-quality.ts +118 -0
- package/src/hub/research-record.ts +279 -0
- package/src/hub/research.ts +126 -27
- package/src/hub/restart.ts +27 -0
- package/src/hub/roles.ts +26 -0
- package/src/hub/routing.ts +4 -1
- package/src/hub/sdlc-merge.ts +39 -1
- package/src/hub/sdlc-release.ts +1 -1
- package/src/hub/sdlc.ts +62 -11
- package/src/hub/settings.ts +5 -0
- package/src/hub/startup-event-seeds.ts +51 -0
- package/src/hub/startup-readiness.ts +65 -0
- package/src/hub/startup-timing.ts +38 -0
- package/src/hub/supervision-proposals.ts +405 -0
- package/src/hub/supervision-rules.ts +388 -0
- package/src/hub/supervision.ts +2 -0
- package/src/hub/task-approval.ts +2 -2
- package/src/hub/task-repository.ts +5 -0
- package/src/hub/tasks.ts +632 -59
- package/src/hub/ui.ts +9 -5
- package/src/hub/visual-assets.ts +50 -0
- package/src/hub/visual.ts +257 -0
- package/src/memory/brief.ts +169 -14
- package/src/memory/capture.ts +4 -3
- package/src/memory/recall.ts +46 -5
- package/src/memory/record-provenance.ts +82 -0
- package/src/memory/records.ts +116 -0
- package/src/models/relay.ts +9 -2
- package/src/models/route/adec.ts +190 -0
- package/src/models/route/config.ts +64 -3
- package/src/models/route/decision-evidence.ts +83 -0
- package/src/models/route/decision.ts +215 -0
- package/src/models/route/relay-selector.ts +8 -7
- package/src/models/route/runtime.ts +35 -22
- package/src/models/route/stage-diagnostics.ts +22 -0
- package/src/models/route/stage-evidence.ts +55 -0
- package/src/models/route/stage-fallback.ts +58 -0
- package/src/models/route/stage-input.ts +155 -0
- package/src/models/route/stage.ts +5 -147
- package/src/ui/guidance-panel.ts +156 -0
- package/src/ui/guidance-view.ts +43 -0
- package/src/ui/index.html +134 -6
- package/src/ui/lineage-view.ts +34 -0
- package/src/ui/plugin.ts +136 -11
- package/templates/AGENTS.block.md +1 -1
- package/templates/config.json +1 -1
- package/templates/profiles/general.json +1 -1
- package/templates/profiles/research.json +1 -1
- package/templates/profiles/writing.json +1 -1
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;
|
package/src/hub/budget.ts
CHANGED
|
@@ -54,7 +54,7 @@ export interface BudgetConfig {
|
|
|
54
54
|
wait_max_min: number;
|
|
55
55
|
}
|
|
56
56
|
// wait_max_min is off here, as approvals.notify is: a project config turns it on (30 unless it says otherwise).
|
|
57
|
-
export const DEFAULT_BUDGET: BudgetConfig = { gate: 0.
|
|
57
|
+
export const DEFAULT_BUDGET: BudgetConfig = { gate: 0.99, stale_min: 30, poll_min: 10, checkpoint_timeout_s: 90, kimi_tokens_5h: 0, wait_max_min: 0 };
|
|
58
58
|
|
|
59
59
|
export type BudgetLedgerEntry =
|
|
60
60
|
| { type: "budget_pause"; peer: PeerId; reason: string; window: string; resetsAt: number; by: "hub" | "person" }
|
|
@@ -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
|
@@ -9,6 +9,7 @@ import { DELIVERY_RETRY_WARNING } from "./delivery-hints.ts";
|
|
|
9
9
|
import { MAX_DEFERRED_HUB, RecoveryDeferredHubError, validateDeferredHub } from "./deferred-hub.ts";
|
|
10
10
|
import { parseRemotePeerId } from "../rooms/application.ts";
|
|
11
11
|
import { PreEffectToolRefusal } from "./tool-refusal.ts";
|
|
12
|
+
import { stripRecordLines } from "../memory/records.ts";
|
|
12
13
|
|
|
13
14
|
export type { DeliveryReceipt } from "./peers.ts";
|
|
14
15
|
|
|
@@ -214,6 +215,10 @@ export class Bus {
|
|
|
214
215
|
* peer was handed (the request is in it, never condensed), so a reply that answers an invocation is found by identity, not by addressing.
|
|
215
216
|
*/
|
|
216
217
|
onAnswer?: (peer: PeerId, text: string, answers: readonly Envelope[]) => boolean;
|
|
218
|
+
/** Completed adapter answers only, under the same public-input observer ceiling as memory delivery. */
|
|
219
|
+
onFinalAnswer?: (peer: PeerId, text: string, context: { out: readonly Envelope[]; originals: readonly Envelope[] }) => void;
|
|
220
|
+
/** Count-only forwarding telemetry; never emitted for a private, review-scoped or unbound answer. */
|
|
221
|
+
onFinalAnswerBytes?: (peer: PeerId, counts: { before: number; after: number }) => void;
|
|
217
222
|
/** Host ledger authority; absent or unknown never permits invocation replay. */
|
|
218
223
|
canRetryInvocation?: (id: string) => boolean;
|
|
219
224
|
onInvocationUncertain?: (id: string) => void;
|
|
@@ -315,7 +320,10 @@ export class Bus {
|
|
|
315
320
|
peer.onDelivery = (receipt) => { if (this.peers.get(peer.id) === peer) this.deliveryReceipt(peer.id, receipt); };
|
|
316
321
|
peer.onDoing = (kind, text) => { if (kind === "reset") this.clearReviewProvenance(peer.id); if (!this.closed && this.peers.get(peer.id) === peer) this.opts.doing?.(peer.id, kind, text); };
|
|
317
322
|
this.opts.doing?.(peer.id, "reset"); // a new adapter never shows what the one it replaces was doing
|
|
318
|
-
|
|
323
|
+
// A final still traverses the current onMessage observer exactly once. This one-shot
|
|
324
|
+
// marker is host-local, never a caller-supplied envelope or wire field.
|
|
325
|
+
let finalMessage: { body: string; options: EnvelopeOpts | undefined; complete: boolean } | undefined;
|
|
326
|
+
const receive = (text: string, opts?: EnvelopeOpts, final = false, complete = true) => {
|
|
319
327
|
if (!this.isRostered(peer.id)) return `off roster: ${peer.id}`;
|
|
320
328
|
// #445 C2: an answer to an invocation is found by what the peer was handed, never by how the answer is addressed, so a headless agent whose final answer is
|
|
321
329
|
// normally shared with every peer cannot leak it. It is the invocation's answer when it names the request itself (an adapter may report its delivery complete before
|
|
@@ -331,12 +339,29 @@ export class Bus {
|
|
|
331
339
|
: parentId === undefined && this.invocationTurnOpen(peer.id)
|
|
332
340
|
? pushedInvocation ? pushed : pulledInvocation ? pulled : undefined
|
|
333
341
|
: undefined;
|
|
342
|
+
let finalPriority: Priority | undefined;
|
|
343
|
+
if (final) {
|
|
344
|
+
const context = parentId === undefined ? pulled ?? pushed : namedPush ? pushed : namedPull ? pulled : undefined;
|
|
345
|
+
const raw = text;
|
|
346
|
+
finalPriority = parseMarker(raw).priority;
|
|
347
|
+
// Strip before invocation routing, publication, journaling, digests or the console event tap.
|
|
348
|
+
text = stripRecordLines(raw);
|
|
349
|
+
let observable = !this.closed && this.peers.get(peer.id) === peer && !!context && opts?.private !== true && !remoteId(peer.id) && !opts?.to?.some(remoteId) && !answerParent;
|
|
350
|
+
try {
|
|
351
|
+
observable &&= this.opts.reviewObserverInputExcluded?.(peer.id, context!.originals) !== true &&
|
|
352
|
+
![...context!.out, ...context!.originals].some(env => env.private || isReviewObserverExcluded(env) || isInvocationKind(env) || remoteId(env.from) || env.to?.some(remoteId));
|
|
353
|
+
} catch { observable = false; }
|
|
354
|
+
if (observable) {
|
|
355
|
+
if (complete) try { this.onFinalAnswer?.(peer.id, raw, context!); } catch { /* capture is optional and never changes answer routing */ }
|
|
356
|
+
try { this.onFinalAnswerBytes?.(peer.id, { before: Buffer.byteLength(parseMarker(raw).body), after: Buffer.byteLength(parseMarker(text).body) }); } catch { /* count-only observer */ }
|
|
357
|
+
}
|
|
358
|
+
}
|
|
334
359
|
if (this.onAnswer && answerParent && (namedPush || namedPull || parentId === undefined && this.invocationTurnOpen(peer.id))) {
|
|
335
360
|
let taken = false;
|
|
336
361
|
try { taken = this.onAnswer(peer.id, text, answerParent.out) === true; } catch { taken = true; } // a throwing host never turns a callee's answer into a broadcast
|
|
337
362
|
if (taken) return;
|
|
338
363
|
}
|
|
339
|
-
const
|
|
364
|
+
const parsed = parseMarker(text), priority = finalPriority ?? parsed.priority, body = parsed.body;
|
|
340
365
|
if (!body) return;
|
|
341
366
|
// What the peer was handed differs from what it stands for once a delivery was condensed; both the audience
|
|
342
367
|
// and the priority ceiling are about what it stands for.
|
|
@@ -393,6 +418,19 @@ export class Bus {
|
|
|
393
418
|
if (hushed.length) this.note(peer.id, noteLine(HUB, "decision", `your message was not delivered to ${hushed.map((h) => h.peer).join(", ")}: ${hushed[0]!.reason}`));
|
|
394
419
|
return heldBack ? hushed[0]!.reason : published.dropped === "hop" ? published : undefined;
|
|
395
420
|
};
|
|
421
|
+
peer.onMessage = (text, opts) => {
|
|
422
|
+
if (this.peers.get(peer.id) !== peer) return;
|
|
423
|
+
const marker = finalMessage?.body === text && finalMessage.options === opts ? finalMessage : undefined;
|
|
424
|
+
if (marker) finalMessage = undefined; // Consume before observers can emit nested diagnostics.
|
|
425
|
+
return receive(text, opts, marker !== undefined, marker?.complete ?? true);
|
|
426
|
+
};
|
|
427
|
+
peer.onFinalAnswer = (text, opts, complete = true) => {
|
|
428
|
+
if (this.closed || this.peers.get(peer.id) !== peer) return;
|
|
429
|
+
const previous = finalMessage;
|
|
430
|
+
finalMessage = { body: text, options: opts, complete };
|
|
431
|
+
try { return peer.onMessage?.(text, opts); }
|
|
432
|
+
finally { finalMessage = previous; }
|
|
433
|
+
};
|
|
396
434
|
peer.onFailed = (envs, failure) => {
|
|
397
435
|
// The adapter got the condensed list; what has to come back is what that list replaced.
|
|
398
436
|
const last = this.lastDelivery.get(peer.id);
|
|
@@ -673,6 +711,18 @@ export class Bus {
|
|
|
673
711
|
return this.storageError ? undefined : this.journal?.heldDeliveryHints(peer, canExposeAccepted);
|
|
674
712
|
}
|
|
675
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
|
+
|
|
676
726
|
/** Whether timeout-originated holds still protect the recovery cause from supersession. */
|
|
677
727
|
hasAcceptedTimeoutHolds(): boolean {
|
|
678
728
|
if (this.closed || this.storageError || !this.journal) throw new Error("delivery timeout hold state unavailable");
|
package/src/hub/ci-watch.ts
CHANGED
|
@@ -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 =
|
|
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";
|