@staix/agent-hub 0.49.1 → 0.51.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 +22 -0
- package/README.md +1 -1
- package/docs/adding-an-ai-tool.md +2 -2
- package/docs/agent-notes/README.md +1 -0
- package/docs/agent-notes/adapters.md +3 -3
- package/docs/agent-notes/daemon.md +1 -1
- package/docs/agent-notes/local-worker.md +3 -3
- package/docs/agent-notes/tasks.md +5 -1
- package/docs/design/adapters.md +17 -0
- package/docs/design/agent-hub.md +1 -1
- package/docs/design/cli-output-inventory.md +24 -19
- package/docs/design/cli-output.md +1 -1
- package/docs/design/roadmap.md +2 -2
- package/docs/design/task-board.md +34 -0
- package/docs/dogfood.md +8 -3
- package/docs/operations.md +53 -4
- package/docs/quickstart.md +26 -2
- package/docs/roadmap.json +20 -20
- package/docs/roadmap.md +2 -2
- package/docs/sdlc.md +3 -2
- package/docs/specs/2026-09-19-agent-hub-design.md +1 -0
- package/docs/verification/2026-11-29-0.50.0.md +54 -0
- package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
- package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
- package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
- package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
- package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
- package/docs/verification/2026-11-30-0.51.0.md +91 -0
- package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
- package/docs/verified.json +31 -27
- package/package.json +1 -1
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +1329 -24629
- package/plugins/agent-hub/server.js +638 -414
- package/scripts/check-docs.mjs +1 -1
- package/src/adapters/acp.ts +13 -13
- package/src/adapters/agy/definition.ts +2 -2
- package/src/adapters/agy/entry.ts +2 -0
- package/src/adapters/claude-channel-evidence.ts +7 -3
- package/src/adapters/compat.ts +4 -3
- package/src/adapters/definitions/builtin-metadata.ts +2 -2
- package/src/adapters/definitions/native-cli-claude-launch.ts +3 -1
- package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
- package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
- package/src/adapters/definitions/native-cli-entry-jcode.ts +2 -0
- package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
- package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
- package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
- package/src/adapters/definitions/native-cli-entry-types.ts +3 -1
- package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
- package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
- package/src/adapters/definitions/native-config-defaults.ts +1 -1
- package/src/adapters/jcode.ts +16 -0
- package/src/adapters/native-facts-hooks.ts +12 -0
- package/src/cli/autonomy-offline.ts +1 -1
- package/src/cli/bench.ts +1 -1
- package/src/cli/claude-profile-hook.ts +31 -11
- package/src/cli/commands/releases.ts +82 -0
- package/src/cli/conductor-recovery.ts +1 -1
- package/src/cli/facts-hook.ts +11 -4
- package/src/cli/help.ts +12 -10
- package/src/cli/identity.ts +5 -1
- package/src/cli/init-prompt.ts +1 -1
- package/src/cli/init-settings.ts +4 -35
- package/src/cli/init.ts +1 -1
- package/src/cli/json-text-spans.ts +57 -0
- package/src/cli/launch-check.ts +157 -0
- package/src/cli/launch.ts +19 -1
- package/src/cli/main.ts +63 -10
- package/src/cli/memory.ts +1 -1
- package/src/cli/output.ts +14 -1
- package/src/cli/preview.ts +1 -1
- package/src/cli/recovery-launch.ts +1 -1
- package/src/cli/setup-homes.ts +2 -2
- package/src/cli/start-agents-run.ts +85 -7
- package/src/cli/start-check.ts +28 -0
- package/src/cli/upgrade-runtime.ts +1 -1
- package/src/cli/warn-line.ts +1 -1
- package/src/hub/ci-watch.ts +311 -79
- package/src/hub/config-apply.ts +1 -1
- package/src/hub/config.ts +518 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +76 -513
- package/src/hub/delivery-public.ts +11 -0
- package/src/hub/hub-check.ts +125 -0
- package/src/hub/path-policy.ts +1 -1
- package/src/hub/permission-mode.ts +3 -40
- package/src/hub/permission-paths.ts +41 -0
- package/src/hub/recovery-policy.ts +1 -1
- package/src/hub/releases-inventory.ts +198 -0
- package/src/hub/runtime-capture-prune.ts +25 -3
- package/src/hub/runtime-prune-health.ts +8 -1
- package/src/hub/sdlc-release-authorization.ts +42 -21
- package/src/hub/sdlc-release-diagnostics.ts +5 -0
- package/src/hub/sdlc-release-policy.ts +21 -7
- package/src/hub/sdlc-release.ts +80 -20
- package/src/hub/sdlc.ts +7 -3
- package/src/hub/tasks.ts +138 -36
- package/src/ui/plugin.ts +1 -1
|
@@ -16,6 +16,17 @@ export function publicDeliveryBodies(originals: readonly Envelope[], policy: Del
|
|
|
16
16
|
}));
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* #1795: the stored reason of a failed or held delivery, under the same rules as its bodies: a private delivery shows the stub only, a public view
|
|
21
|
+
* withholds a reason whose text the task's public rules do not pass, and control characters are removed.
|
|
22
|
+
*/
|
|
23
|
+
export function publicDeliveryReason(originals: readonly Envelope[], reason: string, policy: DeliveryPublicPolicy): string {
|
|
24
|
+
const privateDelivery = originals.some(env => env.private || policy.publicOnly && env.refs?.task && policy.taskPrivate(env.refs.task));
|
|
25
|
+
if (privateDelivery) return "[private: inspect the associated task with ahub task show]";
|
|
26
|
+
if (policy.publicOnly && !policy.publicMetadataText(reason)) return "[withheld]";
|
|
27
|
+
return sanitize(reason).slice(0, 1000);
|
|
28
|
+
}
|
|
29
|
+
|
|
19
30
|
/** Held content is inspection of an uncertain attempt, never a new delivery or instruction to repeat it. */
|
|
20
31
|
export function renderHeldInbox(value: unknown): string {
|
|
21
32
|
const unavailable = "Held message bodies are unavailable; inspect your queue before deciding whether to repeat any action.";
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { AdapterDefinition, StartForm } from "../adapters/registry-types.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* #1798: the one hub check. The daemon builds it once from peer state it already holds and returns it in the status reply; `ahub status`,
|
|
5
|
+
* `ahub up` and every later surface render this result and never recompute it. A row carries peer ids, link names, an evidence value, a
|
|
6
|
+
* queued count and a command, never task text or a message body.
|
|
7
|
+
*/
|
|
8
|
+
export type ExpectedLink = "push" | "pull";
|
|
9
|
+
/** The adapter and launch form determine the expected link independently of the observed attachment. */
|
|
10
|
+
export function expectedHubLink(definition: Pick<AdapterDefinition, "transport" | "attach"> | undefined, form?: StartForm): ExpectedLink {
|
|
11
|
+
return definition?.transport === "ws-pull" || (form !== undefined && definition?.attach?.pullOnlyForms?.includes(form)) ? "pull" : "push";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type ObservedLink = "push" | "tools-only" | "pull-only" | "detached" | "unverified" | "pending" | "offline" | "refused";
|
|
15
|
+
|
|
16
|
+
interface HubCheckPeerInput {
|
|
17
|
+
id: string;
|
|
18
|
+
/** What the launch was meant to give: a push link (channel or prompt delivery) or a pull-only one. */
|
|
19
|
+
expected: ExpectedLink;
|
|
20
|
+
/** The peer has a live attachment to the hub. */
|
|
21
|
+
attached: boolean;
|
|
22
|
+
/** The hub started this peer and it has not attached yet (the bounded `ahub up` wait reports it `pending`). */
|
|
23
|
+
starting?: boolean;
|
|
24
|
+
pullOnly?: boolean;
|
|
25
|
+
/** The adapter's own attach evidence (for Claude, the channel evidence the hello carried). */
|
|
26
|
+
evidence?: string;
|
|
27
|
+
detached?: boolean;
|
|
28
|
+
queued: number;
|
|
29
|
+
/** The full command that fixes this peer's link. */
|
|
30
|
+
nextStep?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface HubCheckPeer {
|
|
34
|
+
id: string;
|
|
35
|
+
expected: ExpectedLink;
|
|
36
|
+
observed: ObservedLink;
|
|
37
|
+
evidence: string;
|
|
38
|
+
pullOnly: boolean;
|
|
39
|
+
detached: boolean;
|
|
40
|
+
queued: number;
|
|
41
|
+
ok: boolean;
|
|
42
|
+
/** Present only when the link is weaker than expected, or the peer has not attached. */
|
|
43
|
+
cause?: string;
|
|
44
|
+
nextStep?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface HubCheck {
|
|
48
|
+
version: string;
|
|
49
|
+
controlPort: number;
|
|
50
|
+
peers: HubCheckPeer[];
|
|
51
|
+
/** Peers whose observed link is weaker than expected, in peer order. */
|
|
52
|
+
degraded: string[];
|
|
53
|
+
/** Peers started but not attached: reported `pending`, never as OK. */
|
|
54
|
+
pending: string[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const UNVERIFIED = new Set(["launch-unverified", "unknown", "unreported"]);
|
|
58
|
+
|
|
59
|
+
function observe(input: HubCheckPeerInput): ObservedLink {
|
|
60
|
+
if (input.detached) return "detached";
|
|
61
|
+
if (!input.attached) return input.starting ? "pending" : "offline";
|
|
62
|
+
if (input.expected === "pull") return "pull-only";
|
|
63
|
+
if (input.pullOnly) return input.evidence && UNVERIFIED.has(input.evidence) ? "unverified" : "tools-only";
|
|
64
|
+
return "push";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function causeOf(input: HubCheckPeerInput, observed: ObservedLink): string | undefined {
|
|
68
|
+
switch (observed) {
|
|
69
|
+
case "push": case "pull-only": case "offline": return undefined;
|
|
70
|
+
case "pending": return "started, not attached yet";
|
|
71
|
+
case "detached": return "the owned launch is not attached";
|
|
72
|
+
case "unverified": return `the launch could not be verified (evidence: ${input.evidence ?? "unknown"}); messages wait for hub_inbox`;
|
|
73
|
+
case "tools-only": return `tools-only link (evidence: ${input.evidence ?? "unknown"}); messages wait for hub_inbox`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function buildHubCheck(input: { version: string; controlPort: number; peers: readonly HubCheckPeerInput[] }): HubCheck {
|
|
78
|
+
const peers = input.peers.map((peer): HubCheckPeer => {
|
|
79
|
+
const observed = observe(peer);
|
|
80
|
+
const weak = peer.expected === "push" && (observed === "tools-only" || observed === "unverified" || observed === "detached");
|
|
81
|
+
const cause = causeOf(peer, observed);
|
|
82
|
+
return { id: peer.id, expected: peer.expected, observed, evidence: peer.evidence ?? "unreported", pullOnly: peer.pullOnly === true,
|
|
83
|
+
detached: peer.detached === true, queued: peer.queued, ok: !weak && observed !== "pending" && !(peer.detached === true),
|
|
84
|
+
...(cause && (weak || observed === "pending") ? { cause } : {}), ...(peer.nextStep && (weak || observed === "pending" || peer.detached) ? { nextStep: peer.nextStep } : {}) };
|
|
85
|
+
});
|
|
86
|
+
return { version: input.version, controlPort: input.controlPort, peers, degraded: peers.filter(peer => !peer.ok && peer.observed !== "pending").map(peer => peer.id),
|
|
87
|
+
pending: peers.filter(peer => peer.observed === "pending").map(peer => peer.id) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** One `Hub check` block, one line per peer: ✓, or ⚠ with the cause and the full next-step command. Plain text for a terminal. */
|
|
91
|
+
export function renderHubCheck(check: HubCheck, only?: readonly string[]): string[] {
|
|
92
|
+
const rows = only ? check.peers.filter(peer => only.includes(peer.id)) : check.peers.filter(peer => peer.observed !== "offline" || !peer.ok);
|
|
93
|
+
const lines = [`Hub check (agent-hub ${check.version}, control port ${check.controlPort})`];
|
|
94
|
+
for (const peer of rows) {
|
|
95
|
+
if (peer.ok && peer.observed !== "offline") { lines.push(` ✓ ${peer.id}: ${peer.observed}${peer.queued ? `, ${peer.queued} queued` : ""}`); continue; }
|
|
96
|
+
lines.push(` ⚠ ${peer.id}: ${peer.observed}${peer.cause ? `, ${peer.cause}` : ""}${peer.queued ? `, ${peer.queued} queued` : ""}${peer.nextStep ? `; next: ${peer.nextStep}` : ""}`);
|
|
97
|
+
}
|
|
98
|
+
if (rows.length === 0) lines.push(" no agents attached");
|
|
99
|
+
return lines;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* `ahub up` asked these agents to start. `started` ids really started (their start reply was ok): an offline row for one is `pending`, never OK.
|
|
104
|
+
* `refused` ids were refused with the hub's own reason: they are `refused` (a warning with that reason and the next step), never `pending`, never OK.
|
|
105
|
+
* This only relabels rows of the one check the daemon returned; it reads nothing else.
|
|
106
|
+
*/
|
|
107
|
+
export function markStarted(check: HubCheck, started: readonly string[], refused: Readonly<Record<string, { cause: string; nextStep?: string }>> = {}, expected: Readonly<Record<string, ExpectedLink>> = {}): HubCheck {
|
|
108
|
+
// A peer `ahub up` asked for that the hub has not seen yet has no row: it is offline, nothing more (no link state is invented for it).
|
|
109
|
+
const missing = [...started, ...Object.keys(refused)].filter((id, index, all) => all.indexOf(id) === index && !check.peers.some(peer => peer.id === id))
|
|
110
|
+
.map((id): HubCheckPeer => ({ id, expected: expected[id] ?? expectedHubLink(undefined), observed: "offline", evidence: "unreported", pullOnly: false, detached: false, queued: 0, ok: true, nextStep: `ahub ${id}` }));
|
|
111
|
+
const peers = [...check.peers, ...missing].map((peer): HubCheckPeer => {
|
|
112
|
+
const refusal = refused[peer.id];
|
|
113
|
+
if (refusal) return { ...peer, observed: "refused", ok: false, cause: refusal.cause, ...(refusal.nextStep ?? peer.nextStep ? { nextStep: refusal.nextStep ?? peer.nextStep } : {}) };
|
|
114
|
+
if (!started.includes(peer.id) || (peer.observed !== "offline" && peer.observed !== "pending")) return peer;
|
|
115
|
+
return { ...peer, observed: "pending", ok: false, cause: peer.cause ?? "started, not attached yet", nextStep: peer.nextStep ?? `ahub ${peer.id}` };
|
|
116
|
+
});
|
|
117
|
+
return { ...check, peers, degraded: peers.filter(peer => !peer.ok && peer.observed !== "pending").map(peer => peer.id), pending: peers.filter(peer => peer.observed === "pending").map(peer => peer.id) };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The check could not be read in time: one warning line with `ahub status` as the next step, and an explicit result for `--json`. */
|
|
121
|
+
interface HubCheckUnavailable { unavailable: true; cause: string; nextStep: string }
|
|
122
|
+
export const HUB_CHECK_UNAVAILABLE: HubCheckUnavailable = { unavailable: true, cause: "the hub check could not be read from the hub", nextStep: "ahub status" };
|
|
123
|
+
export function renderHubCheckUnavailable(result: HubCheckUnavailable = HUB_CHECK_UNAVAILABLE): string[] {
|
|
124
|
+
return [`Hub check: ⚠ ${result.cause}; next: ${result.nextStep}`];
|
|
125
|
+
}
|
package/src/hub/path-policy.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { accessSync, constants, lstatSync, opendirSync, readlinkSync, statSync } from "node:fs";
|
|
2
2
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
3
|
import { realPath } from "./project.ts";
|
|
4
|
-
import { foldSegment } from "./permission-
|
|
4
|
+
import { foldSegment } from "./permission-paths.ts";
|
|
5
5
|
/**
|
|
6
6
|
* Whether `rel`, the result of `relative(root, path)`, names something inside the root: not `..`, not a path that starts with a `..` SEGMENT, and not absolute.
|
|
7
7
|
* A string prefix test is wrong here: `..ignored/f.txt` is a valid directory named `..ignored` inside the project (#552), while `../f.txt` leaves it.
|
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
import { definitionOf, type ProjectAdapterCatalog, type KindMap } from "../adapters/registry.ts";
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
/** Operator-selected approval frequency; agent sandboxes remain separate. */
|
|
6
|
-
export const PERMISSION_MODES = ["ask", "ask-when-needed", "never-ask"] as const;
|
|
7
|
-
export type PermissionMode = typeof PERMISSION_MODES[number];
|
|
2
|
+
import { isPermissionMode, type PermissionMode } from "./permission-paths.ts";
|
|
3
|
+
export * from "./permission-paths.ts";
|
|
8
4
|
export { KIMI_MODE_IDS } from "../adapters/definitions/kimi-native.ts";
|
|
9
5
|
export { QWEN_MODE_IDS } from "../adapters/definitions/qwen-native.ts";
|
|
10
|
-
|
|
6
|
+
|
|
11
7
|
export function permissionDefaults(value: unknown, instances?: KindMap, catalog?: ProjectAdapterCatalog): Record<string, PermissionMode> {
|
|
12
8
|
if (value === undefined) return {};
|
|
13
9
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("permission_modes must be an object with ask, ask-when-needed or never-ask values");
|
|
@@ -38,36 +34,3 @@ export function permissionGrant(peer: string, mode: PermissionMode, instances?:
|
|
|
38
34
|
if (mode === "ask") return "every write, edit and shell command asks";
|
|
39
35
|
return mode === "never-ask" ? "every tool runs without asking, inside the hub sandbox and path guard" : "write, edit and proven bounded read-only shell commands inside the project run without asking; other shell commands and git writes still ask";
|
|
40
36
|
}
|
|
41
|
-
export const PI_EDIT_TOOLS = new Set(["edit", "write"]);
|
|
42
|
-
/** Native agent policy files are never included in scoped automatic file grants. */
|
|
43
|
-
export const AGENT_CONFIG_SEGMENTS: ReadonlySet<string> = new Set([".claude", ".codex", ".qwen", ".kimi", ".kimi-code", ".jcode", ".pi", ".mcp.json", ".agents", ".agent", "_agents", "_agent", ".gemini", ".grok", ".claude.json"]);
|
|
44
|
-
export const INSTRUCTION_FILES: ReadonlySet<string> = new Set(["agents.md", "claude.md", "qwen.md", "gemini.md"]);
|
|
45
|
-
export const isInstructionPath = (path: string): boolean => path.split(/[\\/]/).some(segment => INSTRUCTION_FILES.has(foldSegment(segment)));
|
|
46
|
-
export function instructionProtection(value: unknown): boolean {
|
|
47
|
-
if (value === undefined) return false;
|
|
48
|
-
if (typeof value !== "boolean") throw new Error("protect_instruction_files must be a boolean");
|
|
49
|
-
return value;
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* One spelling per name, as a case-insensitive disk sees it: it opens `.mcp.j\u017Fon` (long s) as `.mcp.json`, and
|
|
53
|
-
* HFS+ also ignores the default-ignorable code points (a zero-width joiner inside `.codex` is still `.codex`).
|
|
54
|
-
*/
|
|
55
|
-
export const foldSegment = (segment: string): string => segment.normalize("NFKC").replace(/\p{Default_Ignorable_Code_Point}/gu, "").toLowerCase().toUpperCase().toLowerCase();
|
|
56
|
-
/** The hub's and git's own directories: writing them changes what runs outside any agent's control. */
|
|
57
|
-
export const HUB_WRITE_SEGMENTS: ReadonlySet<string> = new Set([".git", ".agenthub"]);
|
|
58
|
-
export const isHubWritePath = (path: string): boolean => path.split(/[\\/]/).some(segment => HUB_WRITE_SEGMENTS.has(foldSegment(segment)));
|
|
59
|
-
export const isAgentConfigPath = (path: string): boolean => path.split(/[\\/]/).some(segment => AGENT_CONFIG_SEGMENTS.has(foldSegment(segment)));
|
|
60
|
-
/** A file with a second name somewhere else: a grant for this name would write that one too. */
|
|
61
|
-
export function hardLinked(path: string): boolean {
|
|
62
|
-
try { const st = lstatSync(path); return st.isFile() && st.nlink > 1; } catch { return false; } // a file that does not exist yet has no other name
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Whether a scoped automatic write or edit grant may cover `path` (canonical) in the project at `root` (canonical):
|
|
66
|
-
* inside the project, outside every agent's configuration, judged by the path within the project (a project that
|
|
67
|
-
* itself lives under `.claude/worktrees/` is still a project), and not a hard link.
|
|
68
|
-
*/
|
|
69
|
-
export function grantablePath(root: string, path: string, originalPath?: string, protectInstructions = false): boolean {
|
|
70
|
-
const inside = relative(root, path);
|
|
71
|
-
const original = originalPath === undefined ? inside : relative(root, resolve(root, originalPath));
|
|
72
|
-
return !!inside && inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside) && !isAgentConfigPath(inside) && !isHubWritePath(inside) && !isAgentConfigPath(original) && !isHubWritePath(original) && !(protectInstructions && (isInstructionPath(inside) || isInstructionPath(original))) && !hardLinked(path);
|
|
73
|
-
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { lstatSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Operator-selected approval frequency; agent sandboxes remain separate. */
|
|
5
|
+
export const PERMISSION_MODES = ["ask", "ask-when-needed", "never-ask"] as const;
|
|
6
|
+
export type PermissionMode = typeof PERMISSION_MODES[number];
|
|
7
|
+
export const isPermissionMode = (value: unknown): value is PermissionMode => typeof value === "string" && (PERMISSION_MODES as readonly string[]).includes(value);
|
|
8
|
+
|
|
9
|
+
export const PI_EDIT_TOOLS = new Set(["edit", "write"]);
|
|
10
|
+
/** Native agent policy files are never included in scoped automatic file grants. */
|
|
11
|
+
export const AGENT_CONFIG_SEGMENTS: ReadonlySet<string> = new Set([".claude", ".codex", ".qwen", ".kimi", ".kimi-code", ".jcode", ".pi", ".mcp.json", ".agents", ".agent", "_agents", "_agent", ".gemini", ".grok", ".claude.json"]);
|
|
12
|
+
export const INSTRUCTION_FILES: ReadonlySet<string> = new Set(["agents.md", "claude.md", "qwen.md", "gemini.md"]);
|
|
13
|
+
export const isInstructionPath = (path: string): boolean => path.split(/[\\/]/).some(segment => INSTRUCTION_FILES.has(foldSegment(segment)));
|
|
14
|
+
export function instructionProtection(value: unknown): boolean {
|
|
15
|
+
if (value === undefined) return false;
|
|
16
|
+
if (typeof value !== "boolean") throw new Error("protect_instruction_files must be a boolean");
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* One spelling per name, as a case-insensitive disk sees it: it opens `.mcp.j\u017Fon` (long s) as `.mcp.json`, and
|
|
21
|
+
* HFS+ also ignores the default-ignorable code points (a zero-width joiner inside `.codex` is still `.codex`).
|
|
22
|
+
*/
|
|
23
|
+
export const foldSegment = (segment: string): string => segment.normalize("NFKC").replace(/\p{Default_Ignorable_Code_Point}/gu, "").toLowerCase().toUpperCase().toLowerCase();
|
|
24
|
+
/** The hub's and git's own directories: writing them changes what runs outside any agent's control. */
|
|
25
|
+
export const HUB_WRITE_SEGMENTS: ReadonlySet<string> = new Set([".git", ".agenthub"]);
|
|
26
|
+
export const isHubWritePath = (path: string): boolean => path.split(/[\\/]/).some(segment => HUB_WRITE_SEGMENTS.has(foldSegment(segment)));
|
|
27
|
+
export const isAgentConfigPath = (path: string): boolean => path.split(/[\\/]/).some(segment => AGENT_CONFIG_SEGMENTS.has(foldSegment(segment)));
|
|
28
|
+
/** A file with a second name somewhere else: a grant for this name would write that one too. */
|
|
29
|
+
export function hardLinked(path: string): boolean {
|
|
30
|
+
try { const st = lstatSync(path); return st.isFile() && st.nlink > 1; } catch { return false; } // a file that does not exist yet has no other name
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Whether a scoped automatic write or edit grant may cover `path` (canonical) in the project at `root` (canonical):
|
|
34
|
+
* inside the project, outside every agent's configuration, judged by the path within the project (a project that
|
|
35
|
+
* itself lives under `.claude/worktrees/` is still a project), and not a hard link.
|
|
36
|
+
*/
|
|
37
|
+
export function grantablePath(root: string, path: string, originalPath?: string, protectInstructions = false): boolean {
|
|
38
|
+
const inside = relative(root, path);
|
|
39
|
+
const original = originalPath === undefined ? inside : relative(root, resolve(root, originalPath));
|
|
40
|
+
return !!inside && inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside) && !isAgentConfigPath(inside) && !isHubWritePath(inside) && !isAgentConfigPath(original) && !isHubWritePath(original) && !(protectInstructions && (isInstructionPath(inside) || isInstructionPath(original))) && !hardLinked(path);
|
|
41
|
+
}
|
|
@@ -9,7 +9,7 @@ import { isAbsolute, join, resolve } from "node:path";
|
|
|
9
9
|
import { types } from "node:util";
|
|
10
10
|
import { definitionOf } from "../adapters/registry.ts";
|
|
11
11
|
import { adapterCeiling, applyRoleCeiling } from "../adapters/role-eligibility.ts";
|
|
12
|
-
import type { HubConfig } from "./
|
|
12
|
+
import type { HubConfig } from "./config.ts";
|
|
13
13
|
import type { ConfigSourceTexts } from "./config-reload.ts";
|
|
14
14
|
import { conductorPeer } from "./conductor.ts";
|
|
15
15
|
import { DEFAULT_ROLES } from "./hub-tools.ts";
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync, mkdirSync, readdirSync, renameSync, rmSync, type Stats } from "node:fs";
|
|
3
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { realPath } from "./project.ts";
|
|
5
|
+
import type { Registry } from "./registry.ts";
|
|
6
|
+
import { observeRuntimeReferences, openRuntimeRegistry, underRuntimeReferences, type RuntimeReferences } from "./runtime-capture-prune.ts";
|
|
7
|
+
|
|
8
|
+
/** #1781: what lives under `$AGENTHUB_HOME/releases`, who refers to it, and the explicit removal of what nothing refers to. */
|
|
9
|
+
export const RELEASE_KINDS = ["capture", "coordinator-source", "registry-install"] as const;
|
|
10
|
+
export type ReleaseKind = typeof RELEASE_KINDS[number] | "unknown";
|
|
11
|
+
export interface ReleaseEntry {
|
|
12
|
+
path: string; name: string; kind: ReleaseKind; version: string | null; digest: string | null; bytes: number;
|
|
13
|
+
/** Newest mtime anywhere in the entry's tree, so a file written inside a parent keeps it young. */
|
|
14
|
+
modified: number;
|
|
15
|
+
/** Scan-time identity and direct children, compared again under the lock. */
|
|
16
|
+
identity: { dev: number; ino: number; mtimeMs: number }; children: string[];
|
|
17
|
+
/** Who refers to it (`project <root>`, `recovery operation <id>`, `live manager`, `running process`, `this CLI`). Empty when nothing does. */
|
|
18
|
+
referencedBy: string[];
|
|
19
|
+
/** Why it stays; absent when it is removable. */
|
|
20
|
+
kept?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ReleaseInventory { home: string; entries: ReleaseEntry[]; complete: boolean; cause?: string; next?: string }
|
|
23
|
+
interface InventoryDeps { processTable?: () => string; now?: () => number; executingRoot?: string; /** test seam: runs after the scan and before each entry's locked recheck */ beforeRecheck?: (entry: ReleaseEntry) => void }
|
|
24
|
+
interface PruneOptions { kinds?: readonly ReleaseKind[]; /** Default: one hour. `0` removes entries of any age. */ olderThanDays?: number; apply: boolean }
|
|
25
|
+
/** An entry written by an upgrade or a stage before its receipt or runtime.json exists has no referrer yet; keep anything this young unless --older-than says otherwise. */
|
|
26
|
+
const DEFAULT_MIN_AGE_MS = 60 * 60 * 1000;
|
|
27
|
+
export interface PruneResult extends ReleaseInventory { candidates: string[]; removed: string[]; quarantined: string[]; skipped: { path: string; why: string }[]; applied: boolean }
|
|
28
|
+
|
|
29
|
+
const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
|
|
30
|
+
const SOURCE = /^source-([a-f0-9]{64})$/;
|
|
31
|
+
const MAX_WALK = 200_000;
|
|
32
|
+
const RECOVERY_NEXT = "run ahub doctor, fix what it names (ahub recovery status shows an open operation), then run the command again";
|
|
33
|
+
|
|
34
|
+
const contains = (parent: string, child: string) => { const inside = relative(parent, child); return inside === "" || inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside); };
|
|
35
|
+
function optional(path: string): Stats | undefined {
|
|
36
|
+
try { return lstatSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
|
|
37
|
+
}
|
|
38
|
+
function measure(path: string): { bytes: number; newest: number } {
|
|
39
|
+
let bytes = 0, seen = 0;
|
|
40
|
+
const root = lstatSync(path); bytes += root.size;
|
|
41
|
+
let newest = root.mtimeMs;
|
|
42
|
+
const walk = (directory: string) => {
|
|
43
|
+
for (const name of readdirSync(directory)) {
|
|
44
|
+
if (++seen > MAX_WALK) throw new Error("release entry is too large to measure");
|
|
45
|
+
const info = lstatSync(join(directory, name));
|
|
46
|
+
bytes += info.size; newest = Math.max(newest, info.mtimeMs);
|
|
47
|
+
if (info.isDirectory() && !info.isSymbolicLink()) walk(join(directory, name));
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
if (root.isDirectory() && !root.isSymbolicLink()) walk(path);
|
|
51
|
+
return { bytes, newest };
|
|
52
|
+
}
|
|
53
|
+
/** One `ps` read. A failed or empty read is an error: an unknown process table never means "no process". */
|
|
54
|
+
function readProcessTable(): string {
|
|
55
|
+
const result = Bun.spawnSync(["ps", "-axo", "command="], { stdout: "pipe", stderr: "pipe" });
|
|
56
|
+
const text = result.stdout.toString();
|
|
57
|
+
if (result.exitCode !== 0 || !text.trim()) throw new Error("the process table could not be read");
|
|
58
|
+
return text;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface Raw { path: string; name: string; kind: ReleaseKind; version: string | null; digest: string | null; info: Stats; note?: string }
|
|
62
|
+
function scan(home: string): Raw[] {
|
|
63
|
+
const releases = join(home, "releases"), info = optional(releases);
|
|
64
|
+
if (!info) return [];
|
|
65
|
+
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("the releases directory is a symlink or not a directory");
|
|
66
|
+
const rows: Raw[] = [];
|
|
67
|
+
const add = (path: string, name: string, kind: ReleaseKind, version: string | null, digest: string | null, note?: string) =>
|
|
68
|
+
rows.push({ path, name, kind, version, digest, info: lstatSync(path), ...(note ? { note } : {}) });
|
|
69
|
+
for (const name of readdirSync(releases).sort()) {
|
|
70
|
+
const path = join(releases, name), info = lstatSync(path);
|
|
71
|
+
if (info.isSymbolicLink() || !info.isDirectory()) { add(path, name, "unknown", null, null, info.isSymbolicLink() ? "a symlink is never followed" : "not a directory"); continue; }
|
|
72
|
+
const source = SOURCE.exec(name);
|
|
73
|
+
if (source) { add(path, name, "coordinator-source", null, source[1]!); continue; }
|
|
74
|
+
if (!VERSION.test(name)) { add(path, name, "unknown", null, null, "unrecognized layout"); continue; }
|
|
75
|
+
const children = readdirSync(path).sort();
|
|
76
|
+
const installed = children.includes("verified.json") || children.includes("node_modules");
|
|
77
|
+
const held: string[] = [];
|
|
78
|
+
for (const child of children) {
|
|
79
|
+
const childPath = join(path, child), childInfo = lstatSync(childPath), match = SOURCE.exec(child);
|
|
80
|
+
if (match) {
|
|
81
|
+
if (childInfo.isSymbolicLink() || !childInfo.isDirectory()) add(childPath, `${name}/${child}`, "unknown", name, null, "a symlink is never followed");
|
|
82
|
+
else { add(childPath, `${name}/${child}`, "capture", name, match[1]!); held.push(child); }
|
|
83
|
+
} else if (child === "registry") {
|
|
84
|
+
if (childInfo.isSymbolicLink() || !childInfo.isDirectory()) add(childPath, `${name}/${child}`, "unknown", name, null, "a symlink is never followed");
|
|
85
|
+
else add(childPath, `${name}/${child}`, "registry-install", name, null);
|
|
86
|
+
} else if (!installed || !["verified.json", "node_modules", "package.json", "bun.lock", "bun.lockb"].includes(child)) {
|
|
87
|
+
add(childPath, `${name}/${child}`, "unknown", name, null, "unrecognized layout");
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (installed) add(path, name, "registry-install", name, null, held.length ? "holds captures; remove those first" : undefined);
|
|
91
|
+
}
|
|
92
|
+
return rows;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function holders(row: Raw, references: RuntimeReferences | undefined, table: string | undefined, executing: string): string[] {
|
|
96
|
+
const who: string[] = [];
|
|
97
|
+
if (references) {
|
|
98
|
+
for (const [root, names] of references.referrers) if (contains(row.path, root) || contains(root, row.path)) for (const name of names) who.push(name);
|
|
99
|
+
if (references.managerRoot && (contains(row.path, references.managerRoot) || contains(references.managerRoot, row.path))) who.push("live manager");
|
|
100
|
+
}
|
|
101
|
+
if (contains(row.path, executing)) who.push("this CLI");
|
|
102
|
+
if (table !== undefined && table.includes(row.path)) who.push("running process");
|
|
103
|
+
return [...new Set(who)].sort();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Classification and references only; nothing is changed. A reference check that cannot complete keeps every entry and says why. */
|
|
107
|
+
export function listReleases(homeInput: string, deps: InventoryDeps = {}): ReleaseInventory {
|
|
108
|
+
let home = homeInput;
|
|
109
|
+
try { home = realPath(homeInput); } catch { /* the registry open below names the cause */ }
|
|
110
|
+
let rows: Raw[];
|
|
111
|
+
try { rows = scan(home); }
|
|
112
|
+
catch (error) { return { home, entries: [], complete: false, cause: `the releases directory could not be read completely: ${(error as Error).message}`, next: "inspect the directory with ls -la, then run the command again" }; }
|
|
113
|
+
let references: RuntimeReferences | undefined, table: string | undefined, cause: string | undefined, next: string | undefined;
|
|
114
|
+
let registry: Registry | undefined;
|
|
115
|
+
try {
|
|
116
|
+
if (rows.length) {
|
|
117
|
+
const opened = openRuntimeRegistry(home); registry = opened.registry;
|
|
118
|
+
references = observeRuntimeReferences(opened.home, registry);
|
|
119
|
+
}
|
|
120
|
+
} catch (error) { cause = `references could not be read completely: ${(error as Error).message}`; next = RECOVERY_NEXT; }
|
|
121
|
+
finally { registry?.close(); }
|
|
122
|
+
if (!cause && rows.length) {
|
|
123
|
+
try { table = (deps.processTable ?? readProcessTable)(); }
|
|
124
|
+
catch (error) { cause = `references could not be read completely: ${(error as Error).message}`; next = "check that ps works for this user, then run the command again"; }
|
|
125
|
+
}
|
|
126
|
+
const executing = deps.executingRoot ?? resolve(import.meta.dir, "../..");
|
|
127
|
+
const entries = rows.map((row): ReleaseEntry => {
|
|
128
|
+
const referencedBy = holders(row, references, table, executing);
|
|
129
|
+
let bytes = 0, newest = row.info.mtimeMs, kept: string | undefined = row.note, children: string[] = [];
|
|
130
|
+
try { const measured = measure(row.path); bytes = measured.bytes; newest = measured.newest; } catch (error) { kept ??= `size unreadable: ${(error as Error).message}`; }
|
|
131
|
+
try { children = readdirSync(row.path).sort(); } catch (error) { kept ??= `entries unreadable: ${(error as Error).message}`; }
|
|
132
|
+
if (row.kind === "unknown") kept ??= "unknown layout";
|
|
133
|
+
else if (cause) kept ??= cause;
|
|
134
|
+
else if (referencedBy.length) kept ??= `referenced by ${referencedBy.join(", ")}`;
|
|
135
|
+
return { path: row.path, name: row.name, kind: row.kind, version: row.version, digest: row.digest, bytes, modified: newest,
|
|
136
|
+
identity: { dev: row.info.dev, ino: row.info.ino, mtimeMs: row.info.mtimeMs }, children, referencedBy, ...(kept ? { kept } : {}) };
|
|
137
|
+
});
|
|
138
|
+
// AC5: an entry that holds an unknown or kept entry (a legacy install with a quarantine, a symlinked source, a referenced capture) stays whole.
|
|
139
|
+
for (const entry of entries) {
|
|
140
|
+
if (entry.kept) continue;
|
|
141
|
+
const inside = entries.find(other => other !== entry && other.path.startsWith(entry.path + sep) && (other.kind === "unknown" || other.kept));
|
|
142
|
+
if (inside) entry.kept = `holds ${inside.kind === "unknown" ? "an unknown entry" : "a kept entry"}: ${relative(entry.path, inside.path)}`;
|
|
143
|
+
}
|
|
144
|
+
return { home, entries, complete: !cause, ...(cause ? { cause } : {}), ...(next ? { next } : {}) };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Entries the rule allows removing, after the kind and age filters. `unknown` never qualifies. */
|
|
148
|
+
function pruneCandidates(inventory: ReleaseInventory, options: Pick<PruneOptions, "kinds" | "olderThanDays">, now: number): ReleaseEntry[] {
|
|
149
|
+
const floor = options.olderThanDays === undefined ? DEFAULT_MIN_AGE_MS : options.olderThanDays * 86_400_000;
|
|
150
|
+
return inventory.entries.filter(entry => entry.kind !== "unknown" && !entry.kept && (!options.kinds?.length || options.kinds.includes(entry.kind))
|
|
151
|
+
&& entry.modified <= now - floor);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Preview by default. With `apply`, each entry is rechecked immediately before it moves: fresh references and process table, then, under the
|
|
156
|
+
* registry writer lock the background worker uses, the observed references are re-proved unchanged and the entry's identity is confirmed.
|
|
157
|
+
* Only the atomic rename is locked; recursive removal runs on the reserved quarantine name outside it. Never touches a path that is not a
|
|
158
|
+
* direct, non-symlink child under the home's releases directory.
|
|
159
|
+
*/
|
|
160
|
+
export function pruneReleases(homeInput: string, options: PruneOptions, deps: InventoryDeps = {}): PruneResult {
|
|
161
|
+
const now = (deps.now ?? Date.now)();
|
|
162
|
+
const inventory = listReleases(homeInput, deps);
|
|
163
|
+
const candidates = pruneCandidates(inventory, options, now);
|
|
164
|
+
const result: PruneResult = { ...inventory, candidates: candidates.map(entry => entry.path), removed: [], skipped: [], quarantined: [], applied: options.apply };
|
|
165
|
+
if (!options.apply || !candidates.length) return result;
|
|
166
|
+
const releases = join(inventory.home, "releases");
|
|
167
|
+
let registry: Registry | undefined;
|
|
168
|
+
try {
|
|
169
|
+
registry = openRuntimeRegistry(inventory.home).registry;
|
|
170
|
+
for (const entry of candidates) {
|
|
171
|
+
const skip = (why: string) => { result.skipped.push({ path: entry.path, why }); };
|
|
172
|
+
try {
|
|
173
|
+
const fresh = observeRuntimeReferences(inventory.home, registry);
|
|
174
|
+
const table = (deps.processTable ?? readProcessTable)();
|
|
175
|
+
const row: Raw = { path: entry.path, name: entry.name, kind: entry.kind, version: entry.version, digest: entry.digest, info: lstatSync(entry.path) };
|
|
176
|
+
const now = holders(row, fresh, table, deps.executingRoot ?? resolve(import.meta.dir, "../.."));
|
|
177
|
+
if (now.length) { skip(`now referenced by ${now.join(", ")}`); continue; }
|
|
178
|
+
deps.beforeRecheck?.(entry);
|
|
179
|
+
const staged = underRuntimeReferences(registry, fresh, () => {
|
|
180
|
+
const info = lstatSync(entry.path);
|
|
181
|
+
if (info.isSymbolicLink() || !info.isDirectory() || info.dev !== entry.identity.dev || info.ino !== entry.identity.ino || info.mtimeMs !== entry.identity.mtimeMs
|
|
182
|
+
|| JSON.stringify(readdirSync(entry.path).sort()) !== JSON.stringify(entry.children)) throw new Error("the entry changed since it was listed; list again");
|
|
183
|
+
if (info.mtimeMs > Date.now() - (options.olderThanDays === undefined ? DEFAULT_MIN_AGE_MS : options.olderThanDays * 86_400_000)) throw new Error("the entry is newer than the age floor");
|
|
184
|
+
if (realPath(entry.path) !== entry.path || !contains(releases, entry.path) || entry.path === releases) throw new Error("the entry does not resolve under the releases directory");
|
|
185
|
+
const parent = resolve(entry.path, ".."), container = join(parent, `.runtime-prune-${randomUUID()}`);
|
|
186
|
+
mkdirSync(container, { mode: 0o700 });
|
|
187
|
+
renameSync(entry.path, join(container, "entry"));
|
|
188
|
+
return container;
|
|
189
|
+
});
|
|
190
|
+
result.removed.push(entry.path);
|
|
191
|
+
try { rmSync(staged, { recursive: true }); }
|
|
192
|
+
catch (error) { result.quarantined.push(staged); skip(`removed from releases but the quarantine ${staged} could not be deleted (${(error as Error).message}); delete it by hand, ahub doctor names it`); }
|
|
193
|
+
} catch (error) { skip((error as Error).message); }
|
|
194
|
+
}
|
|
195
|
+
} catch (error) { for (const entry of candidates) if (!result.removed.includes(entry.path) && !result.skipped.some(item => item.path === entry.path)) result.skipped.push({ path: entry.path, why: (error as Error).message }); }
|
|
196
|
+
finally { registry?.close(); }
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
@@ -16,7 +16,7 @@ export interface RuntimeCapturePrunePlan { remove: string[]; kept: string[]; def
|
|
|
16
16
|
export interface RuntimeCapturePruneResult { removed: string[]; kept: string[]; quarantined?: string[]; deferred?: string }
|
|
17
17
|
interface Capture { root: string; version: string; digest: string; dev: number; ino: number; modified: number }
|
|
18
18
|
interface ManagerOwner { slot: number; instance_id: string; pid: number; signature: string | null }
|
|
19
|
-
interface Observation { files: Map<string, string | null>; lists: Map<string, string[]>; projects: string; roots: Set<string>; managerRoot?: string; bytes: number }
|
|
19
|
+
interface Observation { files: Map<string, string | null>; lists: Map<string, string[]>; projects: string; roots: Set<string>; referrers?: Map<string, Set<string>>; managerRoot?: string; bytes: number }
|
|
20
20
|
interface LockBudget { deadline: number; remaining: number }
|
|
21
21
|
const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
|
|
22
22
|
const CAPTURE = /^source-([a-f0-9]{64})$/;
|
|
@@ -92,6 +92,11 @@ function metadata(file: string, observation?: Observation): unknown {
|
|
|
92
92
|
try { return JSON.parse(bytes.subarray(0, count).toString("utf8")); } catch { return fail("runtime retention metadata is invalid"); }
|
|
93
93
|
} finally { closeSync(fd); }
|
|
94
94
|
}
|
|
95
|
+
function addRoot(observation: Observation, root: string, who: string): void {
|
|
96
|
+
observation.roots.add(root);
|
|
97
|
+
const map = observation.referrers ??= new Map();
|
|
98
|
+
const set = map.get(root) ?? new Set<string>(); set.add(who); map.set(root, set);
|
|
99
|
+
}
|
|
95
100
|
function canonicalReference(root: string, observation: Observation): string {
|
|
96
101
|
const canonical = realPath(root); // process-backed platform resolution remains outside the registry writer lock
|
|
97
102
|
const info = optionalInfo(root, observation);
|
|
@@ -155,7 +160,7 @@ function observeReferences(home: string, registry: Registry): Observation {
|
|
|
155
160
|
const root = canonicalReference(runtime.root, observation), named = CAPTURE.exec(basename(root)), version = basename(dirname(root));
|
|
156
161
|
if (named?.[0] === basename(root) && VERSION.exec(version)?.[0] === version && basename(dirname(dirname(root))) === "releases"
|
|
157
162
|
&& (named[1] !== runtime.digest || version !== runtime.version)) fail("project runtime capture path identity is inconsistent");
|
|
158
|
-
observation.
|
|
163
|
+
addRoot(observation, root, `project ${project.root}`);
|
|
159
164
|
}
|
|
160
165
|
// Retain uncertain claims conservatively, rather than running one process probe per registry row under a writer lock.
|
|
161
166
|
if (project.instanceId !== null && (!runtime || runtime.instanceId !== project.instanceId)) fail("a live or uncertain project has no matching retained runtime identity");
|
|
@@ -195,7 +200,7 @@ function observeReferences(home: string, registry: Registry): Observation {
|
|
|
195
200
|
// A retired mutable install may be gone; its lexical path still cannot authorize deletion elsewhere.
|
|
196
201
|
let root: string;
|
|
197
202
|
try { root = realPath(value); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; root = resolve(value); }
|
|
198
|
-
observation.
|
|
203
|
+
addRoot(observation, root, `recovery operation ${record.id}`);
|
|
199
204
|
}
|
|
200
205
|
if (record.targetRoot !== undefined && (typeof record.targetDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.targetDigest))
|
|
201
206
|
|| record.targetRoot === undefined && (record.phase === "completed" || record.targetDigest !== undefined)) fail("retained recovery target identity is incomplete");
|
|
@@ -551,3 +556,20 @@ if (import.meta.main) {
|
|
|
551
556
|
try { if (!home || !isAbsolute(home) || !id || !/^[a-f0-9-]{36}$/.test(id)) fail("runtime maintenance worker identity is invalid"); runScheduledWorker(home, id); }
|
|
552
557
|
catch { process.exitCode = 1; }
|
|
553
558
|
}
|
|
559
|
+
|
|
560
|
+
/** #1781: what `ahub releases` reads. The same observation, lock and registry the background worker uses; nothing here parses runtime.json again. */
|
|
561
|
+
export interface RuntimeReferences { observation: Observation; referrers: ReadonlyMap<string, ReadonlySet<string>>; managerRoot?: string }
|
|
562
|
+
export function observeRuntimeReferences(home: string, registry: Registry): RuntimeReferences {
|
|
563
|
+
const observation = observeReferences(home, registry);
|
|
564
|
+
return { observation, referrers: observation.referrers ?? new Map(), ...(observation.managerRoot ? { managerRoot: observation.managerRoot } : {}) };
|
|
565
|
+
}
|
|
566
|
+
/** Opens the home's registry the way the worker does; throws the worker's own cause when the home or registry is unavailable. */
|
|
567
|
+
export function openRuntimeRegistry(home: string): { home: string; registry: Registry } { return openRegistry(home); }
|
|
568
|
+
/** Runs `action` under the registry writer lock after proving the observed references are unchanged, with the worker's metadata budget. */
|
|
569
|
+
export function underRuntimeReferences<T>(registry: Registry, references: RuntimeReferences, action: () => T): T {
|
|
570
|
+
return registry.runtimeCaptureLocked(() => {
|
|
571
|
+
const budget = { deadline: performance.now() + LOCK_METADATA_MS, remaining: MAX_REFERENCE_FILES * 4 };
|
|
572
|
+
validateObservation(registry, references.observation, budget);
|
|
573
|
+
return action();
|
|
574
|
+
});
|
|
575
|
+
}
|
|
@@ -79,7 +79,7 @@ function admissionHealth(file: string): LedgerHealth {
|
|
|
79
79
|
finally { try { db?.close(); } catch { /* Inspection never repairs or alters admission state. */ } }
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
/** Scan only the two release directory levels, never capture contents or a referenced/symlinked directory. */
|
|
82
|
+
/** Scan only the two release directory levels (and the top-level reserved names), never capture contents or a referenced/symlinked directory. */
|
|
83
83
|
function quarantineHealth(home: string, active: boolean | undefined): RuntimePruneHealthCheck[] {
|
|
84
84
|
const releases = join(home, "releases"), checks: RuntimePruneHealthCheck[] = [];
|
|
85
85
|
let remaining = MAX_SCAN_ENTRIES, found = 0;
|
|
@@ -93,6 +93,13 @@ function quarantineHealth(home: string, active: boolean | undefined): RuntimePru
|
|
|
93
93
|
};
|
|
94
94
|
try {
|
|
95
95
|
scan(releases, version => {
|
|
96
|
+
if (version.name.startsWith(".runtime-prune-")) { // #1781: `ahub releases prune` quarantines a bare coordinator source here
|
|
97
|
+
if (++found > MAX_QUARANTINES) throw new Error("quarantine result bound exceeded");
|
|
98
|
+
const path = join(releases, version.name), stat = info(path); if (!stat) return;
|
|
99
|
+
const unsafe = stat.isSymbolicLink() || !stat.isDirectory();
|
|
100
|
+
checks.push({ ok: undefined, name: "runtime quarantine", detail: `${unsafe ? "unsafe reserved quarantine path" : active === true ? "maintenance quarantine is in use" : "runtime quarantine remains"}; inspect ${path}` });
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
96
103
|
if (VERSION.exec(version.name)?.[0] !== version.name) return;
|
|
97
104
|
const directory = join(releases, version.name);
|
|
98
105
|
if (!version.isDirectory() || version.isSymbolicLink()) throw new Error(`unsafe version directory: ${directory}`);
|