@staix/agent-hub 0.43.0 → 0.45.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 +61 -0
- package/README.md +3 -8
- package/docs/agent-notes/adapters.md +2 -2
- package/docs/agent-notes/daemon.md +4 -4
- package/docs/agent-notes/local-worker.md +2 -1
- package/docs/agent-notes/security-review.md +1 -1
- package/docs/agent-notes/tasks.md +5 -2
- package/docs/agent-notes/tests.md +4 -3
- package/docs/design/adapters.md +4 -2
- package/docs/design/agent-hub-architecture.md +2 -0
- package/docs/design/agent-hub.md +1 -1
- package/docs/design/roadmap.md +75 -2
- package/docs/design/supervision.md +34 -2
- package/docs/design/task-board.md +36 -2
- package/docs/dogfood.md +20 -5
- package/docs/events.md +9 -3
- package/docs/influences.md +7 -0
- package/docs/memory.md +4 -4
- package/docs/operations.md +84 -31
- package/docs/quickstart.md +14 -2
- package/docs/research.md +18 -0
- package/docs/roadmap.json +4 -0
- package/docs/roadmap.md +9 -0
- package/docs/sdlc.md +19 -4
- package/docs/security.md +4 -4
- package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
- package/docs/verification/2026-11-19-0.44.0.md +60 -0
- package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
- package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
- package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
- package/docs/verification/2026-11-21-0.45.0.md +69 -0
- package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
- package/docs/verified.json +32 -26
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +585 -264
- package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
- package/plugins/agent-hub/server.js +629 -293
- package/scripts/check-docs.mjs +9 -1
- package/src/adapters/acp.ts +11 -1
- package/src/adapters/compat.ts +3 -3
- package/src/adapters/definitions/builtin-metadata.ts +2 -2
- package/src/adapters/definitions/native-context.ts +10 -0
- package/src/adapters/jcode.ts +10 -0
- package/src/adapters/local-worker.ts +3 -2
- package/src/adapters/pi.ts +15 -4
- package/src/cli/console-state.ts +3 -1
- package/src/cli/help.ts +3 -1
- package/src/cli/identity.ts +2 -1
- package/src/cli/main.ts +12 -6
- package/src/cli/output.ts +2 -2
- package/src/cli/recovery-package.ts +16 -3
- package/src/cli/roadmap-write.ts +59 -0
- package/src/cli/roadmap.ts +81 -4
- package/src/cli/sdlc-output.ts +11 -1
- package/src/cli/upgrade-runtime.ts +10 -6
- package/src/cli/upgrade.ts +9 -3
- package/src/hub/agent-mem-range.ts +43 -0
- package/src/hub/board.ts +116 -2
- package/src/hub/bus.ts +4 -0
- package/src/hub/check-runner.ts +25 -1
- package/src/hub/claude-shell-wrapper.ts +2 -1
- package/src/hub/config-apply.ts +4 -2
- package/src/hub/config-trust.ts +1 -1
- package/src/hub/context-window.ts +1 -1
- package/src/hub/control-write-trace.ts +39 -2
- package/src/hub/cost-governance.ts +11 -7
- package/src/hub/daemon.ts +318 -53
- package/src/hub/dogfood-read.ts +4 -2
- package/src/hub/edit-guard.ts +100 -0
- package/src/hub/events.ts +79 -8
- package/src/hub/facts.ts +85 -2
- package/src/hub/hub-tools.ts +3 -1
- package/src/hub/lifecycle.ts +6 -1
- package/src/hub/log-rotation.ts +130 -0
- package/src/hub/memory-profile.ts +137 -21
- package/src/hub/no-writes.ts +1 -0
- package/src/hub/operational-authority.ts +3 -2
- package/src/hub/operational-settings.ts +2 -2
- package/src/hub/quota-events.ts +40 -0
- package/src/hub/recovery-store.ts +70 -24
- package/src/hub/report.ts +1 -1
- package/src/hub/research-experiments.ts +132 -0
- package/src/hub/research-quality.ts +13 -3
- package/src/hub/research-record.ts +38 -2
- package/src/hub/research.ts +128 -28
- package/src/hub/restart.ts +49 -2
- package/src/hub/roadmap-check.ts +65 -0
- package/src/hub/roadmap-decompose.ts +80 -0
- package/src/hub/roadmap-export.ts +27 -0
- package/src/hub/roadmap-sync.ts +97 -0
- package/src/hub/roadmap.ts +40 -0
- package/src/hub/runtime-capture-prune.ts +9 -1
- package/src/hub/runtime-prune-health.ts +5 -1
- package/src/hub/sdlc-branch-ci.ts +128 -0
- package/src/hub/sdlc-merge.ts +12 -5
- package/src/hub/sdlc-metrics.ts +33 -10
- package/src/hub/sdlc.ts +90 -10
- package/src/hub/settings.ts +1 -0
- package/src/hub/snapshots.ts +56 -1
- package/src/hub/startup-event-seeds.ts +21 -15
- package/src/hub/startup-timing.ts +3 -1
- package/src/hub/supervision-proposals.ts +10 -2
- package/src/hub/supervision-rules.ts +27 -4
- package/src/hub/supervision.ts +7 -0
- package/src/hub/task-pr.ts +47 -0
- package/src/hub/task-shell-command.ts +124 -0
- package/src/hub/task-worktree.ts +18 -11
- package/src/hub/tasks.ts +617 -45
- package/src/hub/usage-rollup.ts +35 -20
- package/src/hub/worktree-shelf.ts +2 -1
- package/src/local/sandbox.ts +2 -1
- package/src/local/shell-environment.ts +6 -0
- package/src/local/tools.ts +13 -1
- package/src/memory/brief.ts +10 -1
- package/src/memory/client.ts +3 -2
- package/src/pi/extension.ts +15 -3
- package/src/pi/tool-receipts.ts +26 -0
package/src/hub/dogfood-read.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { claimListId } from "./board.ts";
|
|
2
|
+
import { segmentsOf } from "./log-rotation.ts";
|
|
2
3
|
import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
|
|
3
4
|
import { join } from "node:path";
|
|
4
5
|
import { Database } from "bun:sqlite";
|
|
@@ -32,7 +33,8 @@ export function dogfoodLines(file: string, cap = DOGFOOD_BYTE_CAP): Source<strin
|
|
|
32
33
|
if (start) { const newline = text.indexOf("\n"); text = newline < 0 ? "" : text.slice(newline + 1); }
|
|
33
34
|
const whole = text.endsWith("\n") || !text;
|
|
34
35
|
if (!whole) text = text.slice(0,Math.max(0,text.lastIndexOf("\n") + 1));
|
|
35
|
-
|
|
36
|
+
// #1546: rotated segments hold older history this tail never reads, so the read is not whole once the log has rotated.
|
|
37
|
+
return source(text.split("\n").filter(Boolean), !start && n === stat.size && whole && !segmentsOf(file).some(segment => !segment.live));
|
|
36
38
|
} catch { return missing([]); }
|
|
37
39
|
finally { if (fd !== undefined) closeSync(fd); }
|
|
38
40
|
}
|
|
@@ -247,7 +249,7 @@ export async function dogfoodPrs(repo: string, tasks: Source<DogfoodTask[]>, sin
|
|
|
247
249
|
}
|
|
248
250
|
} catch { /* Missing or incomplete recorded heads cannot certify CI. */ }
|
|
249
251
|
return reply;
|
|
250
|
-
});
|
|
252
|
+
}, undefined, undefined, undefined, true);
|
|
251
253
|
const row: DogfoodPr = cost ?? {repo,pr:item.number,state:"MERGED",mergedAt:date(item.mergedAt),complete:false};
|
|
252
254
|
const linked = runsComplete ? runs.filter((r:any)=>date(r.created_at)!<=row.mergedAt!) : [];
|
|
253
255
|
if (runsComplete) {
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, relative } from "node:path";
|
|
4
|
+
import { MAX_RECEIPTS_PER_PEER, type Facts } from "./facts.ts";
|
|
5
|
+
import { MAX_OBSERVATIONS } from "./supervision-rules.ts";
|
|
6
|
+
import { classifyShellWrite } from "./task-shell-command.ts";
|
|
7
|
+
import { PreEffectToolRefusal } from "./tool-refusal.ts";
|
|
8
|
+
|
|
9
|
+
export type EditGuardArm = "baseline" | "route_guard" | "occ_guard" | "combined_guard";
|
|
10
|
+
export type EditGuardAvailability = "admitted" | "unavailable";
|
|
11
|
+
export function parseEditGovernance(raw: unknown): { arm: EditGuardArm } {
|
|
12
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).some(key => key !== "arm")) throw new Error("edit_governance requires an arm");
|
|
13
|
+
const arm = (raw as { arm?: unknown }).arm;
|
|
14
|
+
if (arm !== "baseline" && arm !== "route_guard" && arm !== "occ_guard" && arm !== "combined_guard") throw new Error("edit_governance.arm is invalid");
|
|
15
|
+
return { arm };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A host-bound tool transaction. The caller owns the peer, task, generation and policy checks. */
|
|
19
|
+
export function editGuard(input: { root: string; peer: string; task: number; turn: string; ownerEpoch: string; arm: () => EditGuardArm; current: () => boolean; facts: Facts; evidence?: EditEvidence; revision?: string; changed?: () => void; observeShell?: () => boolean }) {
|
|
20
|
+
const name = (file: string) => {
|
|
21
|
+
const result = relative(input.root, file);
|
|
22
|
+
if (!result || isAbsolute(result) || result === ".." || result.startsWith("../")) throw new PreEffectToolRefusal("edit guard target unavailable; inspect the task before retrying");
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
const current = () => {
|
|
26
|
+
let valid = false; try { valid = input.current(); } catch { /* unknown authority refuses */ }
|
|
27
|
+
if (!valid) throw new PreEffectToolRefusal("edit guard authority changed; inspect the task before retrying");
|
|
28
|
+
};
|
|
29
|
+
const changed = () => { try { input.changed?.(); } catch { /* optional observation */ } };
|
|
30
|
+
const digest = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
|
|
31
|
+
return {
|
|
32
|
+
read(file: string, bytes: Buffer, full: boolean): void {
|
|
33
|
+
current(); input.facts.recordRead(input.peer, input.task, name(file), { sha256: digest(bytes), scope: full ? "full" : "partial", turnId: input.turn, ownerEpoch: input.ownerEpoch });
|
|
34
|
+
if (full && input.revision) input.evidence?.diagnosticRead(input.task, input.revision);
|
|
35
|
+
changed();
|
|
36
|
+
},
|
|
37
|
+
write(file: string): boolean | undefined {
|
|
38
|
+
current(); const arm = input.arm(), path = name(file); let hash: string;
|
|
39
|
+
try { hash = digest(readFileSync(file)); } catch (error) {
|
|
40
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
41
|
+
current();
|
|
42
|
+
if (code === "ENOENT") return true;
|
|
43
|
+
if (arm === "occ_guard" || arm === "combined_guard") {
|
|
44
|
+
const cause = typeof code === "string" && /^[A-Z][A-Z0-9_]{0,31}$/.test(code) ? code : "unavailable";
|
|
45
|
+
throw new PreEffectToolRefusal(`edit guard cannot read the current file (${cause}); inspect it before retrying`);
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
current();
|
|
50
|
+
const receipt = input.facts.readReceipt(input.peer, input.task, path);
|
|
51
|
+
const unverified = !receipt || receipt.ownerEpoch !== input.ownerEpoch || receipt.sha256 !== hash;
|
|
52
|
+
if (unverified && (arm === "occ_guard" || arm === "combined_guard")) throw new PreEffectToolRefusal(`blind or stale write refused; current sha256 ${hash}; re-read the file before retrying`);
|
|
53
|
+
return unverified;
|
|
54
|
+
},
|
|
55
|
+
written(file: string, unverified: boolean | undefined): void {
|
|
56
|
+
if (input.current() && input.revision) { input.evidence?.write(input.task, input.revision, name(file), unverified === true); changed(); }
|
|
57
|
+
},
|
|
58
|
+
shell(command: string): (() => void) | undefined {
|
|
59
|
+
current(); const arm = input.arm(), classified = classifyShellWrite(command);
|
|
60
|
+
if ((arm === "route_guard" || arm === "combined_guard") && classified.kind === "write") throw new PreEffectToolRefusal("shell write refused by route guard; use the dedicated edit tool");
|
|
61
|
+
if (!input.observeShell?.()) return undefined;
|
|
62
|
+
if (classified.kind === "unknown") { if (input.revision) input.evidence?.unknownShell(input.task, input.revision); changed(); return undefined; }
|
|
63
|
+
if (classified.kind !== "write") return undefined;
|
|
64
|
+
const id = randomUUID(), args = { command };
|
|
65
|
+
try { input.facts.preTool(input.peer, id, "Bash", args); } catch { return undefined; }
|
|
66
|
+
return () => { if (input.current()) input.facts.postTool(input.peer, id, "Bash", args); };
|
|
67
|
+
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Bounded, in-memory evidence. File identifiers never leave this store. */
|
|
73
|
+
export class EditEvidence {
|
|
74
|
+
private readonly rows = new Map<number, { revision: string; unverified: number; unknownShell: number; failed: boolean; cascading: Set<string> }>();
|
|
75
|
+
private row(task: number, revision: string) {
|
|
76
|
+
let row = this.rows.get(task);
|
|
77
|
+
if (!row || row.revision !== revision) {
|
|
78
|
+
row = { revision, unverified: 0, unknownShell: 0, failed: false, cascading: new Set() };
|
|
79
|
+
this.rows.delete(task); this.rows.set(task, row);
|
|
80
|
+
while (this.rows.size > MAX_OBSERVATIONS) this.rows.delete(this.rows.keys().next().value as number);
|
|
81
|
+
}
|
|
82
|
+
return row;
|
|
83
|
+
}
|
|
84
|
+
unknownShell(task: number, revision: string): void { const row = this.row(task, revision); row.unknownShell = Math.min(MAX_RECEIPTS_PER_PEER, row.unknownShell + 1); }
|
|
85
|
+
check(task: number, revision: string, result: "failed" | "passed"): void {
|
|
86
|
+
const row = this.row(task, revision); row.failed = result === "failed"; row.cascading.clear();
|
|
87
|
+
}
|
|
88
|
+
diagnosticRead(task: number, revision: string): void { const row = this.row(task, revision); row.failed = false; row.cascading.clear(); }
|
|
89
|
+
write(task: number, revision: string, file: string, unverified: boolean): void {
|
|
90
|
+
const row = this.row(task, revision);
|
|
91
|
+
if (unverified) row.unverified = Math.min(MAX_RECEIPTS_PER_PEER, row.unverified + 1);
|
|
92
|
+
if (row.failed && row.cascading.size < MAX_RECEIPTS_PER_PEER) row.cascading.add(createHash("sha256").update(file).digest("hex"));
|
|
93
|
+
}
|
|
94
|
+
snapshot(task: number, revision: string) {
|
|
95
|
+
const row = this.rows.get(task);
|
|
96
|
+
return row?.revision === revision ? { task, revision, unverified: row.unverified, unknownShell: row.unknownShell, cascading: row.cascading.size } : undefined;
|
|
97
|
+
}
|
|
98
|
+
close(task: number): void { this.rows.delete(task); }
|
|
99
|
+
reset(): void { this.rows.clear(); }
|
|
100
|
+
}
|
package/src/hub/events.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
|
|
2
2
|
import type { TaskAttribution } from "./attribution.ts";
|
|
3
|
+
import { segmentsOf, streamEnd } from "./log-rotation.ts";
|
|
3
4
|
import type { PeerId } from "./envelope.ts";
|
|
4
5
|
import type { StageSwitchTrace as SwitchTrace } from "../models/route/stage-fallback.ts";
|
|
5
6
|
import type { ScreenRecord } from "./inference.ts";
|
|
@@ -24,6 +25,24 @@ export function turnModelFields(observed: unknown): { model: string; modelEviden
|
|
|
24
25
|
return label !== undefined && isModelEvidence(evidence) ? { model: label, modelEvidence: evidence } : {};
|
|
25
26
|
}
|
|
26
27
|
|
|
28
|
+
/** #1556 T2: the closed, text-free edit counts a turn may add to `turn_end` (only when it modified files). `e` is the edit tool [total, verifiedFull, partialOnly, blindOrStale, occRejected], `s` the shell route [total, verifiedFull, partialOnly, blindOrStale, blockedByGuard], `u` tree writes no stream attributed. Counts only: never a path, a command or text. */
|
|
29
|
+
export const EDIT_OBS = ["hook", "stream", "tree"] as const;
|
|
30
|
+
export const EDIT_ARMS = ["baseline", "soft_guidance", "route_guard", "occ_guard", "combined_guard", "shadow"] as const;
|
|
31
|
+
export type EditCounts = [number, number, number, number, number];
|
|
32
|
+
export interface TurnEdits { obs: (typeof EDIT_OBS)[number]; arm?: (typeof EDIT_ARMS)[number]; e?: EditCounts; s?: EditCounts; u?: number; fe?: number; rev?: number }
|
|
33
|
+
const EDIT_MAX = 1_000_000;
|
|
34
|
+
const editCount = (v: unknown): v is number => typeof v === "number" && Number.isSafeInteger(v) && v >= 0 && v <= EDIT_MAX;
|
|
35
|
+
const editCounts = (v: unknown): EditCounts | undefined => Array.isArray(v) && v.length === 5 && v.every(editCount) ? (v as EditCounts).slice() as EditCounts : undefined;
|
|
36
|
+
/** Rebuilds `turn_end.edits` from an untrusted value, field by field: a field that is not exactly the closed shape is dropped whole, and a value with no valid `obs` is dropped altogether. */
|
|
37
|
+
export function turnEdits(raw: unknown): TurnEdits | undefined {
|
|
38
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
|
39
|
+
const r = raw as Record<string, unknown>;
|
|
40
|
+
if (!(EDIT_OBS as readonly unknown[]).includes(r.obs)) return undefined;
|
|
41
|
+
const e = editCounts(r.e), s = editCounts(r.s);
|
|
42
|
+
return { obs: r.obs as TurnEdits["obs"], ...((EDIT_ARMS as readonly unknown[]).includes(r.arm) ? { arm: r.arm as TurnEdits["arm"] } : {}), ...(e ? { e } : {}), ...(s ? { s } : {}),
|
|
43
|
+
...(editCount(r.u) ? { u: r.u } : {}), ...(editCount(r.fe) ? { fe: r.fe } : {}), ...(editCount(r.rev) ? { rev: r.rev } : {}) };
|
|
44
|
+
}
|
|
45
|
+
|
|
27
46
|
/** Bumped whenever a field changes meaning or goes away; new fields and new types do not bump it. */
|
|
28
47
|
export const EVENTS_SCHEMA = 1;
|
|
29
48
|
|
|
@@ -77,7 +96,7 @@ export type HubEvent =
|
|
|
77
96
|
| { type: "state"; peer: string; state: string }
|
|
78
97
|
| { type: "turn_start"; peer: string; turn: string }
|
|
79
98
|
| { type: "native_thread"; peer: string; thread: string; fresh: boolean }
|
|
80
|
-
| ({ type: "turn_end"; peer: string; turn: string; ms: number; tokens?: number; files?: number; snapshotMs?: number; preparedRoles?: RoleIdentity[] | null; model?: string; modelEvidence?: ModelEvidence } & Partial<TaskAttribution>)
|
|
99
|
+
| ({ type: "turn_end"; peer: string; turn: string; ms: number; tokens?: number; files?: number; snapshotMs?: number; preparedRoles?: RoleIdentity[] | null; model?: string; modelEvidence?: ModelEvidence; edits?: TurnEdits } & Partial<TaskAttribution>)
|
|
81
100
|
| { type: "native_turn_end"; peer: string; id?: string; reason?: "user_canceled" | "error" | "max_invocations" | "max_forced_invocations" | "max_token_budget_exceeded" | "terminal_step_type" | "terminal_custom_hook" }
|
|
82
101
|
| { type: "conduct"; peer: string; action: string; task?: number; target?: string }
|
|
83
102
|
| ({ type: "agent_cli"; peer: string; command: string; refused: boolean; delegated?: true; instructed?: true } & Partial<TaskAttribution>)
|
|
@@ -164,15 +183,67 @@ export function tokenDeltas(): (peer: string, total: number, session: string) =>
|
|
|
164
183
|
}
|
|
165
184
|
|
|
166
185
|
/**
|
|
167
|
-
* Events at or after `since` (ms), skipping lines a crash cut short.
|
|
168
|
-
*
|
|
186
|
+
* Events at or after `since` (ms), skipping lines a crash cut short. Reads every rotated segment (`log-rotation.ts`, #1546) oldest first and then the live file, so rotation never hides history from a reader;
|
|
187
|
+
* the segment list is read again afterwards and the read repeated if a rotation moved the live file meanwhile.
|
|
169
188
|
*/
|
|
170
189
|
export function readEvents(file: string, since = 0): StampedEvent[] {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
190
|
+
for (let attempt = 0; ; attempt++) {
|
|
191
|
+
const segments = segmentsOf(file), out: StampedEvent[] = [];
|
|
192
|
+
for (const segment of segments) {
|
|
193
|
+
let text: string;
|
|
194
|
+
try { text = readFileSync(segment.path, "utf8"); } catch { continue; } // moved by a rotation since the listing: the check below repeats the read
|
|
195
|
+
for (const line of text.split("\n")) { const event = parseEventLine(line, since); if (event !== undefined) out.push(event); }
|
|
196
|
+
}
|
|
197
|
+
const again = segmentsOf(file);
|
|
198
|
+
if (attempt >= 3 || (again.length === segments.length && again.every((segment, i) => segment.path === segments[i]!.path && segment.start === segments[i]!.start))) return out;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* #1555 AC5, #1546: the whole lines of the event log (its rotated segments and the live file make one byte stream: an offset is a position in that stream, so it keeps its meaning across a rotation) from byte `from` up to byte `to` (default: the end), each with the byte offset it starts at, read in bounded chunks, never the file from byte 0 unless `from` is 0.
|
|
204
|
+
* A trailing piece with no newline yet is not a line: it is left for the pass that sees its end. Returns the offset after the last whole line, which is where the next pass starts.
|
|
205
|
+
* A line is the bytes between two `\n`, so a multi-byte character never splits one.
|
|
206
|
+
* Bytes below the oldest kept segment are gone: a `from` below it starts at the oldest segment. A trailing piece with no newline can only be the live file's last bytes.
|
|
207
|
+
*/
|
|
208
|
+
export function scanEventLines(file: string, from: number, each: (line: string, offset: number) => void, to = Infinity): number {
|
|
209
|
+
const segments = segmentsOf(file);
|
|
210
|
+
if (!segments.length) return from;
|
|
211
|
+
let position = Math.max(from, segments[0]!.start);
|
|
212
|
+
const end = Math.min(streamEnd(segments), to);
|
|
213
|
+
for (const segment of segments) {
|
|
214
|
+
const segmentEnd = Math.min(segment.start + segment.size, end);
|
|
215
|
+
if (segmentEnd <= position) continue;
|
|
216
|
+
if (segment.start >= end) break;
|
|
217
|
+
position = segment.start + scanFileLines(segment.path, position - segment.start, (line, offset) => each(line, segment.start + offset), segmentEnd - segment.start);
|
|
218
|
+
if (position < segmentEnd) break; // a trailing piece with no newline yet: the next pass sees its end
|
|
219
|
+
}
|
|
220
|
+
return position;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function scanFileLines(file: string, from: number, each: (line: string, offset: number) => void, to: number): number {
|
|
224
|
+
if (!existsSync(file)) return from;
|
|
225
|
+
const fd = openSync(file, "r");
|
|
226
|
+
try {
|
|
227
|
+
const end = Math.min(fstatSync(fd).size, to);
|
|
228
|
+
const chunk = Buffer.alloc(1 << 20);
|
|
229
|
+
let pending = Buffer.alloc(0), base = from, at = from;
|
|
230
|
+
while (at < end) {
|
|
231
|
+
const n = readSync(fd, chunk, 0, Math.min(chunk.length, end - at), at);
|
|
232
|
+
if (n <= 0) break;
|
|
233
|
+
at += n;
|
|
234
|
+
const data = pending.length ? Buffer.concat([pending, chunk.subarray(0, n)]) : Buffer.from(chunk.subarray(0, n));
|
|
235
|
+
let lineStart = 0;
|
|
236
|
+
for (let nl = data.indexOf(0x0a, lineStart); nl >= 0; nl = data.indexOf(0x0a, lineStart)) {
|
|
237
|
+
each(data.toString("utf8", lineStart, nl), base + lineStart);
|
|
238
|
+
lineStart = nl + 1;
|
|
239
|
+
}
|
|
240
|
+
base += lineStart;
|
|
241
|
+
pending = data.subarray(lineStart);
|
|
242
|
+
}
|
|
243
|
+
return base;
|
|
244
|
+
} finally {
|
|
245
|
+
closeSync(fd);
|
|
246
|
+
}
|
|
176
247
|
}
|
|
177
248
|
|
|
178
249
|
/** The historical event-reader predicate, shared without adding shape or line-size restrictions. */
|
package/src/hub/facts.ts
CHANGED
|
@@ -8,6 +8,8 @@ import { isDenied } from "../local/deny.ts";
|
|
|
8
8
|
import { hubGitArgv, hubGitEnv } from "./git.ts";
|
|
9
9
|
import { realPath } from "./project.ts";
|
|
10
10
|
import { insideRoot } from "./path-policy.ts";
|
|
11
|
+
import { classifyShellWrite } from "./task-shell-command.ts";
|
|
12
|
+
import type { EditCounts, TurnEdits } from "./events.ts";
|
|
11
13
|
|
|
12
14
|
/**
|
|
13
15
|
* Turn-free facts (issue #108): what changed in an owner's files since it last acknowledged them, as a diff with who
|
|
@@ -88,6 +90,12 @@ export interface FactsOptions {
|
|
|
88
90
|
deny?: string[];
|
|
89
91
|
/** Configured private paths are never read or shown as automatic facts. */
|
|
90
92
|
privatePath?: (path: string) => boolean;
|
|
93
|
+
/** Optional host-only edit evidence; callbacks never decide whether a tool ran. */
|
|
94
|
+
onEdit?: (peer: PeerId, file: string, route: "edit" | "shell", grade: 1 | 2 | 3 | undefined) => void;
|
|
95
|
+
onDiagnosticRead?: (peer: PeerId) => void;
|
|
96
|
+
onUnknownShell?: (peer: PeerId) => void;
|
|
97
|
+
/** Active public task for edit evidence when no turn-free cohort exists. */
|
|
98
|
+
editTask?: (peer: PeerId) => number | undefined;
|
|
91
99
|
/** Bounded machine-local projection; absent retains raw/binary behavior. */
|
|
92
100
|
projection?: (file: string) => import("./text-projection.ts").ProjectedText | undefined;
|
|
93
101
|
}
|
|
@@ -139,6 +147,9 @@ export interface Offered {
|
|
|
139
147
|
coverage?: boolean;
|
|
140
148
|
}
|
|
141
149
|
|
|
150
|
+
export const MAX_RECEIPTS_PER_PEER = 256;
|
|
151
|
+
export interface ReadReceipt { sha256: string; scope: "full" | "partial"; at: number; turnId: string; ownerEpoch?: string }
|
|
152
|
+
|
|
142
153
|
export class Facts {
|
|
143
154
|
private readonly latest = new Map<string, Version>();
|
|
144
155
|
private readonly transitions = new Map<string, Transition[]>();
|
|
@@ -180,11 +191,13 @@ export class Facts {
|
|
|
180
191
|
*/
|
|
181
192
|
private readonly firstSeen = new Map<PeerId, Map<string, Version>>();
|
|
182
193
|
/** A tool call's observation before it ran, by Claude's tool use id. */
|
|
183
|
-
private readonly before = new Map<string, { peer: PeerId; file?: string; version?: Version }>();
|
|
194
|
+
private readonly before = new Map<string, { peer: PeerId; file?: string; version?: Version; shell?: { file: string; version: Version }[] }>();
|
|
184
195
|
/** Peers whose coverage notice went out in this tracking epoch. */
|
|
185
196
|
private readonly covered = new Set<PeerId>();
|
|
186
197
|
/** Each peer's native session or thread: a new one starts its views over. */
|
|
187
198
|
private readonly sessions = new Map<PeerId, string>();
|
|
199
|
+
/** Read receipts, memory only (#1556 T1): peer -> "task\0path" -> receipt, insertion order is the LRU order. */
|
|
200
|
+
private readonly receipts = new Map<PeerId, Map<string, ReadReceipt>>();
|
|
188
201
|
/** When tracking began: work on a task handed over before that is not covered. */
|
|
189
202
|
private epoch = Date.now();
|
|
190
203
|
private readonly root: string;
|
|
@@ -294,15 +307,61 @@ export class Facts {
|
|
|
294
307
|
this.seenDropped.clear();
|
|
295
308
|
this.unfollowed.clear(); // what was seen is forgotten: a notice about it would be stale
|
|
296
309
|
this.writes.clear();
|
|
310
|
+
this.receipts.clear();
|
|
311
|
+
this.tally.clear();
|
|
297
312
|
this.epoch = Date.now();
|
|
298
313
|
}
|
|
299
314
|
|
|
315
|
+
/** Record what `peer` read of `path` for `task`; bounded per peer, oldest evicted. Never persisted. */
|
|
316
|
+
recordRead(peer: PeerId, task: number, path: string, r: Omit<ReadReceipt, "at"> & { at?: number }): void {
|
|
317
|
+
let m = this.receipts.get(peer);
|
|
318
|
+
if (!m) this.receipts.set(peer, (m = new Map()));
|
|
319
|
+
const key = `${task}\0${path}`;
|
|
320
|
+
m.delete(key);
|
|
321
|
+
m.set(key, { ...r, at: r.at ?? Date.now() });
|
|
322
|
+
while (m.size > MAX_RECEIPTS_PER_PEER) m.delete(m.keys().next().value as string);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
readReceipt(peer: PeerId, task: number, path: string): ReadReceipt | undefined {
|
|
326
|
+
return this.receipts.get(peer)?.get(`${task}\0${path}`);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** #1556 T2: counts of the writes the hook saw this turn, per peer; counts only, never a path or a command. Memory only, cleared at `takeEdits`, `closeTask`-independent. */
|
|
330
|
+
private readonly tally = new Map<PeerId, { obs: "hook" | "stream"; e: EditCounts; s: EditCounts }>();
|
|
331
|
+
/** Grade one write of `path` for `peer`: 1 verified full read, 2 partial read only, 3 blind or stale, undefined when the pre-image is unknown (counted in the total only, never guessed). */
|
|
332
|
+
private grade(peer: PeerId, path: string, pre: string | undefined): 1 | 2 | 3 | undefined {
|
|
333
|
+
if (pre === undefined) return undefined;
|
|
334
|
+
const task = this.o.editTask?.(peer) ?? this.o.scope(peer)?.task?.id;
|
|
335
|
+
const r = task === undefined ? undefined : this.readReceipt(peer, task, path);
|
|
336
|
+
if (!r) return 3;
|
|
337
|
+
if (createHash("sha256").update(pre).digest("hex") !== r.sha256) return 3;
|
|
338
|
+
return r.scope === "full" ? 1 : 2;
|
|
339
|
+
}
|
|
340
|
+
private count(peer: PeerId, route: "e" | "s", grade: 1 | 2 | 3 | undefined, obs: "hook" | "stream" = "hook"): void {
|
|
341
|
+
let t = this.tally.get(peer);
|
|
342
|
+
if (!t) this.tally.set(peer, (t = { obs, e: [0, 0, 0, 0, 0], s: [0, 0, 0, 0, 0] }));
|
|
343
|
+
t[route][0]++;
|
|
344
|
+
if (grade !== undefined) t[route][grade]++;
|
|
345
|
+
}
|
|
346
|
+
/** The counts for the turn that just ended, or undefined when no write was seen (a read-only turn adds no field). Clears them. */
|
|
347
|
+
takeEdits(peer: PeerId): TurnEdits | undefined {
|
|
348
|
+
const t = this.tally.get(peer);
|
|
349
|
+
this.tally.delete(peer);
|
|
350
|
+
return t ? { obs: t.obs, ...(t.e[0] ? { e: t.e } : {}), ...(t.s[0] ? { s: t.s } : {}) } : undefined;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** The task closed: its receipts go. */
|
|
354
|
+
closeTask(task: number): void {
|
|
355
|
+
for (const m of this.receipts.values()) for (const k of [...m.keys()]) if (k.startsWith(`${task}\0`)) m.delete(k);
|
|
356
|
+
}
|
|
357
|
+
|
|
300
358
|
/** A new native session or thread for `peer`: what the old one saw says nothing about the new one. */
|
|
301
359
|
session(peer: PeerId, id: string | undefined): void {
|
|
302
360
|
if (!id) return;
|
|
303
361
|
const was = this.sessions.get(peer);
|
|
304
362
|
this.sessions.set(peer, id);
|
|
305
363
|
if (was === undefined || was === id) return;
|
|
364
|
+
this.receipts.delete(peer);
|
|
306
365
|
this.accepted.delete(peer);
|
|
307
366
|
this.plansAccepted.delete(peer);
|
|
308
367
|
this.offers.delete(peer);
|
|
@@ -554,7 +613,10 @@ export class Facts {
|
|
|
554
613
|
const file = path ? this.rel(path) : undefined;
|
|
555
614
|
const version = file ? this.observe(file) : undefined;
|
|
556
615
|
if (toolUseId) {
|
|
557
|
-
|
|
616
|
+
const shell = tool === "Bash" && typeof input.command === "string" ? classifyShellWrite(input.command) : undefined;
|
|
617
|
+
if (shell?.kind === "unknown") try { this.o.onUnknownShell?.(peer); } catch { /* observation only */ }
|
|
618
|
+
const targets = shell?.kind === "write" ? shell.targets.flatMap(target => { const name = this.rel(target); return name ? [{ file: name, version: this.observe(name) }] : []; }) : [];
|
|
619
|
+
this.before.set(toolUseId, { peer, ...(file ? { file } : {}), ...(version ? { version } : {}), ...(targets.length ? { shell: targets } : {}) });
|
|
558
620
|
if (this.before.size > 256) this.before.delete(this.before.keys().next().value as string);
|
|
559
621
|
}
|
|
560
622
|
}
|
|
@@ -575,17 +637,34 @@ export class Facts {
|
|
|
575
637
|
this.wrote(peer, file);
|
|
576
638
|
const expected = !pre.version.projected && this.latest.get(file)?.hash === pre.version.hash ? applyEdit(pre.version.text, tool, input) : undefined;
|
|
577
639
|
const version = this.observe(file, expected === undefined ? undefined : { peer, expected: sha1(expected) });
|
|
640
|
+
if (pre.peer === peer && expected !== undefined && sha1(expected) === version.hash && version.hash !== pre.version.hash) {
|
|
641
|
+
const grade = this.grade(peer, file, pre.version.text); this.count(peer, "e", grade);
|
|
642
|
+
try { this.o.onEdit?.(peer, file, "edit", grade); } catch { /* observation cannot change a tool result */ }
|
|
643
|
+
}
|
|
578
644
|
const last = this.transitions.get(file)?.at(-1);
|
|
579
645
|
if (last?.seq === version.seq && last.by === peer && this.view(peer).get(file)?.hash === pre.version.hash) this.view(peer).set(file, version);
|
|
580
646
|
return this.observeAll();
|
|
581
647
|
}
|
|
582
648
|
if (tool === "Read") {
|
|
649
|
+
// #1556 T1: a read receipt per (peer, task, path), memory only. Unknown text (large or unreadable file) records nothing, never a guess.
|
|
650
|
+
const task = this.o.editTask?.(peer) ?? this.o.scope(peer)?.task?.id;
|
|
651
|
+
if (task !== undefined && pre.version.text !== undefined) {
|
|
652
|
+
this.recordRead(peer, task, file, { sha256: createHash("sha256").update(pre.version.text).digest("hex"), scope: input.offset === undefined && input.limit === undefined && readWhole(pre.version.text) ? "full" : "partial", turnId: toolUseId ?? "" });
|
|
653
|
+
}
|
|
583
654
|
const version = this.observe(file);
|
|
655
|
+
if (pre.version.text !== undefined && version.hash === pre.version.hash && input.offset === undefined && input.limit === undefined && readWhole(pre.version.text)) try { this.o.onDiagnosticRead?.(peer); } catch { /* observation only */ }
|
|
584
656
|
// Only a whole read of an unchanged file says what the peer saw: no offset or limit, and nothing Read cuts.
|
|
585
657
|
if (!pre.version.projected && version.hash === pre.version.hash && input.offset === undefined && input.limit === undefined && readWhole(pre.version.text)) this.view(peer).set(file, version);
|
|
586
658
|
return this.observeAll();
|
|
587
659
|
}
|
|
588
660
|
}
|
|
661
|
+
if (tool === "Bash" && pre?.peer === peer && pre.shell) {
|
|
662
|
+
// Count each observed file modification, not a command that may touch several files or no file.
|
|
663
|
+
for (const target of pre.shell) if (this.load(target.file).hash !== target.version.hash) {
|
|
664
|
+
const grade = this.grade(peer, target.file, target.version.text); this.count(peer, "s", grade);
|
|
665
|
+
try { this.o.onEdit?.(peer, target.file, "shell", grade); } catch { /* observation only */ }
|
|
666
|
+
}
|
|
667
|
+
}
|
|
589
668
|
this.observeAll();
|
|
590
669
|
}
|
|
591
670
|
|
|
@@ -611,6 +690,10 @@ export class Facts {
|
|
|
611
690
|
this.wrote(peer, file);
|
|
612
691
|
const now = this.load(file);
|
|
613
692
|
const matches = was && !was.projected && !now.projected ? codexEffect(was.text, now, change, (a, b) => this.diff(a, b)) : false;
|
|
693
|
+
if (matches && was && was.hash !== now.hash) {
|
|
694
|
+
const grade = this.grade(peer, file, was.text); this.count(peer, "e", grade, "stream");
|
|
695
|
+
try { this.o.onEdit?.(peer, file, "edit", grade); } catch { /* observation only */ }
|
|
696
|
+
}
|
|
614
697
|
const version = this.observe(file, matches ? { peer, expected: now.hash } : undefined);
|
|
615
698
|
const last = this.transitions.get(file)?.at(-1);
|
|
616
699
|
if (was && last?.seq === version.seq && last.by === peer && this.view(peer).get(file)?.hash === was.hash) this.view(peer).set(file, version);
|
package/src/hub/hub-tools.ts
CHANGED
|
@@ -238,8 +238,10 @@ export const CAPABILITY_TOOLS = new Set(["hub_capabilities", "hub_capabilities_p
|
|
|
238
238
|
export const TASK_TOOLS: HubTool[] = [
|
|
239
239
|
tool("hub_roadmap_list", "Read public milestones with computed task/issue/spec/train progress. Private work is a count only; unknown evidence stays unknown. Read only, with no GitHub or model call.", {}),
|
|
240
240
|
tool("hub_roadmap_show", "Read a milestone's public links, inherited membership and computed progress. Inspect this before editing and copy its current revision. Private tasks are counts only.", { id: { type: "integer", minimum: 1 } }, ["id"]),
|
|
241
|
+
tool("hub_roadmap_check", "Read roadmap drift findings and unknown evidence. Private tasks stay withheld; no writes are made.", {}),
|
|
241
242
|
tool("hub_roadmap_unplaced", "Read the open GitHub issues, open board tasks and active/draft specs that no live milestone places, each with why. Private tasks are a count only. partial: true means the GitHub read stopped early or a list was cut, so the lists are a lower bound; unavailable names evidence that could not be read. Read only: no write, no model call. Optional repo is owner/name.", { repo: { type: "string", maxLength: MILESTONE_LIMITS.issue } }),
|
|
242
243
|
tool("hub_roadmap_triage", "Ask the hub's model to suggest a milestone (or a new one) for unplaced work. Each suggestion cites the milestone and item words it matched and is saved as a pending model answer; nothing is linked until hub_roadmap_edit accept. Configured planner or unique conductor only. list: true reads the pending public suggestions without a model call and is open to any agent.", { repo: { type: "string", maxLength: MILESTONE_LIMITS.issue }, list: { type: "boolean" } }),
|
|
244
|
+
tool("hub_roadmap_decompose", "Ask the hub's model to decompose one milestone into parts, from its outcome, the specs it links and the issues it links. Each part cites linked ids and says whether it needs a spec issue or goes straight to a task; the answer is saved as a pending model answer and nothing is linked, intaken or published. Pass accept with one part's number to hold that part as an intake draft instead: it is linked to the milestone, carries the part's spec-issue or task kind, and is offered to nobody until the person releases it with ahub intake approve. Configured planner or unique conductor only. On refusal inspect hub_roadmap_show and correct the named input.", { id: { type: "integer", minimum: 1 }, accept: { type: "integer", minimum: 1 } }, ["id"]),
|
|
243
245
|
tool("hub_roadmap_edit", "Create or change a milestone. Configured planner or unique conductor only; done/dropped are person-only. new/edit take fields; edit also needs the current revision. Link kinds are spec/issue/task/release; issue refs are owner/repo#N. accept applies exactly one pending triage suggestion through link (creating its proposed milestone first); reject drops it. No GitHub write, task assignment or model call. On refusal inspect hub_roadmap_show and correct the named input.", {
|
|
244
246
|
op: { type: "string", enum: ["new", "edit", "link", "unlink", "order", "state", "accept", "reject"] }, id: { type: "integer", minimum: 1 }, revision: { type: "integer", minimum: 0 }, suggestion: { type: "integer", minimum: 1, description: "accept or reject: a pending suggestion id from hub_roadmap_triage" },
|
|
245
247
|
fields: { type: "object", additionalProperties: false, properties: {
|
|
@@ -263,7 +265,7 @@ export const TASK_TOOLS: HubTool[] = [
|
|
|
263
265
|
tool("hub_delivery_resolve", "Confirm completion or discard your own needs_review delivery using the revision shown by hub_inbox. Requires a reason. Never replays the delivery or changes task state; another peer's row and stale revisions are refused.", { delivery_id: { type: "string", minLength: 1, maxLength: 256 }, revision: { type: "integer", minimum: 0 }, action: { type: "string", enum: ["completed", "discard"] }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["delivery_id", "revision", "action", "reason"]),
|
|
264
266
|
tool("hub_backlog_list", "Read public backlog cards with planning revisions. Configured planners only; PII remains a stub.", {}),
|
|
265
267
|
tool("hub_backlog_plan", "Plan an unpinned backlog item outside frozen releases with the revision you read and a bounded reason. Omit fields or give {} for a note-only revision. fields.sdlc accepts only repo/issue identity on unstarted backlog work; relinking clears old spec acceptance. A person's rank is retained. Actual dates cannot be set. fields.needsPerson (marking a leg only the person can run) is the person's: an agent that sends it, or plans a marked card, is refused.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", maxLength: 1000 }, fields: { type: "object", properties: { sdlc: { type: "object", minProperties: 1, properties: { repo: { type: ["string", "null"], maxLength: 400 }, issue: { type: ["integer", "null"], minimum: 1 } }, additionalProperties: false }, rank: { type: ["integer", "null"], minimum: 0 }, priority: { type: ["integer", "null"], minimum: 0, maximum: 3 }, release: { type: ["integer", "null"], minimum: 1 }, plannedStart: { type: ["integer", "null"], minimum: 1 }, due: { type: ["integer", "null"], minimum: 1 }, deps: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, reserved: { type: ["string", "null"], minLength: 1, maxLength: 32 }, needsPerson: { type: "boolean" } }, additionalProperties: false } }, ["id", "revision", "reason"]),
|
|
266
|
-
tool("hub_backlog_pull", "Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
|
|
268
|
+
tool("hub_backlog_pull", "Configured planners only. Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
|
|
267
269
|
tool("hub_backlog_split", "Split unstarted backlog work into two to eight staged parts. The original card retains integration/acceptance and depends on the children. Use after for existing prerequisite ids and afterParts for earlier zero-based part indexes. Latest unused unchanged children can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 }, parts: { type: "array", minItems: 2, maxItems: 8, items: { type: "object", properties: { title: { type: "string", minLength: 1, maxLength: 300 }, detail: { type: "string", maxLength: 8000 }, class: str, refs, plan, after: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, afterParts: { type: "array", maxItems: 8, uniqueItems: true, items: { type: "integer", minimum: 0 } } }, required: ["title"], additionalProperties: false } } }, ["id", "revision", "reason", "parts"]),
|
|
268
270
|
tool("hub_backlog_undo", "Undo your latest planning change at its current revision. Refuses intervening changes and another actor's edit.", { id, revision: { type: "integer", minimum: 1 } }, ["id", "revision"]),
|
|
269
271
|
tool("hub_study_draft", "Store a research campaign contract as a DRAFT revision 1 on an approved parent task. Configured planners only; it creates no task, dispatches nothing and never approves (only the person approves, with ahub study approve). The contract is data: question, scope, exclusions, sourceIds, units, deliverableSections, stopPolicy and an optional budget.", { parentTaskId: id, contract: { type: "object" } }, ["parentTaskId", "contract"]),
|
package/src/hub/lifecycle.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { waitForStartupReadiness, type StartupOwner } from "./startup-readiness.ts";
|
|
2
|
+
import { rotateTextLogAtStart } from "./log-rotation.ts";
|
|
2
3
|
import { resolveProjectRuntime, recordProjectRuntime, confirmProjectRuntime, readProjectRuntimeForCaller, projectRuntimeRefusal, type ProjectRuntimeSelection } from "./project-runtime.ts";
|
|
3
4
|
import { scheduleRuntimeCapturePrune } from "./runtime-capture-prune.ts";
|
|
4
5
|
import { createProjectRuntimeAccess, type ProjectRuntimeAccess } from "./project-runtime-state.ts";
|
|
5
6
|
import { isDatabaseBusyReply, RecoveryDatabaseBusy } from "./recovery-error.ts";
|
|
6
7
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
7
8
|
import { randomUUID } from "node:crypto";
|
|
8
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync, writeSync } from "node:fs";
|
|
9
10
|
import { join, resolve } from "node:path";
|
|
10
11
|
import { createServer, type Server } from "node:net";
|
|
11
12
|
import { ControlClient, PROTOCOL, PROTOCOL_MIN, controlProtocolWindow, readControl } from "./control-client.ts";
|
|
@@ -218,7 +219,11 @@ export async function startProject(project: Project, options: { unattended?: boo
|
|
|
218
219
|
const temporary = `${marker}.${randomUUID()}.tmp`;
|
|
219
220
|
writeFileSync(temporary, JSON.stringify({ root: project.root, projectId: project.id }), { mode: 0o600 });
|
|
220
221
|
renameSync(temporary, marker);
|
|
222
|
+
let rotationNote = "";
|
|
223
|
+
try { rotateTextLogAtStart(join(project.stateDir, "hub.log")); } // #1546: no daemon holds it open yet, so an oversized log is moved aside before the new one opens it
|
|
224
|
+
catch (error) { rotationNote = `${new Date().toISOString()} hub.log rotation failed: ${(error as Error).message.slice(0, 160)}\n`; }
|
|
221
225
|
const log = openSync(join(project.stateDir, "hub.log"), "a");
|
|
226
|
+
if (rotationNote) try { writeSync(log, rotationNote); } catch { /* the note is advisory */ }
|
|
222
227
|
try {
|
|
223
228
|
options.current?.();
|
|
224
229
|
const child = spawn(process.execPath, [join(runtime.root, "src/cli/main.ts"), "--project", project.root, ...(options.liveTest ? ["--live-test"] : []), "daemon",
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { appendFileSync, closeSync, copyFileSync, existsSync, fstatSync, openSync, readdirSync, readSync, renameSync, rmSync, statSync, truncateSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* #1546: size-based rotation for `events.jsonl` and `hub.log`.
|
|
6
|
+
*
|
|
7
|
+
* A rotated segment is named `<file>.<start>`, where `start` is the byte offset, in the one stream the segments and the live file make together, of the segment's first byte. The live file is always
|
|
8
|
+
* the newest bytes, so its start is the end of the newest segment. Reading the segments oldest first and then the live file gives exactly the lines the unrotated file would have held, and a byte
|
|
9
|
+
* offset in that stream keeps its meaning when the live file is rotated away or the oldest segment is dropped: a reader that persisted an offset (the usage roll-up, the research tail) needs no
|
|
10
|
+
* translation. A segment of the event log always ends in a newline (a crash-cut last line is terminated before the move), so no line spans two files.
|
|
11
|
+
*
|
|
12
|
+
* Operational limits: an event segment is 64 MiB and three are kept, hub.log keeps two of 16 MiB. ponytail: constants, not settings; the upgrade path is config keys once a project needs other bounds.
|
|
13
|
+
*/
|
|
14
|
+
export const EVENTS_SEGMENT_BYTES = 64 * 1024 * 1024;
|
|
15
|
+
export const EVENTS_SEGMENTS_KEPT = 3;
|
|
16
|
+
export const HUB_LOG_SEGMENT_BYTES = 16 * 1024 * 1024;
|
|
17
|
+
export const HUB_LOG_SEGMENTS_KEPT = 2;
|
|
18
|
+
|
|
19
|
+
export interface Segment { path: string; start: number; size: number; live: boolean }
|
|
20
|
+
|
|
21
|
+
/** Every segment of `file`, oldest first, the live file last when it exists. */
|
|
22
|
+
export function segmentsOf(file: string): Segment[] {
|
|
23
|
+
const dir = dirname(file), prefix = `${basename(file)}.`;
|
|
24
|
+
let names: string[];
|
|
25
|
+
try { names = readdirSync(dir); } catch { names = []; }
|
|
26
|
+
const rotated: Segment[] = [];
|
|
27
|
+
for (const name of names) {
|
|
28
|
+
if (!name.startsWith(prefix)) continue;
|
|
29
|
+
const digits = /^(0|[1-9][0-9]{0,15})$/.exec(name.slice(prefix.length));
|
|
30
|
+
if (!digits) continue;
|
|
31
|
+
const path = join(dir, name);
|
|
32
|
+
try { const stat = statSync(path); if (stat.isFile()) rotated.push({ path, start: Number(digits[1]), size: stat.size, live: false }); } catch { /* removed while listing */ }
|
|
33
|
+
}
|
|
34
|
+
rotated.sort((a, b) => a.start - b.start);
|
|
35
|
+
const last = rotated[rotated.length - 1];
|
|
36
|
+
const start = last ? last.start + last.size : 0;
|
|
37
|
+
try { const stat = statSync(file); if (stat.isFile()) rotated.push({ path: file, start, size: stat.size, live: true }); } catch { /* no live file yet */ }
|
|
38
|
+
return rotated;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The offset just past the last byte of the stream: where the next appended byte lands. */
|
|
42
|
+
export const streamEnd = (segments: readonly Segment[]): number => { const last = segments[segments.length - 1]; return last ? last.start + last.size : 0; };
|
|
43
|
+
|
|
44
|
+
/** Whether the file's last byte is something other than a newline. */
|
|
45
|
+
function endsMidLine(file: string): boolean {
|
|
46
|
+
const fd = openSync(file, "r");
|
|
47
|
+
try {
|
|
48
|
+
const { size } = fstatSync(fd);
|
|
49
|
+
if (!size) return false;
|
|
50
|
+
const last = Buffer.alloc(1);
|
|
51
|
+
readSync(fd, last, 0, 1, size - 1);
|
|
52
|
+
return last[0] !== 0x0a;
|
|
53
|
+
} finally { closeSync(fd); }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface RotateOptions {
|
|
57
|
+
/** Rotated segments kept besides the live file (at least 1). */
|
|
58
|
+
keep: number;
|
|
59
|
+
/** `rename` moves the live file (nothing else holds it open); `copytruncate` copies it and truncates it in place, for a file a child process also holds open for append. */
|
|
60
|
+
mode: "rename" | "copytruncate";
|
|
61
|
+
/** Why the oldest segment must stay (it holds something still needed), or undefined when it may go. Asked only when the oldest segment would be dropped. */
|
|
62
|
+
keepOldest?: (oldest: Segment) => string | undefined;
|
|
63
|
+
/** Called right after a segment's file is removed, so a holder of state derived from it (the reviewer-accounting journal) can drop it too even when a later step throws. */
|
|
64
|
+
onDrop?: (segment: Segment) => void;
|
|
65
|
+
}
|
|
66
|
+
export interface RotateResult { rotated: boolean; dropped: Segment[]; kept?: { segment: Segment; reason: string } }
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Move the live file to `<file>.<start>`, and drop the oldest segment when `keep` segments already exist and `keepOldest` allows it. A segment that is kept makes the log grow past `keep` until its reason
|
|
70
|
+
* ends: nothing an open task needs is ever dropped. Not safe against a second rotator on one file: the daemon is the only one.
|
|
71
|
+
*/
|
|
72
|
+
export function rotateSegments(file: string, options: RotateOptions): RotateResult {
|
|
73
|
+
if (!Number.isSafeInteger(options.keep) || options.keep < 1) throw new Error("rotation must keep at least one segment; pass keep >= 1");
|
|
74
|
+
const all = segmentsOf(file), live = all[all.length - 1];
|
|
75
|
+
if (!live?.live || live.size === 0) return { rotated: false, dropped: [] };
|
|
76
|
+
const rotated = all.filter(segment => !segment.live);
|
|
77
|
+
const result: RotateResult = { rotated: false, dropped: [] };
|
|
78
|
+
if (options.mode === "rename" && endsMidLine(file)) { appendFileSync(file, "\n"); live.size += 1; }
|
|
79
|
+
const target = `${file}.${live.start}`;
|
|
80
|
+
if (existsSync(target)) throw new Error(`rotation target ${basename(target)} already exists; remove or rename it, then rotate again`);
|
|
81
|
+
// Drop the oldest segments the hold allows until the bound holds again, and stop at the first one that must stay: after a hold ends, one rotation brings the count back to `keep`.
|
|
82
|
+
while (rotated.length >= options.keep) {
|
|
83
|
+
const oldest = rotated[0]!, reason = options.keepOldest?.(oldest);
|
|
84
|
+
if (reason !== undefined) { result.kept = { segment: oldest, reason }; break; }
|
|
85
|
+
rmSync(oldest.path, { force: true }); result.dropped.push(oldest); rotated.shift(); options.onDrop?.(oldest);
|
|
86
|
+
}
|
|
87
|
+
if (options.mode === "rename") renameSync(file, target);
|
|
88
|
+
else { copyFileSync(file, target); truncateSync(file, 0); }
|
|
89
|
+
result.rotated = true;
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The event log: rotate when the live file reached `maxBytes`. */
|
|
94
|
+
export function rotateEventsIfLarge(file: string, options: { maxBytes?: number; keep?: number; keepOldest?: RotateOptions["keepOldest"]; onDrop?: RotateOptions["onDrop"] } = {}): RotateResult {
|
|
95
|
+
// A stuck rotation (an existing target name, EACCES) throws to the caller, which logs it: the size bound must never stop holding silently.
|
|
96
|
+
if (!existsSync(file) || statSync(file).size < (options.maxBytes ?? EVENTS_SEGMENT_BYTES)) return { rotated: false, dropped: [] };
|
|
97
|
+
return rotateSegments(file, { keep: options.keep ?? EVENTS_SEGMENTS_KEPT, mode: "rename", ...(options.keepOldest ? { keepOldest: options.keepOldest } : {}), ...(options.onDrop ? { onDrop: options.onDrop } : {}) });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The hub.log writer's size check: one `stat` every `every` calls. The daemon's own stderr also appends to the file, so a running count alone would drift. */
|
|
101
|
+
export function textLogRotator(file: string, maxBytes = HUB_LOG_SEGMENT_BYTES, keep = HUB_LOG_SEGMENTS_KEPT, every = 256): () => RotateResult | undefined {
|
|
102
|
+
let calls = 0;
|
|
103
|
+
return () => {
|
|
104
|
+
if (++calls % every !== 0) return undefined;
|
|
105
|
+
if (statSync(file).size < maxBytes) return undefined;
|
|
106
|
+
return rotateSegments(file, { keep, mode: "copytruncate" });
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Before a daemon starts, an oversized hub.log is moved away: no process holds it open yet. A failure throws to the caller, which reports it. */
|
|
111
|
+
export function rotateTextLogAtStart(file: string, maxBytes = HUB_LOG_SEGMENT_BYTES, keep = HUB_LOG_SEGMENTS_KEPT): boolean {
|
|
112
|
+
if (!existsSync(file) || statSync(file).size < maxBytes) return false;
|
|
113
|
+
return rotateSegments(file, { keep, mode: "rename" }).rotated;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The `at` of the last parseable line of `path`, read from its tail; undefined when none can be read (the caller keeps the segment then). */
|
|
117
|
+
export function lastEventTime(path: string): number | undefined {
|
|
118
|
+
let fd: number | undefined;
|
|
119
|
+
try {
|
|
120
|
+
fd = openSync(path, "r");
|
|
121
|
+
const { size } = fstatSync(fd), len = Math.min(size, 256 * 1024), buffer = Buffer.alloc(len);
|
|
122
|
+
readSync(fd, buffer, 0, len, size - len);
|
|
123
|
+
const lines = buffer.toString("utf8").split("\n");
|
|
124
|
+
for (let i = lines.length - 1; i >= (size > len ? 1 : 0); i--) {
|
|
125
|
+
try { const at = Date.parse((JSON.parse(lines[i]!) as { at?: string }).at ?? ""); if (Number.isFinite(at)) return at; } catch { /* a cut line */ }
|
|
126
|
+
}
|
|
127
|
+
return undefined;
|
|
128
|
+
} catch { return undefined; }
|
|
129
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
130
|
+
}
|