@staix/agent-hub 0.52.0 → 0.54.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 +37 -0
- package/README.md +4 -3
- package/docs/addons/open-code-review.md +3 -6
- package/docs/agent-notes/README.md +1 -1
- package/docs/agent-notes/adapters.md +5 -4
- package/docs/agent-notes/budget.md +2 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +6 -5
- package/docs/agent-notes/models.md +1 -1
- package/docs/agent-notes/tasks.md +3 -3
- package/docs/agent-notes/tests.md +4 -4
- package/docs/contracts/companion-cli-v2.json +90 -0
- package/docs/contracts/companion-cli-v3.json +348 -0
- package/docs/design/adapters.md +1 -1
- package/docs/design/agent-hub-architecture.md +8 -5
- package/docs/design/bus.md +1 -1
- package/docs/design/cli-output-inventory.md +4 -2
- package/docs/design/execution-reference.md +1 -1
- package/docs/design/guidance-experiments.md +1 -0
- package/docs/design/guidance-probes.md +1 -0
- package/docs/design/model-routes.md +20 -5
- package/docs/design/roadmap.md +6 -4
- package/docs/design/task-board.md +21 -2
- package/docs/dogfood.md +13 -6
- package/docs/events.md +1 -1
- package/docs/memory.md +2 -2
- package/docs/operations.md +158 -50
- package/docs/quickstart.md +14 -2
- package/docs/security.md +17 -9
- package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
- package/docs/specs/2026-09-19-multi-project-design.md +1 -1
- package/docs/specs/2026-09-20-upgrade-recovery-design.md +24 -0
- package/docs/specs/2026-12-04-arev-adoption-design.md +84 -0
- package/docs/specs/mcp-endpoint.md +15 -4
- package/docs/specs/relay-contract.md +38 -0
- package/docs/verification/2026-12-04-host-shared-receipts.md +43 -0
- package/docs/verification/2026-12-05-0.53.0.md +101 -0
- package/docs/verification/2026-12-05-agy-1.5.24.md +55 -0
- package/docs/verification/2026-12-05-claude-implementer-2.1.337.md +43 -0
- package/docs/verification/2026-12-06-0.54.0.md +76 -0
- package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
- package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
- package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
- package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
- package/docs/verified.json +38 -29
- package/package.json +9 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/.mcp.json +1 -1
- package/plugins/agent-hub/compat.json +9 -5
- package/plugins/agent-hub/kimi-hook.js +892 -874
- package/plugins/agent-hub/relay-launcher.js +24 -0
- package/plugins/agent-hub/server.js +27271 -25146
- package/src/adapters/acp-session-model.ts +1 -1
- package/src/adapters/acp.ts +5 -4
- package/src/adapters/agy/definition.ts +1 -1
- package/src/adapters/agy/hooks.ts +1 -1
- package/src/adapters/channel-peer.ts +3 -1
- package/src/adapters/claude-channel-evidence.ts +26 -1
- package/src/adapters/claude-channel.ts +27 -30
- package/src/adapters/claude-connection-policy.ts +62 -0
- package/src/adapters/claude-relay.ts +255 -0
- package/src/adapters/codex-review-isolation.ts +1 -2
- package/src/adapters/compat.ts +28 -18
- package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
- package/src/adapters/definitions/native-config-defaults.ts +1 -1
- package/src/adapters/definitions/native-context.ts +1 -2
- package/src/adapters/definitions/native-factories.ts +4 -1
- package/src/adapters/definitions/native-quota.ts +1 -1
- package/src/adapters/definitions/native-recovery.ts +3 -1
- package/src/adapters/external-modules.ts +2 -2
- package/src/adapters/kimi-review.ts +1 -1
- package/src/adapters/kimi-tui-facts.ts +1 -1
- package/src/adapters/local-worker.ts +3 -3
- package/src/adapters/native-capabilities.ts +1 -1
- package/src/adapters/pi.ts +26 -7
- package/src/adapters/registry-types.ts +2 -0
- package/src/adapters/relay-launcher.ts +27 -0
- package/src/adapters/reviewer-mcp.ts +1 -1
- package/src/cli/agents.ts +20 -8
- package/src/cli/agy-mcp.ts +1 -1
- package/src/cli/claude-profile-hook.ts +1 -1
- package/src/cli/command-table.ts +1 -0
- package/src/cli/commands/agents.ts +18 -1
- package/src/cli/commands/doctor.ts +18 -4
- package/src/cli/commands/launch-line.ts +32 -0
- package/src/cli/commands/status.ts +14 -3
- package/src/cli/help.ts +7 -4
- package/src/cli/identity.ts +1 -1
- package/src/cli/init-roles.ts +1 -1
- package/src/cli/init-settings.ts +1 -1
- package/src/cli/launch-line-plan.ts +82 -0
- package/src/cli/launch-line-project.ts +13 -0
- package/src/cli/main.ts +10 -9
- package/src/cli/pi-steps-warning.ts +14 -0
- package/src/cli/recovery-package.ts +60 -6
- package/src/cli/reset.ts +1 -1
- package/src/cli/shell-quote.ts +1 -3
- package/src/cli/upgrade-interactive.ts +7 -2
- package/src/cli/upgrade-keep-plan.ts +47 -0
- package/src/cli/upgrade-restore-state.ts +1 -1
- package/src/cli/upgrade-runtime.ts +119 -18
- package/src/cli/upgrade.ts +17 -2
- package/src/hub/accounts.ts +8 -4
- package/src/hub/action-class.ts +1 -3
- package/src/hub/adec-triage.ts +105 -0
- package/src/hub/autonomy.ts +1 -1
- package/src/hub/board.ts +3 -27
- package/src/hub/bus.ts +39 -6
- package/src/hub/capabilities.ts +1 -1
- package/src/hub/channel-project-base.ts +46 -0
- package/src/hub/channel-project.ts +21 -46
- package/src/hub/config-apply.ts +1 -1
- package/src/hub/config-edit.ts +1 -1
- package/src/hub/config-tier.ts +1 -1
- package/src/hub/config.ts +2 -2
- package/src/hub/confirmation-matrix.ts +1 -1
- package/src/hub/control/board-messages.ts +415 -0
- package/src/hub/control/dashboard-messages.ts +221 -0
- package/src/hub/control/delivery-messages.ts +356 -0
- package/src/hub/control/dispatch.ts +114 -0
- package/src/hub/control/hub-tool-helpers.ts +243 -0
- package/src/hub/control/hub-tools.ts +147 -0
- package/src/hub/control/native-messages.ts +665 -0
- package/src/hub/control/operations-messages.ts +269 -0
- package/src/hub/control/peer-messages.ts +126 -0
- package/src/hub/control/recovery-messages.ts +391 -0
- package/src/hub/control/recovery-operation.ts +480 -0
- package/src/hub/control/scope.ts +460 -0
- package/src/hub/control/sdlc-messages.ts +373 -0
- package/src/hub/control/task-ops-more.ts +245 -0
- package/src/hub/control/task-ops.ts +553 -0
- package/src/hub/control/ui-actions.ts +241 -0
- package/src/hub/control-write-trace.ts +1 -4
- package/src/hub/daemon.ts +485 -4324
- package/src/hub/delivery-hints.ts +2 -0
- package/src/hub/delivery-journal.ts +17 -6
- package/src/hub/events.ts +2 -1
- package/src/hub/execution-reference.ts +1 -1
- package/src/hub/host.ts +41 -9
- package/src/hub/hub-tools.ts +3 -4
- package/src/hub/invocations.ts +1 -1
- package/src/hub/lifecycle.ts +4 -3
- package/src/hub/mcp-endpoint-serve.ts +4 -3
- package/src/hub/mcp-endpoint.ts +15 -6
- package/src/hub/memory-profile-check.ts +1 -1
- package/src/hub/no-writes.ts +1 -1
- package/src/hub/peers.ts +2 -0
- package/src/hub/pi-exit-policy.ts +27 -0
- package/src/hub/progress.ts +1 -1
- package/src/hub/project-runtime-state.ts +17 -4
- package/src/hub/project-runtime.ts +3 -1
- package/src/hub/protocol-window.ts +1 -1
- package/src/hub/recovery-continuity.ts +3 -3
- package/src/hub/recovery-kept-roster.ts +50 -0
- package/src/hub/review-anchor.ts +13 -181
- package/src/hub/review-brief.ts +78 -28
- package/src/hub/review-findings.ts +15 -193
- package/src/hub/review-ledger.ts +162 -0
- package/src/hub/review-material.ts +3 -3
- package/src/hub/reviewer-pool.ts +4 -2
- package/src/hub/roadmap-issue-states.ts +65 -14
- package/src/hub/roadmap-sync.ts +39 -14
- package/src/hub/routing.ts +9 -0
- package/src/hub/runtime-capture-prune.ts +8 -2
- package/src/hub/runtime-package-assets.ts +3 -0
- package/src/hub/sdlc-release-policy.ts +1 -2
- package/src/hub/settings.ts +1 -1
- package/src/hub/spec-ack-tool.ts +4 -0
- package/src/hub/spec-report-history.ts +36 -0
- package/src/hub/specs.ts +1 -4
- package/src/hub/supervision.ts +33 -6
- package/src/hub/tasks-audit.ts +390 -0
- package/src/hub/tasks-backlog.ts +522 -0
- package/src/hub/tasks-handoff.ts +208 -0
- package/src/hub/tasks-release.ts +257 -0
- package/src/hub/tasks-roadmap.ts +17 -3
- package/src/hub/tasks-specs.ts +672 -0
- package/src/hub/tasks-types.ts +334 -0
- package/src/hub/tasks.ts +286 -1961
- package/src/hub/upgrade-session-contract.ts +11 -0
- package/src/local/probe-sandbox.ts +1 -2
- package/src/local/probe-workspace.ts +1 -1
- package/src/models/route/config.ts +4 -4
- package/src/models/route/decision.ts +18 -10
- package/src/models/route/observation-signals.ts +1 -2
- package/src/models/route/runtime.ts +8 -5
- package/src/npm-artifact.ts +76 -0
- package/src/omniroute/client.ts +6 -0
- package/src/pi/extension.ts +5 -2
- package/src/pi/install.ts +77 -0
- package/src/pi/pin.ts +49 -0
- package/src/primitives.ts +14 -0
- package/src/version.ts +2 -0
- package/templates/adec/README.md +10 -6
- package/templates/config.json +1 -1
- package/templates/specs.block.md +1 -0
package/src/hub/routing.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { contextHeadroom, type ContextAdmission } from "./context-window.ts";
|
|
2
|
+
import { DEFAULT_TRIAGE_ENDPOINT, isTriageEndpoint } from "./adec-triage.ts";
|
|
2
3
|
import { queueBackpressure, type QueueBackpressureCode, type QueueBackpressurePolicy, type QueuePressure } from "./queue-backpressure.ts";
|
|
3
4
|
import { selectReviewerPool, type ReviewerPoolSelection } from "./reviewer-pool.ts";
|
|
4
5
|
import type { ReviewBudgetSnapshot } from "./review-budget.ts";
|
|
@@ -37,6 +38,8 @@ export interface Routing {
|
|
|
37
38
|
local: { route?: string; fixed_model: string };
|
|
38
39
|
/** Loader-owned diagnostics for ignored legacy routing tables. */
|
|
39
40
|
retired?: string[];
|
|
41
|
+
/** #1936: the person's switch for adec triage, read from routing.toml only (the overlay cannot set it). */
|
|
42
|
+
inference: { triage_adec: "off" | "shadow" | "enforce"; triage_adec_endpoint: string };
|
|
40
43
|
hub_routes?: Record<string, HubRoute>;
|
|
41
44
|
/** Session-aware stay/switch for `hub/auto` and hub stage routes (#197). */
|
|
42
45
|
stay_switch: StaySwitchMode;
|
|
@@ -251,8 +254,14 @@ export function parseRouting(text: string, overlay?: RoutingOverlay): Routing {
|
|
|
251
254
|
if (nested) throw new Error(`routing.toml: ${nested} is inside a table; stay_switch and max_switch_prefill_tokens are top-level keys, before any table`);
|
|
252
255
|
if (!["off", "shadow", "enforce"].includes(stay_switch)) throw new Error('routing.toml: stay_switch must be "off", "shadow" or "enforce" (a top-level key, before any table)');
|
|
253
256
|
if (!(Number.isSafeInteger(max_switch_prefill_tokens) && max_switch_prefill_tokens > 0)) throw new Error("routing.toml: max_switch_prefill_tokens must be a positive integer");
|
|
257
|
+
const rawInference = ((raw as Record<string, unknown>).inference ?? {}) as Record<string, unknown>;
|
|
258
|
+
for (const name of Object.keys(rawInference)) if (name !== "triage_adec" && name !== "triage_adec_endpoint") throw new Error(`routing.toml: [inference] ${name} is not a key; use triage_adec or triage_adec_endpoint`);
|
|
259
|
+
const triageAdec = rawInference.triage_adec ?? "off", triageEndpoint = rawInference.triage_adec_endpoint ?? DEFAULT_TRIAGE_ENDPOINT;
|
|
260
|
+
if (triageAdec !== "off" && triageAdec !== "shadow" && triageAdec !== "enforce") throw new Error('routing.toml: [inference] triage_adec must be "off", "shadow" or "enforce"');
|
|
261
|
+
if (!isTriageEndpoint(triageEndpoint)) throw new Error("routing.toml: [inference] triage_adec_endpoint must be an HTTP numeric loopback /v1/systemone URL without credentials, query or fragment");
|
|
254
262
|
return {
|
|
255
263
|
local: raw.local,
|
|
264
|
+
inference: { triage_adec: triageAdec, triage_adec_endpoint: triageEndpoint },
|
|
256
265
|
...(retired.length ? { retired } : {}),
|
|
257
266
|
hub_routes: parseHubRoutes(raw.hub_routes),
|
|
258
267
|
stay_switch,
|
|
@@ -10,7 +10,7 @@ import { hubHome, realPath } from "./project.ts";
|
|
|
10
10
|
import { readProjectRuntimeReference, projectRuntimeFile } from "./project-runtime-state.ts";
|
|
11
11
|
import { Registry, REGISTRY_DB_BUSY_TIMEOUT_MS } from "./registry.ts";
|
|
12
12
|
import { anyRecoveryHold, retireOperation } from "./recovery-store.ts";
|
|
13
|
-
import { MEMORY_RUNTIME_LAYOUTS } from "./runtime-package-assets.ts";
|
|
13
|
+
import { MEMORY_RUNTIME_LAYOUTS, REVIEW_RUNTIME_LAYOUT } from "./runtime-package-assets.ts";
|
|
14
14
|
|
|
15
15
|
export interface RuntimeCapturePrunePlan { remove: string[]; kept: string[]; deferred?: string }
|
|
16
16
|
export interface RuntimeCapturePruneResult { removed: string[]; kept: string[]; quarantined?: string[]; deferred?: string }
|
|
@@ -285,7 +285,13 @@ function captureLayout(root: string): void {
|
|
|
285
285
|
if (optionalInfo(modules)) {
|
|
286
286
|
knownLayout(modules, ["@staix"], []);
|
|
287
287
|
const scope = join(modules, "@staix"), layouts = Object.entries(MEMORY_RUNTIME_LAYOUTS);
|
|
288
|
-
knownLayout(scope, ["agent-mem"], [], layouts.map(([name]) => basename(name)));
|
|
288
|
+
knownLayout(scope, ["agent-mem"], [], [...layouts.map(([name]) => basename(name)), "agent-review"]);
|
|
289
|
+
const review = join(scope, "agent-review");
|
|
290
|
+
if (optionalInfo(review)) {
|
|
291
|
+
const hub = metadata(join(root, "package.json")) as { dependencies?: Record<string, unknown> } | null;
|
|
292
|
+
if (typeof hub?.dependencies?.["@staix/agent-review"] !== "string") fail("a runtime capture contains an undeclared AREV dependency");
|
|
293
|
+
knownLayout(review, REVIEW_RUNTIME_LAYOUT.directories, REVIEW_RUNTIME_LAYOUT.files);
|
|
294
|
+
}
|
|
289
295
|
const memory = join(scope, "agent-mem");
|
|
290
296
|
knownLayout(memory, ["src", "bin"], ["package.json", "README.md", "LICENSE"]);
|
|
291
297
|
const present = layouts.filter(([name]) => optionalInfo(join(scope, basename(name))));
|
|
@@ -4,3 +4,6 @@ export const MEMORY_RUNTIME_LAYOUTS = {
|
|
|
4
4
|
"@staix/mcp-stdio": { directories: ["src", "fixtures"], files: ["package.json", "README.md", "LICENSE"] },
|
|
5
5
|
"@staix/agent-hosts": { directories: ["src", "fixtures"], files: ["package.json", "README.md", "LICENSE"] },
|
|
6
6
|
} as const;
|
|
7
|
+
|
|
8
|
+
/** AREV's core entry is pure application code. The CLI and its transport are excluded. */
|
|
9
|
+
export const REVIEW_RUNTIME_LAYOUT = { directories: ["src"], files: ["package.json"] } as const;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { asRecord as record } from "../primitives.ts";
|
|
1
2
|
import type { ReleaseGit } from "./sdlc-release.ts";
|
|
2
3
|
|
|
3
4
|
export type ReleaseVersionPolicy =
|
|
@@ -13,8 +14,6 @@ export const DEFAULT_RELEASE_POLICY: ReleasePolicy = {
|
|
|
13
14
|
};
|
|
14
15
|
export const DEFAULT_RELEASE_NOTES_PATH = "docs/releases/v{version}.md";
|
|
15
16
|
|
|
16
|
-
const record = (value: unknown): Record<string, unknown> | undefined =>
|
|
17
|
-
!!value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
18
17
|
|
|
19
18
|
function checkedNotesPath(value: unknown): string {
|
|
20
19
|
if (typeof value !== "string" || value.length > 1024 || !value.includes("{version}")
|
package/src/hub/settings.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { PERMISSION_MODES, permissionBoundary } from "./permission-mode.ts";
|
|
|
18
18
|
import { START_MODES } from "./start-mode.ts";
|
|
19
19
|
import { checkStartAgents } from "./start-agents.ts";
|
|
20
20
|
import { OVERLAY_FILE, overlayToml, parseOverlay, parseRouting, routingText, type Routing, type RoutingOverlay } from "./routing.ts";
|
|
21
|
+
import { isRecord as isObject } from "../primitives.ts";
|
|
21
22
|
|
|
22
23
|
/**
|
|
23
24
|
* #269: the settings a person may change from the dashboard or `ahub settings`. A key that is not in SETTINGS cannot be
|
|
@@ -277,7 +278,6 @@ const readText = (file: string): string | null => {
|
|
|
277
278
|
throw new Error(`.agenthub/${basename(file)} could not be read (${(error as NodeJS.ErrnoException).code ?? "unknown error"})`);
|
|
278
279
|
}
|
|
279
280
|
};
|
|
280
|
-
const isObject = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
281
281
|
function parseObject(text: string, name: string): Record<string, unknown> {
|
|
282
282
|
let doc: unknown;
|
|
283
283
|
try { doc = JSON.parse(text); } catch { throw new Error(`.agenthub/${name} is not valid JSON; fix it in your editor first`); }
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export const specAck = { type: "array", maxItems: 20, items: { type: "object", properties: { id: { type: "string", minLength: 1, maxLength: 160 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, required: ["id", "reason"], additionalProperties: false } } as const;
|
|
2
|
+
|
|
3
|
+
export const specAckDescription = "Owner or configured conductor: add public reasons for unchanged covering specs at the filed head. The existing review and approval remain bound.";
|
|
4
|
+
export const specAckFields = { id: { type: "integer", minimum: 1 }, head: { type: "string", pattern: "^[a-f0-9]{40}$" }, spec_ack: { ...specAck, minItems: 1 } };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { HistoryEntry, SpecRef, SpecTaskReport, Task } from "./board.ts";
|
|
2
|
+
|
|
3
|
+
export function specReportHistory(report: unknown, binding: unknown, event: string, task: Task): Pick<HistoryEntry, "specReport" | "specRefBinding"> {
|
|
4
|
+
if (!report || typeof report !== "object" || Array.isArray(report) || !["done", "done (checking)", "spec acknowledged"].includes(event)
|
|
5
|
+
|| typeof binding !== "string" || !/^[a-f0-9]{64}$/.test(binding)) throw new Error("invalid task spec report metadata");
|
|
6
|
+
const value = report as Record<string, unknown>;
|
|
7
|
+
if (Object.keys(value).some(key => !["head", "complete", "errors", "unchanged", "changed", "truncated", "reason"].includes(key))
|
|
8
|
+
|| typeof value.head !== "string" || value.head !== "" && !/^[a-f0-9]{40}$/.test(value.head)
|
|
9
|
+
|| value.head === "" && value.complete !== false || typeof value.complete !== "boolean"
|
|
10
|
+
|| !Number.isSafeInteger(value.errors) || (value.errors as number) < 0 || (value.errors as number) > 1_000_000
|
|
11
|
+
|| value.truncated !== undefined && value.truncated !== true
|
|
12
|
+
|| value.reason !== undefined && (typeof value.reason !== "string" || value.reason.length > 500 || /[\p{Cc}\p{Cf}]/u.test(value.reason))
|
|
13
|
+
|| !Array.isArray(value.unchanged) || value.unchanged.length > 20 || !Array.isArray(value.changed) || value.changed.length > 20) throw new Error("invalid task spec report metadata");
|
|
14
|
+
const ref = (raw: unknown): SpecRef => {
|
|
15
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("invalid task spec report metadata");
|
|
16
|
+
const row = raw as Record<string, unknown>;
|
|
17
|
+
if (Object.keys(row).some(key => !["id", "path", "title", "reason"].includes(key))
|
|
18
|
+
|| typeof row.id !== "string" || !row.id.trim() || row.id.length > 160 || /[\p{Cc}\p{Cf}]/u.test(row.id)
|
|
19
|
+
|| typeof row.path !== "string" || !row.path.trim() || row.path.length > 1000 || /[\p{Cc}\p{Cf}]/u.test(row.path)
|
|
20
|
+
|| typeof row.title !== "string" || !row.title.trim() || row.title.length > 1000 || /[\p{Cc}\p{Cf}]/u.test(row.title)
|
|
21
|
+
|| row.reason !== undefined && (typeof row.reason !== "string" || row.reason.length > 1000 || /[\p{Cc}\p{Cf}]/u.test(row.reason))) throw new Error("invalid task spec report metadata");
|
|
22
|
+
return { id: row.id, path: row.path, title: row.title, ...(typeof row.reason === "string" ? { reason: row.reason } : {}) };
|
|
23
|
+
};
|
|
24
|
+
const specReport: SpecTaskReport = { head: value.head, complete: value.complete, errors: value.errors as number,
|
|
25
|
+
unchanged: value.unchanged.map(ref), changed: value.changed.map(ref), ...(value.truncated === true ? { truncated: true } : {}), ...(typeof value.reason === "string" ? { reason: value.reason } : {}) };
|
|
26
|
+
if (event === "spec acknowledged") {
|
|
27
|
+
const index = task.history.findLastIndex(entry => entry.event === "done" || entry.event === "done (checking)");
|
|
28
|
+
const filing = task.history[index];
|
|
29
|
+
if (!filing || filing.specRefBinding !== binding || filing.specReport?.head !== specReport.head) throw new Error("filed spec report changed; read hub_task_show and retry hub_spec_ack");
|
|
30
|
+
const reasons = new Map(specReport.unchanged.filter(spec => spec.reason).map(spec => [spec.id, spec.reason]));
|
|
31
|
+
const unchanged = filing.specReport.unchanged.map(spec => !spec.reason?.trim() && reasons.has(spec.id) ? { ...spec, reason: reasons.get(spec.id) } : spec);
|
|
32
|
+
task.history[index] = { ...filing, specReport: { ...filing.specReport, unchanged } };
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
return { specReport, specRefBinding: binding };
|
|
36
|
+
}
|
package/src/hub/specs.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { join, relative, resolve } from "node:path";
|
|
|
5
5
|
import { hubGitSync } from "./git.ts";
|
|
6
6
|
import { realPath } from "./project.ts";
|
|
7
7
|
import { parseSpecsConfig, type SpecsConfig } from "./specs-config.ts";
|
|
8
|
+
import { isRecord } from "../primitives.ts";
|
|
8
9
|
|
|
9
10
|
export { DEFAULT_SPECS_CONFIG, parseSpecsConfig, type SpecsConfig, type SpecsReview } from "./specs-config.ts";
|
|
10
11
|
|
|
@@ -141,10 +142,6 @@ function item(severity: SpecsSeverity, code: string, message: string, cause: str
|
|
|
141
142
|
return { severity, code, message, cause, nextSteps, ...extra };
|
|
142
143
|
}
|
|
143
144
|
|
|
144
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
145
|
-
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
145
|
function isSafeRepoPath(value: string): boolean {
|
|
149
146
|
return value.length > 0 && value.length <= 1024 && !value.startsWith("/") && !value.startsWith("-")
|
|
150
147
|
&& !/^[A-Za-z]:/.test(value) && !value.includes("\\") && !/[\u0000-\u001f\u007f]/.test(value)
|
package/src/hub/supervision.ts
CHANGED
|
@@ -44,9 +44,14 @@ export interface SupervisionDeps {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
/** Deterministic milestone producer. The Bus alone owns batching, retry and native turns. */
|
|
47
|
+
/** #1946: the delivery id a hold notice key names, for the first notice and its one `:repeat`; undefined for any other key. */
|
|
48
|
+
export const holdNoticeDelivery = (key: string): string | undefined => key.match(/:hold:[^:]+:([^:]+?)(?::repeat)?$/)?.[1];
|
|
49
|
+
|
|
47
50
|
export class SupervisionFeed {
|
|
48
51
|
private readonly approvals = new Set<string>();
|
|
49
52
|
private readonly holds = new Set<string>();
|
|
53
|
+
private readonly holdSentAt = new Map<string, number>();
|
|
54
|
+
private readonly holdRepeated = new Set<string>();
|
|
50
55
|
private readonly rounds = new Map<string, string>();
|
|
51
56
|
/** #1738: the key of the last round check that sent nothing; never set after a refused send, which must stay retryable. */
|
|
52
57
|
private quietRound: string | undefined;
|
|
@@ -59,7 +64,7 @@ export class SupervisionFeed {
|
|
|
59
64
|
/** Pending notices may have been withdrawn on role/off change; live requests can notify again on regrant. */
|
|
60
65
|
resetPending(peer: string): void {
|
|
61
66
|
for (const key of this.approvals) if (key.startsWith(`${peer}:`)) this.approvals.delete(key);
|
|
62
|
-
for (const key of this.holds) if (key.startsWith(`${peer}:`)) this.holds.delete(key);
|
|
67
|
+
for (const key of this.holds) if (key.startsWith(`${peer}:`)) { this.holds.delete(key); this.holdSentAt.delete(key); this.holdRepeated.delete(key); }
|
|
63
68
|
}
|
|
64
69
|
|
|
65
70
|
private recipient(): string | undefined {
|
|
@@ -157,13 +162,35 @@ export class SupervisionFeed {
|
|
|
157
162
|
return sent;
|
|
158
163
|
}
|
|
159
164
|
|
|
160
|
-
|
|
165
|
+
/**
|
|
166
|
+
* The hold notice for a needs_review row. #1946: the conductor may run `ahub queue resolve` for a plain row, so the notice says so; an invocation row stays person-only.
|
|
167
|
+
* It repeats once after `afterMs` while the row is still held, then stops. A thunk is built only when a notice is sent, not on every tick.
|
|
168
|
+
*/
|
|
169
|
+
needsReview(peer: string, deliveryId: string, command: string | (() => string) = () => queueResolveCommand({ id: deliveryId, peer }), opts?: { personOnly?: boolean; afterMs: number }): boolean {
|
|
161
170
|
const conductor = this.recipient();
|
|
162
171
|
const key = `${conductor}:${peer}:${deliveryId}`;
|
|
163
|
-
if (!conductor
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
172
|
+
if (!conductor) return false;
|
|
173
|
+
if (!opts) { // a row that holds the peer wide keeps the notice it always had
|
|
174
|
+
if (this.holds.has(key)) return false;
|
|
175
|
+
const sent = this.send(`hold:${peer}:${deliveryId}`, `${peer}: needs_review hold; delivery ${deliveryId}; give the person this command exactly as printed: ${typeof command === "string" ? command : command()}`, "important");
|
|
176
|
+
if (sent) this.holds.add(key);
|
|
177
|
+
return sent;
|
|
178
|
+
}
|
|
179
|
+
const text = (prefix: string) => `${peer}: needs_review hold; delivery ${deliveryId}; ${prefix}${opts.personOnly
|
|
180
|
+
? "an invocation row is person-only: give the person this command exactly as printed"
|
|
181
|
+
: "you, the conductor, may run this command exactly as printed (the person may too)"}: ${typeof command === "string" ? command : command()}`;
|
|
182
|
+
if (!this.holds.has(key)) {
|
|
183
|
+
const sent = this.send(`hold:${peer}:${deliveryId}`, text(""), "important");
|
|
184
|
+
if (sent) { this.holds.add(key); this.holdSentAt.set(key, this.d.now?.() ?? Date.now()); }
|
|
185
|
+
return sent;
|
|
186
|
+
}
|
|
187
|
+
const at = this.holdSentAt.get(key);
|
|
188
|
+
if (opts.afterMs > 0 && at !== undefined && !this.holdRepeated.has(key) && (this.d.now?.() ?? Date.now()) - at >= opts.afterMs) {
|
|
189
|
+
const sent = this.send(`hold:${peer}:${deliveryId}:repeat`, text("still unresolved; "), "important");
|
|
190
|
+
if (sent) this.holdRepeated.add(key);
|
|
191
|
+
return sent;
|
|
192
|
+
}
|
|
193
|
+
return false;
|
|
167
194
|
}
|
|
168
195
|
|
|
169
196
|
checkRound(): boolean {
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
// #1830 S4e-4: the audit and evidence methods. Tasks owns the board writes and supplies the host operations.
|
|
2
|
+
import type { taskShowAllowed } from "./conductor.ts";
|
|
3
|
+
import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceReceipt, type EvidenceLinkV1 } from "./research-evidence.ts";
|
|
4
|
+
import { evidenceOriginKeys, type EvidenceSourceRead } from "./source-read.ts";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { SECURITY_CHECKLIST } from "./security-pass.ts";
|
|
7
|
+
import { AUDIT_PROFILES, applyUnitReports, auditBrief, auditFindingView, auditIsPartial, auditSummary, parseUnitReports, seedLedger, settlementRefusal, SETTLEMENTS, unitId, verificationRefusal, type AuditProfile, type AuditSummary, type CarryLookup } from "./security-audit.ts";
|
|
8
|
+
import { type AuditSource } from "./audit-source.ts";
|
|
9
|
+
import { matchConfigPath } from "./eval-gate.ts";
|
|
10
|
+
import { DEFAULT_MAX_NITS, parseReviewFindings, type ReviewFinding } from "./review-findings.ts";
|
|
11
|
+
import { taskClaimIdentity, isClosedTaskState, type Board, type Task } from "./board.ts";
|
|
12
|
+
import { USER, type PeerId } from "./envelope.ts";
|
|
13
|
+
import { PreEffectToolRefusal } from "./tool-refusal.ts";
|
|
14
|
+
import { type ReviewBrief } from "./review-brief.ts";
|
|
15
|
+
import { type ReviewCheckoutEvidence } from "./review-checkout.ts";
|
|
16
|
+
import { sdlcConfig } from "./sdlc.ts";
|
|
17
|
+
import { type EvidenceReadOrigins, type EvidenceReadResult, type AuditView } from "./tasks-types.ts";
|
|
18
|
+
import type { Tasks } from "./tasks.ts";
|
|
19
|
+
import type { TasksDeps } from "./tasks-types.ts";
|
|
20
|
+
|
|
21
|
+
interface AuditHost {
|
|
22
|
+
taskShowAllowed: typeof taskShowAllowed;
|
|
23
|
+
cancel: Tasks["cancel"];
|
|
24
|
+
configuredManualConductor: (by: PeerId) => boolean;
|
|
25
|
+
consideredBrief: Tasks["consideredBrief"];
|
|
26
|
+
isConfiguredPlanner: Tasks["isConfiguredPlanner"];
|
|
27
|
+
readonly isPii: Tasks["isPii"];
|
|
28
|
+
readonly nameable: Tasks["nameable"];
|
|
29
|
+
propose: Tasks["propose"];
|
|
30
|
+
readonly publicMetadataText: Tasks["publicMetadataText"];
|
|
31
|
+
recordConsideredAfter: Tasks["recordConsideredAfter"];
|
|
32
|
+
releaseNotice: (line: string) => void;
|
|
33
|
+
readonly repositories: Tasks["repositories"];
|
|
34
|
+
requestCheck: Tasks["requestCheck"];
|
|
35
|
+
requireLocalTaskPeer: (peer: unknown) => void;
|
|
36
|
+
saveAuditApply: Board["auditApply"];
|
|
37
|
+
saveAuditCreate: Board["auditCreate"];
|
|
38
|
+
saveEvidenceLink: Board["recordEvidenceLink"];
|
|
39
|
+
screenCall: Tasks["screenCall"];
|
|
40
|
+
readonly screenOn: Tasks["screenOn"];
|
|
41
|
+
studyFields: Tasks["studyFields"];
|
|
42
|
+
studyHold: Tasks["studyHold"];
|
|
43
|
+
studyParent: Tasks["studyParent"];
|
|
44
|
+
studySource: Tasks["studySource"];
|
|
45
|
+
studyWrite: Tasks["studyWrite"];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class AuditDomain {
|
|
49
|
+
constructor(private readonly d: TasksDeps, private readonly host: AuditHost) {}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* #1646 T2: what the checkout the reviewer read held, read from the brief's own reviewed paths. The reviewing session's own
|
|
53
|
+
* checkout is read and named when the host resolved one; otherwise the project checkout is read and named as such, so a later
|
|
54
|
+
* count separates a reviewer that read other bytes from a hub that looked at the root. A port that cannot answer, or a known
|
|
55
|
+
* checkout it cannot read, leaves the verdict with no evidence: an unread checkout is unknown, never clean.
|
|
56
|
+
*/
|
|
57
|
+
checkoutEvidence(brief: ReviewBrief, reviewer: PeerId): ReviewCheckoutEvidence | undefined {
|
|
58
|
+
const paths = brief.reviewable.map(file => file.path);
|
|
59
|
+
const peer = this.d.reviewerCheckout?.(reviewer);
|
|
60
|
+
if (peer) {
|
|
61
|
+
const reads = peer.readsAt?.(brief.head, paths);
|
|
62
|
+
// The hub knows where this reviewer read: when that checkout cannot answer, the project checkout is not a substitute.
|
|
63
|
+
return reads ? { source: "peer-cwd", head: peer.head() ?? null, differing: reads.differing, untracked: reads.untracked } : undefined;
|
|
64
|
+
}
|
|
65
|
+
const root = this.d.auditSource, reads = root?.readsAt?.(brief.head, paths);
|
|
66
|
+
return reads ? { source: "project-root", head: root?.head() ?? null, differing: reads.differing, untracked: reads.untracked } : undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Resolve declared provenance afresh, without manufacturing a #901 judgment or synthesis readiness. */
|
|
70
|
+
async evidenceRead(by: PeerId, input: unknown): Promise<EvidenceReadResult> {
|
|
71
|
+
const refuse = () => new PreEffectToolRefusal("evidence read unavailable; use a current evidence id on a research task visible through hub_task_show");
|
|
72
|
+
try { this.host.requireLocalTaskPeer(by); } catch { throw refuse(); }
|
|
73
|
+
if (this.d.profile !== "research") throw refuse();
|
|
74
|
+
const check = this.host.requestCheck(by, () => this.host.studyHold());
|
|
75
|
+
let id: string, revision: number | undefined;
|
|
76
|
+
try {
|
|
77
|
+
const fields = this.host.studyFields(input, ["id", "revision"]);
|
|
78
|
+
if (Object.values(Object.getOwnPropertyDescriptors(input)).some(field => !field.enumerable)
|
|
79
|
+
|| typeof fields.id !== "string" || !/^ev:[a-f0-9]{32}$/.test(fields.id)
|
|
80
|
+
|| fields.revision !== undefined && (typeof fields.revision !== "number" || !Number.isSafeInteger(fields.revision) || fields.revision < 1)) throw refuse();
|
|
81
|
+
id = fields.id; revision = fields.revision as number | undefined;
|
|
82
|
+
} catch { throw refuse(); }
|
|
83
|
+
return this.host.studyWrite(async () => {
|
|
84
|
+
check(); const link = this.d.board.evidenceLink(this.d.project, id, revision);
|
|
85
|
+
if (!link) throw refuse();
|
|
86
|
+
const receipt = { id: link.id, revision: link.revision, taskId: link.taskId };
|
|
87
|
+
const stub = (status: "private" | "stale" | "unavailable" | "withdrawn"): EvidenceReadResult => ({ ...receipt, status });
|
|
88
|
+
const context = () => {
|
|
89
|
+
check(); let task: Task;
|
|
90
|
+
try { task = this.host.studyParent(link.taskId); } catch { throw refuse(); }
|
|
91
|
+
if (task.profile !== "research" || by !== USER && !this.host.taskShowAllowed(by, task, this.d.roles, this.host.isConfiguredPlanner(by))) throw refuse();
|
|
92
|
+
let status: "private" | "stale" | "unavailable" | undefined;
|
|
93
|
+
try {
|
|
94
|
+
if (this.d.privateTurn?.(by) || task.signals.includes("pii") || task.signals.includes("pii_path") || this.host.isPii(task)
|
|
95
|
+
|| this.host.publicMetadataText(evidenceLinkCanonical(link)) !== true) status = "private";
|
|
96
|
+
} catch { status = "private"; }
|
|
97
|
+
if (!status) {
|
|
98
|
+
try { const identity = taskClaimIdentity(task, Number(link.claimId.split(":").at(-1))); if (identity.claimId !== link.claimId || identity.claimRevision !== link.claimRevision) status = "stale"; }
|
|
99
|
+
catch { status = "stale"; }
|
|
100
|
+
}
|
|
101
|
+
const source = this.host.studySource(link.sourceId);
|
|
102
|
+
if (source?.private) status = "private";
|
|
103
|
+
else if (!status && !source) status = "unavailable";
|
|
104
|
+
else if (!status && source?.sha256 !== link.rawSha256) status = "stale";
|
|
105
|
+
return { task, status, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.plan?.claims, source]) };
|
|
106
|
+
};
|
|
107
|
+
const before = context(); if (before.status) return stub(before.status);
|
|
108
|
+
if (link.status === "withdrawn") return stub("withdrawn");
|
|
109
|
+
if (!this.d.evidenceSourceRead) return stub("unavailable");
|
|
110
|
+
const current = () => { try { const next = context(); return !next.status && next.key === before.key; } catch { return false; } };
|
|
111
|
+
// A returned passage can be quoted by any later tool or final answer in this input.
|
|
112
|
+
// Reuse the host review-input exclusion before crossing the async read boundary.
|
|
113
|
+
try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return stub("unavailable"); }
|
|
114
|
+
let read: EvidenceSourceRead;
|
|
115
|
+
try { read = await this.d.evidenceSourceRead(by, link, current); }
|
|
116
|
+
catch { check(); const after = context(); return stub(after.status ?? "unavailable"); }
|
|
117
|
+
check(); const after = context();
|
|
118
|
+
if (after.status) return stub(after.status);
|
|
119
|
+
if (after.key !== before.key) return stub("stale");
|
|
120
|
+
const resolution = read.resolution;
|
|
121
|
+
if (resolution.status !== "resolved") return stub(resolution.status === "stale" ? "stale" : resolution.cause === "private" ? "private" : "unavailable");
|
|
122
|
+
const result: EvidenceReadResult = { ...receipt, status: "resolved", link, excerpt: resolution.excerpt, excerptSha256: resolution.excerptSha256, locator: resolution.locator, origins: this.evidenceOrigins(link) };
|
|
123
|
+
try { if (this.host.publicMetadataText(JSON.stringify(result)) !== true) return stub("private"); } catch { return stub("private"); }
|
|
124
|
+
if (!current()) { const final = context(); return stub(final.status ?? "stale"); }
|
|
125
|
+
return result;
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
evidenceOrigins(link: EvidenceLinkV1): EvidenceReadOrigins {
|
|
130
|
+
const unknown: EvidenceReadOrigins = { state: "unknown" };
|
|
131
|
+
if (!this.d.evidenceSourceMeta) return unknown;
|
|
132
|
+
// #931 follow-up: an inventory that changed since the caller read it (a link revision gone between the list and its read) leaves the origins unknown beside the evidence that did resolve;
|
|
133
|
+
// it never fails the whole read. Any other board error (storage invalid) is not this case and still throws, so a damaged hub.db is not hidden behind an advisory field.
|
|
134
|
+
let inventory: ReturnType<Board["latestEvidenceLinks"]>;
|
|
135
|
+
try { inventory = this.d.board.latestEvidenceLinks(this.d.project, link.taskId, link.claimId, link.claimRevision, 128); }
|
|
136
|
+
catch (error) { if (error instanceof Error && error.message.startsWith("evidence inventory changed")) return unknown; throw error; }
|
|
137
|
+
if (!inventory.complete || !inventory.links.some(row => row.id === link.id && row.revision === link.revision)) return unknown;
|
|
138
|
+
try {
|
|
139
|
+
const groups: Set<string>[] = [], member: { id: string; keys: readonly string[] }[] = [];
|
|
140
|
+
for (const row of inventory.links.filter(row => row.status !== "withdrawn")) {
|
|
141
|
+
const meta = this.d.evidenceSourceMeta(row.sourceId);
|
|
142
|
+
if (!meta || meta.id !== row.sourceId || meta.private || meta.sha256 !== row.rawSha256 || this.host.publicMetadataText(JSON.stringify(meta)) !== true) return unknown;
|
|
143
|
+
const keys = evidenceOriginKeys(meta); if (!keys?.length) return unknown;
|
|
144
|
+
member.push({ id: row.id, keys });
|
|
145
|
+
const matches = groups.filter(group => keys.some(key => group.has(key)));
|
|
146
|
+
const merged = new Set([...keys, ...matches.flatMap(group => [...group])]);
|
|
147
|
+
for (const group of matches) groups.splice(groups.indexOf(group), 1);
|
|
148
|
+
groups.push(merged);
|
|
149
|
+
}
|
|
150
|
+
const selected = member.find(row => row.id === link.id), group = selected && groups.find(group => selected.keys.some(key => group.has(key)));
|
|
151
|
+
if (!group) return unknown;
|
|
152
|
+
// Connected registered origins express provenance grouping only, never independent corroboration or source quality.
|
|
153
|
+
return { state: "known", group: `origin:${createHash("sha256").update(JSON.stringify([...group].sort())).digest("hex").slice(0, 32)}`, groups: groups.length };
|
|
154
|
+
} catch { return unknown; }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** T1 records declared provenance only; no locator resolution or #901 judgment is manufactured. */
|
|
158
|
+
async evidenceRecord(by: PeerId, input: unknown): Promise<EvidenceReceipt> {
|
|
159
|
+
try { this.host.requireLocalTaskPeer(by); }
|
|
160
|
+
catch { throw new PreEffectToolRefusal("remote peers cannot record local evidence; ask the current local research task owner to record it"); }
|
|
161
|
+
const requestCheck = this.host.requestCheck(by, () => this.host.studyHold());
|
|
162
|
+
let proposed: ReturnType<typeof parseEvidenceRecord>;
|
|
163
|
+
try { proposed = parseEvidenceRecord(input); }
|
|
164
|
+
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid evidence record; check the bounded evidence fields before retrying"); }
|
|
165
|
+
return this.host.studyWrite(async () => {
|
|
166
|
+
const context = () => {
|
|
167
|
+
requestCheck();
|
|
168
|
+
let task: Task;
|
|
169
|
+
try { task = this.host.studyParent(proposed.taskId); }
|
|
170
|
+
catch { throw new PreEffectToolRefusal("evidence task is unavailable or outside this project; refresh ahub task show and select an active research task in this project"); }
|
|
171
|
+
const personWithdrawal = by === USER && proposed.status === "withdrawn";
|
|
172
|
+
if (task.profile === "research" && (task.owner === by || personWithdrawal) && isClosedTaskState(task.state))
|
|
173
|
+
throw new PreEffectToolRefusal("a closed research task's evidence records are final; open a follow-up research task to correct evidence and create a new manifest binding");
|
|
174
|
+
if (task.profile !== "research" || task.state !== "in_progress" || !task.owner || task.owner !== by && !personWithdrawal) throw new PreEffectToolRefusal("evidence recording requires the current in-progress research task owner; accept an assigned research task before recording evidence");
|
|
175
|
+
if (this.d.privateTurn?.(by) || this.host.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) throw new PreEffectToolRefusal("private evidence recording is unavailable in T1; use a public research task outside a private turn");
|
|
176
|
+
let identity;
|
|
177
|
+
try { identity = taskClaimIdentity(task, Number(proposed.claimId.split(":").at(-1))); }
|
|
178
|
+
catch { throw new PreEffectToolRefusal("evidence claim is unavailable; refresh hub_task_show or ahub task show --json and use a current claim binding"); }
|
|
179
|
+
if (identity.claimId !== proposed.claimId || identity.claimRevision !== proposed.claimRevision) throw new PreEffectToolRefusal("evidence claim revision changed; refresh hub_task_show or ahub task show --json and record the current claim binding");
|
|
180
|
+
const source = this.host.studySource(proposed.sourceId);
|
|
181
|
+
if (!source || source.sha256 !== proposed.rawSha256) throw new PreEffectToolRefusal("evidence source is unknown or its raw hash changed; use ahub source list and read the registered snapshot before retrying");
|
|
182
|
+
if (source.private) throw new PreEffectToolRefusal("private evidence sources are unavailable in T1; select a registered public source");
|
|
183
|
+
return { task, key: JSON.stringify([task.created, task.history.length, task.owner, identity, source]) };
|
|
184
|
+
};
|
|
185
|
+
const before = context();
|
|
186
|
+
const link = parseEvidenceLink({ ...proposed, id: proposed.id ?? evidenceLinkId(proposed, by), recordedBy: by });
|
|
187
|
+
const canonical = evidenceLinkCanonical(link);
|
|
188
|
+
const requirePublicMetadata = () => {
|
|
189
|
+
let nameable = false;
|
|
190
|
+
try { nameable = this.host.publicMetadataText(canonical) === true; } catch { /* unknown privacy is refused */ }
|
|
191
|
+
if (!nameable) throw new PreEffectToolRefusal("evidence metadata is private or sensitive; remove sensitive metadata before recording a public link");
|
|
192
|
+
};
|
|
193
|
+
requirePublicMetadata();
|
|
194
|
+
const requireRevision = () => {
|
|
195
|
+
const latest = this.d.board.evidenceLink(this.d.project, link.id);
|
|
196
|
+
const next = (latest?.revision ?? 0) + 1;
|
|
197
|
+
if (latest && (latest.taskId !== link.taskId || latest.claimId !== link.claimId)) throw new PreEffectToolRefusal("evidence id belongs to another claim; use a new evidence id");
|
|
198
|
+
const known = this.d.board.evidenceLink(this.d.project, link.id, link.revision);
|
|
199
|
+
if (known && evidenceLinkCanonical(known) !== canonical) throw new PreEffectToolRefusal(`evidence revision already records different content; use next revision ${next} or a new evidence id`);
|
|
200
|
+
if (!known && link.revision !== next) throw new PreEffectToolRefusal(`evidence revision is out of sequence; expected next revision ${next}; use that revision or replay an unchanged recorded revision`);
|
|
201
|
+
return !!known;
|
|
202
|
+
};
|
|
203
|
+
const replay = requireRevision();
|
|
204
|
+
if (!replay && this.host.screenOn()) {
|
|
205
|
+
const screen = await this.host.screenCall(canonical);
|
|
206
|
+
requestCheck();
|
|
207
|
+
if (screen.label !== "clear") throw new PreEffectToolRefusal("evidence privacy screening did not clear the metadata; use public evidence metadata and retry when the screen is available");
|
|
208
|
+
}
|
|
209
|
+
requestCheck();
|
|
210
|
+
const current = context();
|
|
211
|
+
if (current.key !== before.key) throw new PreEffectToolRefusal("evidence task, claim or source changed during admission; refresh hub_task_show or ahub task show --json and registered source metadata before retrying");
|
|
212
|
+
requirePublicMetadata();
|
|
213
|
+
requireRevision();
|
|
214
|
+
const saved = this.host.saveEvidenceLink(this.d.project, link, { taskFlowRevision: current.task.history.length, taskCreated: current.task.created, owner: current.task.owner!, ...(by === USER ? { personWithdrawal: true as const } : {}) });
|
|
215
|
+
return { id: saved.id, revision: saved.revision, taskId: saved.taskId };
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** #1403 A4: a summary of the newest audit for the release report: ref, profile, partial and unit counts, never a finding or a path. */
|
|
220
|
+
auditLine(): AuditSummary | undefined {
|
|
221
|
+
const audit = this.d.board.audits(1)[0];
|
|
222
|
+
return audit ? auditSummary({ audit: audit.id, task: audit.task, ref: audit.ref, profile: audit.profile, scoped: audit.scoped, at: audit.at }, audit.units, this.d.board.auditFindings(audit.id)) : undefined;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
auditCarry(head: string, source: AuditSource): CarryLookup {
|
|
226
|
+
const audits = this.d.board.audits(32, true), changed = new Map<string, string[] | undefined>();
|
|
227
|
+
const since = (base: string) => { if (!changed.has(base)) changed.set(base, source.changed(base, head)); return changed.get(base); };
|
|
228
|
+
return (surface, companion) => {
|
|
229
|
+
const id = unitId(surface, companion);
|
|
230
|
+
for (const audit of audits) {
|
|
231
|
+
const unit = audit.units.find(row => row.unit === id);
|
|
232
|
+
// The newest audit that lists the unit decides: a scoped audit that left it out says nothing, but a deferred, out-of-scope or still planned unit plans it again.
|
|
233
|
+
if (!unit) continue;
|
|
234
|
+
if (unit.state !== "covered") return undefined;
|
|
235
|
+
const base = unit.prior?.head ?? audit.ref, origin = unit.prior?.audit ?? audit.id, paths = since(base);
|
|
236
|
+
// Unknown never carries: an unreadable change list, or a changed path under the surface, plans the unit again.
|
|
237
|
+
return paths && !paths.some(path => matchConfigPath(surface, path)) ? { audit: origin, head: base } : undefined;
|
|
238
|
+
}
|
|
239
|
+
return undefined;
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* #1403 A4: `ahub sdlc audit start`. The person or the one configured conductor files one read-only `review` task whose brief lists the ledger, and the hub seeds the ledger in `hub.db`
|
|
245
|
+
* (surface x companion, `planned`, or `covered (prior)` for a surface whose paths are unchanged since its last covered state). Nothing is written until every check has passed.
|
|
246
|
+
*/
|
|
247
|
+
async auditStart(by: PeerId, input: { profile?: unknown; since?: unknown }, fence?: () => string | undefined): Promise<{ task: number; audit: number; units: number; planned: number; carried: number; partial: boolean; ref: string }> {
|
|
248
|
+
const check = this.host.requestCheck(by, fence);
|
|
249
|
+
if (by !== USER && (!this.host.configuredManualConductor(by) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("only the person or the current configured conductor may start a security audit; ask the person to run ahub sdlc audit start");
|
|
250
|
+
if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("a security audit cannot start in a private turn; finish that turn and retry ahub sdlc audit start");
|
|
251
|
+
const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
|
|
252
|
+
if (config.mode === "off") throw new PreEffectToolRefusal("security audits need the lifecycle on: set sdlc.mode to advise or enforce in .agenthub/sdlc.toml");
|
|
253
|
+
if (!config.security) throw new PreEffectToolRefusal("security audits need a [security] table in .agenthub/sdlc.toml (paths and companions)");
|
|
254
|
+
const source = this.d.auditSource;
|
|
255
|
+
if (!source) throw new PreEffectToolRefusal("this hub has no git source to read for an audit; start the hub from a git checkout of the project and retry ahub sdlc audit start");
|
|
256
|
+
const profile = input.profile === undefined ? "standard" : input.profile;
|
|
257
|
+
if (typeof profile !== "string" || !(AUDIT_PROFILES as readonly string[]).includes(profile)) throw new PreEffectToolRefusal(`profile is one of ${AUDIT_PROFILES.join(", ")}`);
|
|
258
|
+
const head = source.head();
|
|
259
|
+
if (!head) throw new PreEffectToolRefusal("the checkout's head commit could not be read; run the audit from a git checkout with a commit");
|
|
260
|
+
let scoped: string[] | undefined;
|
|
261
|
+
if (input.since !== undefined) {
|
|
262
|
+
if (typeof input.since !== "string" || !input.since.trim() || input.since.length > 200) throw new PreEffectToolRefusal("--since names a commit, tag or branch of this checkout");
|
|
263
|
+
const base = source.resolve(input.since.trim());
|
|
264
|
+
if (!base) throw new PreEffectToolRefusal("--since does not name a commit in this checkout");
|
|
265
|
+
scoped = source.changed(base, head);
|
|
266
|
+
if (!scoped) throw new PreEffectToolRefusal("the paths changed since that ref could not be listed completely; narrow --since or run an unscoped audit");
|
|
267
|
+
}
|
|
268
|
+
if (this.d.board.list().some(t => t.class === "review" && t.title.startsWith("Security audit (") && !isClosedTaskState(t.state) && t.state !== "approved" && this.d.board.auditOfTask(t.id, t.created))) throw new PreEffectToolRefusal("a security audit is already open; finish or cancel it first");
|
|
269
|
+
const units = seedLedger(config.security, profile as AuditProfile, { ...(scoped ? { scoped } : {}), carry: this.auditCarry(head, source) });
|
|
270
|
+
if (!units.length) throw new PreEffectToolRefusal("no configured security surface has a changed path in that scope; nothing to audit");
|
|
271
|
+
const partial = auditIsPartial(profile as AuditProfile, scoped !== undefined);
|
|
272
|
+
const inline = units.filter(u => !u.prior).slice(0, 40), cut = units.filter(u => !u.prior).length - inline.length;
|
|
273
|
+
const brief = auditBrief([...inline, ...units.filter(u => u.prior)], { profile: profile as AuditProfile, partial, checklist: SECURITY_CHECKLIST, ref: head }) + (cut > 0 ? `\n(${cut} more units: hub_audit_report {id: <this task>, show: true} lists the ledger)` : "")
|
|
274
|
+
+ "\n" + this.host.consideredBrief(this.host.repositories.scope({}).key, head, config.security.paths);
|
|
275
|
+
check();
|
|
276
|
+
const task = await this.host.propose(by, { title: `Security audit (${profile}${scoped ? ", scoped" : ""}) at ${head.slice(0, 12)}`, detail: brief, class: "review" }, undefined, undefined, fence);
|
|
277
|
+
let audit: number;
|
|
278
|
+
try {
|
|
279
|
+
if (this.host.isPii(task)) throw new PreEffectToolRefusal("the audit brief matched a private-data pattern; rename the configured surface");
|
|
280
|
+
audit = this.host.saveAuditCreate({ task: task.id, taskCreated: task.created, ref: head, ...(typeof input.since === "string" ? { since: input.since.trim() } : {}), profile, scoped: scoped !== undefined, by, at: this.d.now?.() ?? Date.now(), units });
|
|
281
|
+
} catch (error) {
|
|
282
|
+
// The ledger is the audit: a task without one would be an empty promise, so it is cancelled rather than left to run.
|
|
283
|
+
await this.host.cancel(task.id, by, { reason: "security audit ledger could not be created" }).catch(() => undefined);
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
return { task: task.id, audit, units: units.length, planned: units.filter(u => !u.prior).length, carried: units.filter(u => u.prior).length, partial, ref: head };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
auditView(audit: NonNullable<ReturnType<Board["audit"]>>, full: boolean): AuditView {
|
|
290
|
+
const findings = this.d.board.auditFindings(audit.id);
|
|
291
|
+
const summary = auditSummary({ audit: audit.id, task: audit.task, ref: audit.ref, profile: audit.profile, scoped: audit.scoped, at: audit.at }, audit.units, findings);
|
|
292
|
+
return { ...summary, units: audit.units.map(u => ({ unit: u.unit, state: u.state, ...(u.prior ? { prior: u.prior } : {}), ...(u.reason ? { reason: u.reason } : {}) })), items: findings.map(row => auditFindingView(row, full)), ...(full ? {} : { withheld: findings.filter(row => !!auditFindingView(row, false).withheld).length }) };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** `ahub sdlc audit show`: the newest audit, or the one named. The full view (open important boundary text included) is the person's alone; a conductor reads the public one. */
|
|
296
|
+
auditShow(by: PeerId, id?: unknown): AuditView | undefined {
|
|
297
|
+
if (by !== USER && (!this.host.configuredManualConductor(by) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("the audit readback is for the person or the configured conductor");
|
|
298
|
+
if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("the audit readback is unavailable in a private turn");
|
|
299
|
+
const audit = id === undefined ? this.d.board.audits(1)[0] : Number.isSafeInteger(id) && (id as number) > 0 ? this.d.board.audit(id as number) : undefined;
|
|
300
|
+
if (id !== undefined && !audit) throw new PreEffectToolRefusal("no such security audit");
|
|
301
|
+
return audit ? this.auditView(audit, by === USER) : undefined;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* #1403 A4, A5: `hub_audit_report`. The assigned auditor (the audit task's owner) reports a state per unit and its findings; the hub alone writes the ledger. A reviewer-role peer that did
|
|
306
|
+
* not file a `confirmed` important finding verifies or rejects it; until then it stays a `candidate`. Boundary text of an open important finding is read only through this tool by the
|
|
307
|
+
* auditor, a reviewer-role peer or the person, and never rides a message to anyone else.
|
|
308
|
+
*/
|
|
309
|
+
async auditReport(by: PeerId, input: { id?: unknown; units?: unknown; findings?: unknown; verify?: unknown; settle?: unknown; show?: unknown }, fence?: () => string | undefined): Promise<AuditView> {
|
|
310
|
+
const check = this.host.requestCheck(by, fence);
|
|
311
|
+
const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
|
|
312
|
+
if (config.mode === "off" || !config.security) throw new PreEffectToolRefusal("audit reports need the lifecycle on and a [security] table in .agenthub/sdlc.toml");
|
|
313
|
+
if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("audit reports are unavailable in a private turn: their text must not leave this machine");
|
|
314
|
+
if (!Number.isSafeInteger(input.id) || (input.id as number) <= 0) throw new PreEffectToolRefusal("hub_audit_report needs the audit task id");
|
|
315
|
+
const task = this.d.board.get(input.id as number), audit = task ? this.d.board.auditOfTask(task.id, task.created) : undefined;
|
|
316
|
+
if (!task || !audit) throw new PreEffectToolRefusal("no security audit on that task");
|
|
317
|
+
if (this.host.isPii(task)) throw new PreEffectToolRefusal("that task is private");
|
|
318
|
+
const isOwner = by !== USER && task.owner === by && task.state === "in_progress";
|
|
319
|
+
const reviewerRole = by !== USER && (this.d.roles?.[by] ?? []).includes("reviewer") && this.d.bus.isRostered(by);
|
|
320
|
+
const writes = input.units !== undefined || input.findings !== undefined, verifies = input.verify !== undefined, settles = input.settle !== undefined;
|
|
321
|
+
if (!writes && !verifies && !settles && input.show !== true) throw new PreEffectToolRefusal("give units and findings (the auditor), verify or settle (a reviewer other than the finder, or the person) or show: true");
|
|
322
|
+
if (writes && !isOwner) throw new PreEffectToolRefusal("only the assigned auditor reports units and findings, while the audit task is in progress");
|
|
323
|
+
if (verifies && !(reviewerRole || by === USER)) throw new PreEffectToolRefusal("only a reviewer-role peer or the person verifies a finding");
|
|
324
|
+
if (settles && !(reviewerRole || by === USER)) throw new PreEffectToolRefusal("only a reviewer-role peer other than the finder, or the person, settles a verified finding; ask a reviewer or the person to settle it");
|
|
325
|
+
if ((verifies || settles) && (task.state === "cancelled" || task.state === "backlog")) throw new PreEffectToolRefusal("the audit task is closed");
|
|
326
|
+
if (!isOwner && !reviewerRole && by !== USER) throw new PreEffectToolRefusal("only the auditor, a reviewer-role peer or the person reads an audit report");
|
|
327
|
+
const when = this.d.now?.() ?? Date.now();
|
|
328
|
+
let units = audit.units, filed: { finding: ReviewFinding; foundBy: string; at: number }[] = [];
|
|
329
|
+
const decisions: { finding: string; verdict: "verified" | "rejected" }[] = [];
|
|
330
|
+
const settlements: { finding: string; disposition: "fixed" | "false_positive" }[] = [];
|
|
331
|
+
if (input.units !== undefined) {
|
|
332
|
+
try { units = applyUnitReports(audit.units, parseUnitReports(input.units, audit.units), by, when); }
|
|
333
|
+
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid units"); }
|
|
334
|
+
}
|
|
335
|
+
if (input.findings !== undefined) {
|
|
336
|
+
let parsed: ReviewFinding[];
|
|
337
|
+
try { parsed = parseReviewFindings(input.findings, { person: false, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS, contract: "required" }); }
|
|
338
|
+
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid findings"); }
|
|
339
|
+
if (parsed.some(item => item.pass !== "security")) throw new PreEffectToolRefusal("an audit takes security findings only (pass: security)");
|
|
340
|
+
if (parsed.some(item => item.anchor !== undefined)) throw new PreEffectToolRefusal("anchors belong to review verdicts; name the file in path");
|
|
341
|
+
const text = JSON.stringify(parsed);
|
|
342
|
+
if (!this.host.nameable(text) || this.host.screenOn() && (await this.host.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("finding text was not cleared for the audit ledger: it matches a private-data pattern or the PII screen did not clear it");
|
|
343
|
+
filed = parsed.map(finding => ({ finding, foundBy: by, at: when }));
|
|
344
|
+
}
|
|
345
|
+
if (input.verify !== undefined) {
|
|
346
|
+
if (!Array.isArray(input.verify) || !input.verify.length || input.verify.length > 32) throw new PreEffectToolRefusal("verify is a list of 1 to 32 {finding, verdict: verified|rejected}");
|
|
347
|
+
const stored = this.d.board.auditFindings(audit.id);
|
|
348
|
+
for (const item of input.verify as unknown[]) {
|
|
349
|
+
const record = item && typeof item === "object" && !Array.isArray(item) ? item as Record<string, unknown> : undefined;
|
|
350
|
+
if (!record || Object.keys(record).some(key => key !== "finding" && key !== "verdict") || typeof record.finding !== "string" || (record.verdict !== "verified" && record.verdict !== "rejected")) throw new PreEffectToolRefusal("each verify entry is {finding: <id>, verdict: verified|rejected}");
|
|
351
|
+
const refusal = verificationRefusal(stored.find(row => row.finding.id === record.finding), by);
|
|
352
|
+
if (refusal) throw new PreEffectToolRefusal(`${record.finding.slice(0, 80)}: ${refusal}`);
|
|
353
|
+
decisions.push({ finding: record.finding, verdict: record.verdict });
|
|
354
|
+
}
|
|
355
|
+
if (new Set(decisions.map(d => d.finding)).size !== decisions.length) throw new PreEffectToolRefusal("a finding is decided once per call");
|
|
356
|
+
}
|
|
357
|
+
if (input.settle !== undefined) {
|
|
358
|
+
if (!Array.isArray(input.settle) || !input.settle.length || input.settle.length > 32) throw new PreEffectToolRefusal("settle is a list of 1 to 32 {finding, disposition: fixed|false_positive}");
|
|
359
|
+
const stored = this.d.board.auditFindings(audit.id);
|
|
360
|
+
for (const item of input.settle as unknown[]) {
|
|
361
|
+
const record = item && typeof item === "object" && !Array.isArray(item) ? item as Record<string, unknown> : undefined;
|
|
362
|
+
if (!record || Object.keys(record).some(key => key !== "finding" && key !== "disposition") || typeof record.finding !== "string" || !(SETTLEMENTS as readonly unknown[]).includes(record.disposition)) throw new PreEffectToolRefusal("each settle entry is {finding: <id>, disposition: fixed|false_positive}");
|
|
363
|
+
const refusal = settlementRefusal(stored.find(row => row.finding.id === record.finding), by);
|
|
364
|
+
if (refusal) throw new PreEffectToolRefusal(`${record.finding.slice(0, 80)}: ${refusal}`);
|
|
365
|
+
settlements.push({ finding: record.finding, disposition: record.disposition as "fixed" | "false_positive" });
|
|
366
|
+
}
|
|
367
|
+
if (new Set(settlements.map(item => item.finding)).size !== settlements.length) throw new PreEffectToolRefusal("a finding is settled once per call");
|
|
368
|
+
// A finding verified in this same call is not settled in it: the verification is a separate reader's decision and its result is read before the settlement.
|
|
369
|
+
if (settlements.some(item => decisions.some(decision => decision.finding === item.finding))) throw new PreEffectToolRefusal("verify a finding and settle it in separate calls");
|
|
370
|
+
}
|
|
371
|
+
check();
|
|
372
|
+
const now = this.d.board.audit(audit.id), nowTask = this.d.board.get(task.id);
|
|
373
|
+
if (!now || !nowTask || nowTask.owner !== task.owner || nowTask.state !== task.state || JSON.stringify(now.units) !== JSON.stringify(audit.units)) throw new PreEffectToolRefusal("the audit changed while the report was checked; read it again and retry");
|
|
374
|
+
// One transaction: a unit report, its findings, the verifications and the settlements land together or not at all.
|
|
375
|
+
const skipped = this.host.saveAuditApply(audit.id, { units: writes ? units : undefined, findings: filed, decisions, ...(settlements.length ? { settlements } : {}), by });
|
|
376
|
+
if (skipped === undefined) throw new PreEffectToolRefusal("a finding was decided meanwhile; read the audit again and retry");
|
|
377
|
+
try {
|
|
378
|
+
const rejected = new Set(decisions.filter(row => row.verdict === "rejected").map(row => row.finding));
|
|
379
|
+
const falsePositives = new Set(settlements.filter(row => row.disposition === "false_positive").map(row => row.finding));
|
|
380
|
+
const savedAudit = this.d.board.audit(audit.id);
|
|
381
|
+
if (savedAudit?.task === nowTask.id && savedAudit.taskCreated === nowTask.created) {
|
|
382
|
+
const saved = this.d.board.auditFindings(audit.id).filter(row => rejected.has(row.finding.id) && row.rejectedBy === by
|
|
383
|
+
|| falsePositives.has(row.finding.id) && row.settledAs === "false_positive" && row.settledBy === by);
|
|
384
|
+
this.host.recordConsideredAfter(nowTask, saved.map(row => row.finding), "audit", savedAudit.ref);
|
|
385
|
+
}
|
|
386
|
+
} catch { this.host.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`); }
|
|
387
|
+
const full = this.d.board.audit(audit.id)!;
|
|
388
|
+
return { ...this.auditView(full, true), ...(skipped.length ? { notUpdated: skipped } : {}) };
|
|
389
|
+
}
|
|
390
|
+
}
|