pi-better-server 0.2.4 → 0.4.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/package.json +6 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +165 -0
- package/scripts/test-on-pi.sh +21 -3
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +48 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +7 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +182 -0
- package/src/runtime/cancellation.ts +99 -0
- package/src/runtime/catalog-admission.ts +50 -0
- package/src/runtime/catalog.ts +133 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +120 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
- package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
- package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
- package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
- package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
- package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
- package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
- package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
- package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
- package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
- package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
- package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
- package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
- package/src/runtime/domain/catalog/thinking.d.mts +8 -0
- package/src/runtime/domain/catalog/thinking.mjs +22 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +245 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/mutation-store.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +277 -0
- package/src/runtime/query-worker.mjs +119 -0
- package/src/runtime/read-model.ts +409 -0
- package/src/runtime/result-supervision.ts +63 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +14 -0
- package/src/runtime/work-client.mjs +102 -0
- package/src/server.ts +199 -14
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,810 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/catalog-store.ts. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Filesystem catalog: project, personal, and bundled sources.
|
|
4
|
+
*
|
|
5
|
+
* Discovery is deterministic and reads the disk on every call. There is no
|
|
6
|
+
* launch cache. Callers that launch a batch must retain the returned snapshot
|
|
7
|
+
* and reuse that object for every job.
|
|
8
|
+
*
|
|
9
|
+
* Project files are read only when `projectTrusted` is true. Pass Pi's
|
|
10
|
+
* `ctx.isProjectTrusted()` and `CONFIG_DIR_NAME` from the host; this module
|
|
11
|
+
* does not import Pi. Writes default to the personal root. Project scope is
|
|
12
|
+
* explicit and refused when the project is untrusted. Bundled files are immutable.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
15
|
+
import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeSync, } from "node:fs";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
import { readCatalogPreferences, writeCatalogPreferences } from "./catalog-preferences.mjs";
|
|
20
|
+
import { CATALOG_SCHEMA_VERSION, DiagnosticCodes, kindForId, parseDefinition, serializeDefinition, } from "./catalog-schema.mjs";
|
|
21
|
+
export const DEFAULT_PROJECT_CONFIG_DIR_NAME = ".pi";
|
|
22
|
+
export const SOURCE_PRECEDENCE = ["project", "user", "bundled"];
|
|
23
|
+
class FrozenMap extends Map {
|
|
24
|
+
static fill(entries) {
|
|
25
|
+
const map = new FrozenMap();
|
|
26
|
+
for (const [key, value] of entries)
|
|
27
|
+
Map.prototype.set.call(map, key, value);
|
|
28
|
+
return map;
|
|
29
|
+
}
|
|
30
|
+
set() {
|
|
31
|
+
throw new TypeError("Catalog snapshot is immutable.");
|
|
32
|
+
}
|
|
33
|
+
delete() {
|
|
34
|
+
throw new TypeError("Catalog snapshot is immutable.");
|
|
35
|
+
}
|
|
36
|
+
clear() {
|
|
37
|
+
throw new TypeError("Catalog snapshot is immutable.");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Rebuild the same immutable domain value after a JSON socket round trip. */
|
|
41
|
+
export function catalogSnapshotFromWire(wire) {
|
|
42
|
+
return deepFreeze({ ...wire, roles: FrozenMap.fill(wire.roles), agents: FrozenMap.fill(wire.agents) });
|
|
43
|
+
}
|
|
44
|
+
export function defaultUserRoot(env = process.env, home = homedir()) {
|
|
45
|
+
const configured = env.PI_CODING_AGENT_DIR?.trim();
|
|
46
|
+
return configured ? configured : join(home, ".pi", "agent");
|
|
47
|
+
}
|
|
48
|
+
export function bundledRolesRoot(moduleUrl = import.meta.url) {
|
|
49
|
+
return join(dirname(fileURLToPath(moduleUrl)), "roles");
|
|
50
|
+
}
|
|
51
|
+
export function projectCatalogPaths(cwd, projectConfigDirName = DEFAULT_PROJECT_CONFIG_DIR_NAME) {
|
|
52
|
+
const root = join(cwd, projectConfigDirName, "agents");
|
|
53
|
+
return { root, roles: join(root, "roles"), agents: join(root, "agents") };
|
|
54
|
+
}
|
|
55
|
+
export function userCatalogPaths(userRoot) {
|
|
56
|
+
const root = join(userRoot, "agents");
|
|
57
|
+
return { root, roles: join(root, "roles"), agents: join(root, "agents") };
|
|
58
|
+
}
|
|
59
|
+
export function contentDigest(raw) {
|
|
60
|
+
return createHash("sha256").update(raw).digest("hex");
|
|
61
|
+
}
|
|
62
|
+
/** Import matching needs every source in the destination scope, including shadowed IDs. */
|
|
63
|
+
export function listScopedAgents(input, scope) {
|
|
64
|
+
const diagnostics = [];
|
|
65
|
+
if (scope === "project" && !input.projectTrusted)
|
|
66
|
+
throw new Error("Project catalog access requires a trusted host.");
|
|
67
|
+
const config = input.projectConfigDirName ?? DEFAULT_PROJECT_CONFIG_DIR_NAME;
|
|
68
|
+
if (!isSafeConfigDirName(config))
|
|
69
|
+
throw new Error("Unsafe project config directory");
|
|
70
|
+
const directory = scope === "project" ? projectCatalogPaths(input.cwd, config).agents : userCatalogPaths(input.userRoot).agents;
|
|
71
|
+
const occurrences = new Map();
|
|
72
|
+
collectDirectory(directory, scope, "agent", occurrences, diagnostics);
|
|
73
|
+
const agents = [...occurrences.values()].flat().flatMap(item => item.parse.definition?.kind === "agent"
|
|
74
|
+
? [{ path: item.path, definition: item.parse.definition }] : []);
|
|
75
|
+
return { agents, diagnostics };
|
|
76
|
+
}
|
|
77
|
+
/** Read every source again. Identical bytes produce the same digest and a new object. */
|
|
78
|
+
export function loadCatalog(input) {
|
|
79
|
+
const loadedAt = new Date().toISOString();
|
|
80
|
+
const diagnostics = [];
|
|
81
|
+
const configDirName = input.projectConfigDirName ?? DEFAULT_PROJECT_CONFIG_DIR_NAME;
|
|
82
|
+
if (!isSafeConfigDirName(configDirName)) {
|
|
83
|
+
diagnostics.push(diagnostic(DiagnosticCodes.unsafeConfigDir, `Project config directory ${JSON.stringify(configDirName)} is not a single safe path segment.`, {
|
|
84
|
+
blocking: true,
|
|
85
|
+
structural: true,
|
|
86
|
+
}));
|
|
87
|
+
return finishSnapshot([], [], diagnostics, loadedAt);
|
|
88
|
+
}
|
|
89
|
+
const groups = new Map();
|
|
90
|
+
for (const scope of SOURCE_PRECEDENCE)
|
|
91
|
+
groups.set(scope, new Map());
|
|
92
|
+
if (input.projectTrusted) {
|
|
93
|
+
const project = projectCatalogPaths(input.cwd, configDirName);
|
|
94
|
+
collectDirectory(project.roles, "project", "role", groups.get("project"), diagnostics);
|
|
95
|
+
collectDirectory(project.agents, "project", "agent", groups.get("project"), diagnostics);
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
const project = projectCatalogPaths(input.cwd, configDirName);
|
|
99
|
+
if (pathExists(project.roles) || pathExists(project.agents) || pathExists(project.root)) {
|
|
100
|
+
diagnostics.push(diagnostic(DiagnosticCodes.projectCatalogSuppressed, `Project catalog at ${project.root} was not loaded because the project is not trusted. Personal and bundled definitions remain available. Trust the project or copy a definition into the personal catalog.`, { scope: "project", path: project.root, blocking: false, structural: false, severity: "info" }));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const user = userCatalogPaths(input.userRoot);
|
|
104
|
+
collectDirectory(user.roles, "user", "role", groups.get("user"), diagnostics);
|
|
105
|
+
collectDirectory(user.agents, "user", "agent", groups.get("user"), diagnostics);
|
|
106
|
+
const bundledRoles = input.bundledRoot ?? bundledRolesRoot();
|
|
107
|
+
if (!existsSync(bundledRoles)) {
|
|
108
|
+
diagnostics.push(diagnostic(DiagnosticCodes.bundledMissing, `Bundled role directory ${bundledRoles} is missing.`, {
|
|
109
|
+
scope: "bundled",
|
|
110
|
+
path: bundledRoles,
|
|
111
|
+
blocking: false,
|
|
112
|
+
structural: false,
|
|
113
|
+
severity: "warning",
|
|
114
|
+
}));
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled"), diagnostics);
|
|
118
|
+
}
|
|
119
|
+
if (input.bundledAgentsRoot) {
|
|
120
|
+
collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled"), diagnostics);
|
|
121
|
+
}
|
|
122
|
+
const { entries, blocked } = selectIdentities(groups, diagnostics);
|
|
123
|
+
const savedSettings = {};
|
|
124
|
+
const preferenceSources = {};
|
|
125
|
+
const preferenceDigests = [];
|
|
126
|
+
const scopes = [
|
|
127
|
+
{ scope: "user", root: user.root },
|
|
128
|
+
...(input.projectTrusted ? [{ scope: "project", root: projectCatalogPaths(input.cwd, configDirName).root }] : []),
|
|
129
|
+
];
|
|
130
|
+
for (const { scope, root } of scopes) {
|
|
131
|
+
try {
|
|
132
|
+
const preferences = readCatalogPreferences(root);
|
|
133
|
+
preferenceDigests.push(preferences.digest);
|
|
134
|
+
for (const entry of entries) {
|
|
135
|
+
if (scope === "user" && entry.scope === "project")
|
|
136
|
+
continue;
|
|
137
|
+
const own = preferences.settings[entry.id];
|
|
138
|
+
if (!own)
|
|
139
|
+
continue;
|
|
140
|
+
const resolved = {};
|
|
141
|
+
if (own.bundled) {
|
|
142
|
+
const fallbacks = entry.scope === "bundled" ? [entry] : entry.unused.filter(source => source.scope === "bundled");
|
|
143
|
+
const fallback = fallbacks.length === 1 ? fallbacks[0] : undefined;
|
|
144
|
+
const raw = fallback ? readFileSync(fallback.path, "utf8") : undefined;
|
|
145
|
+
const parsed = raw === undefined ? undefined : parseDefinition(raw, fallback.path);
|
|
146
|
+
if (!fallback || !parsed?.ok || parsed.definition?.id !== entry.id || parsed.diagnostics.some(item => item.blocking)
|
|
147
|
+
|| contentDigest(raw) !== fallback.contentDigest) {
|
|
148
|
+
const failure = diagnostic("catalog-preferences", `Cannot inherit bundled runtime defaults for ${entry.id}: a single valid bundled definition is required.`, {
|
|
149
|
+
scope, path: join(root, "settings.json"), id: entry.id, blocking: true, structural: false,
|
|
150
|
+
});
|
|
151
|
+
entry.diagnostics = [...entry.diagnostics, failure];
|
|
152
|
+
entry.schemaLaunchable = false;
|
|
153
|
+
diagnostics.push(failure);
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
const bundled = parsed.definition.kind === "role" ? parsed.definition.defaults : parsed.definition.overrides;
|
|
157
|
+
resolved.model = bundled.model ?? null;
|
|
158
|
+
resolved.effort = bundled.effort ?? null;
|
|
159
|
+
}
|
|
160
|
+
for (const key of ["model", "effort"]) {
|
|
161
|
+
if (Object.hasOwn(own, key))
|
|
162
|
+
Object.assign(resolved, { [key]: own[key] });
|
|
163
|
+
}
|
|
164
|
+
savedSettings[entry.id] = { ...savedSettings[entry.id], ...resolved };
|
|
165
|
+
const sources = preferenceSources[entry.id] ??= {};
|
|
166
|
+
for (const key of ["model", "effort"]) {
|
|
167
|
+
if (Object.hasOwn(resolved, key))
|
|
168
|
+
sources[key] = { scope, path: join(root, "settings.json"), ...(own.bundled && !Object.hasOwn(own, key) ? { bundled: true } : {}) };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
const failure = diagnostic("catalog-preferences", error instanceof Error ? error.message : String(error), {
|
|
174
|
+
scope, path: join(root, "settings.json"), blocking: true, structural: false,
|
|
175
|
+
});
|
|
176
|
+
diagnostics.push(failure);
|
|
177
|
+
for (const entry of entries) {
|
|
178
|
+
if (scope === "user" && entry.scope === "project")
|
|
179
|
+
continue;
|
|
180
|
+
entry.diagnostics = [...entry.diagnostics, failure];
|
|
181
|
+
entry.schemaLaunchable = false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt);
|
|
186
|
+
const digest = contentDigest(JSON.stringify([snapshot.digest, preferenceDigests, savedSettings, preferenceSources]));
|
|
187
|
+
return deepFreeze({ ...snapshot, digest, revision: digest, savedSettings, preferenceSources });
|
|
188
|
+
}
|
|
189
|
+
export function refreshCatalog(input) {
|
|
190
|
+
return loadCatalog(input);
|
|
191
|
+
}
|
|
192
|
+
export function createDefinition(input) {
|
|
193
|
+
return saveDefinition({ ...input, replace: input.replace ?? false });
|
|
194
|
+
}
|
|
195
|
+
/** Archive one displayed user override, preserving its model and effort preferences. */
|
|
196
|
+
export function resetUserDefinition(input) {
|
|
197
|
+
return resetDefinition(input, false);
|
|
198
|
+
}
|
|
199
|
+
/** Restore bundled defaults, archiving a user definition and clearing only this id's user preferences. */
|
|
200
|
+
export function resetToBundled(input) {
|
|
201
|
+
return resetDefinition(input, true);
|
|
202
|
+
}
|
|
203
|
+
/** Restore bundled model and effort while keeping every Markdown definition intact. */
|
|
204
|
+
export function resetRuntimeToBundled(input) {
|
|
205
|
+
return resetDefinition(input, true, true);
|
|
206
|
+
}
|
|
207
|
+
function assertNoProjectPreferences(snapshot, id) {
|
|
208
|
+
if (Object.values(snapshot.preferenceSources?.[id] ?? {}).some(source => source.scope === "project")) {
|
|
209
|
+
throw new Error("Project preferences are active for this id. Reset to bundled cannot clear project preferences. Nothing was archived.");
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
function resetDefinition(input, clearPreferences, runtimeOnly = false) {
|
|
213
|
+
try {
|
|
214
|
+
const snapshot = loadCatalog(input);
|
|
215
|
+
const entry = snapshot.roles.get(input.id) ?? snapshot.agents.get(input.id);
|
|
216
|
+
if (!entry || (entry.scope !== "user" && !(clearPreferences && entry.scope === "bundled")) || entry.duplicate || entry.paths.length !== 1) {
|
|
217
|
+
throw new Error(clearPreferences
|
|
218
|
+
? "Only a single user or bundled definition can be reset. Project definitions are unchanged."
|
|
219
|
+
: "Only a single user override can be reset. Project and bundled definitions are unchanged.");
|
|
220
|
+
}
|
|
221
|
+
if (clearPreferences)
|
|
222
|
+
assertNoProjectPreferences(snapshot, input.id);
|
|
223
|
+
if (entry.path !== input.expectedPath || entry.contentDigest !== input.expectedDigest) {
|
|
224
|
+
throw new Error("The user definition changed since this screen was opened. Reopen its settings before resetting.");
|
|
225
|
+
}
|
|
226
|
+
const fallbacks = entry.scope === "bundled" ? [entry] : entry.unused.filter(source => source.scope === "bundled");
|
|
227
|
+
if (fallbacks.length !== 1)
|
|
228
|
+
throw new Error("Exactly one bundled definition must be available for this id. Nothing was changed.");
|
|
229
|
+
const fallback = fallbacks[0];
|
|
230
|
+
const bundledRoot = entry.kind === "role" ? input.bundledRoot ?? bundledRolesRoot() : input.bundledAgentsRoot;
|
|
231
|
+
if (!bundledRoot || lstatSync(bundledRoot).isSymbolicLink())
|
|
232
|
+
throw new Error("The bundled catalog is unavailable or symlinked.");
|
|
233
|
+
assertInside(bundledRoot, fallback.path);
|
|
234
|
+
assertNoSymlinkWalk(bundledRoot, fallback.path);
|
|
235
|
+
const bundledRaw = readFileSync(fallback.path, "utf8");
|
|
236
|
+
const bundled = parseDefinition(bundledRaw, fallback.path);
|
|
237
|
+
if (!bundled.ok || bundled.diagnostics.some(item => item.blocking) || bundled.definition?.id !== input.id || contentDigest(bundledRaw) !== fallback.contentDigest) {
|
|
238
|
+
throw new Error("The bundled definition is invalid. Nothing was changed.");
|
|
239
|
+
}
|
|
240
|
+
const root = userCatalogPaths(input.userRoot).root;
|
|
241
|
+
const directory = join(root, entry.kind === "role" ? "roles" : "agents");
|
|
242
|
+
const definitionRoot = entry.scope === "user" ? input.userRoot : bundledRoot;
|
|
243
|
+
if (entry.scope === "user" && resolve(dirname(entry.path)) !== resolve(directory))
|
|
244
|
+
throw new Error("The user definition is outside its catalog directory.");
|
|
245
|
+
assertInside(definitionRoot, entry.path);
|
|
246
|
+
assertNoSymlinkWalk(definitionRoot, entry.path);
|
|
247
|
+
const stats = lstatSync(entry.path);
|
|
248
|
+
const raw = readFileSync(entry.path);
|
|
249
|
+
const text = raw.toString("utf8");
|
|
250
|
+
if (!stats.isFile() || stats.isSymbolicLink() || !Buffer.from(text).equals(raw) || contentDigest(text) !== input.expectedDigest) {
|
|
251
|
+
throw new Error("The user definition changed before reset. Nothing was changed.");
|
|
252
|
+
}
|
|
253
|
+
let previous = {};
|
|
254
|
+
const legacy = entry.definition?.kind === "role" ? entry.definition.defaults : entry.definition?.overrides;
|
|
255
|
+
const bundledPreferences = bundled.definition?.kind === "role" ? bundled.definition.defaults : bundled.definition?.overrides;
|
|
256
|
+
const legacyPreferences = {
|
|
257
|
+
...(legacy?.model !== undefined ? { model: legacy.model } : bundledPreferences?.model !== undefined ? { model: null } : {}),
|
|
258
|
+
...(legacy?.effort !== undefined ? { effort: legacy.effort } : bundledPreferences?.effort !== undefined ? { effort: null } : {}),
|
|
259
|
+
};
|
|
260
|
+
// Clearing JSON alone would reveal legacy runtime choices in user Markdown.
|
|
261
|
+
const runtimePreferences = entry.scope === "user" ? { bundled: true } : {};
|
|
262
|
+
const assertBundledUnchanged = () => {
|
|
263
|
+
if (lstatSync(bundledRoot).isSymbolicLink())
|
|
264
|
+
throw new Error("The bundled catalog is unavailable or symlinked.");
|
|
265
|
+
assertInside(bundledRoot, fallback.path);
|
|
266
|
+
assertNoSymlinkWalk(bundledRoot, fallback.path);
|
|
267
|
+
if (readFileSync(fallback.path, "utf8") !== bundledRaw) {
|
|
268
|
+
throw new Error("The bundled fallback changed while saving preferences. Nothing was archived. Reopen its settings.");
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
const saved = writeCatalogPreferences(root, input.id, current => {
|
|
272
|
+
if (runtimeOnly)
|
|
273
|
+
assertBundledUnchanged();
|
|
274
|
+
previous = current;
|
|
275
|
+
return runtimeOnly ? runtimePreferences : clearPreferences ? {} : current.bundled ? current : { ...legacyPreferences, ...current };
|
|
276
|
+
});
|
|
277
|
+
// Discovery skips hidden files. Keep the original bytes for manual recovery.
|
|
278
|
+
const backupPath = entry.scope === "user" && !runtimeOnly
|
|
279
|
+
? join(directory, `.${basename(entry.path)}.${randomBytes(12).toString("hex")}.backup`)
|
|
280
|
+
: undefined;
|
|
281
|
+
try {
|
|
282
|
+
const refreshed = loadCatalog(input);
|
|
283
|
+
const current = refreshed.roles.get(input.id) ?? refreshed.agents.get(input.id);
|
|
284
|
+
if (clearPreferences)
|
|
285
|
+
assertNoProjectPreferences(refreshed, input.id);
|
|
286
|
+
const currentFallbacks = current?.scope === "bundled" ? [current] : current?.unused.filter(source => source.scope === "bundled") ?? [];
|
|
287
|
+
if (current?.scope !== entry.scope || current.duplicate || current.path !== entry.path || current.contentDigest !== input.expectedDigest
|
|
288
|
+
|| currentFallbacks.length !== 1 || currentFallbacks[0]?.path !== fallback.path || currentFallbacks[0]?.contentDigest !== fallback.contentDigest) {
|
|
289
|
+
throw new Error("The definition or bundled fallback changed while saving preferences. Nothing was archived. Reopen its settings.");
|
|
290
|
+
}
|
|
291
|
+
assertBundledUnchanged();
|
|
292
|
+
assertNoSymlinkWalk(definitionRoot, entry.path);
|
|
293
|
+
const latest = readFileSync(entry.path);
|
|
294
|
+
if (!latest.equals(raw) || !lstatSync(entry.path).isFile()) {
|
|
295
|
+
throw new Error("The user definition changed while saving preferences. Nothing was archived. Reopen its settings.");
|
|
296
|
+
}
|
|
297
|
+
if (backupPath)
|
|
298
|
+
renameSync(entry.path, backupPath);
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
// Compare and roll back under the same lock; preserve any later edit.
|
|
302
|
+
try {
|
|
303
|
+
writeCatalogPreferences(root, input.id, current => JSON.stringify(current) === JSON.stringify(saved.settings[input.id] ?? {}) ? previous : current);
|
|
304
|
+
}
|
|
305
|
+
catch (rollback) {
|
|
306
|
+
throw new Error(`${error instanceof Error ? error.message : String(error)} Preference rollback also failed: ${rollback instanceof Error ? rollback.message : String(rollback)}`);
|
|
307
|
+
}
|
|
308
|
+
throw error;
|
|
309
|
+
}
|
|
310
|
+
return { ok: true, path: backupPath ? entry.path : saved.path, backupPath, scope: "user", diagnostics: [] };
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
return { ok: false, diagnostics: [diagnostic("agents-reset", error instanceof Error ? error.message : String(error), {
|
|
314
|
+
scope: "user", id: input.id, blocking: true, structural: false,
|
|
315
|
+
})] };
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
export function saveDefinition(input) {
|
|
319
|
+
const scope = input.scope ?? "user";
|
|
320
|
+
const diagnostics = [];
|
|
321
|
+
if (scope === "project" && !input.projectTrusted) {
|
|
322
|
+
diagnostics.push(diagnostic(DiagnosticCodes.untrustedWrite, "Refusing to write a project catalog in an untrusted project. Save to the personal catalog or trust the project and pass scope: \"project\" explicitly.", { scope: "project", blocking: true, structural: true }));
|
|
323
|
+
return { ok: false, diagnostics };
|
|
324
|
+
}
|
|
325
|
+
const configDirName = input.projectConfigDirName ?? DEFAULT_PROJECT_CONFIG_DIR_NAME;
|
|
326
|
+
if (!isSafeConfigDirName(configDirName)) {
|
|
327
|
+
diagnostics.push(diagnostic(DiagnosticCodes.unsafeConfigDir, `Project config directory ${JSON.stringify(configDirName)} is not a single safe path segment.`, {
|
|
328
|
+
blocking: true,
|
|
329
|
+
structural: true,
|
|
330
|
+
}));
|
|
331
|
+
return { ok: false, diagnostics };
|
|
332
|
+
}
|
|
333
|
+
const serialized = serializeDefinition(input.definition);
|
|
334
|
+
diagnostics.push(...serialized.diagnostics.map((item) => ({ ...item, scope })));
|
|
335
|
+
if (!serialized.ok || !serialized.markdown)
|
|
336
|
+
return { ok: false, diagnostics };
|
|
337
|
+
const root = scope === "project"
|
|
338
|
+
? projectCatalogPaths(input.cwd, configDirName).root
|
|
339
|
+
: userCatalogPaths(input.userRoot).root;
|
|
340
|
+
const directory = join(root, input.definition.kind === "role" ? "roles" : "agents");
|
|
341
|
+
const canonicalPath = join(directory, `${input.definition.id}.md`);
|
|
342
|
+
try {
|
|
343
|
+
mkdirWithin(root, directory);
|
|
344
|
+
const existing = findExisting(directory, input.definition.id);
|
|
345
|
+
if (!existing.ok)
|
|
346
|
+
return { ok: false, diagnostics: [...diagnostics, ...existing.diagnostics] };
|
|
347
|
+
if (existing.paths.length > 1) {
|
|
348
|
+
diagnostics.push(diagnostic(DiagnosticCodes.duplicateId, `Id ${input.definition.id} already appears in ${existing.paths.length} ${scope} files (${existing.paths.join(", ")}). No file was written. Keep one file for this id.`, { scope, id: input.definition.id, blocking: true, structural: true }));
|
|
349
|
+
return { ok: false, diagnostics };
|
|
350
|
+
}
|
|
351
|
+
const target = existing.paths[0] ?? canonicalPath;
|
|
352
|
+
if (existing.paths.length === 1 && !input.replace) {
|
|
353
|
+
diagnostics.push(diagnostic(DiagnosticCodes.definitionExists, `Id ${input.definition.id} already exists at ${target}. Nothing was overwritten. Pass replace: true to update that file in place.`, { scope, path: target, id: input.definition.id, blocking: true, structural: true }));
|
|
354
|
+
return { ok: false, diagnostics };
|
|
355
|
+
}
|
|
356
|
+
if (existing.paths.length === 0 && existsSync(canonicalPath)) {
|
|
357
|
+
diagnostics.push(diagnostic(DiagnosticCodes.definitionExists, `${canonicalPath} exists and does not already hold id ${input.definition.id}. Refusing to overwrite it.`, { scope, path: canonicalPath, id: input.definition.id, blocking: true, structural: true }));
|
|
358
|
+
return { ok: false, diagnostics };
|
|
359
|
+
}
|
|
360
|
+
writeAtomic(target, serialized.markdown, root);
|
|
361
|
+
return { ok: true, path: target, scope, diagnostics };
|
|
362
|
+
}
|
|
363
|
+
catch (error) {
|
|
364
|
+
diagnostics.push(diagnostic(DiagnosticCodes.ioError, error instanceof Error ? error.message : String(error), {
|
|
365
|
+
scope,
|
|
366
|
+
blocking: true,
|
|
367
|
+
structural: true,
|
|
368
|
+
}));
|
|
369
|
+
return { ok: false, diagnostics };
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
export function isSafeConfigDirName(name) {
|
|
373
|
+
return /^\.[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name) || /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name);
|
|
374
|
+
}
|
|
375
|
+
function collectDirectory(directory, scope, directoryKind, into, diagnostics) {
|
|
376
|
+
let stats;
|
|
377
|
+
try {
|
|
378
|
+
stats = lstatSync(directory);
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
if (error.code === "ENOENT")
|
|
382
|
+
return;
|
|
383
|
+
diagnostics.push(diagnostic(DiagnosticCodes.ioError, `Could not read ${directory}: ${error.message}`, {
|
|
384
|
+
scope,
|
|
385
|
+
path: directory,
|
|
386
|
+
blocking: false,
|
|
387
|
+
structural: false,
|
|
388
|
+
}));
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (stats.isSymbolicLink()) {
|
|
392
|
+
diagnostics.push(diagnostic(DiagnosticCodes.symlinkIgnored, `Ignoring symlinked catalog directory ${directory}. Discovery does not follow links outside the scope.`, { scope, path: directory, blocking: false, structural: false, severity: "warning" }));
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
if (!stats.isDirectory()) {
|
|
396
|
+
diagnostics.push(diagnostic(DiagnosticCodes.ioError, `${directory} is not a directory and was skipped.`, {
|
|
397
|
+
scope,
|
|
398
|
+
path: directory,
|
|
399
|
+
blocking: false,
|
|
400
|
+
structural: false,
|
|
401
|
+
severity: "warning",
|
|
402
|
+
}));
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
let names;
|
|
406
|
+
try {
|
|
407
|
+
names = readdirSync(directory);
|
|
408
|
+
}
|
|
409
|
+
catch (error) {
|
|
410
|
+
// lstat can succeed and readdir still fail: mode 000, or the directory
|
|
411
|
+
// disappearing between the two calls. Keep the failure on this path.
|
|
412
|
+
diagnostics.push(diagnostic(DiagnosticCodes.ioError, `Could not read ${directory}: ${error.message}`, {
|
|
413
|
+
scope,
|
|
414
|
+
path: directory,
|
|
415
|
+
blocking: false,
|
|
416
|
+
structural: false,
|
|
417
|
+
}));
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
names.sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right)));
|
|
421
|
+
for (const name of names) {
|
|
422
|
+
if (name.startsWith(".") || !name.endsWith(".md"))
|
|
423
|
+
continue;
|
|
424
|
+
const path = join(directory, name);
|
|
425
|
+
let fileStats;
|
|
426
|
+
try {
|
|
427
|
+
fileStats = lstatSync(path);
|
|
428
|
+
}
|
|
429
|
+
catch (error) {
|
|
430
|
+
diagnostics.push(diagnostic(DiagnosticCodes.ioError, `Could not stat ${path}: ${error.message}`, {
|
|
431
|
+
scope,
|
|
432
|
+
path,
|
|
433
|
+
blocking: false,
|
|
434
|
+
structural: false,
|
|
435
|
+
}));
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
if (fileStats.isSymbolicLink()) {
|
|
439
|
+
diagnostics.push(diagnostic(DiagnosticCodes.symlinkIgnored, `Ignoring symlink ${path}. The target was not read.`, {
|
|
440
|
+
scope,
|
|
441
|
+
path,
|
|
442
|
+
blocking: false,
|
|
443
|
+
structural: false,
|
|
444
|
+
severity: "warning",
|
|
445
|
+
}));
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (!fileStats.isFile())
|
|
449
|
+
continue;
|
|
450
|
+
let raw;
|
|
451
|
+
try {
|
|
452
|
+
raw = readFileSync(path, "utf8");
|
|
453
|
+
}
|
|
454
|
+
catch (error) {
|
|
455
|
+
diagnostics.push(diagnostic(DiagnosticCodes.ioError, `Could not read ${path}: ${error.message}`, {
|
|
456
|
+
scope,
|
|
457
|
+
path,
|
|
458
|
+
blocking: false,
|
|
459
|
+
structural: false,
|
|
460
|
+
}));
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
let parse;
|
|
464
|
+
try {
|
|
465
|
+
parse = parseDefinition(raw, path);
|
|
466
|
+
}
|
|
467
|
+
catch (error) {
|
|
468
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
469
|
+
diagnostics.push(diagnostic(DiagnosticCodes.parserLimit, `Stopped reading ${path}: ${detail.length > 500 ? `${detail.slice(0, 500)}\u2026` : detail}. This file was isolated so valid catalog entries remain usable.`, { scope, path, blocking: false, structural: true }));
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
const id = parse.definition?.id ?? parse.occupantId;
|
|
473
|
+
if (!id || !kindForId(id)) {
|
|
474
|
+
for (const item of parse.diagnostics) {
|
|
475
|
+
diagnostics.push({ ...item, scope, path: item.path ?? path });
|
|
476
|
+
}
|
|
477
|
+
if (parse.diagnostics.length === 0) {
|
|
478
|
+
diagnostics.push(diagnostic(DiagnosticCodes.malformedFrontmatter, `${path} produced no catalog id and was skipped.`, {
|
|
479
|
+
scope,
|
|
480
|
+
path,
|
|
481
|
+
blocking: false,
|
|
482
|
+
structural: true,
|
|
483
|
+
severity: "error",
|
|
484
|
+
}));
|
|
485
|
+
}
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
const occurrence = {
|
|
489
|
+
scope,
|
|
490
|
+
path,
|
|
491
|
+
contentDigest: contentDigest(raw),
|
|
492
|
+
directoryKind,
|
|
493
|
+
parse,
|
|
494
|
+
};
|
|
495
|
+
const list = into.get(id) ?? [];
|
|
496
|
+
list.push(occurrence);
|
|
497
|
+
into.set(id, list);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
function selectIdentities(groups, diagnostics) {
|
|
501
|
+
const ids = new Set();
|
|
502
|
+
for (const scope of SOURCE_PRECEDENCE) {
|
|
503
|
+
for (const id of groups.get(scope).keys())
|
|
504
|
+
ids.add(id);
|
|
505
|
+
}
|
|
506
|
+
const entries = [];
|
|
507
|
+
const blocked = [];
|
|
508
|
+
for (const id of [...ids].sort()) {
|
|
509
|
+
const considered = SOURCE_PRECEDENCE
|
|
510
|
+
.map((scope) => ({ scope, group: groups.get(scope).get(id) ?? [] }))
|
|
511
|
+
.filter((item) => item.group.length > 0);
|
|
512
|
+
const [highest, ...lower] = considered;
|
|
513
|
+
if (!highest)
|
|
514
|
+
continue;
|
|
515
|
+
const unused = lower.flatMap((item) => item.group.map((occurrence) => unusedSource(occurrence, highest.group.length > 1
|
|
516
|
+
? "blocked-by-duplicate-higher-priority"
|
|
517
|
+
: highest.group[0].parse.ok
|
|
518
|
+
? "shadowed-by-whole-definition"
|
|
519
|
+
: "blocked-by-invalid-higher-priority")));
|
|
520
|
+
if (highest.group.length > 1) {
|
|
521
|
+
const paths = highest.group.map((occurrence) => occurrence.path);
|
|
522
|
+
const duplicateDiagnostic = diagnostic(DiagnosticCodes.duplicateId, `Duplicate id ${id} in ${highest.scope} scope: ${paths.join(", ")}. No file was selected by filesystem order, and lower-priority sources were not used. Keep a single file for this id.`, { scope: highest.scope, id, blocking: true, structural: true });
|
|
523
|
+
diagnostics.push(duplicateDiagnostic);
|
|
524
|
+
blocked.push({
|
|
525
|
+
id,
|
|
526
|
+
kind: kindForId(id),
|
|
527
|
+
scope: highest.scope,
|
|
528
|
+
path: paths[0],
|
|
529
|
+
paths,
|
|
530
|
+
contentDigest: contentDigest(highest.group.map((occurrence) => occurrence.contentDigest).join("\n")),
|
|
531
|
+
diagnostics: [
|
|
532
|
+
duplicateDiagnostic,
|
|
533
|
+
...highest.group.flatMap((occurrence) => occurrence.parse.diagnostics.map((item) => ({
|
|
534
|
+
...item,
|
|
535
|
+
scope: highest.scope,
|
|
536
|
+
path: item.path ?? occurrence.path,
|
|
537
|
+
id,
|
|
538
|
+
}))),
|
|
539
|
+
],
|
|
540
|
+
structurallyValid: false,
|
|
541
|
+
schemaLaunchable: false,
|
|
542
|
+
duplicate: true,
|
|
543
|
+
unused,
|
|
544
|
+
});
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
const winner = highest.group[0];
|
|
548
|
+
const winnerDiagnostics = winner.parse.diagnostics.map((item) => ({
|
|
549
|
+
...item,
|
|
550
|
+
scope: winner.scope,
|
|
551
|
+
path: item.path ?? winner.path,
|
|
552
|
+
id: item.id ?? id,
|
|
553
|
+
}));
|
|
554
|
+
if (winner.parse.ok && winner.parse.definition && winner.directoryKind !== winner.parse.definition.kind) {
|
|
555
|
+
winnerDiagnostics.push(diagnostic(DiagnosticCodes.kindDirectoryMismatch, `${winner.path} is in the ${winner.directoryKind} directory but declares kind ${winner.parse.definition.kind}. Identity comes from id ${id}, not the directory.`, { scope: winner.scope, path: winner.path, id, blocking: false, structural: false, severity: "warning" }));
|
|
556
|
+
}
|
|
557
|
+
if (!winner.parse.ok) {
|
|
558
|
+
winnerDiagnostics.push(diagnostic(DiagnosticCodes.invalidShadow, `Invalid ${winner.scope} definition at ${winner.path} blocks id ${id}. Lower-priority definitions were not used. Repair or remove this file.`, { scope: winner.scope, path: winner.path, id, blocking: true, structural: true }));
|
|
559
|
+
diagnostics.push(winnerDiagnostics.at(-1));
|
|
560
|
+
}
|
|
561
|
+
const blocking = winnerDiagnostics.some((item) => item.blocking);
|
|
562
|
+
const entry = {
|
|
563
|
+
id,
|
|
564
|
+
kind: kindForId(id),
|
|
565
|
+
scope: winner.scope,
|
|
566
|
+
path: winner.path,
|
|
567
|
+
paths: [winner.path],
|
|
568
|
+
contentDigest: winner.contentDigest,
|
|
569
|
+
definition: winner.parse.definition,
|
|
570
|
+
diagnostics: winnerDiagnostics,
|
|
571
|
+
structurallyValid: winner.parse.ok,
|
|
572
|
+
schemaLaunchable: winner.parse.ok && !blocking,
|
|
573
|
+
duplicate: false,
|
|
574
|
+
unused,
|
|
575
|
+
};
|
|
576
|
+
entries.push(entry);
|
|
577
|
+
}
|
|
578
|
+
return { entries, blocked };
|
|
579
|
+
}
|
|
580
|
+
function unusedSource(occurrence, reason) {
|
|
581
|
+
return {
|
|
582
|
+
scope: occurrence.scope,
|
|
583
|
+
path: occurrence.path,
|
|
584
|
+
contentDigest: occurrence.contentDigest,
|
|
585
|
+
id: occurrence.parse.definition?.id ?? occurrence.parse.occupantId,
|
|
586
|
+
reason,
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
function finishSnapshot(entries, blocked, diagnostics, loadedAt) {
|
|
590
|
+
const roleEntries = [];
|
|
591
|
+
const agentEntries = [];
|
|
592
|
+
for (const entry of entries) {
|
|
593
|
+
const frozen = deepFreeze(cloneEntry(entry));
|
|
594
|
+
if (frozen.kind === "role")
|
|
595
|
+
roleEntries.push([frozen.id, frozen]);
|
|
596
|
+
else
|
|
597
|
+
agentEntries.push([frozen.id, frozen]);
|
|
598
|
+
}
|
|
599
|
+
const roles = FrozenMap.fill(roleEntries);
|
|
600
|
+
const agents = FrozenMap.fill(agentEntries);
|
|
601
|
+
const frozenBlocked = deepFreeze(blocked.map(cloneEntry));
|
|
602
|
+
const frozenDiagnostics = deepFreeze(sortDiagnostics(diagnostics));
|
|
603
|
+
const digest = snapshotDigest({
|
|
604
|
+
schema: CATALOG_SCHEMA_VERSION,
|
|
605
|
+
entries: [...roles.values(), ...agents.values()].map(digestEntry),
|
|
606
|
+
blocked: frozenBlocked.map(digestEntry),
|
|
607
|
+
diagnostics: frozenDiagnostics.map((item) => ({
|
|
608
|
+
severity: item.severity,
|
|
609
|
+
code: item.code,
|
|
610
|
+
id: item.id ?? null,
|
|
611
|
+
path: item.path ?? null,
|
|
612
|
+
message: item.message,
|
|
613
|
+
})),
|
|
614
|
+
});
|
|
615
|
+
const snapshot = {
|
|
616
|
+
schema: CATALOG_SCHEMA_VERSION,
|
|
617
|
+
digest,
|
|
618
|
+
revision: digest,
|
|
619
|
+
loadedAt,
|
|
620
|
+
roles,
|
|
621
|
+
agents,
|
|
622
|
+
blocked: frozenBlocked,
|
|
623
|
+
diagnostics: frozenDiagnostics,
|
|
624
|
+
};
|
|
625
|
+
return deepFreeze(snapshot);
|
|
626
|
+
}
|
|
627
|
+
function digestEntry(entry) {
|
|
628
|
+
return {
|
|
629
|
+
id: entry.id,
|
|
630
|
+
kind: entry.kind,
|
|
631
|
+
scope: entry.scope,
|
|
632
|
+
paths: [...entry.paths],
|
|
633
|
+
contentDigest: entry.contentDigest,
|
|
634
|
+
structurallyValid: entry.structurallyValid,
|
|
635
|
+
schemaLaunchable: entry.schemaLaunchable,
|
|
636
|
+
duplicate: entry.duplicate,
|
|
637
|
+
unused: entry.unused.map((item) => ({
|
|
638
|
+
scope: item.scope,
|
|
639
|
+
path: item.path,
|
|
640
|
+
contentDigest: item.contentDigest,
|
|
641
|
+
reason: item.reason,
|
|
642
|
+
})),
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
function snapshotDigest(payload) {
|
|
646
|
+
return createHash("sha256").update(JSON.stringify(stableJson(payload))).digest("hex");
|
|
647
|
+
}
|
|
648
|
+
function stableJson(value) {
|
|
649
|
+
if (Array.isArray(value))
|
|
650
|
+
return value.map(stableJson);
|
|
651
|
+
if (value && typeof value === "object") {
|
|
652
|
+
const output = {};
|
|
653
|
+
for (const key of Object.keys(value).sort()) {
|
|
654
|
+
const item = value[key];
|
|
655
|
+
if (item !== undefined)
|
|
656
|
+
output[key] = stableJson(item);
|
|
657
|
+
}
|
|
658
|
+
return output;
|
|
659
|
+
}
|
|
660
|
+
return value;
|
|
661
|
+
}
|
|
662
|
+
function cloneEntry(entry) {
|
|
663
|
+
return {
|
|
664
|
+
...entry,
|
|
665
|
+
paths: [...entry.paths],
|
|
666
|
+
diagnostics: entry.diagnostics.map((item) => ({ ...item })),
|
|
667
|
+
unused: entry.unused.map((item) => ({ ...item })),
|
|
668
|
+
definition: entry.definition ? structuredClone(entry.definition) : undefined,
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
function sortDiagnostics(diagnostics) {
|
|
672
|
+
return diagnostics
|
|
673
|
+
.map((item) => ({ ...item }))
|
|
674
|
+
.sort((left, right) => `${left.code}\0${left.path ?? ""}\0${left.message}`.localeCompare(`${right.code}\0${right.path ?? ""}\0${right.message}`));
|
|
675
|
+
}
|
|
676
|
+
function findExisting(directory, id) {
|
|
677
|
+
if (!existsSync(directory))
|
|
678
|
+
return { ok: true, paths: [] };
|
|
679
|
+
let stats;
|
|
680
|
+
try {
|
|
681
|
+
stats = lstatSync(directory);
|
|
682
|
+
}
|
|
683
|
+
catch (error) {
|
|
684
|
+
return { ok: false, diagnostics: [diagnostic(DiagnosticCodes.ioError, error.message, { path: directory, blocking: true, structural: true })] };
|
|
685
|
+
}
|
|
686
|
+
if (stats.isSymbolicLink()) {
|
|
687
|
+
return {
|
|
688
|
+
ok: false,
|
|
689
|
+
diagnostics: [diagnostic(DiagnosticCodes.symlinkIgnored, `Refusing to write through symlinked directory ${directory}.`, {
|
|
690
|
+
path: directory,
|
|
691
|
+
blocking: true,
|
|
692
|
+
structural: true,
|
|
693
|
+
})],
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
const paths = [];
|
|
697
|
+
for (const name of readdirSync(directory)) {
|
|
698
|
+
if (name.startsWith(".") || !name.endsWith(".md"))
|
|
699
|
+
continue;
|
|
700
|
+
const path = join(directory, name);
|
|
701
|
+
const fileStats = lstatSync(path);
|
|
702
|
+
if (fileStats.isSymbolicLink() || !fileStats.isFile())
|
|
703
|
+
continue;
|
|
704
|
+
const parsed = parseDefinition(readFileSync(path, "utf8"), path);
|
|
705
|
+
const found = parsed.definition?.id ?? parsed.occupantId;
|
|
706
|
+
if (found === id)
|
|
707
|
+
paths.push(path);
|
|
708
|
+
}
|
|
709
|
+
paths.sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right)));
|
|
710
|
+
return { ok: true, paths };
|
|
711
|
+
}
|
|
712
|
+
function mkdirWithin(root, directory) {
|
|
713
|
+
mkdirSync(directory, { recursive: true });
|
|
714
|
+
assertInside(root, directory);
|
|
715
|
+
assertNoSymlinkWalk(root, directory);
|
|
716
|
+
}
|
|
717
|
+
function writeAtomic(target, content, root) {
|
|
718
|
+
const directory = dirname(target);
|
|
719
|
+
assertInside(root, directory);
|
|
720
|
+
assertNoSymlinkWalk(root, directory);
|
|
721
|
+
if (existsSync(target)) {
|
|
722
|
+
const stats = lstatSync(target);
|
|
723
|
+
if (stats.isSymbolicLink()) {
|
|
724
|
+
throw new Error(`Refusing to replace symlink ${target}.`);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
const temporary = join(directory, `.${basename(target)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
|
728
|
+
const fd = openSync(temporary, "w", 0o600);
|
|
729
|
+
try {
|
|
730
|
+
writeSync(fd, content);
|
|
731
|
+
fsyncSync(fd);
|
|
732
|
+
}
|
|
733
|
+
catch (error) {
|
|
734
|
+
closeSync(fd);
|
|
735
|
+
rmSync(temporary, { force: true });
|
|
736
|
+
throw error;
|
|
737
|
+
}
|
|
738
|
+
closeSync(fd);
|
|
739
|
+
try {
|
|
740
|
+
renameSync(temporary, target);
|
|
741
|
+
}
|
|
742
|
+
catch (error) {
|
|
743
|
+
rmSync(temporary, { force: true });
|
|
744
|
+
throw error;
|
|
745
|
+
}
|
|
746
|
+
assertInside(root, target);
|
|
747
|
+
}
|
|
748
|
+
function containedRoot(root) {
|
|
749
|
+
return existsSync(root) ? realpathSync(root) : resolve(root);
|
|
750
|
+
}
|
|
751
|
+
function assertInside(root, target) {
|
|
752
|
+
const resolvedRoot = containedRoot(root);
|
|
753
|
+
const resolvedTarget = existsSync(target) ? realpathSync(target) : resolve(target);
|
|
754
|
+
const rel = relative(resolvedRoot, resolvedTarget);
|
|
755
|
+
if (rel.startsWith("..") || isAbsolute(rel)) {
|
|
756
|
+
throw new Error(`Path ${target} escapes catalog root ${root}.`);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
function assertNoSymlinkWalk(root, target) {
|
|
760
|
+
const lexicalRoot = resolve(root);
|
|
761
|
+
const rel = relative(lexicalRoot, resolve(target));
|
|
762
|
+
if (rel.startsWith("..") || isAbsolute(rel)) {
|
|
763
|
+
throw new Error(`Path ${target} escapes catalog root ${root}.`);
|
|
764
|
+
}
|
|
765
|
+
let current = lexicalRoot;
|
|
766
|
+
for (const part of rel.split(sep).filter(Boolean)) {
|
|
767
|
+
current = join(current, part);
|
|
768
|
+
const stats = lstatSync(current);
|
|
769
|
+
if (stats.isSymbolicLink()) {
|
|
770
|
+
throw new Error(`Refusing to follow symlink at ${current}.`);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
function pathExists(path) {
|
|
775
|
+
try {
|
|
776
|
+
lstatSync(path);
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
catch {
|
|
780
|
+
return false;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
function deepFreeze(value) {
|
|
784
|
+
if (!value || typeof value !== "object")
|
|
785
|
+
return value;
|
|
786
|
+
if (value instanceof Map) {
|
|
787
|
+
for (const child of value.values())
|
|
788
|
+
deepFreeze(child);
|
|
789
|
+
Object.freeze(value);
|
|
790
|
+
return value;
|
|
791
|
+
}
|
|
792
|
+
if (Object.isFrozen(value))
|
|
793
|
+
return value;
|
|
794
|
+
for (const child of Object.values(value))
|
|
795
|
+
deepFreeze(child);
|
|
796
|
+
Object.freeze(value);
|
|
797
|
+
return value;
|
|
798
|
+
}
|
|
799
|
+
function diagnostic(code, message, fields) {
|
|
800
|
+
return {
|
|
801
|
+
severity: fields.severity ?? (fields.blocking ? "error" : "warning"),
|
|
802
|
+
code,
|
|
803
|
+
message,
|
|
804
|
+
scope: fields.scope,
|
|
805
|
+
path: fields.path,
|
|
806
|
+
id: fields.id,
|
|
807
|
+
blocking: fields.blocking,
|
|
808
|
+
structural: fields.structural,
|
|
809
|
+
};
|
|
810
|
+
}
|