@staix/agent-hub 0.44.0 → 0.46.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 +66 -0
- package/README.md +12 -11
- package/docs/adding-an-ai-tool.md +1 -0
- package/docs/agent-notes/adapters.md +35 -6
- package/docs/agent-notes/budget.md +2 -1
- package/docs/agent-notes/daemon.md +5 -1
- package/docs/agent-notes/local-worker.md +1 -1
- package/docs/agent-notes/security-review.md +3 -2
- package/docs/agent-notes/tasks.md +6 -2
- package/docs/agent-notes/tests.md +4 -3
- package/docs/design/adapters.md +20 -2
- package/docs/design/agent-hub-architecture.md +12 -0
- package/docs/design/agent-hub.md +1 -1
- package/docs/design/cli-output.md +2 -0
- package/docs/design/roadmap.md +158 -4
- package/docs/design/supervision.md +21 -1
- package/docs/design/task-board.md +32 -4
- package/docs/dogfood.md +28 -4
- package/docs/events.md +7 -3
- package/docs/influences.md +7 -0
- package/docs/memory.md +4 -4
- package/docs/operations.md +151 -36
- package/docs/quickstart.md +16 -4
- package/docs/research.md +16 -0
- package/docs/roadmap.json +4 -0
- package/docs/roadmap.md +9 -0
- package/docs/sdlc.md +15 -3
- package/docs/security.md +9 -7
- package/docs/smoke.md +1 -1
- package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -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-agy-1.5.14.md +27 -0
- package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
- package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
- package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
- package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
- package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
- package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
- package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
- package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
- package/docs/verification/2026-11-23-0.46.0.md +44 -0
- package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
- package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
- package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
- package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
- package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
- package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
- package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
- package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
- package/docs/verified.json +33 -27
- package/package.json +3 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +4743 -4048
- package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
- package/plugins/agent-hub/server.js +1641 -1265
- package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
- package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
- package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
- package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
- package/scripts/check-docs.mjs +9 -1
- package/src/adapters/acp.ts +11 -1
- package/src/adapters/claude-channel.ts +2 -1
- package/src/adapters/compat.ts +15 -14
- package/src/adapters/definitions/builtin-metadata.ts +2 -2
- package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
- package/src/adapters/definitions/native-cli-doctor.ts +8 -5
- package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
- package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
- package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
- package/src/adapters/definitions/native-cli-skills.ts +29 -0
- 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/claude-profile-hook.ts +40 -3
- package/src/cli/console-state.ts +58 -27
- package/src/cli/console-usage.ts +5 -3
- package/src/cli/console.ts +35 -4
- package/src/cli/help.ts +17 -10
- package/src/cli/identity.ts +4 -2
- package/src/cli/instruction-hook.ts +28 -0
- package/src/cli/jcode-mcp.ts +2 -1
- package/src/cli/main.js +8 -0
- package/src/cli/main.ts +149 -23
- package/src/cli/output-standard.ts +3 -55
- package/src/cli/output.ts +8 -2
- package/src/cli/recovery-package.ts +62 -13
- package/src/cli/roadmap-write.ts +59 -0
- package/src/cli/roadmap.ts +115 -4
- package/src/cli/sdlc-output.ts +4 -0
- package/src/cli/setup-homes.ts +1 -0
- package/src/cli/setup.ts +1 -1
- package/src/cli/skills-install.ts +463 -0
- package/src/cli/task-output.ts +1 -1
- package/src/cli/upgrade-presentation-flags.ts +1 -1
- package/src/cli/upgrade-runtime.ts +10 -6
- package/src/hub/agent-mem-range.ts +43 -0
- package/src/hub/board.ts +144 -5
- package/src/hub/budget-projection.ts +99 -0
- package/src/hub/check-runner.ts +25 -1
- package/src/hub/claude-launch-proof.ts +5 -1
- package/src/hub/conductor.ts +8 -3
- package/src/hub/config-apply.ts +6 -3
- package/src/hub/config-tier.ts +1 -1
- package/src/hub/config-trust.ts +1 -1
- package/src/hub/context-window.ts +1 -1
- package/src/hub/control-client.ts +9 -2
- package/src/hub/cost-governance.ts +11 -7
- package/src/hub/daemon.ts +707 -53
- package/src/hub/dogfood-read.ts +4 -2
- package/src/hub/edit-guard.ts +100 -0
- package/src/hub/events.ts +80 -9
- package/src/hub/execution-budget.ts +29 -8
- package/src/hub/facts.ts +57 -4
- package/src/hub/hub-tools.ts +3 -1
- package/src/hub/inference.ts +1 -1
- package/src/hub/instances.ts +10 -1
- package/src/hub/instructed-exact.ts +95 -0
- package/src/hub/instructed-intent.ts +64 -0
- package/src/hub/instructed-ipc.ts +33 -0
- package/src/hub/instructed-runtime.ts +19 -0
- package/src/hub/instruction-receipt.ts +218 -0
- package/src/hub/lifecycle.ts +6 -1
- package/src/hub/log-rotation.ts +130 -0
- package/src/hub/manager.ts +46 -3
- 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/recovery-store.ts +49 -21
- package/src/hub/registry.ts +1 -1
- package/src/hub/research-experiments.ts +132 -0
- package/src/hub/research-quality.ts +8 -2
- package/src/hub/research-record.ts +35 -0
- package/src/hub/research.ts +128 -28
- package/src/hub/roadmap-check.ts +65 -0
- package/src/hub/roadmap-decompose.ts +139 -0
- package/src/hub/roadmap-export.ts +27 -0
- package/src/hub/roadmap-sync.ts +97 -0
- package/src/hub/roadmap.ts +59 -1
- package/src/hub/routing.ts +18 -1
- package/src/hub/runtime-capture-prune.ts +2 -1
- package/src/hub/sdlc-branch-ci.ts +128 -0
- package/src/hub/sdlc-merge.ts +6 -3
- package/src/hub/sdlc-metrics.ts +19 -5
- package/src/hub/sdlc.ts +73 -5
- package/src/hub/settings.ts +3 -1
- package/src/hub/snapshots.ts +13 -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 +26 -3
- package/src/hub/supervision.ts +7 -0
- package/src/hub/task-pr.ts +47 -0
- package/src/hub/task-worktree.ts +18 -11
- package/src/hub/tasks.ts +694 -44
- package/src/hub/ui.ts +6 -2
- package/src/hub/usage-rollup.ts +77 -22
- package/src/local/tools.ts +13 -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/ui/index.html +342 -8
- package/src/ui/plugin.ts +6 -2
- package/src/ui/roadmap-model.ts +70 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { parseModelCommand } from "../cli/model.ts";
|
|
3
|
+
import { parseStudyArgs } from "../cli/study.ts";
|
|
4
|
+
import { SCREEN_TIMEOUT_MS } from "./inference.ts";
|
|
5
|
+
|
|
6
|
+
export const INSTRUCTION_CHILD_TIMEOUT_MS = 30_000;
|
|
7
|
+
export const INSTRUCTION_CONTROL_TIMEOUT_MS = INSTRUCTION_CHILD_TIMEOUT_MS + 3 * SCREEN_TIMEOUT_MS + 5_000;
|
|
8
|
+
|
|
9
|
+
/** Parse only the explicit skill's `run` form; no shell syntax or implicit quoting is accepted. */
|
|
10
|
+
export function parseExactInstruction(args: string): string[] | undefined {
|
|
11
|
+
if (!args.isWellFormed() || /[\p{Cc}\p{Cf}'"\\$`<>&]/u.test(args)) return;
|
|
12
|
+
const words = args.trim().split(/ +/u);
|
|
13
|
+
if (words[0] !== "run" || !words[1] || words[1]!.startsWith("-")) return;
|
|
14
|
+
return words.slice(1);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A missing machine-local setting uses intent mode; malformed values never enable it. */
|
|
18
|
+
export function instructedMode(value: unknown): "off" | "exact" | "intent" {
|
|
19
|
+
if (value === undefined) return "intent";
|
|
20
|
+
if (value === "off" || value === "exact" || value === "intent") return value;
|
|
21
|
+
throw new Error("instructed.mode must be off, exact or intent");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ExactForm { argv: string[]; taskId?: number; targetPeer?: string; screen?: true; titleTarget?: true; study?: { id: string; revision: number } }
|
|
25
|
+
|
|
26
|
+
/** Closed, syntax-checked forms only. New and unclassified forms never inherit authority. */
|
|
27
|
+
export function exactForm(argv: readonly string[]): ExactForm | undefined {
|
|
28
|
+
if (argv.some(word => word === "--as-user" || word.startsWith("--as-user=") || word === "--project" || word.startsWith("--project=") || word === "--live-test")) return;
|
|
29
|
+
const [command, sub, ...tail] = argv;
|
|
30
|
+
if (command === "task" && sub === "claim") {
|
|
31
|
+
const [id, slot, verdict, ...extra] = tail;
|
|
32
|
+
if (!extra.length && id && slot && /^[1-9]\d*$/.test(id) && /^[1-9]\d*$/.test(slot)
|
|
33
|
+
&& Number.isSafeInteger(Number(id)) && Number.isSafeInteger(Number(slot)) && ["supported", "unsupported", "unclear"].includes(verdict ?? "")) return { argv: [...argv], taskId: Number(id) };
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (command === "task" && (sub === "assign" || sub === "unassign")) {
|
|
37
|
+
const positional: string[] = [], flags = new Map<string, string>();
|
|
38
|
+
for (let i = 0; i < tail.length; i++) {
|
|
39
|
+
const word = tail[i]!;
|
|
40
|
+
if (word.startsWith("--")) {
|
|
41
|
+
if (!["--role", "--revision"].includes(word) || flags.has(word) || !tail[i + 1]) return;
|
|
42
|
+
flags.set(word, tail[++i]!);
|
|
43
|
+
} else positional.push(word);
|
|
44
|
+
}
|
|
45
|
+
if (positional.length !== (sub === "assign" ? 2 : 1) || !/^[1-9]\d*$/.test(positional[0]!) || !Number.isSafeInteger(Number(positional[0]))) return;
|
|
46
|
+
if (sub === "assign" && !/^[a-z][a-z0-9-]*$/.test(positional[1]!)) return;
|
|
47
|
+
const role = flags.get("--role");
|
|
48
|
+
if (role && !(sub === "assign" ? ["owner", "reviewer", "planner"] : ["owner", "reviewer"]).includes(role)) return;
|
|
49
|
+
const revision = flags.get("--revision");
|
|
50
|
+
if (revision !== undefined && (!/^\d+$/.test(revision) || !Number.isSafeInteger(Number(revision)))) return;
|
|
51
|
+
return { argv: [...argv], taskId: Number(positional[0]) };
|
|
52
|
+
}
|
|
53
|
+
if (command === "backlog" && (sub === "pull" || sub === "return") && tail.length === 1 && /^[1-9]\d*$/.test(tail[0]!) && Number.isSafeInteger(Number(tail[0]))) return { argv: [...argv], taskId: Number(tail[0]) };
|
|
54
|
+
if (command === "backlog" && (sub === "pin" || sub === "pull-ready")) {
|
|
55
|
+
const [id, revision, ...rest] = tail;
|
|
56
|
+
if (!id || !/^[1-9]\d*$/.test(id) || !Number.isSafeInteger(Number(id)) || !revision || !/^\d+$/.test(revision) || !Number.isSafeInteger(Number(revision))) return;
|
|
57
|
+
const reason = sub === "pin" ? rest.slice(1) : rest;
|
|
58
|
+
if (sub === "pin" && !["true", "false"].includes(rest[0] ?? "")) return;
|
|
59
|
+
if (!reason.length || reason.some(word => !word || word.startsWith("--"))) return;
|
|
60
|
+
return { argv: [...argv], taskId: Number(id), screen: true };
|
|
61
|
+
}
|
|
62
|
+
if (command === "backlog" && sub === "add") {
|
|
63
|
+
const [taskClass, ...title] = tail;
|
|
64
|
+
if (taskClass && /^[a-z][a-z0-9_-]*$/.test(taskClass) && title.length && title.every(word => word && !word.startsWith("--"))) return { argv: [...argv], screen: true };
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (command === "roadmap" && sub === "state") {
|
|
68
|
+
const [id, state, ...extra] = tail;
|
|
69
|
+
if (!extra.length && id && /^[1-9]\d*$/.test(id) && Number.isSafeInteger(Number(id)) && (state === "done" || state === "dropped")) return { argv: [...argv] };
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (command === "study" && sub === "approve") {
|
|
73
|
+
const parsed = parseStudyArgs(argv.slice(1));
|
|
74
|
+
if (!("usage" in parsed) && parsed.op === "approve") return { argv: [...argv], screen: true, study: { id: parsed.id, revision: parsed.revision } };
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (command === "title" && sub && /^[a-z][a-z0-9-]*$/.test(sub) && tail.length && tail.every(word => word && !word.startsWith("--"))) return { argv: [...argv], targetPeer: sub, screen: true, titleTarget: true };
|
|
78
|
+
if (command === "model") {
|
|
79
|
+
try { const model = parseModelCommand(argv.slice(1)); if ((model.op === "set" || model.op === "clear") && model.peer) return { argv: [...argv], targetPeer: model.peer }; } catch { return; }
|
|
80
|
+
}
|
|
81
|
+
if (["stop", "pause", "resume"].includes(command ?? "") && argv.length === 2 && sub && /^[a-z][a-z0-9-]*$/.test(sub)) return { argv: [...argv], targetPeer: sub };
|
|
82
|
+
if (command === "settings" && sub === "set" && tail.length >= 2 && tail.length <= 3) {
|
|
83
|
+
const [key, value, flag] = tail;
|
|
84
|
+
if (key && value && (key === "tasks.auto_pull" || /^tasks\.wip_limits\.[a-z][a-z0-9-]*$/.test(key) || key === "tasks.queue_backpressure.max_queued" || key === "tasks.queue_backpressure.max_oldest_s") && (flag === undefined || flag === "--yes")) return { argv: [...argv] };
|
|
85
|
+
}
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface InstructedExecution { peer: string; receipt: string; taskId?: number; active: boolean; current(): void; beginStudy?(): void }
|
|
90
|
+
/** Host-only provenance follows the actual control request into board writes. */
|
|
91
|
+
export const instructedExecution = new AsyncLocalStorage<InstructedExecution>();
|
|
92
|
+
export function instructedHistory(by: string): { instructed: true; instructedPeer: string; instructionReceipt: string } | Record<string, never> {
|
|
93
|
+
const context = instructedExecution.getStore();
|
|
94
|
+
return by === "user" && context?.active ? { instructed: true, instructedPeer: context.peer, instructionReceipt: context.receipt } : {};
|
|
95
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { exactForm } from "./instructed-exact.ts";
|
|
2
|
+
|
|
3
|
+
export interface IntentForm { argv: string[]; taskId?: number; targetPeer?: string; verdictIds?: string[]; review?: true }
|
|
4
|
+
|
|
5
|
+
/** Each id must occur as its own literal token; repeated ids need separate occurrences. */
|
|
6
|
+
export function literalInstructionIds(prompt: string, ids: readonly string[]): boolean {
|
|
7
|
+
const used: { start: number; end: number }[] = [];
|
|
8
|
+
for (const id of ids) {
|
|
9
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(id)) return false;
|
|
10
|
+
let at = prompt.indexOf(id), found = false;
|
|
11
|
+
while (at >= 0) {
|
|
12
|
+
const before = prompt[at - 1], after = prompt[at + id.length];
|
|
13
|
+
if ((!before || !/[\p{L}\p{N}_-]/u.test(before)) && (!after || !/[\p{L}\p{N}_-]/u.test(after)) && !used.some(span => at < span.end && at + id.length > span.start)) {
|
|
14
|
+
used.push({ start: at, end: at + id.length }); found = true; break;
|
|
15
|
+
}
|
|
16
|
+
at = prompt.indexOf(id, at + 1);
|
|
17
|
+
}
|
|
18
|
+
if (!found) return false;
|
|
19
|
+
}
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Closed intent forms; child argv is passed directly, never to a shell. */
|
|
24
|
+
export function intentForm(argv: readonly string[]): IntentForm | undefined {
|
|
25
|
+
if (!argv.length || argv.some(word => typeof word !== "string" || !word.isWellFormed() || /[\p{Cc}\p{Cf}]/u.test(word))) return;
|
|
26
|
+
if (argv.some(word => word === "--as-user" || word.startsWith("--as-user=") || word === "--live-test" || word.startsWith("--live-test=") || word === "--project" || word.startsWith("--project="))) return;
|
|
27
|
+
const [command, sub, ...tail] = argv;
|
|
28
|
+
const exact = exactForm(argv);
|
|
29
|
+
if (exact && (command === "task" && sub === "assign" || command === "backlog" && (sub === "pull" || sub === "return") || command === "model" || command === "stop")) return exact;
|
|
30
|
+
const integer = (value: string | undefined) => !!value && /^[1-9]\d*$/.test(value) && Number.isSafeInteger(Number(value));
|
|
31
|
+
if (command === "task" && sub === "claim") {
|
|
32
|
+
const [id, slot, verdict, ...extra] = tail;
|
|
33
|
+
if (!extra.length && integer(id) && integer(slot) && ["supported", "unsupported", "unclear"].includes(verdict ?? "")) return { argv: [...argv], taskId: Number(id), verdictIds: [id!, slot!] };
|
|
34
|
+
}
|
|
35
|
+
// #1622 family 4: a final milestone verdict. The milestone id must be written literally in the person's prompt; the history entry carries the instructed provenance.
|
|
36
|
+
if (command === "roadmap" && sub === "state") {
|
|
37
|
+
const [id, state, ...extra] = tail;
|
|
38
|
+
if (!extra.length && integer(id) && (state === "done" || state === "dropped")) return { argv: [...argv], verdictIds: [id!] };
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (command === "results" && argv.slice(1).every(word => ["--unread", "--json", "--full", "--color=auto", "--color=always", "--color=never"].includes(word))) return { argv: [...argv] };
|
|
42
|
+
if (command === "capabilities" && argv.slice(1).every(word => ["--json", "--color=auto", "--color=always", "--color=never"].includes(word))) return { argv: [...argv] };
|
|
43
|
+
if (command === "learn" && sub === "list" && tail.every(word => ["--all", "--json", "--color=auto", "--color=always", "--color=never"].includes(word))) return { argv: [...argv] };
|
|
44
|
+
if (command === "learn" && ["accept", "reject"].includes(sub ?? "") && tail.length === 1 && integer(tail[0])) return { argv: [...argv], taskId: Number(tail[0]), verdictIds: [tail[0]!] };
|
|
45
|
+
if (command === "review" && integer(sub)) {
|
|
46
|
+
const [verdict, flag, head, ...extra] = tail;
|
|
47
|
+
if (["approved", "changes_requested"].includes(verdict ?? "") && !extra.length && (flag === undefined && head === undefined || flag === "--head" && !!head && /^[a-f0-9]{40}$/.test(head))) return { argv: [...argv], taskId: Number(sub), verdictIds: [sub!], review: true };
|
|
48
|
+
}
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A closed family gets an explanation without echoing its operands. */
|
|
53
|
+
export function intentRefusal(argv: readonly string[]): string {
|
|
54
|
+
const [command, sub] = argv;
|
|
55
|
+
if (command === "role") return "role changes are trust settings and stay person-only";
|
|
56
|
+
if (command === "task" && sub === "claim" && argv.includes("--manifest")) return "file-backed claim verdicts stay person-only";
|
|
57
|
+
if (command === "task" && sub === "handoff") return "cross-project handoff lacks an instruction revocation fence";
|
|
58
|
+
if (command === "backlog" && ["add", "split"].includes(sub ?? "")) return "task creation requires instruction-bound privacy screening";
|
|
59
|
+
if (command === "study" && sub === "approve") return "study approval requires instruction-bound privacy screening";
|
|
60
|
+
if (command === "roadmap" && sub === "state") return "only roadmap state done or dropped for one milestone id is admitted; other states stay with the person";
|
|
61
|
+
if (command === "title") return "titles contain free text, and an unnamed title cannot be restored";
|
|
62
|
+
if (command === "backlog" && ["plan", "pin", "pull-ready"].includes(sub ?? "") || command === "review") return "this form contains free text or unclassified options";
|
|
63
|
+
return "this form is not proven for instructed intent mode";
|
|
64
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** WebSocket-shaped adapter over the daemon-created Bun IPC channel, never a network socket. */
|
|
2
|
+
export class InstructedIpcSocket {
|
|
3
|
+
readyState: number = WebSocket.CONNECTING;
|
|
4
|
+
onopen: (() => void) | null = null;
|
|
5
|
+
onmessage: ((event: { data: string }) => void) | null = null;
|
|
6
|
+
onerror: (() => void) | null = null;
|
|
7
|
+
onclose: ((event: { code: number; reason: string }) => void) | null = null;
|
|
8
|
+
private readonly message = (value: unknown) => {
|
|
9
|
+
try {
|
|
10
|
+
const data = JSON.stringify(value);
|
|
11
|
+
if (typeof data !== "string" || Buffer.byteLength(data) > this.maxFrame) throw new Error("invalid inherited control frame");
|
|
12
|
+
this.onmessage?.({ data });
|
|
13
|
+
} catch { this.close(); }
|
|
14
|
+
};
|
|
15
|
+
private readonly disconnected = () => { this.readyState = WebSocket.CLOSED; this.onclose?.({ code: 1006, reason: "inherited control channel closed" }); };
|
|
16
|
+
constructor(private readonly maxFrame: number) {
|
|
17
|
+
if (typeof process.send !== "function") throw new Error("inherited control channel unavailable");
|
|
18
|
+
process.on("message", this.message);
|
|
19
|
+
process.once("disconnect", this.disconnected);
|
|
20
|
+
queueMicrotask(() => { if (this.readyState === WebSocket.CONNECTING) { this.readyState = WebSocket.OPEN; this.onopen?.(); } });
|
|
21
|
+
}
|
|
22
|
+
send(message: string): void {
|
|
23
|
+
if (this.readyState !== WebSocket.OPEN || Buffer.byteLength(message) > this.maxFrame || typeof process.send !== "function") throw new Error("invalid inherited control frame");
|
|
24
|
+
process.send(JSON.parse(message));
|
|
25
|
+
}
|
|
26
|
+
close(): void {
|
|
27
|
+
if (this.readyState === WebSocket.CLOSED) return;
|
|
28
|
+
this.readyState = WebSocket.CLOSED;
|
|
29
|
+
process.removeListener("message", this.message);
|
|
30
|
+
process.removeListener("disconnect", this.disconnected);
|
|
31
|
+
if (process.connected && typeof process.disconnect === "function") process.disconnect();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { lstatSync } from "node:fs";
|
|
2
|
+
import { dirname, isAbsolute, join, relative } from "node:path";
|
|
3
|
+
import { realPath } from "./project.ts";
|
|
4
|
+
|
|
5
|
+
/** Runtime root is captured by the daemon once; unknown project or sandbox roots refuse. */
|
|
6
|
+
export function instructedRuntimeAllowed(runtimeRoot: string, projectRoots: readonly string[]): boolean {
|
|
7
|
+
if (!isAbsolute(runtimeRoot)) return false;
|
|
8
|
+
try {
|
|
9
|
+
for (const root of projectRoots) {
|
|
10
|
+
const rel = relative(realPath(root), runtimeRoot);
|
|
11
|
+
if (!rel || rel !== ".." && !rel.startsWith("../") && !isAbsolute(rel)) return false;
|
|
12
|
+
}
|
|
13
|
+
for (let current = runtimeRoot; ; current = dirname(current)) {
|
|
14
|
+
try { lstatSync(join(current, ".git")); return false; }
|
|
15
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false; }
|
|
16
|
+
if (dirname(current) === current) return true;
|
|
17
|
+
}
|
|
18
|
+
} catch { return false; }
|
|
19
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { openHubDatabase, type Database } from "./db-schema.ts";
|
|
5
|
+
import { realPath } from "./project.ts";
|
|
6
|
+
|
|
7
|
+
export const INSTRUCTION_PROBED_VERSIONS = ["2.1.328", "2.1.329"] as const;
|
|
8
|
+
export const INSTRUCTION_PREFIX = "/agent-hub:ahub";
|
|
9
|
+
export const MAX_PROMPT_BYTES = 16 * 1024;
|
|
10
|
+
const MAX_TRANSCRIPT_TAIL = 1024 * 1024;
|
|
11
|
+
const MAX_AGE_MS = 10 * 60 * 1000;
|
|
12
|
+
const MAX_OPERATIONS = 10;
|
|
13
|
+
const MAX_RECEIPTS = 1024;
|
|
14
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
15
|
+
|
|
16
|
+
/** Keep internal whitespace byte-for-byte; a transcript delimiter is not an argument. */
|
|
17
|
+
export function canonicalInstruction(prompt: unknown): string | undefined {
|
|
18
|
+
if (typeof prompt !== "string" || !prompt.isWellFormed() || Buffer.byteLength(prompt, "utf8") > MAX_PROMPT_BYTES || !prompt.startsWith(INSTRUCTION_PREFIX)) return;
|
|
19
|
+
const rest = prompt.slice(INSTRUCTION_PREFIX.length);
|
|
20
|
+
if (rest && !/^\s/u.test(rest)) return;
|
|
21
|
+
const args = rest.trim();
|
|
22
|
+
if (/[<>&]/u.test(args) || Buffer.from(args).includes(0)) return;
|
|
23
|
+
return args;
|
|
24
|
+
}
|
|
25
|
+
export function instructionHash(args: string): string {
|
|
26
|
+
return createHash("sha256").update(INSTRUCTION_PREFIX).update(Buffer.from([0])).update(args).digest("hex");
|
|
27
|
+
}
|
|
28
|
+
export interface PendingInstruction {
|
|
29
|
+
session: string; promptId: string; transcript: string; home: string; cwd: string; project: string; hash: string; peer?: string;
|
|
30
|
+
}
|
|
31
|
+
interface Row {
|
|
32
|
+
id: string; session: string; prompt_id: string; transcript: string; home: string; cwd: string; project: string; hash: string; peer: string | null; created: number; state: string; uses: number; record_uuid: string | null;
|
|
33
|
+
}
|
|
34
|
+
export interface ConfirmedInstruction { id: string; session: string; args: string; peer?: string }
|
|
35
|
+
/** Supplied by the daemon from its own session and managed-home inventory, never from a control message. */
|
|
36
|
+
export interface InstructionSessionEvidence { session: string; transcript: string; home: string; cwd: string; peer: string }
|
|
37
|
+
export type InstructionEvidence = (session: string, peer: string) => Promise<InstructionSessionEvidence | undefined>;
|
|
38
|
+
|
|
39
|
+
/** Session transcript must be its own file under this home's exact project directory. */
|
|
40
|
+
function transcriptTail(row: Row): string | undefined {
|
|
41
|
+
if (!UUID.test(row.session) || !isAbsolute(row.home) || !isAbsolute(row.cwd) || !isAbsolute(row.transcript)) return;
|
|
42
|
+
let fd: number | undefined;
|
|
43
|
+
try {
|
|
44
|
+
const home = realPath(row.home), cwd = realPath(row.cwd);
|
|
45
|
+
const slug = cwd.replace(/[^a-zA-Z0-9]/g, "-");
|
|
46
|
+
const expected = join(home, "projects", slug, `${row.session}.jsonl`);
|
|
47
|
+
if (row.transcript !== expected || realPath(expected) !== expected) return;
|
|
48
|
+
fd = openSync(expected, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
49
|
+
const stat = fstatSync(fd);
|
|
50
|
+
if (!stat.isFile() || stat.nlink !== 1) return;
|
|
51
|
+
const start = Math.max(0, stat.size - MAX_TRANSCRIPT_TAIL);
|
|
52
|
+
const bytes = Buffer.alloc(stat.size - start);
|
|
53
|
+
const n = readSync(fd, bytes, 0, bytes.length, start);
|
|
54
|
+
let data = bytes.subarray(0, n);
|
|
55
|
+
if (start) { const newline = data.indexOf(10); if (newline < 0) return; data = data.subarray(newline + 1); }
|
|
56
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(data);
|
|
57
|
+
} catch { return; }
|
|
58
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function commandRecord(raw: unknown, row: Row, now: number): { uuid: string; args: string } | undefined {
|
|
62
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
|
|
63
|
+
const record = raw as Record<string, any>, message = record.message;
|
|
64
|
+
if (record.type !== "user" || (record.isMeta !== undefined && record.isMeta !== false) || record.isSidechain !== false || record.origin?.kind !== "human" || Object.hasOwn(record, "promptSource")
|
|
65
|
+
|| record.sessionId !== row.session || record.cwd !== row.cwd || !INSTRUCTION_PROBED_VERSIONS.includes(record.version as typeof INSTRUCTION_PROBED_VERSIONS[number]) || record.promptId !== row.prompt_id || !UUID.test(record.uuid ?? "") || !message || message.role !== "user" || typeof message.content !== "string") return;
|
|
66
|
+
if (typeof record.timestamp !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(record.timestamp)) return;
|
|
67
|
+
const at = Date.parse(record.timestamp);
|
|
68
|
+
if (!Number.isFinite(at) || at < row.created || at > now) return;
|
|
69
|
+
const match = /^<command-message>agent-hub:ahub<\/command-message>\n<command-name>\/agent-hub:ahub<\/command-name>\n<command-args>([\s\S]*)<\/command-args>$/.exec(message.content);
|
|
70
|
+
if (!match) return;
|
|
71
|
+
const args = canonicalInstruction(`${INSTRUCTION_PREFIX} ${match[1]!}`);
|
|
72
|
+
if (args === undefined || instructionHash(args) !== row.hash) return;
|
|
73
|
+
return { uuid: record.uuid.toLowerCase(), args };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Private local state. No caller receives prompt text until host-only confirmation. */
|
|
77
|
+
export class InstructionReceipts {
|
|
78
|
+
private readonly db: Database;
|
|
79
|
+
private readonly exactLeases = new Map<string, { session: string; created: number }>();
|
|
80
|
+
constructor(path: string, private readonly evidence: InstructionEvidence, private readonly clock: () => number = Date.now) {
|
|
81
|
+
this.db = openHubDatabase(path, { create: true });
|
|
82
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS instruction_receipts (
|
|
83
|
+
id TEXT PRIMARY KEY, session TEXT NOT NULL, prompt_id TEXT NOT NULL, transcript TEXT NOT NULL, home TEXT NOT NULL, cwd TEXT NOT NULL, project TEXT NOT NULL,
|
|
84
|
+
hash TEXT NOT NULL, peer TEXT, created INTEGER NOT NULL, state TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, record_uuid TEXT UNIQUE)`);
|
|
85
|
+
this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS instruction_prompt_id ON instruction_receipts(session, prompt_id)");
|
|
86
|
+
this.db.run("CREATE TABLE IF NOT EXISTS instructed_mode (id INTEGER PRIMARY KEY CHECK (id = 1), mode TEXT NOT NULL)");
|
|
87
|
+
}
|
|
88
|
+
close(): void { this.exactLeases.clear(); this.db.close(); }
|
|
89
|
+
/** A new witness inherits an off or exact display copy; a retained witness always wins. */
|
|
90
|
+
seedMode(display: () => "off" | "exact" | "intent" | undefined): void {
|
|
91
|
+
if (this.db.query("SELECT 1 FROM instructed_mode WHERE id = 1").get()) return;
|
|
92
|
+
const value = display();
|
|
93
|
+
if (value === "off" || value === "exact") this.db.query("INSERT OR IGNORE INTO instructed_mode(id, mode) VALUES(1, ?)").run(value);
|
|
94
|
+
}
|
|
95
|
+
/** Missing witness uses the shipped default; malformed retained state never enables the tier. */
|
|
96
|
+
mode(): "off" | "exact" | "intent" {
|
|
97
|
+
const row = this.db.query("SELECT mode FROM instructed_mode WHERE id = 1").get() as { mode: unknown } | null;
|
|
98
|
+
if (!row) return "intent";
|
|
99
|
+
if (row.mode !== "off" && row.mode !== "exact" && row.mode !== "intent") throw new Error("instructed mode witness is invalid");
|
|
100
|
+
return row.mode;
|
|
101
|
+
}
|
|
102
|
+
hasIntentWitness(): boolean {
|
|
103
|
+
const row = this.db.query("SELECT mode FROM instructed_mode WHERE id = 1").get() as { mode: unknown } | null;
|
|
104
|
+
if (!row) return false;
|
|
105
|
+
if (row.mode !== "off" && row.mode !== "exact" && row.mode !== "intent") throw new Error("instructed mode witness is invalid");
|
|
106
|
+
return row.mode === "intent";
|
|
107
|
+
}
|
|
108
|
+
setMode(value: "off" | "exact" | "intent"): void {
|
|
109
|
+
if (value !== "off" && value !== "exact" && value !== "intent") throw new Error("invalid instructed mode");
|
|
110
|
+
this.db.query("INSERT INTO instructed_mode(id, mode) VALUES(1, ?) ON CONFLICT(id) DO UPDATE SET mode = excluded.mode").run(value);
|
|
111
|
+
}
|
|
112
|
+
pending(value: PendingInstruction, now: number): boolean {
|
|
113
|
+
if (!UUID.test(value.session) || !UUID.test(value.promptId)
|
|
114
|
+
|| !/^[0-9a-f]{64}$/.test(value.hash) || !Number.isSafeInteger(now) || now < 0 || !isAbsolute(value.home) || !isAbsolute(value.cwd) || !isAbsolute(value.project) || !isAbsolute(value.transcript)
|
|
115
|
+
|| [value.home, value.cwd, value.project, value.transcript].some(path => path.length > 4096 || /[\p{Cc}\p{Cf}]/u.test(path))
|
|
116
|
+
|| value.peer !== undefined && !/^[a-z][a-z0-9_-]{0,63}$/.test(value.peer)) return false;
|
|
117
|
+
return this.db.transaction(() => {
|
|
118
|
+
for (const [id, lease] of this.exactLeases) if (lease.created <= now - MAX_AGE_MS || lease.created > now) this.exactLeases.delete(id);
|
|
119
|
+
this.db.query("DELETE FROM instruction_receipts WHERE created <= ?").run(now - MAX_AGE_MS);
|
|
120
|
+
const count = this.db.query("SELECT COUNT(*) AS n FROM instruction_receipts").get() as { n: number };
|
|
121
|
+
if (count.n >= MAX_RECEIPTS) return false;
|
|
122
|
+
return this.db.query("INSERT OR IGNORE INTO instruction_receipts(id, session, prompt_id, transcript, home, cwd, project, hash, peer, created, state) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')")
|
|
123
|
+
.run(randomUUID(), value.session, value.promptId, value.transcript, value.home, value.cwd, value.project, value.hash, value.peer ?? null, now).changes === 1;
|
|
124
|
+
})();
|
|
125
|
+
}
|
|
126
|
+
forPeer(peer: string): { confirmReceipt(session: string, now: number): Promise<ConfirmedInstruction | undefined>; confirmIntent(session: string, now: number): Promise<ConfirmedInstruction | undefined> } {
|
|
127
|
+
return { confirmReceipt: (session, now) => this.confirmForPeer(session, now, peer).catch(() => undefined), confirmIntent: (session, now) => this.confirmForPeer(session, now, peer, true).catch(() => undefined) };
|
|
128
|
+
}
|
|
129
|
+
private async confirmForPeer(session: string, now: number, peer: string, reusable = false): Promise<ConfirmedInstruction | undefined> {
|
|
130
|
+
if (!UUID.test(session) || !Number.isSafeInteger(now) || !/^[a-z][a-z0-9_-]{0,63}$/.test(peer)) return;
|
|
131
|
+
const evidence = await this.evidence(session, peer);
|
|
132
|
+
if (!evidence || evidence.session !== session || evidence.peer !== peer) return;
|
|
133
|
+
this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE state != 'closed' AND (created <= ? OR created > ?)").run(now - MAX_AGE_MS, now);
|
|
134
|
+
let rows = this.db.query(reusable ? "SELECT * FROM instruction_receipts WHERE session = ? ORDER BY created DESC, id DESC" : "SELECT * FROM instruction_receipts WHERE session = ? AND state = 'pending' ORDER BY created, id").all(session) as Row[];
|
|
135
|
+
if (reusable && rows[0] && rows[1]?.created === rows[0].created) return; // Equal timestamps do not establish which instruction is current.
|
|
136
|
+
if (reusable) rows = rows.slice(0, 1);
|
|
137
|
+
if (rows.length === 0 || reusable && rows[0]!.state === "closed") return;
|
|
138
|
+
const boundEvidence = { ...rows[0], session, home: evidence.home, cwd: evidence.cwd, transcript: evidence.transcript } as Row;
|
|
139
|
+
const tail = transcriptTail(boundEvidence); if (tail === undefined) return;
|
|
140
|
+
const lines = tail.split("\n");
|
|
141
|
+
const byPrompt = new Map<string, unknown[]>();
|
|
142
|
+
for (const line of lines) {
|
|
143
|
+
let parsed: unknown; try { parsed = JSON.parse(line); } catch { continue; }
|
|
144
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
|
|
145
|
+
const id = (parsed as { promptId?: unknown }).promptId;
|
|
146
|
+
if (typeof id !== "string") continue;
|
|
147
|
+
const bucket = byPrompt.get(id) ?? []; bucket.push(parsed); byPrompt.set(id, bucket);
|
|
148
|
+
}
|
|
149
|
+
for (const row of rows) {
|
|
150
|
+
if (now < row.created || now - row.created >= MAX_AGE_MS || (row.peer !== null && row.peer !== peer) || row.transcript !== evidence.transcript) continue;
|
|
151
|
+
const bound = { ...row, home: evidence.home, cwd: evidence.cwd, transcript: evidence.transcript };
|
|
152
|
+
const candidates: { uuid: string; args: string; at: number }[] = [];
|
|
153
|
+
for (const parsed of byPrompt.get(row.prompt_id) ?? []) {
|
|
154
|
+
const record = commandRecord(parsed, bound, now); if (!record) continue;
|
|
155
|
+
candidates.push({ ...record, at: Date.parse((parsed as { timestamp: string }).timestamp) });
|
|
156
|
+
}
|
|
157
|
+
candidates.sort((a, b) => a.at - b.at || a.uuid.localeCompare(b.uuid));
|
|
158
|
+
for (const record of candidates) {
|
|
159
|
+
const current = await this.evidence(session, peer);
|
|
160
|
+
const checkedAt = this.clock();
|
|
161
|
+
if (!Number.isSafeInteger(checkedAt) || checkedAt < now || checkedAt - row.created >= MAX_AGE_MS) {
|
|
162
|
+
this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE id = ?").run(row.id);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (!current || current.session !== evidence.session || current.peer !== evidence.peer || current.home !== evidence.home || current.cwd !== evidence.cwd || current.transcript !== evidence.transcript) return;
|
|
166
|
+
const refreshed = transcriptTail(bound);
|
|
167
|
+
if (refreshed !== tail) return;
|
|
168
|
+
const finalAt = this.clock();
|
|
169
|
+
if (!Number.isSafeInteger(finalAt) || finalAt < checkedAt || finalAt - row.created >= MAX_AGE_MS) {
|
|
170
|
+
this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE id = ?").run(row.id);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (reusable && row.state === "confirmed" && row.peer === peer && row.record_uuid === record.uuid) {
|
|
174
|
+
const stillOpen = this.db.query("SELECT 1 FROM instruction_receipts WHERE id = ? AND state = 'confirmed' AND peer = ? AND record_uuid = ?").get(row.id, peer, record.uuid);
|
|
175
|
+
if (stillOpen) return { id: row.id, session, args: record.args, peer };
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const changed = this.db.query("UPDATE instruction_receipts SET state = 'confirmed', record_uuid = ?, peer = ? WHERE id = ? AND state = 'pending' AND NOT EXISTS (SELECT 1 FROM instruction_receipts WHERE record_uuid = ?)")
|
|
179
|
+
.run(record.uuid, peer, row.id, record.uuid);
|
|
180
|
+
if (changed.changes === 1) return { id: row.id, session, args: record.args, ...(row.peer ? { peer: row.peer } : {}) };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
consume(id: string, now: number): boolean {
|
|
185
|
+
if (!Number.isSafeInteger(now) || now < 0) return false;
|
|
186
|
+
this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE id = ? AND state != 'closed' AND (created <= ? OR created > ?)").run(id, now - MAX_AGE_MS, now);
|
|
187
|
+
return this.db.query("UPDATE instruction_receipts SET uses = uses + 1, state = CASE WHEN uses + 1 >= ? THEN 'closed' ELSE state END WHERE id = ? AND state = 'confirmed' AND created <= ? AND created > ? AND uses < ?")
|
|
188
|
+
.run(MAX_OPERATIONS, id, now, now - MAX_AGE_MS, MAX_OPERATIONS).changes === 1;
|
|
189
|
+
}
|
|
190
|
+
/** Exact mode closes the durable receipt before the effect; a host-only lease tracks an in-flight stop. */
|
|
191
|
+
consumeExact(id: string, now: number): boolean {
|
|
192
|
+
if (!Number.isSafeInteger(now) || now < 0) return false;
|
|
193
|
+
const row = this.db.query("UPDATE instruction_receipts SET uses = 1, state = 'closed' WHERE id = ? AND state = 'confirmed' AND uses = 0 AND created <= ? AND created > ? RETURNING session, created")
|
|
194
|
+
.get(id, now, now - MAX_AGE_MS) as { session: string; created: number } | null;
|
|
195
|
+
if (!row) return false;
|
|
196
|
+
this.exactLeases.set(id, row);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
/** Serialize intent operations and retain a revocable lease even for the tenth use. */
|
|
200
|
+
consumeIntent(id: string, now: number): boolean {
|
|
201
|
+
if (!Number.isSafeInteger(now) || now < 0 || this.exactLeases.has(id)) return false;
|
|
202
|
+
const row = this.db.query("UPDATE instruction_receipts SET uses = uses + 1, state = CASE WHEN uses + 1 >= ? THEN 'closed' ELSE state END WHERE id = ? AND state = 'confirmed' AND created <= ? AND created > ? AND uses < ? RETURNING session, created")
|
|
203
|
+
.get(MAX_OPERATIONS, id, now, now - MAX_AGE_MS, MAX_OPERATIONS) as { session: string; created: number } | null;
|
|
204
|
+
if (!row) return false;
|
|
205
|
+
this.exactLeases.set(id, row);
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
exactCurrent(id: string, now: number): boolean {
|
|
209
|
+
const lease = this.exactLeases.get(id);
|
|
210
|
+
return !!lease && Number.isSafeInteger(now) && now >= lease.created && now - lease.created < MAX_AGE_MS;
|
|
211
|
+
}
|
|
212
|
+
finishExact(id: string): void { this.exactLeases.delete(id); }
|
|
213
|
+
stop(session: string, peer?: string): void {
|
|
214
|
+
if (!UUID.test(session)) return;
|
|
215
|
+
for (const [id, lease] of this.exactLeases) if (lease.session === session) this.exactLeases.delete(id);
|
|
216
|
+
this.db.query("UPDATE instruction_receipts SET state = 'closed' WHERE session = ? AND state != 'closed' AND (? IS NULL OR peer IS NULL OR peer = ?)").run(session, peer ?? null, peer ?? null);
|
|
217
|
+
}
|
|
218
|
+
}
|
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
|
+
}
|