@staix/agent-hub 0.46.0 → 0.47.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 +85 -0
- package/README.md +8 -4
- package/docs/adding-an-ai-tool.md +20 -4
- package/docs/agent-notes/adapters.md +3 -3
- package/docs/agent-notes/benchmarks.md +7 -1
- package/docs/agent-notes/daemon.md +6 -5
- package/docs/agent-notes/tasks.md +4 -2
- package/docs/agent-notes/tests.md +3 -0
- package/docs/contracts/companion-cli-v1.json +3 -0
- package/docs/data-policy.md +9 -0
- package/docs/design/adapters.md +14 -0
- package/docs/design/cli-output-inventory.md +362 -0
- package/docs/design/cli-output.md +42 -1
- package/docs/design/execution-reference.md +5 -2
- package/docs/design/guidance-probes.md +2 -2
- package/docs/design/refusal-inventory.md +26 -0
- package/docs/design/roadmap.md +4 -0
- package/docs/design/task-board.md +17 -1
- package/docs/dogfood.md +26 -10
- package/docs/events.md +9 -0
- package/docs/friction.md +46 -0
- package/docs/memory.md +35 -3
- package/docs/operations.md +63 -15
- package/docs/profiles.md +1 -0
- package/docs/quickstart.md +14 -2
- package/docs/roles.md +6 -0
- package/docs/sdlc.md +44 -1
- package/docs/security.md +16 -7
- package/docs/specs/2026-09-19-agent-hub-design.md +17 -0
- package/docs/specs/2026-09-19-multi-project-design.md +7 -1
- package/docs/verification/2026-11-24-0.46.1.md +48 -0
- package/docs/verification/2026-11-25-agy-1.5.16.md +31 -0
- package/docs/verification/2026-11-25-claude-implementer-2.1.332.md +47 -0
- package/docs/verification/2026-11-25-codex-0172-reviewer-isolation.md +47 -0
- package/docs/verification/2026-11-25-kimi-272-reviewer-compat.md +38 -0
- package/docs/verification/2026-11-25-kimi-tui-272.md +14 -0
- package/docs/verification/2026-11-25-pi-160-compat.md +40 -0
- package/docs/verification/2026-11-26-0.47.0.md +43 -0
- package/docs/verification/2026-11-26-codex-0172-reviewer-tool-call.md +29 -0
- package/docs/verification/dogfood/2026-11-24.md +2829 -0
- package/docs/verification/pi-160-model-free.ts +57 -0
- package/docs/verification/pi-160-native.mjs +21 -0
- package/docs/verified.json +43 -31
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +679 -134
- package/plugins/agent-hub/server.js +776 -154
- package/src/adapters/acp.ts +5 -0
- package/src/adapters/channel-peer.ts +7 -0
- package/src/adapters/claude-print-child.ts +27 -5
- package/src/adapters/codex-appserver.ts +9 -0
- package/src/adapters/compat.ts +12 -11
- package/src/adapters/configured-acp.ts +45 -2
- package/src/adapters/configured-print.ts +163 -0
- package/src/adapters/conformance/index.ts +1 -0
- package/src/adapters/conformance/print.ts +57 -0
- package/src/adapters/definitions/native-activity.ts +57 -0
- package/src/adapters/definitions/native-factories.ts +4 -2
- package/src/adapters/jcode.ts +10 -2
- package/src/adapters/local-worker.ts +2 -0
- package/src/adapters/registry-types.ts +5 -3
- package/src/adapters/role-eligibility.ts +5 -0
- package/src/cli/bench.ts +2 -1
- package/src/cli/broker.ts +2 -1
- package/src/cli/capabilities-output.ts +10 -14
- package/src/cli/configured-acp-entry.ts +10 -2
- package/src/cli/console-state.ts +25 -5
- package/src/cli/error-format.ts +2 -0
- package/src/cli/guidance.ts +1 -1
- package/src/cli/handoff-output.ts +20 -17
- package/src/cli/help.ts +78 -40
- package/src/cli/init-settings.ts +15 -0
- package/src/cli/intake-output.ts +13 -13
- package/src/cli/launch.ts +3 -2
- package/src/cli/learn-output.ts +40 -21
- package/src/cli/main.ts +148 -77
- package/src/cli/memory.ts +47 -2
- package/src/cli/output.ts +54 -31
- package/src/cli/recovery-package.ts +6 -1
- package/src/cli/roadmap.ts +2 -2
- package/src/cli/room-output.ts +71 -0
- package/src/cli/room.ts +19 -33
- package/src/cli/schedule-output.ts +20 -19
- package/src/cli/sdlc-output.ts +188 -170
- package/src/cli/source-output.ts +17 -14
- package/src/cli/specs.ts +13 -13
- package/src/cli/study-output.ts +66 -69
- package/src/cli/task-output.ts +106 -158
- package/src/cli/terminal-recovery.ts +2 -1
- package/src/cli/upgrade-runtime.ts +2 -1
- package/src/cli/warn-line.ts +18 -0
- package/src/cli/worktrees-output.ts +25 -23
- package/src/hub/audit-source.ts +45 -0
- package/src/hub/board.ts +141 -5
- package/src/hub/bus.ts +13 -2
- package/src/hub/config-apply.ts +14 -1
- package/src/hub/config-trust.ts +1 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +371 -45
- package/src/hub/handoff.ts +5 -1
- package/src/hub/hub-tools.ts +23 -5
- package/src/hub/instance-config.ts +3 -3
- package/src/hub/learn-followup.ts +103 -0
- package/src/hub/learning.ts +63 -1
- package/src/hub/manager.ts +15 -1
- package/src/hub/memory-policy.ts +2 -1
- package/src/hub/memory-review.ts +217 -0
- package/src/hub/peer-activity.ts +37 -0
- package/src/hub/peers.ts +3 -0
- package/src/hub/project-move.ts +258 -0
- package/src/hub/registry.ts +16 -5
- package/src/hub/restart.ts +7 -0
- package/src/hub/review-brief.ts +8 -4
- package/src/hub/review-checkout.ts +26 -0
- package/src/hub/review-findings.ts +6 -3
- package/src/hub/risk-tier.ts +129 -0
- package/src/hub/roadmap-check.ts +1 -0
- package/src/hub/routing.ts +3 -1
- package/src/hub/sdlc-merge.ts +9 -0
- package/src/hub/sdlc-metrics.ts +24 -1
- package/src/hub/sdlc-queue.ts +1 -1
- package/src/hub/sdlc.ts +15 -6
- package/src/hub/settings.ts +2 -0
- package/src/hub/spec-readback.ts +136 -0
- package/src/hub/specs.ts +1 -1
- package/src/hub/task-list-page.ts +1 -1
- package/src/hub/tasks.ts +558 -65
- package/src/hub/ui.ts +4 -2
- package/src/ui/index.html +26 -2
- package/src/ui/overview-model.ts +138 -0
- package/src/ui/plugin.ts +30 -4
- package/templates/roles/ops/project-manager.md +1 -1
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const ACTIVITY_KINDS = ["files", "shell", "network", "hub", "memory", "agents", "model", "unknown"] as const;
|
|
2
|
+
export type ActivityKind = (typeof ACTIVITY_KINDS)[number];
|
|
3
|
+
interface PeerActivity { kind: ActivityKind; since: number }
|
|
4
|
+
|
|
5
|
+
function isActivityKind(value: unknown): value is ActivityKind {
|
|
6
|
+
return typeof value === "string" && (ACTIVITY_KINDS as readonly string[]).includes(value);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** One transient row per busy peer. Privacy suppression lasts through the current turn. */
|
|
10
|
+
export class PeerActivityTracker {
|
|
11
|
+
private readonly rows = new Map<string, PeerActivity>();
|
|
12
|
+
private readonly hidden = new Set<string>();
|
|
13
|
+
|
|
14
|
+
observe(peer: string, kind: unknown, isPrivate: () => boolean, now = Date.now()): void {
|
|
15
|
+
if (kind === undefined) { this.clear(peer); return; }
|
|
16
|
+
if (!isActivityKind(kind) || this.withheld(peer, isPrivate)) return;
|
|
17
|
+
this.rows.set(peer, { kind, since: now });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
view(peer: string, isPrivate: () => boolean): PeerActivity | undefined {
|
|
21
|
+
if (!this.rows.has(peer) || this.withheld(peer, isPrivate)) return undefined;
|
|
22
|
+
return this.rows.get(peer);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
private withheld(peer: string, isPrivate: () => boolean): boolean {
|
|
26
|
+
if (this.hidden.has(peer)) return true;
|
|
27
|
+
try { if (!isPrivate()) return false; } catch { /* Unknown privacy withholds the row. */ }
|
|
28
|
+
this.hidden.add(peer);
|
|
29
|
+
this.rows.delete(peer);
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
private clear(peer: string): void {
|
|
34
|
+
this.rows.delete(peer);
|
|
35
|
+
this.hidden.delete(peer);
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/hub/peers.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ActivityKind } from "./peer-activity.ts";
|
|
1
2
|
import type { DeliveryFailureCause } from "./delivery-failure.ts";
|
|
2
3
|
import type { Envelope, EnvelopeOpts, PeerId, PeerState } from "./envelope.ts";
|
|
3
4
|
import type { PermissionMode } from "./permission-mode.ts";
|
|
@@ -141,6 +142,7 @@ export interface PeerAdapter {
|
|
|
141
142
|
onDelivery?: (receipt: DeliveryReceipt) => void;
|
|
142
143
|
/** Set by the bus (#878): a native session title or current plan item the adapter observed; `reset` on a new session. */
|
|
143
144
|
onDoing?: (kind: DoingKind, text?: unknown) => void;
|
|
145
|
+
onActivity?: (kind: ActivityKind | undefined) => void;
|
|
144
146
|
/** Safe restart metadata only: ids and launch parameters, never prompt/message text. */
|
|
145
147
|
recoveryMetadata?(): Record<string, unknown>;
|
|
146
148
|
/** Current native TUI ownership, correlated to one launcher. A start acknowledgement is never evidence. */
|
|
@@ -161,6 +163,7 @@ export abstract class BasePeer implements PeerAdapter {
|
|
|
161
163
|
onFailed?: (envs: Envelope[], failure?: { quota?: true; failureCause?: DeliveryFailureCause }) => void;
|
|
162
164
|
onDelivery?: (receipt: DeliveryReceipt) => void;
|
|
163
165
|
onDoing?: (kind: DoingKind, text?: unknown) => void;
|
|
166
|
+
onActivity?: (kind: ActivityKind | undefined) => void;
|
|
164
167
|
private _state: PeerState = "offline";
|
|
165
168
|
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
166
169
|
private nextWatchdogMs: number | undefined;
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { chmodSync, closeSync, copyFileSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { basename, dirname, isAbsolute, join, relative } from "node:path";
|
|
5
|
+
import { processLiveness } from "../pi/process-signature.ts";
|
|
6
|
+
import { projectRoot, realPath } from "./project.ts";
|
|
7
|
+
import { assertHubDbCompatible } from "./db-schema.ts";
|
|
8
|
+
import { HUB_DB_BUSY_TIMEOUT_MS } from "./db-timeout.ts";
|
|
9
|
+
import { parseProjectRuntime } from "./project-runtime-state.ts";
|
|
10
|
+
import { recoveryLock } from "./recovery-store.ts";
|
|
11
|
+
import { idFor, type Project, type Registry } from "./registry.ts";
|
|
12
|
+
|
|
13
|
+
type Rewrite = { table: string; column: string; count: number; root?: true };
|
|
14
|
+
type Store = { project: Project; file: string; rewrites: Rewrite[]; pending: boolean };
|
|
15
|
+
type Marker = { file: string; before: string; after?: string };
|
|
16
|
+
type Backup = { file: string; backup: string; database: boolean };
|
|
17
|
+
type MoveJournal = { before: string; after: string; backups: Backup[] };
|
|
18
|
+
|
|
19
|
+
const journalPath = (registry: Registry): string => join(dirname(registry.path), "project-move.pending.json");
|
|
20
|
+
const ident = (name: string): string => '"' + name.replaceAll('"', '""') + '"';
|
|
21
|
+
const hash = (body: string): string => createHash("sha256").update(body).digest("hex");
|
|
22
|
+
const fileOrMissing = (file: string): boolean => {
|
|
23
|
+
try {
|
|
24
|
+
const stat = lstatSync(file);
|
|
25
|
+
if (!stat.isFile() || stat.nlink !== 1) throw new Error(`${file} must be a regular unlinked state file`);
|
|
26
|
+
return true;
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function sync(file: string): void {
|
|
34
|
+
const fd = openSync(file, "r");
|
|
35
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function replaceFile(file: string, write: (temporary: string) => void): void {
|
|
39
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
40
|
+
try {
|
|
41
|
+
write(temporary);
|
|
42
|
+
sync(temporary);
|
|
43
|
+
renameSync(temporary, file);
|
|
44
|
+
sync(dirname(file));
|
|
45
|
+
} finally { rmSync(temporary, { force: true }); }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function marker(file: string, old: Project, next: Project, runtime: boolean): Marker | undefined {
|
|
49
|
+
if (!fileOrMissing(file)) return undefined;
|
|
50
|
+
const before = readFileSync(file, "utf8");
|
|
51
|
+
const input = JSON.parse(before) as Record<string, unknown>;
|
|
52
|
+
const value = runtime ? { ...parseProjectRuntime(old, input) } : { ...input };
|
|
53
|
+
const root = runtime ? "projectRoot" : "root";
|
|
54
|
+
if (value.projectId !== old.id || value[root] !== old.root || (runtime && value.stateDir !== old.stateDir))
|
|
55
|
+
throw new Error(`${file} does not identify the old registration; verify the state directory and retry`);
|
|
56
|
+
value.projectId = next.id;
|
|
57
|
+
value[root] = next.root;
|
|
58
|
+
if (runtime) {
|
|
59
|
+
value.stateDir = next.stateDir;
|
|
60
|
+
value.instanceId = null;
|
|
61
|
+
}
|
|
62
|
+
return { file, before, after: JSON.stringify(value) };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function stopped(project: Project): boolean {
|
|
66
|
+
if (project.instanceId && processLiveness(project.pid, project.pidSignature) !== "gone") return false;
|
|
67
|
+
const status = join(project.stateDir, "status.json");
|
|
68
|
+
if (fileOrMissing(status)) {
|
|
69
|
+
try {
|
|
70
|
+
const owner = JSON.parse(readFileSync(status, "utf8")) as { pid?: unknown; pidSignature?: unknown };
|
|
71
|
+
if (typeof owner.pid !== "number" || processLiveness(owner.pid,
|
|
72
|
+
typeof owner.pidSignature === "string" ? owner.pidSignature : undefined) !== "gone") return false;
|
|
73
|
+
} catch { return false; }
|
|
74
|
+
} else if (existsSync(join(project.stateDir, "control-token"))) return false;
|
|
75
|
+
const legacy = join(project.stateDir, "hub.pid");
|
|
76
|
+
return !existsSync(legacy) || processLiveness(Number(readFileSync(legacy, "utf8").trim())) === "gone";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function counts(db: Database, id: string, own: boolean): Rewrite[] {
|
|
80
|
+
const tables = db.query<{ name: string }, []>("SELECT name FROM sqlite_schema WHERE type='table' ORDER BY name").all();
|
|
81
|
+
const rewrites: Rewrite[] = [];
|
|
82
|
+
for (const { name } of tables) {
|
|
83
|
+
if (!own && name !== "task_handoff_origin" && name !== "task_handoff_outbound") continue;
|
|
84
|
+
const columns = db.query<{ name: string }, []>(`PRAGMA table_info(${ident(name)})`).all();
|
|
85
|
+
const column = name === "task_handoff_outbound" ? "remote_project" : "project_id";
|
|
86
|
+
if (!columns.some(item => item.name === column)) continue;
|
|
87
|
+
const count = countRows(db, name, column, id);
|
|
88
|
+
if (own || count) rewrites.push({ table: name, column, count,
|
|
89
|
+
...(name === "delivery_meta" && columns.some(item => item.name === "project_root") ? { root: true } : {}) });
|
|
90
|
+
}
|
|
91
|
+
return rewrites;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function countRows(db: Database, table: string, column: string, id: string): number {
|
|
95
|
+
return db.query<{ n: number }, [string]>(`SELECT count(*) AS n FROM ${ident(table)} WHERE ${ident(column)} = ?`).get(id)!.n;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function inspectStore(project: Project, old: Project, own: boolean): Store | undefined {
|
|
99
|
+
const file = join(project.stateDir, "hub.db");
|
|
100
|
+
if (!fileOrMissing(file)) {
|
|
101
|
+
if (own) throw new Error(`missing ${file}; select the moved state with --state`);
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
assertHubDbCompatible(file);
|
|
105
|
+
const db = new Database(file, { readonly: true, strict: true });
|
|
106
|
+
try {
|
|
107
|
+
db.run(`PRAGMA busy_timeout = ${HUB_DB_BUSY_TIMEOUT_MS}`);
|
|
108
|
+
const rewrites = counts(db, old.id, own);
|
|
109
|
+
if (!own && !rewrites.length) return undefined;
|
|
110
|
+
const pending = own && rewrites.some(change => change.table === "deliveries") &&
|
|
111
|
+
!!db.query("SELECT 1 FROM deliveries WHERE state IN ('queued','dispatching','accepted','needs_review') LIMIT 1").get();
|
|
112
|
+
return { project, file, rewrites, pending };
|
|
113
|
+
} finally { db.close(); }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function planMove(registry: Registry, oldRef: string, newRoot: string, state?: string, timestamp = new Date().toISOString().replaceAll(":", "-")) {
|
|
117
|
+
const projects = registry.list();
|
|
118
|
+
// Prefer the registered spelling. An old path can now be a symlink to the new path.
|
|
119
|
+
const oldPath = isAbsolute(oldRef) ? oldRef : join(process.cwd(), oldRef);
|
|
120
|
+
const old = projects.find(row => row.id === oldRef || row.root === oldPath);
|
|
121
|
+
if (!old) throw new Error("old registration not found; run ahub projects --full and use its project id");
|
|
122
|
+
const root = realPath(isAbsolute(newRoot) ? newRoot : `${process.cwd()}/${newRoot}`);
|
|
123
|
+
if (projectRoot(root) !== root) throw new Error("new path must be the project root");
|
|
124
|
+
const requestedState = state ?? join(root, ".agenthub", "state");
|
|
125
|
+
const stateDir = realPath(isAbsolute(requestedState) ? requestedState : `${root}/${requestedState}`);
|
|
126
|
+
const next = { ...old, id: idFor(root), root, stateDir, instanceId: null, pid: null, pidSignature: null };
|
|
127
|
+
if (root === old.root) throw new Error("the project is already registered at this root. Move the repository before re-keying it");
|
|
128
|
+
if (projects.some(row => row.id === next.id || row.root === root || (row.id !== old.id && row.stateDir === stateDir)))
|
|
129
|
+
throw new Error("destination is registered; inspect ahub projects --full and remove the duplicate registration before retrying");
|
|
130
|
+
if (existsSync(old.stateDir) && realPath(old.stateDir) !== stateDir)
|
|
131
|
+
throw new Error("the original state directory still exists separately; select it with --state or move it before retrying");
|
|
132
|
+
const moved = { ...old, stateDir };
|
|
133
|
+
const own = inspectStore(moved, old, true)!;
|
|
134
|
+
const peers = projects.filter(row => row.id !== old.id).flatMap(row => inspectStore(row, old, false) ?? []);
|
|
135
|
+
const active = [moved, ...peers.map(item => item.project)].filter(row => !stopped(row));
|
|
136
|
+
if (active.length) throw new Error(`stop the live or uncertain hubs before retrying:\n${active.map(row => `ahub --project ${row.id} kill`).join("\n")}`);
|
|
137
|
+
if (own.pending) throw new Error(`project ${old.id} has pending deliveries; move the repository back, start the old hub, settle its queue and stop it before retrying`);
|
|
138
|
+
const projectFile = marker(join(stateDir, "project.json"), old, next, false);
|
|
139
|
+
if (!projectFile) throw new Error("project.json is missing; select the original state directory with --state");
|
|
140
|
+
const runtime = marker(join(stateDir, "runtime.json"), old, next, true);
|
|
141
|
+
const markers = runtime ? [projectFile, runtime] : [projectFile];
|
|
142
|
+
const continuity = join(stateDir, "recovery-continuity.json");
|
|
143
|
+
if (fileOrMissing(continuity)) markers.push({ file: continuity, before: readFileSync(continuity, "utf8") });
|
|
144
|
+
const stores = [own, ...peers];
|
|
145
|
+
for (const row of [next, ...stores.map(store => store.project)]) {
|
|
146
|
+
const operation = recoveryLock(dirname(registry.path), row.root);
|
|
147
|
+
if (operation) throw new Error(`project ${row.id} has active recovery; run ahub recovery status ${operation} before retrying`);
|
|
148
|
+
}
|
|
149
|
+
const databaseVersions = stores.flatMap(({ file }) => [file, file + "-wal"]).map(file => {
|
|
150
|
+
if (!fileOrMissing(file)) return null;
|
|
151
|
+
const stat = lstatSync(file, { bigint: true });
|
|
152
|
+
return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].map(String);
|
|
153
|
+
});
|
|
154
|
+
const fingerprint = `${timestamp}.${hash(JSON.stringify({ timestamp, old, next, stores, databaseVersions, markers: markers.map(item => hash(item.before)) }))}`;
|
|
155
|
+
return { old, next, stores, markers, fingerprint, archive: join(root, ".agenthub", "archive", `move-${timestamp}`) };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
type ProjectMovePreview = ReturnType<typeof planMove>;
|
|
159
|
+
export function previewProjectMove(registry: Registry, oldRef: string, root: string, state?: string): ProjectMovePreview {
|
|
160
|
+
return registry.runtimeCaptureLocked(() => planMove(registry, oldRef, root, state));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function backupDatabase(file: string, target: string): void {
|
|
164
|
+
const db = new Database(file, { readonly: true, strict: true });
|
|
165
|
+
try {
|
|
166
|
+
db.run(`PRAGMA busy_timeout = ${HUB_DB_BUSY_TIMEOUT_MS}`);
|
|
167
|
+
db.query("VACUUM INTO ?").run(target);
|
|
168
|
+
} finally { db.close(); }
|
|
169
|
+
sync(target);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function rewriteStore(store: Store, old: Project, next: Project): void {
|
|
173
|
+
assertHubDbCompatible(store.file);
|
|
174
|
+
const db = new Database(store.file, { readwrite: true, create: false, strict: true });
|
|
175
|
+
try {
|
|
176
|
+
db.run(`PRAGMA busy_timeout = ${HUB_DB_BUSY_TIMEOUT_MS}`);
|
|
177
|
+
db.run("PRAGMA synchronous = FULL");
|
|
178
|
+
db.transaction(() => {
|
|
179
|
+
for (const rewrite of store.rewrites) {
|
|
180
|
+
const { table, column, count, root } = rewrite;
|
|
181
|
+
const sql = `UPDATE ${ident(table)} SET ${ident(column)} = ?${root ? ", project_root = ?" : ""} WHERE ${ident(column)} = ?`;
|
|
182
|
+
const args = root ? [next.id, next.root, old.id] : [next.id, old.id];
|
|
183
|
+
if (db.query(sql).run(...args).changes !== count || countRows(db, table, column, old.id))
|
|
184
|
+
throw new Error(`${table} changed during move; preview again`);
|
|
185
|
+
}
|
|
186
|
+
}).immediate();
|
|
187
|
+
} finally { db.close(); }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Called under the registry write transaction before a new claim or launch can proceed. */
|
|
191
|
+
export function recoverProjectMove(registry: Registry): void {
|
|
192
|
+
const file = journalPath(registry);
|
|
193
|
+
if (!fileOrMissing(file)) return;
|
|
194
|
+
const journal = JSON.parse(readFileSync(file, "utf8")) as MoveJournal;
|
|
195
|
+
if (registry.get(journal.before) && !registry.get(journal.after)) {
|
|
196
|
+
for (const backup of journal.backups) {
|
|
197
|
+
if (backup.database) for (const suffix of ["-wal", "-shm", "-journal"]) rmSync(backup.file + suffix, { force: true });
|
|
198
|
+
replaceFile(backup.file, temporary => {
|
|
199
|
+
copyFileSync(backup.backup, temporary);
|
|
200
|
+
chmodSync(temporary, 0o600);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
} else if (registry.get(journal.before) || !registry.get(journal.after)) {
|
|
204
|
+
throw new Error(`ambiguous project move; inspect ${file} before starting a hub`);
|
|
205
|
+
}
|
|
206
|
+
rmSync(file);
|
|
207
|
+
sync(dirname(file));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function applyProjectMove(registry: Registry, oldRef: string, root: string, state: string | undefined, fingerprint: string,
|
|
211
|
+
afterRewrite?: () => void): ProjectMovePreview {
|
|
212
|
+
try {
|
|
213
|
+
return registry.runtimeCaptureLocked(() => {
|
|
214
|
+
const timestamp = /^([0-9-]+T[0-9-]+\.[0-9]+Z)\.[a-f0-9]{64}$/.exec(fingerprint)?.[1];
|
|
215
|
+
if (!timestamp) throw new Error("invalid project move fingerprint; run a new preview");
|
|
216
|
+
const plan = planMove(registry, oldRef, root, state, timestamp);
|
|
217
|
+
if (plan.fingerprint !== fingerprint) throw new Error("project move changed; run a new preview");
|
|
218
|
+
const { archive, old, next, stores, markers } = plan;
|
|
219
|
+
const parent = dirname(archive);
|
|
220
|
+
mkdirSync(parent, { recursive: true, mode: 0o700 });
|
|
221
|
+
const archivePath = relative(next.root, realPath(parent));
|
|
222
|
+
if (archivePath !== join(".agenthub", "archive")) throw new Error("move archive must be the project's .agenthub/archive directory");
|
|
223
|
+
mkdirSync(archive, { mode: 0o700 });
|
|
224
|
+
backupDatabase(registry.path, join(archive, "registry.db"));
|
|
225
|
+
const backups: Backup[] = stores.map(({ file, project }) => ({ file, backup: join(archive, `${project.id}.db`), database: true }));
|
|
226
|
+
for (const { file, backup } of backups) backupDatabase(file, backup);
|
|
227
|
+
for (const item of markers) {
|
|
228
|
+
const backup = join(archive, basename(item.file));
|
|
229
|
+
writeFileSync(backup, item.before, { mode: 0o600, flag: "wx" });
|
|
230
|
+
sync(backup);
|
|
231
|
+
backups.push({ file: item.file, backup, database: false });
|
|
232
|
+
}
|
|
233
|
+
const restore = join(archive, "restore.json");
|
|
234
|
+
writeFileSync(restore, JSON.stringify({ registry: registry.path, backups }, null, 2), { mode: 0o600, flag: "wx" });
|
|
235
|
+
sync(restore);
|
|
236
|
+
sync(archive);
|
|
237
|
+
sync(parent);
|
|
238
|
+
const journal: MoveJournal = { before: old.id, after: next.id, backups };
|
|
239
|
+
replaceFile(journalPath(registry), temporary => writeFileSync(temporary, JSON.stringify(journal), { mode: 0o600, flag: "wx" }));
|
|
240
|
+
for (const store of stores) {
|
|
241
|
+
rewriteStore(store, old, next);
|
|
242
|
+
if (store === stores[0]) afterRewrite?.();
|
|
243
|
+
}
|
|
244
|
+
for (const item of markers) {
|
|
245
|
+
const after = item.after;
|
|
246
|
+
if (after === undefined) {
|
|
247
|
+
rmSync(item.file);
|
|
248
|
+
sync(dirname(item.file));
|
|
249
|
+
} else replaceFile(item.file, temporary => writeFileSync(temporary, after, { mode: 0o600, flag: "wx" }));
|
|
250
|
+
}
|
|
251
|
+
registry.replaceMovedProject(old, next);
|
|
252
|
+
return plan;
|
|
253
|
+
});
|
|
254
|
+
} finally {
|
|
255
|
+
// Registry commit or rollback has returned, so the durable registry identity decides recovery.
|
|
256
|
+
registry.runtimeCaptureLocked(() => {});
|
|
257
|
+
}
|
|
258
|
+
}
|
package/src/hub/registry.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs";
|
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { canonicalPath, hubHome, projectRoot } from "./project.ts";
|
|
6
|
+
import { recoverProjectMove } from "./project-move.ts";
|
|
6
7
|
import { processLiveness } from "../pi/process-signature.ts";
|
|
7
8
|
|
|
8
9
|
const BASE_PORT = 4600;
|
|
@@ -68,7 +69,7 @@ export class Registry {
|
|
|
68
69
|
try { this.db.run("ALTER TABLE projects ADD COLUMN pid_signature TEXT"); }
|
|
69
70
|
catch (error) { if (!/duplicate column/i.test((error as Error).message)) throw error; } // a concurrent open added it
|
|
70
71
|
}
|
|
71
|
-
this.importLegacy();
|
|
72
|
+
this.runtimeCaptureLocked(() => this.importLegacy());
|
|
72
73
|
}
|
|
73
74
|
|
|
74
75
|
register(root: string, stateDir?: string): Project {
|
|
@@ -94,7 +95,7 @@ export class Registry {
|
|
|
94
95
|
throw new Error(`cannot register ${canonicalRoot}: ${(error as Error).message}`);
|
|
95
96
|
}
|
|
96
97
|
});
|
|
97
|
-
|
|
98
|
+
this.runtimeCaptureLocked(tx);
|
|
98
99
|
return this.get(id)!;
|
|
99
100
|
}
|
|
100
101
|
|
|
@@ -108,7 +109,17 @@ export class Registry {
|
|
|
108
109
|
|
|
109
110
|
/** Serialize capture publication, durable project references and pruning with registry writers. */
|
|
110
111
|
runtimeCaptureLocked<T>(fn: () => T): T {
|
|
111
|
-
return this.db.inTransaction ? fn() : this.db.transaction(
|
|
112
|
+
return this.db.inTransaction ? fn() : this.db.transaction(() => {
|
|
113
|
+
recoverProjectMove(this);
|
|
114
|
+
return fn();
|
|
115
|
+
}).immediate();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
replaceMovedProject(previous: Project, next: Project): void {
|
|
119
|
+
if (!this.db.inTransaction) throw new Error("project move requires the registry writer transaction");
|
|
120
|
+
const changed = this.db.query("UPDATE projects SET id = ?, root = ?, state_dir = ?, instance_id = NULL, pid = NULL, pid_signature = NULL, claimed_at = NULL WHERE id = ? AND root = ? AND state_dir = ?")
|
|
121
|
+
.run(next.id, next.root, next.stateDir, previous.id, previous.root, previous.stateDir);
|
|
122
|
+
if (changed.changes !== 1) throw new Error("old project registration changed; preview the move again");
|
|
112
123
|
}
|
|
113
124
|
|
|
114
125
|
allocate(root: string): number {
|
|
@@ -141,7 +152,7 @@ export class Registry {
|
|
|
141
152
|
.run(instanceId, pid, signature ? `${instanceId} ${signature}` : null, Date.now(), id);
|
|
142
153
|
claimed = true;
|
|
143
154
|
});
|
|
144
|
-
|
|
155
|
+
this.runtimeCaptureLocked(tx);
|
|
145
156
|
return claimed;
|
|
146
157
|
}
|
|
147
158
|
|
|
@@ -168,7 +179,7 @@ export class Registry {
|
|
|
168
179
|
}
|
|
169
180
|
this.db.query("DELETE FROM projects WHERE id = ?").run(id);
|
|
170
181
|
});
|
|
171
|
-
|
|
182
|
+
this.runtimeCaptureLocked(tx);
|
|
172
183
|
}
|
|
173
184
|
|
|
174
185
|
close(): void {
|
package/src/hub/restart.ts
CHANGED
|
@@ -62,6 +62,7 @@ export interface RestartSnapshot {
|
|
|
62
62
|
researchEvidence?: { links: number; revisions: number; digest: string };
|
|
63
63
|
reviewerQuota?: { rows: number; completed: number; pending: number; unknown: number; complete: boolean; waits: number; digest: string };
|
|
64
64
|
advisorSurveys?: { surveys: number; findings: number; considered: number; digest: string };
|
|
65
|
+
specReadbacks?: { readbacks: number; digest: string };
|
|
65
66
|
reviewComments?: { comments: number; packages: number; digest: string };
|
|
66
67
|
/** Stored visual payloads and image metadata, never external image bytes. */
|
|
67
68
|
visuals?: { count: number; digest: string };
|
|
@@ -187,6 +188,12 @@ export function readRestartSnapshot(stateDir: string, expected: RestartReadExpec
|
|
|
187
188
|
|| ![value.surveys, value.findings, value.considered].every(count => Number.isSafeInteger(count) && count >= 0)
|
|
188
189
|
|| typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
|
|
189
190
|
}
|
|
191
|
+
if (s.integrity && Object.hasOwn(s.integrity, "specReadbacks")) {
|
|
192
|
+
const value = s.integrity.specReadbacks;
|
|
193
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(key => !["readbacks", "digest"].includes(key))
|
|
194
|
+
|| !Number.isSafeInteger(value.readbacks) || value.readbacks < 0
|
|
195
|
+
|| typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
|
|
196
|
+
}
|
|
190
197
|
if (s.integrity && Object.hasOwn(s.integrity, "reviewComments")) {
|
|
191
198
|
const value = s.integrity.reviewComments;
|
|
192
199
|
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(key => !["comments", "packages", "digest"].includes(key))
|
package/src/hub/review-brief.ts
CHANGED
|
@@ -20,9 +20,10 @@ export function renderFindingAnchor(finding: ReviewFinding, placement: ReviewAnc
|
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
22
|
* #520: the review brief ahub builds itself, in place of `ocr delegate preview` and `rule`. Every reviewer gets the same
|
|
23
|
-
* one: the changed files of the head against
|
|
24
|
-
*
|
|
25
|
-
*
|
|
23
|
+
* one: the changed files of the head against the default branch it merges into, the files left out and why, the review rules
|
|
24
|
+
* that apply to each file, and the files the plain name list shows that the brief does not. The head and the merge base are
|
|
25
|
+
* full commit ids and the list does not depend on any checkout's state, so the same pair always gives the same brief. Only
|
|
26
|
+
* git is read, bounded; nothing here touches the board.
|
|
26
27
|
*/
|
|
27
28
|
export interface BriefFile { path: string; status: string; oldPath?: string; insertions?: number; deletions?: number }
|
|
28
29
|
export interface BriefExcluded { path: string; status: string; oldPath?: string; reason: string }
|
|
@@ -44,6 +45,8 @@ export interface ReviewBrief {
|
|
|
44
45
|
ruleGroups: { sources: string[]; paths: string[] }[];
|
|
45
46
|
/** Paths in the plain name list of the range that the brief does not list: read them directly. */
|
|
46
47
|
unlisted: string[];
|
|
48
|
+
/** #1645 T4: the tier this head was filed at and what it still owes, already rendered by `risk-tier.ts`; absent without a `[risk]` table. */
|
|
49
|
+
risk?: string;
|
|
47
50
|
}
|
|
48
51
|
|
|
49
52
|
/** A bounded, public summary of the design specs affected by one exact task head. */
|
|
@@ -219,7 +222,8 @@ function renderCodeSymbols(brief:ReviewBrief):string[] {
|
|
|
219
222
|
export function renderReviewBrief(brief: ReviewBrief): string {
|
|
220
223
|
const file = (f: BriefFile) => `- ${f.oldPath ? `${f.oldPath} -> ` : ""}${f.path} (${f.status}${f.insertions !== undefined ? `, +${f.insertions} -${f.deletions}` : ""})`;
|
|
221
224
|
return [
|
|
222
|
-
`Review brief: head ${brief.head} against ${brief.base} (merge base ${brief.mergeBase
|
|
225
|
+
`Review brief: head ${brief.head} against ${brief.base} (merge base ${brief.mergeBase}); ${brief.reviewable.length} reviewable, ${brief.excluded.length} excluded${brief.withheld ? `, ${brief.withheld} withheld by the privacy policy` : ""}.`,
|
|
226
|
+
...(brief.risk ? [brief.risk] : []),
|
|
223
227
|
...(brief.reviewable.length ? ["Reviewable:", ...brief.reviewable.map(file)] : ["Reviewable: none (record why in the note)."]),
|
|
224
228
|
...(brief.excluded.length ? ["Excluded (still read their diff when it matters):", ...brief.excluded.map(e => `- ${e.oldPath ? `${e.oldPath} -> ` : ""}${e.path} (${e.status}): ${e.reason}`)] : []),
|
|
225
229
|
...renderCodeSymbols(brief),
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #1646 T2: what the checkout the reviewer read held when the verdict was given. The hub reads it, never the reviewer, and it
|
|
3
|
+
* lives on the verdict's history entry: the approval's coverage receipt is hashed from `sdlc`, so evidence kept there would
|
|
4
|
+
* invalidate an in-flight verdict against itself.
|
|
5
|
+
*
|
|
6
|
+
* Every list is empty only because the read said so. An unreadable checkout is no evidence at all, never an empty one.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Which checkout the evidence describes. `peer-cwd` is the checkout the reviewing session reported for itself on the control
|
|
11
|
+
* socket, so the record names the bytes that session read; `project-root` is the hub's own project checkout, recorded only
|
|
12
|
+
* when the hub knows no checkout of its own for that reviewer. A later count separates "the reviewer read other bytes" from
|
|
13
|
+
* "the hub looked at the root" only because every record says which of the two it is.
|
|
14
|
+
*/
|
|
15
|
+
type ReviewCheckoutSource = "peer-cwd" | "project-root";
|
|
16
|
+
|
|
17
|
+
export interface ReviewCheckoutEvidence {
|
|
18
|
+
/** The checkout that was read: the reviewing session's own, or the project checkout. */
|
|
19
|
+
source: ReviewCheckoutSource;
|
|
20
|
+
/** That checkout's HEAD, or null when it could not be read. */
|
|
21
|
+
head: string | null;
|
|
22
|
+
/** Reviewed paths whose worktree content differs from the reviewed commit. */
|
|
23
|
+
differing: string[];
|
|
24
|
+
/** Reviewed paths the checkout holds as untracked files. */
|
|
25
|
+
untracked: string[];
|
|
26
|
+
}
|
|
@@ -12,6 +12,7 @@ export interface ReviewFinding {
|
|
|
12
12
|
path?: string;
|
|
13
13
|
disposition: "open" | "fixed" | "false_positive" | "accepted";
|
|
14
14
|
rationale?: string;
|
|
15
|
+
reopen_reason?: string;
|
|
15
16
|
anchor?: ReviewAnchor;
|
|
16
17
|
/** #1403 A1, important security findings only (an enabled lifecycle). `needs_validation` is a source-grounded hypothesis blocked on `blocker`; it never blocks approval. */
|
|
17
18
|
state?: "confirmed" | "needs_validation";
|
|
@@ -55,7 +56,7 @@ function boundaryOf(raw: unknown): FindingBoundary {
|
|
|
55
56
|
}
|
|
56
57
|
const NEEDS_SECURITY_FIELDS = "an important security finding needs state (confirmed or needs_validation) and boundary {principal, control, resource, result}: the lower-trust principal, the control that was meant to hold, the resource affected and the result observed; a missing best practice or a guessed deployment fact is not a finding";
|
|
57
58
|
/** Supplied findings are validated independently of lifecycle mode, before any board effect. */
|
|
58
|
-
export function parseReviewFindings(raw: unknown, options: { person: boolean; maxNits: number; contract?: FindingContract }): ReviewFinding[] {
|
|
59
|
+
export function parseReviewFindings(raw: unknown, options: { person: boolean; maxNits: number; contract?: FindingContract; reopenReason?: boolean }): ReviewFinding[] {
|
|
59
60
|
if (typeof options.person !== "boolean" || !Number.isSafeInteger(options.maxNits) || options.maxNits < 0 || options.maxNits > MAX_ITEMS) return fail("invalid finding authority or nit limit");
|
|
60
61
|
const contract = options.contract ?? "off";
|
|
61
62
|
if (contract !== "off" && contract !== "required" && contract !== "stored") return fail("invalid finding contract");
|
|
@@ -68,7 +69,7 @@ export function parseReviewFindings(raw: unknown, options: { person: boolean; ma
|
|
|
68
69
|
const result = Array.from({ length: raw.length }, (_, index): ReviewFinding => {
|
|
69
70
|
const entry = descriptors[String(index)];
|
|
70
71
|
if (!entry || !Object.hasOwn(entry, "value") || !entry.enumerable) return fail("finding array accessors refused");
|
|
71
|
-
const item = fields(entry.value, contract === "off" ? BASE_FIELDS : [...BASE_FIELDS, ...SECURITY_FIELDS]), id: unknown = item.id?.value, pass: unknown = item.pass?.value;
|
|
72
|
+
const item = fields(entry.value, contract === "off" ? BASE_FIELDS : [...BASE_FIELDS, ...SECURITY_FIELDS, ...(contract === "stored" || options.reopenReason ? ["reopen_reason"] : [])]), id: unknown = item.id?.value, pass: unknown = item.pass?.value;
|
|
72
73
|
const severity: unknown = item.severity?.value, disposition: unknown = item.disposition?.value;
|
|
73
74
|
if (typeof id !== "string" || !/^[A-Za-z0-9._:-]+$/.test(id) || Buffer.byteLength(id) > 96 || ids.has(id)) return fail("invalid or duplicate finding id");
|
|
74
75
|
ids.add(id);
|
|
@@ -77,6 +78,7 @@ export function parseReviewFindings(raw: unknown, options: { person: boolean; ma
|
|
|
77
78
|
if (disposition !== "open" && disposition !== "fixed" && disposition !== "false_positive" && disposition !== "accepted") return fail("invalid finding disposition");
|
|
78
79
|
const path = item.path ? text(item.path.value, 512, true) : undefined;
|
|
79
80
|
const rationale = item.rationale ? text(item.rationale.value, 2048, false) : undefined;
|
|
81
|
+
const reopenReason = item.reopen_reason ? text(item.reopen_reason.value, 512, false) : undefined;
|
|
80
82
|
const anchor = item.anchor ? parseReviewAnchor(item.anchor.value) : undefined;
|
|
81
83
|
if (path !== undefined && anchor && path !== anchor.path) return fail("path and anchor.path differ; use the same task-scoped file path");
|
|
82
84
|
if (disposition === "accepted" && (!options.person || !rationale)) return fail("accepted findings require a person and rationale");
|
|
@@ -92,7 +94,7 @@ export function parseReviewFindings(raw: unknown, options: { person: boolean; ma
|
|
|
92
94
|
if (state === "needs_validation" && blocker === undefined) return fail("a needs_validation finding names its blocker: the missing fact that settles it");
|
|
93
95
|
if (state === "confirmed" && blocker !== undefined) return fail("a confirmed finding carries no blocker; use needs_validation for a hypothesis blocked on a named fact");
|
|
94
96
|
}
|
|
95
|
-
return { id, pass, severity, disposition, ...(path !== undefined ? { path } : {}), ...(rationale !== undefined ? { rationale } : {}), ...(anchor ? { anchor } : {}),
|
|
97
|
+
return { id, pass, severity, disposition, ...(path !== undefined ? { path } : {}), ...(rationale !== undefined ? { rationale } : {}), ...(anchor ? { anchor } : {}), ...(reopenReason === undefined ? {} : { reopen_reason: reopenReason }),
|
|
96
98
|
...(state !== undefined ? { state } : {}), ...(boundary !== undefined ? { boundary } : {}), ...(blocker !== undefined ? { blocker } : {}), ...(origin !== undefined ? { origin } : {}) } as ReviewFinding;
|
|
97
99
|
});
|
|
98
100
|
if (result.filter(item => item.severity === "nit").length > options.maxNits) return fail("nit limit exceeded");
|
|
@@ -128,6 +130,7 @@ const SECURITY_KEYS = ["state", "boundary", "blocker", "origin"] as const;
|
|
|
128
130
|
*/
|
|
129
131
|
function merged(prior: ReviewFinding | undefined, item: ReviewFinding): ReviewFinding {
|
|
130
132
|
const next: ReviewFinding = { ...prior, ...item };
|
|
133
|
+
if (item.reopen_reason === undefined) delete next.reopen_reason;
|
|
131
134
|
for (const key of SECURITY_KEYS) if (item[key] === undefined) delete next[key];
|
|
132
135
|
if (prior && blocksApproval(prior) && item.disposition === "open" && !blocksApproval(item)) {
|
|
133
136
|
next.severity = "important";
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { configPathList, matchConfigPath } from "./eval-gate.ts";
|
|
2
|
+
import { completePlanInventory } from "./plan-conformance.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* #1645 T1: the risk tier of a filed change, derived from its complete file inventory. Pure: no clock, no I/O, no board, and never
|
|
6
|
+
* the worktree. `[risk]` in `.agenthub/sdlc.toml` names the paths that make a change `high` and the ones that keep it `low`; a path
|
|
7
|
+
* no pattern names is `medium`, and a path `[security]` names is always `high`, so a project with a security table can never derive
|
|
8
|
+
* `low` from a change the security pass treats as sensitive. The tier names are this repository's closed set, never a model's word for one, and they stay
|
|
9
|
+
* unexported: the one place outside this file that spells a tier's rules is `riskMinimum`, which the verdict, the plan review and the merge gate all read
|
|
10
|
+
* (#1645 T3).
|
|
11
|
+
*/
|
|
12
|
+
const RISK_TIERS = ["low", "medium", "high"] as const;
|
|
13
|
+
type RiskTier = (typeof RISK_TIERS)[number];
|
|
14
|
+
/** Globs only, in the `config_paths` pattern language: no model call ever decides a tier. */
|
|
15
|
+
export interface RiskPolicy { high: string[]; low: string[] }
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Validated at load, like `securityPolicy`: unknown fields, a non-table, an empty table, a repeated pattern or a pattern outside the
|
|
19
|
+
* language are refused with the language spelled out, because these names are printed back in review requests and merge gates.
|
|
20
|
+
*/
|
|
21
|
+
export function riskPolicy(value: unknown): RiskPolicy {
|
|
22
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("sdlc.risk: expected a table with high and low");
|
|
23
|
+
const raw = value as Record<string, unknown>;
|
|
24
|
+
for (const key of Object.keys(raw)) if (key !== "high" && key !== "low") throw new Error(`sdlc.risk.${key}: unknown field (use high and low)`);
|
|
25
|
+
if (raw.high === undefined && raw.low === undefined) throw new Error("sdlc.risk: name at least one of high and low (for example high = [\"src/hub/sdlc-merge.ts\"], low = [\"docs/**\"])");
|
|
26
|
+
const high = raw.high === undefined ? [] : configPathList(raw.high, "sdlc.risk.high");
|
|
27
|
+
const low = raw.low === undefined ? [] : configPathList(raw.low, "sdlc.risk.low");
|
|
28
|
+
const both = high.find(pattern => low.includes(pattern));
|
|
29
|
+
if (both !== undefined) throw new Error(`sdlc.risk: "${both}" is named in both high and low`);
|
|
30
|
+
return { high, low };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What a filing recorded: the tier, the head it was derived for, and how many changed paths decided it. A tier for another head is never read. */
|
|
34
|
+
export interface RiskRecord { tier: RiskTier; head: string; matched: number }
|
|
35
|
+
|
|
36
|
+
/** The lifecycle receipt a re-file starts from: the tier it carried belonged to the head that filing replaced, so it is dropped rather than read across heads. */
|
|
37
|
+
export function withoutRisk<T extends object>(receipt: T | undefined): Omit<T, "risk"> | undefined {
|
|
38
|
+
if (!receipt) return undefined;
|
|
39
|
+
const rest: Record<string, unknown> = {};
|
|
40
|
+
for (const [key, value] of Object.entries(receipt)) if (key !== "risk") rest[key] = value;
|
|
41
|
+
return rest as Omit<T, "risk">;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* `undefined` when no `[risk]` table exists (the project keeps today's behaviour), when the inventory is incomplete or unreadable
|
|
46
|
+
* (never `medium` by default: an unreadable change is not a classified one), when the PR changed no file at all, or when the evidence
|
|
47
|
+
* belongs to a head other than the one being filed: a tier is a statement about one inventory, so it is never carried across heads.
|
|
48
|
+
*/
|
|
49
|
+
export function deriveRiskTier(policy: RiskPolicy | undefined, securityPaths: readonly string[], evidence: { head: string; paths: readonly string[]; pathsComplete?: boolean; typesComplete?: boolean } | undefined, head: string | undefined): RiskRecord | undefined {
|
|
50
|
+
if (!policy || !evidence || !head || evidence.head !== head) return undefined;
|
|
51
|
+
const inventory = completePlanInventory(evidence);
|
|
52
|
+
if (inventory === undefined || !inventory.length) return undefined;
|
|
53
|
+
const matching = (patterns: readonly string[]): number => inventory.filter(path => patterns.some(pattern => matchConfigPath(pattern, path))).length;
|
|
54
|
+
const high = matching([...securityPaths, ...policy.high]);
|
|
55
|
+
if (high) return { tier: "high", head: evidence.head, matched: high };
|
|
56
|
+
const low = matching(policy.low);
|
|
57
|
+
if (low === inventory.length) return { tier: "low", head: evidence.head, matched: low };
|
|
58
|
+
return { tier: "medium", head: evidence.head, matched: inventory.length - low };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The one-review floor of the workspace lifecycle: no tier and no plan goes below it (#1645, "Family constraint"). */
|
|
62
|
+
const RISK_REVIEW_FLOOR = 1;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* #1645 T3: what one tier owes. The floor is one reviewer on every tier and this file is the only place it is spelled, so raising it moves
|
|
66
|
+
* the verdict check, the plan-review report, the review request, the brief and the merge gate together. `high` adds a verifier card, which is
|
|
67
|
+
* a task of class `test` (docs/sdlc.md's own lifecycle table gives that stage the acting role verifier/reviewer) owned by a peer other than
|
|
68
|
+
* the implementer. That is the person's table of 2026-11-25 and nothing else.
|
|
69
|
+
*/
|
|
70
|
+
interface RiskMinimum { reviewers: number; verifier: boolean }
|
|
71
|
+
export function riskMinimum(tier: RiskTier): RiskMinimum {
|
|
72
|
+
return { reviewers: RISK_REVIEW_FLOOR, verifier: tier === "high" };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* A board card as the verdict check sees it: only the fields that say which change it verified and for whom. A verifier is identified by what
|
|
77
|
+
* the board already records and never by a new field - class `test`, the subject's repository and branch, the filed head in `refs.commit`, an
|
|
78
|
+
* approved state and another peer's owner - so #1645 T3 invents no card shape and no board column.
|
|
79
|
+
*/
|
|
80
|
+
export interface RiskCard { id: number; class: string; state: string; owner: string | null; repo?: string; branch?: string; commit?: string }
|
|
81
|
+
/** The filed change a verifier answers to: its repository, branch and head, and whoever implemented it. */
|
|
82
|
+
interface RiskSubject { repo?: string; branch?: string; head?: string; implementer: string | null }
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The approved verifier card of this exact change, or `undefined`. What identifies a card is the head it verified: `refs.commit` must be the filed
|
|
86
|
+
* head, and a card for an older head is never one because a tier is a statement about one head. The branch narrows it to the same change when the
|
|
87
|
+
* filing named one; a task filed without `refs.branch` is matched by repository and head instead, so it can still satisfy its tier (a change filed
|
|
88
|
+
* that way would otherwise owe a card no proposal could satisfy).
|
|
89
|
+
*/
|
|
90
|
+
function riskVerifier(cards: readonly RiskCard[], subject: RiskSubject): RiskCard | undefined {
|
|
91
|
+
if (!subject.head) return undefined;
|
|
92
|
+
const repo = subject.repo?.toLowerCase();
|
|
93
|
+
return cards.find(card => card.class === "test" && card.state === "approved" && card.owner !== null && card.owner !== subject.implementer
|
|
94
|
+
&& card.commit === subject.head && (subject.branch === undefined || card.branch === subject.branch)
|
|
95
|
+
&& (repo === undefined || card.repo === undefined || card.repo.toLowerCase() === repo));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What the receipt's tier says about the head being judged, with the verifier the board holds for it. `undefined` for another head, never a carried tier. */
|
|
99
|
+
export interface RiskView { tier: RiskTier; head: string; matched: number; repo?: string; branch?: string; minimum: RiskMinimum; verifier?: { id: number; owner: string | null } }
|
|
100
|
+
export function riskView(risk: RiskRecord | undefined, cards: readonly RiskCard[], subject: RiskSubject): RiskView | undefined {
|
|
101
|
+
if (!risk || risk.head !== subject.head) return undefined;
|
|
102
|
+
const minimum = riskMinimum(risk.tier), verifier = minimum.verifier ? riskVerifier(cards, subject) : undefined;
|
|
103
|
+
return { tier: risk.tier, head: risk.head, matched: risk.matched, ...(subject.repo ? { repo: subject.repo } : {}), ...(subject.branch ? { branch: subject.branch } : {}), minimum, ...(verifier ? { verifier: { id: verifier.id, owner: verifier.owner } } : {}) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* #1645 T3, AC3 and AC5's display: what this head owes its tier and whether the board holds it, in one line the review request, the brief, the
|
|
108
|
+
* task view and a verdict's note all print. The command that supplies a missing card is not here: a refusal writes its own continuation, and
|
|
109
|
+
* `scripts/refusal-inventory.ts` reads a command only from the site that throws it.
|
|
110
|
+
*/
|
|
111
|
+
export function riskLine(view: RiskView): string {
|
|
112
|
+
const decided = `${view.matched} path${view.matched === 1 ? "" : "s"} decided it`;
|
|
113
|
+
const owes = view.minimum.verifier ? "one reviewer plus a verifier card by another peer" : "one reviewer";
|
|
114
|
+
if (view.minimum.verifier && !view.verifier) return `risk ${view.tier} (${decided}); minimum ${owes}; no verifier card by another peer is approved at this head`;
|
|
115
|
+
const met = view.verifier ? `; verifier card ${view.verifier.id} is approved` : "";
|
|
116
|
+
return `risk ${view.tier} (${decided}); minimum ${owes}${met}`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* #1645 T4, AC5: a plan's `review` metadata is cost metadata and may ask for more than the floor, never less. No tier exists before a filed
|
|
121
|
+
* inventory, so the plan-review report compares against the floor; where a tier does exist (the review request and the merge gate) the caller
|
|
122
|
+
* passes that tier's minimum, because `high` owes the verifier card as well.
|
|
123
|
+
*/
|
|
124
|
+
export function riskPlanFloor(review: { scope?: string; reviewers?: number } | undefined, minimum: RiskMinimum = riskMinimum("low")): string | undefined {
|
|
125
|
+
const asked = review?.scope === "none" ? 0 : review?.reviewers;
|
|
126
|
+
if (asked === undefined || asked >= minimum.reviewers) return undefined;
|
|
127
|
+
const owes = `${minimum.reviewers} reviewer${minimum.reviewers === 1 ? "" : "s"}${minimum.verifier ? " plus a verifier card" : ""}`;
|
|
128
|
+
return `plan review asked for ${asked} reviewer${asked === 1 ? "" : "s"}, below the minimum of ${owes}`;
|
|
129
|
+
}
|