@vortex-os/base 0.11.0 → 0.12.1
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/README.md +29 -1
- package/dist/chunk-2FVNWW77.js +166 -0
- package/dist/chunk-2FVNWW77.js.map +1 -0
- package/dist/{chunk-DWANI3LV.js → chunk-P7IMUUNY.js} +41 -10
- package/dist/chunk-P7IMUUNY.js.map +1 -0
- package/dist/chunk-T53UWSTR.js +301 -0
- package/dist/chunk-T53UWSTR.js.map +1 -0
- package/dist/chunk-UV76ZEDC.js +292 -0
- package/dist/chunk-UV76ZEDC.js.map +1 -0
- package/dist/failures-PMURLMVB.js +25 -0
- package/dist/guard-IMJR6ET7.js +23 -0
- package/dist/guard-IMJR6ET7.js.map +1 -0
- package/dist/index.d.ts +295 -7
- package/dist/index.js +459 -629
- package/dist/index.js.map +1 -1
- package/dist/{statusline-NQKJ3NWD.js → statusline-JTSL5CCH.js} +8 -2
- package/dist/statusline-JTSL5CCH.js.map +1 -0
- package/package.json +1 -1
- package/templates/manifest.json +2 -2
- package/templates/routers/AI-RULES.md +3 -1
- package/dist/chunk-DWANI3LV.js.map +0 -1
- /package/dist/{statusline-NQKJ3NWD.js.map → failures-PMURLMVB.js.map} +0 -0
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__export
|
|
3
|
+
} from "./chunk-PZ5AY32C.js";
|
|
4
|
+
|
|
5
|
+
// ../core/dist/frontmatter.js
|
|
6
|
+
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
|
|
7
|
+
var FENCE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
|
|
8
|
+
var BOM = "\uFEFF";
|
|
9
|
+
function parseFrontmatter(source) {
|
|
10
|
+
const cleaned = source.startsWith(BOM) ? source.slice(1) : source;
|
|
11
|
+
const match = cleaned.match(FENCE);
|
|
12
|
+
if (!match) {
|
|
13
|
+
return {
|
|
14
|
+
frontmatter: {},
|
|
15
|
+
body: cleaned
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const yaml = match[1] ?? "";
|
|
19
|
+
const body = cleaned.slice(match[0].length);
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
const value = parseYaml(yaml);
|
|
23
|
+
parsed = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
24
|
+
} catch {
|
|
25
|
+
parsed = {};
|
|
26
|
+
}
|
|
27
|
+
return { frontmatter: parsed, body };
|
|
28
|
+
}
|
|
29
|
+
function serializeFrontmatter(doc) {
|
|
30
|
+
const keys = Object.keys(doc.frontmatter ?? {});
|
|
31
|
+
if (keys.length === 0)
|
|
32
|
+
return doc.body;
|
|
33
|
+
const yaml = stringifyYaml(doc.frontmatter).trimEnd();
|
|
34
|
+
return `---
|
|
35
|
+
${yaml}
|
|
36
|
+
---
|
|
37
|
+
${doc.body}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ../core/dist/paths.js
|
|
41
|
+
import { resolve, join } from "path";
|
|
42
|
+
function makeContext(repoRoot) {
|
|
43
|
+
const root = resolve(repoRoot);
|
|
44
|
+
return {
|
|
45
|
+
repoRoot: root,
|
|
46
|
+
agentDir: join(root, ".agent"),
|
|
47
|
+
dataDir: join(root, "data"),
|
|
48
|
+
modulesDir: join(root, "modules"),
|
|
49
|
+
pluginsDir: join(root, "plugins")
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function moduleDir(ctx, moduleName) {
|
|
53
|
+
return join(ctx.modulesDir, moduleName);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ../core/dist/config.js
|
|
57
|
+
import { existsSync, readFileSync } from "fs";
|
|
58
|
+
import { join as join2 } from "path";
|
|
59
|
+
var DEFAULT_CONFIG = {
|
|
60
|
+
autoRecord: { sessionStart: true, worklog: true, decision: true, ambientRecall: true, archive: true, vectorize: true, vectorizeAutoDownload: true, commitFrameworkChanges: true, handoff: true, handoffRetentionDays: 7, reindex: true, backfill: true, failures: true },
|
|
61
|
+
updates: { check: "session" },
|
|
62
|
+
environments: []
|
|
63
|
+
};
|
|
64
|
+
function vortexConfigPath(ctx) {
|
|
65
|
+
return join2(ctx.agentDir, "vortex.json");
|
|
66
|
+
}
|
|
67
|
+
function parseEnvironmentRule(raw) {
|
|
68
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
|
69
|
+
return null;
|
|
70
|
+
const candidate = raw;
|
|
71
|
+
if (typeof candidate.label !== "string")
|
|
72
|
+
return null;
|
|
73
|
+
const rule = {
|
|
74
|
+
label: candidate.label
|
|
75
|
+
};
|
|
76
|
+
if (typeof candidate.pathExists === "string")
|
|
77
|
+
rule.pathExists = candidate.pathExists;
|
|
78
|
+
if (typeof candidate.hostname === "string")
|
|
79
|
+
rule.hostname = candidate.hostname;
|
|
80
|
+
if (typeof candidate.envVar === "string") {
|
|
81
|
+
rule.envVar = candidate.envVar;
|
|
82
|
+
} else if (typeof candidate.envVar === "object" && candidate.envVar !== null) {
|
|
83
|
+
const ev = candidate.envVar;
|
|
84
|
+
if (typeof ev.name === "string") {
|
|
85
|
+
rule.envVar = typeof ev.equals === "string" ? { name: ev.name, equals: ev.equals } : { name: ev.name };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return rule;
|
|
89
|
+
}
|
|
90
|
+
function loadVortexConfig(ctx) {
|
|
91
|
+
const path = vortexConfigPath(ctx);
|
|
92
|
+
if (!existsSync(path))
|
|
93
|
+
return DEFAULT_CONFIG;
|
|
94
|
+
try {
|
|
95
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
96
|
+
const environments = Array.isArray(raw.environments) ? raw.environments.map(parseEnvironmentRule).filter((rule) => rule !== null) : [];
|
|
97
|
+
const rawUpdates = raw.updates && typeof raw.updates === "object" && !Array.isArray(raw.updates) ? raw.updates : {};
|
|
98
|
+
const rawCheck = rawUpdates.check;
|
|
99
|
+
const check = rawCheck === void 0 ? "session" : typeof rawCheck === "string" && rawCheck.trim().toLowerCase() === "session" ? "session" : "off";
|
|
100
|
+
const rawAuto = raw.autoRecord && typeof raw.autoRecord === "object" && !Array.isArray(raw.autoRecord) ? raw.autoRecord : {};
|
|
101
|
+
const vectorizeAutoDownload = rawAuto.vectorizeAutoDownload === void 0 ? true : rawAuto.vectorizeAutoDownload === true;
|
|
102
|
+
const commitFrameworkChanges = rawAuto.commitFrameworkChanges === void 0 ? true : rawAuto.commitFrameworkChanges === true;
|
|
103
|
+
const handoff = rawAuto.handoff === void 0 ? true : rawAuto.handoff === true;
|
|
104
|
+
const reindex = rawAuto.reindex === void 0 ? true : rawAuto.reindex === true;
|
|
105
|
+
const backfill = rawAuto.backfill === void 0 ? true : rawAuto.backfill === true;
|
|
106
|
+
const failures = rawAuto.failures === void 0 ? true : rawAuto.failures === true;
|
|
107
|
+
const rawDays = rawAuto.handoffRetentionDays;
|
|
108
|
+
const handoffRetentionDays = typeof rawDays === "number" && Number.isFinite(rawDays) && rawDays > 0 ? Math.floor(rawDays) : DEFAULT_CONFIG.autoRecord.handoffRetentionDays;
|
|
109
|
+
return {
|
|
110
|
+
autoRecord: {
|
|
111
|
+
...DEFAULT_CONFIG.autoRecord,
|
|
112
|
+
...raw.autoRecord ?? {},
|
|
113
|
+
vectorizeAutoDownload,
|
|
114
|
+
commitFrameworkChanges,
|
|
115
|
+
handoff,
|
|
116
|
+
handoffRetentionDays,
|
|
117
|
+
reindex,
|
|
118
|
+
backfill,
|
|
119
|
+
failures
|
|
120
|
+
},
|
|
121
|
+
updates: { check },
|
|
122
|
+
environments
|
|
123
|
+
};
|
|
124
|
+
} catch {
|
|
125
|
+
return DEFAULT_CONFIG;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function resolveEnvironment(config, signals) {
|
|
129
|
+
const host = signals.hostname?.toLowerCase();
|
|
130
|
+
const env = signals.env ?? {};
|
|
131
|
+
const pathExists = signals.pathExists ?? (() => false);
|
|
132
|
+
for (const rule of config.environments) {
|
|
133
|
+
if (rule.pathExists && pathExists(rule.pathExists))
|
|
134
|
+
return rule.label;
|
|
135
|
+
if (rule.hostname && host && rule.hostname.toLowerCase() === host)
|
|
136
|
+
return rule.label;
|
|
137
|
+
if (rule.envVar) {
|
|
138
|
+
if (typeof rule.envVar === "string") {
|
|
139
|
+
if (env[rule.envVar] !== void 0)
|
|
140
|
+
return rule.label;
|
|
141
|
+
} else {
|
|
142
|
+
const v = env[rule.envVar.name];
|
|
143
|
+
if (v !== void 0 && (rule.envVar.equals === void 0 || v === rule.envVar.equals)) {
|
|
144
|
+
return rule.label;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ../core/dist/index.js
|
|
153
|
+
var dist_exports = {};
|
|
154
|
+
__export(dist_exports, {
|
|
155
|
+
Privacy: () => Privacy,
|
|
156
|
+
atomicWriteFile: () => atomicWriteFile,
|
|
157
|
+
exclusiveCreateFile: () => exclusiveCreateFile,
|
|
158
|
+
isVisibleAt: () => isVisibleAt,
|
|
159
|
+
loadVortexConfig: () => loadVortexConfig,
|
|
160
|
+
makeContext: () => makeContext,
|
|
161
|
+
maxPrivacy: () => maxPrivacy,
|
|
162
|
+
moduleDir: () => moduleDir,
|
|
163
|
+
normalizePrivacy: () => normalizePrivacy,
|
|
164
|
+
parseFrontmatter: () => parseFrontmatter,
|
|
165
|
+
resolveEnvironment: () => resolveEnvironment,
|
|
166
|
+
serializeFrontmatter: () => serializeFrontmatter,
|
|
167
|
+
validateDataRelativePath: () => validateDataRelativePath,
|
|
168
|
+
vortexConfigPath: () => vortexConfigPath
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// ../core/dist/types.js
|
|
172
|
+
var Privacy = {
|
|
173
|
+
Public: "public",
|
|
174
|
+
Internal: "internal",
|
|
175
|
+
Personal: "personal"
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
// ../core/dist/privacy.js
|
|
179
|
+
var ORDER = {
|
|
180
|
+
public: 0,
|
|
181
|
+
internal: 1,
|
|
182
|
+
personal: 2
|
|
183
|
+
};
|
|
184
|
+
function isVisibleAt(docPrivacy, viewerPrivacy) {
|
|
185
|
+
return ORDER[docPrivacy] <= ORDER[viewerPrivacy];
|
|
186
|
+
}
|
|
187
|
+
function maxPrivacy(a, b) {
|
|
188
|
+
return ORDER[a] >= ORDER[b] ? a : b;
|
|
189
|
+
}
|
|
190
|
+
function normalizePrivacy(value, fallback = "internal") {
|
|
191
|
+
if (value === "public" || value === "internal" || value === "personal") {
|
|
192
|
+
return value;
|
|
193
|
+
}
|
|
194
|
+
return fallback;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ../core/dist/safe-fs.js
|
|
198
|
+
import { rename, writeFile } from "fs/promises";
|
|
199
|
+
import { isAbsolute, relative, resolve as resolve2, sep } from "path";
|
|
200
|
+
var SYSTEM_META_DIRS = /* @__PURE__ */ new Set([
|
|
201
|
+
"worklog",
|
|
202
|
+
"decision-log",
|
|
203
|
+
"runbooks",
|
|
204
|
+
"hubs",
|
|
205
|
+
"_memory",
|
|
206
|
+
"_templates",
|
|
207
|
+
"_proactive-curator",
|
|
208
|
+
// Framework metadata carve-out: `data/.vortex/` holds the update-lifecycle
|
|
209
|
+
// ownership manifest and template backups. It is NOT user space — the curate
|
|
210
|
+
// value loop (and any LLM-chosen write path) must never target it, even
|
|
211
|
+
// though it does not start with `_`. (The leading-`_` rule below does not
|
|
212
|
+
// cover a leading-dot dir, so it is listed explicitly.)
|
|
213
|
+
".vortex"
|
|
214
|
+
]);
|
|
215
|
+
var DRIVE_QUALIFIED = /^[a-zA-Z]:/;
|
|
216
|
+
var CONTROL_CHARS = /[\u0000-\u001F]/;
|
|
217
|
+
function validateDataRelativePath(dataDir, rel, _options = {}) {
|
|
218
|
+
if (typeof rel !== "string" || rel.length === 0) {
|
|
219
|
+
throw new Error("Invalid data-relative path: must be a non-empty string.");
|
|
220
|
+
}
|
|
221
|
+
if (CONTROL_CHARS.test(rel)) {
|
|
222
|
+
throw new Error("Invalid data-relative path: contains control characters.");
|
|
223
|
+
}
|
|
224
|
+
const normalized = rel.replace(/\\/g, "/");
|
|
225
|
+
if (normalized === "" || normalized === ".") {
|
|
226
|
+
throw new Error(`Invalid data-relative path: "${rel}" is empty or '.'.`);
|
|
227
|
+
}
|
|
228
|
+
if (DRIVE_QUALIFIED.test(normalized)) {
|
|
229
|
+
throw new Error(`Invalid data-relative path: "${rel}" is drive-qualified (must be data-relative).`);
|
|
230
|
+
}
|
|
231
|
+
if (isAbsolute(normalized) || normalized.startsWith("/")) {
|
|
232
|
+
throw new Error(`Invalid data-relative path: "${rel}" is absolute (must be data-relative).`);
|
|
233
|
+
}
|
|
234
|
+
const segments = normalized.split("/");
|
|
235
|
+
for (const segment of segments) {
|
|
236
|
+
if (segment === "" || segment === "." || segment === "..") {
|
|
237
|
+
throw new Error(`Invalid data-relative path: "${rel}" contains an empty, '.', or '..' segment (path traversal).`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const filename = segments[segments.length - 1];
|
|
241
|
+
if (filename.length === 0 || filename.includes("/") || filename.includes("\\")) {
|
|
242
|
+
throw new Error(`Invalid data-relative path: "${rel}" has an invalid filename.`);
|
|
243
|
+
}
|
|
244
|
+
const first = segments[0];
|
|
245
|
+
if (SYSTEM_META_DIRS.has(first) || first.startsWith("_")) {
|
|
246
|
+
throw new Error(`Invalid data-relative path: "${rel}" targets a reserved system/meta directory ("${first}"). The curate value loop writes user documents only \u2014 not worklog/decision-log/runbooks/hubs or any _* directory.`);
|
|
247
|
+
}
|
|
248
|
+
const absPath = resolve2(dataDir, normalized);
|
|
249
|
+
const rootResolved = resolve2(dataDir);
|
|
250
|
+
let relToData = relative(rootResolved, absPath);
|
|
251
|
+
let relCompare = relToData;
|
|
252
|
+
let upPrefix = ".." + sep;
|
|
253
|
+
if (sep === "\\") {
|
|
254
|
+
relCompare = relToData.toLowerCase();
|
|
255
|
+
upPrefix = upPrefix.toLowerCase();
|
|
256
|
+
}
|
|
257
|
+
if (relCompare === ".." || relCompare.startsWith(upPrefix) || isAbsolute(relToData)) {
|
|
258
|
+
throw new Error(`Invalid data-relative path: "${rel}" resolves outside the data directory.`);
|
|
259
|
+
}
|
|
260
|
+
return absPath;
|
|
261
|
+
}
|
|
262
|
+
async function exclusiveCreateFile(absPath, body) {
|
|
263
|
+
try {
|
|
264
|
+
await writeFile(absPath, body, { encoding: "utf8", flag: "wx" });
|
|
265
|
+
} catch (e) {
|
|
266
|
+
if (e.code === "EEXIST") {
|
|
267
|
+
throw new Error(`Refusing to overwrite existing file: ${absPath}. create-file is an exclusive create; to add to an existing document use append-section instead.`);
|
|
268
|
+
}
|
|
269
|
+
throw e;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
var atomicWriteCounter = 0;
|
|
273
|
+
async function atomicWriteFile(absPath, body) {
|
|
274
|
+
const tmp = `${absPath}.tmp-${process.pid}-${atomicWriteCounter++}`;
|
|
275
|
+
try {
|
|
276
|
+
await writeFile(tmp, body, { encoding: "utf8" });
|
|
277
|
+
await rename(tmp, absPath);
|
|
278
|
+
} catch (e) {
|
|
279
|
+
try {
|
|
280
|
+
const { rm } = await import("fs/promises");
|
|
281
|
+
await rm(tmp, { force: true });
|
|
282
|
+
} catch {
|
|
283
|
+
}
|
|
284
|
+
throw e;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export {
|
|
289
|
+
parseFrontmatter,
|
|
290
|
+
serializeFrontmatter,
|
|
291
|
+
isVisibleAt,
|
|
292
|
+
normalizePrivacy,
|
|
293
|
+
makeContext,
|
|
294
|
+
loadVortexConfig,
|
|
295
|
+
resolveEnvironment,
|
|
296
|
+
validateDataRelativePath,
|
|
297
|
+
exclusiveCreateFile,
|
|
298
|
+
atomicWriteFile,
|
|
299
|
+
dist_exports
|
|
300
|
+
};
|
|
301
|
+
//# sourceMappingURL=chunk-T53UWSTR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../core/src/frontmatter.ts","../../core/src/paths.ts","../../core/src/config.ts","../../core/src/index.ts","../../core/src/types.ts","../../core/src/privacy.ts","../../core/src/safe-fs.ts"],"sourcesContent":["import { parse as parseYaml, stringify as stringifyYaml } from \"yaml\";\nimport type { FrontmatterDoc, Privacy } from \"./types.js\";\n\nconst FENCE = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?/;\nconst BOM = \"\";\n\n/**\n * Parse a markdown source into its YAML frontmatter and body. If no frontmatter\n * fence is present, returns an empty frontmatter object and the source unchanged.\n *\n * A leading UTF-8 BOM is stripped before matching. Windows-authored files\n * frequently begin with ``, which would otherwise prevent the fence\n * regex from anchoring to `---` at byte 0.\n */\nexport function parseFrontmatter<T = Record<string, unknown>>(\n source: string,\n): FrontmatterDoc<T> {\n const cleaned = source.startsWith(BOM) ? source.slice(1) : source;\n const match = cleaned.match(FENCE);\n if (!match) {\n return {\n frontmatter: {} as T & { privacy?: Privacy },\n body: cleaned,\n };\n }\n const yaml = match[1] ?? \"\";\n const body = cleaned.slice(match[0].length);\n let parsed: T & { privacy?: Privacy };\n try {\n const value: unknown = parseYaml(yaml);\n // Frontmatter must be a mapping. Scalars, arrays, and null (e.g. a fence\n // holding only a string, a list, or nothing) are normalized to an empty\n // object so the result keeps its record shape and downstream code that\n // assumes key access cannot crash.\n parsed =\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as T & { privacy?: Privacy })\n : ({} as T & { privacy?: Privacy });\n } catch {\n // The fence was present but its YAML body did not parse — often the\n // result of copy/paste artifacts (a stray `---` mid-document, headings\n // accidentally pasted inside the fence). Treat as no frontmatter so\n // callers can still read the body; the fence content is discarded.\n parsed = {} as T & { privacy?: Privacy };\n }\n return { frontmatter: parsed, body };\n}\n\n/**\n * Serialize a `FrontmatterDoc` back into markdown text. If the frontmatter is\n * empty, the body is returned unchanged (no empty fence is emitted).\n */\nexport function serializeFrontmatter<T = Record<string, unknown>>(\n doc: FrontmatterDoc<T>,\n): string {\n const keys = Object.keys(doc.frontmatter ?? {});\n if (keys.length === 0) return doc.body;\n const yaml = stringifyYaml(doc.frontmatter).trimEnd();\n return `---\\n${yaml}\\n---\\n${doc.body}`;\n}\n","import { resolve, join } from \"node:path\";\nimport type { ModuleContext } from \"./types.js\";\n\n/**\n * Build a `ModuleContext` for the given VortEX repository root. The root is\n * resolved to an absolute path; standard subdirectories are derived by\n * convention and are not guaranteed to exist on disk.\n */\nexport function makeContext(repoRoot: string): ModuleContext {\n const root = resolve(repoRoot);\n return {\n repoRoot: root,\n agentDir: join(root, \".agent\"),\n dataDir: join(root, \"data\"),\n modulesDir: join(root, \"modules\"),\n pluginsDir: join(root, \"plugins\"),\n };\n}\n\n/**\n * Resolve the directory of a named module within the repository.\n */\nexport function moduleDir(ctx: ModuleContext, moduleName: string): string {\n return join(ctx.modulesDir, moduleName);\n}\n","import { existsSync, readFileSync } from \"node:fs\";\r\nimport { join } from \"node:path\";\r\nimport type { ModuleContext } from \"./types.js\";\r\n\r\n/**\r\n * Instance configuration for VortEX, read from `<agentDir>/vortex.json`.\r\n *\r\n * The config exists to give the user control over the **auto-maintained**\r\n * operational behaviors (see `AI-RULES.md` → \"Default behaviors\") without\r\n * touching code: toggle any auto-record off, and declare how this machine's\r\n * environment is detected. A fresh instance has no config file — everything\r\n * is on, no environment — so the framework works out of the box and the file\r\n * is purely opt-in tuning.\r\n */\r\n\r\n/** Which auto-maintained operational records are enabled. Default: all on. */\r\nexport interface AutoRecordConfig {\r\n readonly sessionStart: boolean;\r\n readonly worklog: boolean;\r\n readonly decision: boolean;\r\n readonly ambientRecall: boolean;\r\n /**\r\n * Catch-up: at session start, ingest conversation transcripts that have not\r\n * been archived yet (the host's own machine only). Text is stored\r\n * immediately; vectorization is deferred to recall/rebuild so start stays\r\n * fast. Off → no automatic ingest; the archive only grows when explicitly\r\n * rebuilt.\r\n */\r\n readonly archive: boolean;\r\n /**\r\n * Auto-vectorize: at session start (after catch-up), embed any\r\n * newly-archived sessions and memories so semantic recall — including the\r\n * ambient \"did we discuss this?\" path — stays current without a manual\r\n * rebuild. **Gated on the recall index already existing** (`_indexes/\r\n * memory.sqlite`): until the user has set recall up once (which downloads the\r\n * embedding model), this is a silent no-op, so it never triggers a download\r\n * on its own. On by default; off → vectors only update on an explicit\r\n * `/recall` / rebuild.\r\n */\r\n readonly vectorize: boolean;\r\n /**\r\n * Auto-download the embedding model the FIRST time recall is set up. When\r\n * `@vortex-os/memory-extended` is installed but the recall index does not\r\n * exist yet, session start kicks off a **background** worker that downloads\r\n * the model (~470 MB, once) and builds the index — so installing the add-on\r\n * is itself the opt-in and search turns on without a manual `/recall`. The\r\n * download never blocks session start (it runs detached). On by default; set\r\n * `false` — or env `VORTEX_VECTORIZE_AUTO_DOWNLOAD=0` — to keep the first\r\n * download manual (metered connections, CI). Independent of `vectorize`: if\r\n * `vectorize` is off, nothing runs regardless.\r\n */\r\n readonly vectorizeAutoDownload: boolean;\r\n /**\r\n * Auto-commit framework bookkeeping. When `vortex update` refreshes\r\n * framework-owned files it also rewrites the ownership manifest\r\n * (`data/.vortex/ownership.json`); on its own that leaves an uncommitted\r\n * \"trail\" that the next session reports as carried-over work, even though it\r\n * is plumbing the user never touched. With this on, `vortex update` commits\r\n * exactly the framework files it changed (the manifest + the templates it\r\n * refreshed) — and nothing else in the working tree — so an update leaves a\r\n * clean tree. Best-effort: a non-git folder, or any git failure, is a silent\r\n * no-op (the command still succeeds). On by default; set `false` to keep the\r\n * commit manual (e.g. you prefer to review and commit framework changes\r\n * yourself). Conflicts (`<file>.new`) are never auto-committed — those still\r\n * wait for you to merge.\r\n */\r\n readonly commitFrameworkChanges: boolean;\r\n /**\r\n * Use the dedicated session hand-off store (`data/_handoff/`) — a forward-\r\n * looking baton kept separate from the worklog. On by default. When off,\r\n * hand-offs fall back to the legacy `## 다음 작업` worklog section and no\r\n * auto-archiving runs.\r\n */\r\n readonly handoff: boolean;\r\n /**\r\n * Days a hand-off stays \"active\" before session start sweeps it to\r\n * `_handoff/_archive/` (deterministic, age-based — git keeps the history).\r\n * Default 7 (covers a week-long absence); set lower to tidy faster, higher to\r\n * keep more around. A non-positive / malformed value falls back to the default.\r\n */\r\n readonly handoffRetentionDays: number;\r\n /**\r\n * Auto-reindex the on-demand memory index (`_memory/_INDEX.md`) at session\r\n * start when it looks stale (a memory file is newer than the index).\r\n * Mechanical and idempotent — it only rewrites `_INDEX.md` from each memory's\r\n * frontmatter, never a memory's content, and writes only when the rendered\r\n * index actually changes (then refreshes the index's mtime so the stale flag\r\n * clears). On by default; off → the start report just flags the stale index\r\n * for the agent to fix instead of fixing it automatically.\r\n */\r\n readonly reindex: boolean;\r\n /**\r\n * Auto-backfill a missed worklog. When a past day had commits but no worklog,\r\n * the in-session agent reconstructs and writes it at the next session start\r\n * (zero-worklog days only, capped, labeled as reconstructed — see AI-RULES.md\r\n * \"Default behaviors\"). Gated by `worklog` as well: turning `worklog` off\r\n * suppresses backfill too. On by default; off → the start report still flags\r\n * the gap but the agent leaves it for you.\r\n */\r\n readonly backfill: boolean;\r\n /**\r\n * The failure ledger (`data/_failures/`) — the self-improvement loop's\r\n * evidence store. With this on, the agent records noticed failures\r\n * (append-only, one file per occurrence) and the session-start report\r\n * surfaces recurring keys with their escalation-ladder stage (2nd occurrence\r\n * → the covering rule's gate is mandatory; 3rd+ → propose a deterministic\r\n * guard — always a proposal, never auto-installed). On by default; off → no\r\n * recording ritual and no report section ( `vortex failure` still works when\r\n * invoked explicitly).\r\n */\r\n readonly failures: boolean;\r\n}\r\n\r\n/**\r\n * One environment label plus the signal that selects it. Rules are evaluated\r\n * in order; the first match wins. Generalizes the operator's home/work\r\n * `Test-Path` pattern into a portable, declarative form.\r\n */\r\nexport interface EnvironmentRule {\r\n readonly label: string;\r\n /** Match when this absolute path exists on the machine. */\r\n readonly pathExists?: string;\r\n /** Match when the OS hostname equals this (case-insensitive). */\r\n readonly hostname?: string;\r\n /**\r\n * Match when an environment variable is set. A bare string matches on\r\n * presence; the object form additionally requires a specific value.\r\n */\r\n readonly envVar?: string | { readonly name: string; readonly equals?: string };\r\n}\r\n\r\n/**\r\n * Update-awareness behavior. `check` controls the once-per-session check for a\r\n * newer published `@vortex-os/base`:\r\n * - `\"session\"` (default): check the npm registry once at session start and,\r\n * when a newer version exists, surface it (the agent then asks before any\r\n * install — nothing is installed automatically). Offline → silent skip.\r\n * - `\"off\"`: no automatic check, no network contact for updates.\r\n * On either setting the local \"templates not yet applied\" notice (no network)\r\n * and the on-demand `vortex check-updates` still work.\r\n */\r\nexport interface UpdatesConfig {\r\n readonly check: \"session\" | \"off\";\r\n}\r\n\r\nexport interface VortexConfig {\r\n readonly autoRecord: AutoRecordConfig;\r\n readonly updates: UpdatesConfig;\r\n readonly environments: readonly EnvironmentRule[];\r\n}\r\n\r\nconst DEFAULT_CONFIG: VortexConfig = {\r\n autoRecord: { sessionStart: true, worklog: true, decision: true, ambientRecall: true, archive: true, vectorize: true, vectorizeAutoDownload: true, commitFrameworkChanges: true, handoff: true, handoffRetentionDays: 7, reindex: true, backfill: true, failures: true },\r\n updates: { check: \"session\" },\r\n environments: [],\r\n};\r\n\r\n/** Path of the instance config file: `<agentDir>/vortex.json`. */\r\nexport function vortexConfigPath(ctx: ModuleContext): string {\r\n return join(ctx.agentDir, \"vortex.json\");\r\n}\r\n\r\n/**\r\n * Validate one raw environment rule, returning a clean `EnvironmentRule` or\r\n * `null` when it is unusable. A rule must be a plain object with a string\r\n * `label`; `hostname`/`pathExists` are accepted only as strings (dropped\r\n * otherwise) and `envVar` only as a string or an object with a string `name`\r\n * (with an optional string `equals`). Dropping malformed rules keeps a bad\r\n * config from throwing later in `resolveEnvironment`.\r\n */\r\nfunction parseEnvironmentRule(raw: unknown): EnvironmentRule | null {\r\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) return null;\r\n const candidate = raw as Record<string, unknown>;\r\n if (typeof candidate.label !== \"string\") return null;\r\n const rule: { -readonly [K in keyof EnvironmentRule]: EnvironmentRule[K] } = {\r\n label: candidate.label,\r\n };\r\n if (typeof candidate.pathExists === \"string\") rule.pathExists = candidate.pathExists;\r\n if (typeof candidate.hostname === \"string\") rule.hostname = candidate.hostname;\r\n if (typeof candidate.envVar === \"string\") {\r\n rule.envVar = candidate.envVar;\r\n } else if (typeof candidate.envVar === \"object\" && candidate.envVar !== null) {\r\n const ev = candidate.envVar as Record<string, unknown>;\r\n if (typeof ev.name === \"string\") {\r\n rule.envVar =\r\n typeof ev.equals === \"string\" ? { name: ev.name, equals: ev.equals } : { name: ev.name };\r\n }\r\n }\r\n return rule;\r\n}\r\n\r\n/**\r\n * Load the instance config, merged over defaults. A missing, unreadable, or\r\n * invalid file yields defaults (everything on, no environments) rather than\r\n * throwing — config is opt-in tuning, never a prerequisite. Environment rules\r\n * are validated individually; malformed ones are dropped so that a partly bad\r\n * config still resolves rather than throwing in `resolveEnvironment`.\r\n */\r\nexport function loadVortexConfig(ctx: ModuleContext): VortexConfig {\r\n const path = vortexConfigPath(ctx);\r\n if (!existsSync(path)) return DEFAULT_CONFIG;\r\n try {\r\n const raw = JSON.parse(readFileSync(path, \"utf8\")) as Partial<VortexConfig>;\r\n const environments = Array.isArray(raw.environments)\r\n ? raw.environments\r\n .map(parseEnvironmentRule)\r\n .filter((rule): rule is EnvironmentRule => rule !== null)\r\n : [];\r\n // Resolve `updates.check`, normalizing and FAILING CLOSED toward no network:\r\n // - missing / a malformed `updates` shape → the default (\"session\", on);\r\n // - an explicit \"session\" (any case/whitespace) stays on;\r\n // - ANY other explicit value (incl. \"off\", \"OFF\", \" off \", a typo, or a\r\n // non-string) DISABLES the check — the only reason to set a non-default\r\n // value is to turn it off, so a mistyped opt-out must not silently keep\r\n // phoning home.\r\n const rawUpdates =\r\n raw.updates && typeof raw.updates === \"object\" && !Array.isArray(raw.updates)\r\n ? (raw.updates as unknown as Record<string, unknown>)\r\n : {};\r\n const rawCheck = rawUpdates.check;\r\n const check: UpdatesConfig[\"check\"] =\r\n rawCheck === undefined\r\n ? \"session\"\r\n : typeof rawCheck === \"string\" && rawCheck.trim().toLowerCase() === \"session\"\r\n ? \"session\"\r\n : \"off\";\r\n // `vectorizeAutoDownload` fails CLOSED toward NOT downloading: absent → on\r\n // (the default opt-in); explicit `true` → on; ANY other explicit value\r\n // (false, \"off\", a typo, a non-boolean) → off, so a mistyped opt-out never\r\n // silently keeps the ~470 MB auto-download on.\r\n const rawAuto =\r\n raw.autoRecord && typeof raw.autoRecord === \"object\" && !Array.isArray(raw.autoRecord)\r\n ? (raw.autoRecord as unknown as Record<string, unknown>)\r\n : {};\r\n const vectorizeAutoDownload =\r\n rawAuto.vectorizeAutoDownload === undefined ? true : rawAuto.vectorizeAutoDownload === true;\r\n // `commitFrameworkChanges` fails CLOSED toward NOT committing: absent → on\r\n // (the default), explicit `true` → on, ANY other explicit value (false,\r\n // \"off\", a typo, a non-boolean) → off — so a mistyped opt-out never leaves\r\n // the framework silently committing into the user's repo.\r\n const commitFrameworkChanges =\r\n rawAuto.commitFrameworkChanges === undefined ? true : rawAuto.commitFrameworkChanges === true;\r\n // `handoff` fails CLOSED toward the legacy worklog-section behavior: absent →\r\n // on (the default), explicit `true` → on, ANY other explicit value → off.\r\n const handoff = rawAuto.handoff === undefined ? true : rawAuto.handoff === true;\r\n // `reindex` / `backfill` fail CLOSED toward NOT auto-writing: absent → on\r\n // (the default), explicit `true` → on, ANY other explicit value (false,\r\n // \"off\", a typo, a non-boolean) → off — so a mistyped opt-out never leaves\r\n // the framework auto-writing the memory index or a backfilled worklog.\r\n const reindex = rawAuto.reindex === undefined ? true : rawAuto.reindex === true;\r\n const backfill = rawAuto.backfill === undefined ? true : rawAuto.backfill === true;\r\n // `failures` (the failure ledger) fails CLOSED toward NOT auto-writing,\r\n // same shape as reindex/backfill: absent → on, explicit `true` → on, ANY\r\n // other explicit value → off.\r\n const failures = rawAuto.failures === undefined ? true : rawAuto.failures === true;\r\n // `handoffRetentionDays`: a positive finite number is honored (floored);\r\n // anything else falls back to the default, so a typo never disables pruning\r\n // silently or sets a nonsensical window.\r\n const rawDays = rawAuto.handoffRetentionDays;\r\n const handoffRetentionDays =\r\n typeof rawDays === \"number\" && Number.isFinite(rawDays) && rawDays > 0\r\n ? Math.floor(rawDays)\r\n : DEFAULT_CONFIG.autoRecord.handoffRetentionDays;\r\n return {\r\n autoRecord: {\r\n ...DEFAULT_CONFIG.autoRecord,\r\n ...(raw.autoRecord ?? {}),\r\n vectorizeAutoDownload,\r\n commitFrameworkChanges,\r\n handoff,\r\n handoffRetentionDays,\r\n reindex,\r\n backfill,\r\n failures,\r\n },\r\n updates: { check },\r\n environments,\r\n };\r\n } catch {\r\n return DEFAULT_CONFIG;\r\n }\r\n}\r\n\r\n/**\r\n * Resolve the active environment label from the config rules (first match\r\n * wins), or null when none match. Pure — the caller injects the signals\r\n * (hostname, env vars, a path-existence probe) so this stays testable and\r\n * free of direct OS access.\r\n */\r\nexport function resolveEnvironment(\r\n config: VortexConfig,\r\n signals: {\r\n readonly hostname?: string;\r\n readonly env?: Record<string, string | undefined>;\r\n readonly pathExists?: (p: string) => boolean;\r\n },\r\n): string | null {\r\n const host = signals.hostname?.toLowerCase();\r\n const env = signals.env ?? {};\r\n const pathExists = signals.pathExists ?? (() => false);\r\n for (const rule of config.environments) {\r\n if (rule.pathExists && pathExists(rule.pathExists)) return rule.label;\r\n if (rule.hostname && host && rule.hostname.toLowerCase() === host) return rule.label;\r\n if (rule.envVar) {\r\n if (typeof rule.envVar === \"string\") {\r\n if (env[rule.envVar] !== undefined) return rule.label;\r\n } else {\r\n const v = env[rule.envVar.name];\r\n if (v !== undefined && (rule.envVar.equals === undefined || v === rule.envVar.equals)) {\r\n return rule.label;\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n}\r\n","export { Privacy } from \"./types.js\";\r\nexport type { FrontmatterDoc, ModuleContext } from \"./types.js\";\r\nexport { parseFrontmatter, serializeFrontmatter } from \"./frontmatter.js\";\r\nexport { isVisibleAt, maxPrivacy, normalizePrivacy } from \"./privacy.js\";\r\nexport { makeContext, moduleDir } from \"./paths.js\";\r\nexport { loadVortexConfig, resolveEnvironment, vortexConfigPath } from \"./config.js\";\r\nexport type { AutoRecordConfig, EnvironmentRule, UpdatesConfig, VortexConfig } from \"./config.js\";\r\nexport { atomicWriteFile, exclusiveCreateFile, validateDataRelativePath } from \"./safe-fs.js\";\r\nexport type { ValidateDataRelativePathOptions } from \"./safe-fs.js\";\r\n","/**\n * Three-tier privacy classification used across VortEX.\n *\n * - `public` — safe to share with anyone, including in published repositories.\n * - `internal` — visible to the operator and their organization; not for public release.\n * - `personal` — personal data; never shared, never published.\n */\nexport const Privacy = {\n Public: \"public\",\n Internal: \"internal\",\n Personal: \"personal\",\n} as const;\n\nexport type Privacy = (typeof Privacy)[keyof typeof Privacy];\n\n/**\n * Parsed markdown document with separated YAML frontmatter and body.\n */\nexport interface FrontmatterDoc<T = Record<string, unknown>> {\n frontmatter: T & { privacy?: Privacy };\n body: string;\n}\n\n/**\n * Resolved paths for a VortEX repository root.\n *\n * Every module receives a `ModuleContext` from the host (CLI, plugin runtime,\n * or test harness) and resolves its own paths against it. Modules must not\n * derive paths by string manipulation against an assumed layout.\n */\nexport interface ModuleContext {\n repoRoot: string;\n agentDir: string;\n dataDir: string;\n modulesDir: string;\n pluginsDir: string;\n}\n","import type { Privacy } from \"./types.js\";\n\nconst ORDER: Record<Privacy, number> = {\n public: 0,\n internal: 1,\n personal: 2,\n};\n\n/**\n * Returns true if a document with `docPrivacy` is visible to a viewer authorized\n * at `viewerPrivacy`. Viewers see content at or below their own level.\n *\n * - `public` viewer sees → public only\n * - `internal` viewer sees → public + internal\n * - `personal` viewer sees → all three\n */\nexport function isVisibleAt(docPrivacy: Privacy, viewerPrivacy: Privacy): boolean {\n return ORDER[docPrivacy] <= ORDER[viewerPrivacy];\n}\n\n/**\n * Returns the more-restrictive of two privacy levels.\n * Useful when combining content from multiple sources for sharing.\n */\nexport function maxPrivacy(a: Privacy, b: Privacy): Privacy {\n return ORDER[a] >= ORDER[b] ? a : b;\n}\n\n/**\n * Coerce an unknown value (e.g. user input or untyped frontmatter) into a\n * valid `Privacy`. Falls back to `internal` by default — the safest default\n * for unclassified content.\n */\nexport function normalizePrivacy(value: unknown, fallback: Privacy = \"internal\"): Privacy {\n if (value === \"public\" || value === \"internal\" || value === \"personal\") {\n return value;\n }\n return fallback;\n}\n","import { rename, writeFile } from \"node:fs/promises\";\nimport { isAbsolute, relative, resolve, sep } from \"node:path\";\n\n/**\n * Path-safety primitives shared by every VortEX write path.\n *\n * Two concerns are deliberately separated:\n *\n * - {@link validateDataRelativePath} is the *gate* — it turns an\n * untrusted, possibly-LLM-chosen `data/`-relative path into a vetted\n * absolute path under `dataDir`, or throws. It must run before ANY write\n * so a traversal/absolute/drive-qualified/system-dir path can never reach\n * the filesystem.\n * - {@link exclusiveCreateFile} is the *write* — an exclusive create that\n * refuses to overwrite, so an accidental collision surfaces as an error\n * rather than silent data loss.\n *\n * The validator is the security boundary. The proactive-curator's placement\n * decisions come from an LLM; the CLI accept path takes a serialized payload\n * from an agent. Neither is trusted to stay inside `data/` on its own.\n */\n\n/**\n * Directories at the top of `data/` that VortEX maintains structurally and\n * that the curate value loop must never write into. Mirrors the\n * proactive-curator's own `SYSTEM_META_DIRS`, plus the leading-`_` rule\n * (any `_*` first segment is reserved) enforced separately below.\n */\nconst SYSTEM_META_DIRS = new Set([\n \"worklog\",\n \"decision-log\",\n \"runbooks\",\n \"hubs\",\n \"_memory\",\n \"_templates\",\n \"_proactive-curator\",\n // Framework metadata carve-out: `data/.vortex/` holds the update-lifecycle\n // ownership manifest and template backups. It is NOT user space — the curate\n // value loop (and any LLM-chosen write path) must never target it, even\n // though it does not start with `_`. (The leading-`_` rule below does not\n // cover a leading-dot dir, so it is listed explicitly.)\n \".vortex\",\n]);\n\n/** Match a drive-qualified prefix such as `C:` or `c:/...` (Windows). */\nconst DRIVE_QUALIFIED = /^[a-zA-Z]:/;\n\n/** Control characters (U+0000–U+001F) are never valid in a path we accept. */\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARS = /[\\u0000-\\u001F]/;\n\n/**\n * Options for {@link validateDataRelativePath}. Shaped so a future\n * symlink-aware mode can be added WITHOUT changing any caller: today every\n * caller passes no options (or `{}`) and gets the lexical check. When the\n * realpath mode lands it becomes `{ resolveSymlinks: true }` and callers that\n * want it opt in; the default stays lexical-only.\n *\n * The symlink/realpath ancestor check is intentionally DEFERRED for v1 — the\n * lexical containment check (resolve + `path.relative`) already blocks\n * traversal, absolute, and drive-qualified paths. A symlink *inside* `data/`\n * pointing outside it is the remaining gap; closing it needs an async\n * `realpath` walk, which this synchronous API leaves room for.\n */\nexport interface ValidateDataRelativePathOptions {\n /**\n * Reserved for the deferred realpath/symlink-ancestor mode. Currently\n * ignored — accepted now so enabling it later is not a breaking change.\n */\n readonly resolveSymlinks?: boolean;\n}\n\n/**\n * Validate an untrusted `data/`-relative path and return the vetted absolute\n * path under `dataDir`, or throw a clear {@link Error}.\n *\n * Rejection rules (in order — the cheap lexical checks run before the\n * resolve so a hostile input never even reaches `path.resolve`):\n *\n * 1. Not a non-empty string.\n * 2. Contains a control character (U+0000–U+001F).\n * 3. After normalizing `\\` → `/`: empty, `.`, drive-qualified (`C:`),\n * absolute, or has a leading separator.\n * 4. Any segment is empty (collapsed `//`), `.`, or `..` (traversal).\n * 5. The final segment (the filename) is empty.\n * 6. The first segment is a system/meta dir (worklog, decision-log,\n * runbooks, hubs, _memory, _templates, _proactive-curator) or starts\n * with `_` (any reserved/meta dir).\n *\n * Then it resolves against `dataDir` and confirms containment using\n * `path.relative` (NOT a string prefix — `data` vs `data-evil` would fool a\n * prefix check). On Windows the relative check is done case-insensitively.\n *\n * @param dataDir Absolute path of the instance's `data/` directory.\n * @param rel Untrusted `data/`-relative path (LLM- or agent-supplied).\n * @returns The validated absolute path, guaranteed under `dataDir`.\n */\nexport function validateDataRelativePath(\n dataDir: string,\n rel: string,\n // Options are accepted for forward-compatibility (deferred symlink mode);\n // unused today. Underscore-prefixed so noUnusedParameters stays happy.\n _options: ValidateDataRelativePathOptions = {},\n): string {\n if (typeof rel !== \"string\" || rel.length === 0) {\n throw new Error(\"Invalid data-relative path: must be a non-empty string.\");\n }\n if (CONTROL_CHARS.test(rel)) {\n throw new Error(\"Invalid data-relative path: contains control characters.\");\n }\n\n const normalized = rel.replace(/\\\\/g, \"/\");\n\n if (normalized === \"\" || normalized === \".\") {\n throw new Error(`Invalid data-relative path: \"${rel}\" is empty or '.'.`);\n }\n if (DRIVE_QUALIFIED.test(normalized)) {\n throw new Error(`Invalid data-relative path: \"${rel}\" is drive-qualified (must be data-relative).`);\n }\n if (isAbsolute(normalized) || normalized.startsWith(\"/\")) {\n throw new Error(`Invalid data-relative path: \"${rel}\" is absolute (must be data-relative).`);\n }\n\n const segments = normalized.split(\"/\");\n for (const segment of segments) {\n if (segment === \"\" || segment === \".\" || segment === \"..\") {\n throw new Error(\n `Invalid data-relative path: \"${rel}\" contains an empty, '.', or '..' segment (path traversal).`,\n );\n }\n }\n\n // The final segment is the filename; it must not itself be a separator-\n // bearing value (defensive — split already removed separators) and must\n // be non-empty (covered by the segment loop, asserted here for clarity).\n const filename = segments[segments.length - 1]!;\n if (filename.length === 0 || filename.includes(\"/\") || filename.includes(\"\\\\\")) {\n throw new Error(`Invalid data-relative path: \"${rel}\" has an invalid filename.`);\n }\n\n const first = segments[0]!;\n if (SYSTEM_META_DIRS.has(first) || first.startsWith(\"_\")) {\n throw new Error(\n `Invalid data-relative path: \"${rel}\" targets a reserved system/meta directory (\"${first}\"). ` +\n \"The curate value loop writes user documents only — not worklog/decision-log/runbooks/hubs or any _* directory.\",\n );\n }\n\n const absPath = resolve(dataDir, normalized);\n const rootResolved = resolve(dataDir);\n\n // Containment via path.relative — a true ancestor relationship, not a\n // string prefix (which would accept a sibling like `<dataDir>-evil`).\n let relToData = relative(rootResolved, absPath);\n let relCompare = relToData;\n let upPrefix = \"..\" + sep;\n if (sep === \"\\\\\") {\n // Windows: filesystem is case-insensitive — compare case-folded so a\n // drive-letter/segment casing difference does not read as \"escaped\".\n relCompare = relToData.toLowerCase();\n upPrefix = upPrefix.toLowerCase();\n }\n if (\n relCompare === \"..\" ||\n relCompare.startsWith(upPrefix) ||\n isAbsolute(relToData)\n ) {\n throw new Error(`Invalid data-relative path: \"${rel}\" resolves outside the data directory.`);\n }\n\n return absPath;\n}\n\n/**\n * Create a file exclusively (refusing to overwrite). Writes `body` with the\n * `wx` flag so an existing target throws `EEXIST`, which is re-thrown as a\n * clear \"refusing to overwrite\" error. Use for the create-file action where\n * clobbering an existing document would be silent data loss.\n *\n * The caller is responsible for ensuring the parent directory exists (the\n * create-file path in the curator does its own `mkdir` after validation).\n *\n * @param absPath Absolute target path (already validated by\n * {@link validateDataRelativePath}).\n * @param body File contents (UTF-8).\n */\nexport async function exclusiveCreateFile(absPath: string, body: string): Promise<void> {\n try {\n await writeFile(absPath, body, { encoding: \"utf8\", flag: \"wx\" });\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"EEXIST\") {\n throw new Error(\n `Refusing to overwrite existing file: ${absPath}. ` +\n \"create-file is an exclusive create; to add to an existing document use append-section instead.\",\n );\n }\n throw e;\n }\n}\n\n/**\n * Write `body` to `absPath` atomically: stage to a sibling temp file, then\n * `rename` over the target. A reader of `absPath` therefore sees either the old\n * bytes or the new bytes in full — never a partially-written file. The temp\n * file is a sibling (same directory ⇒ same filesystem) so the rename is atomic;\n * `counter` disambiguates concurrent writers in the same process.\n *\n * This is the write primitive for the update lifecycle's transaction model —\n * template replacements and the ownership manifest must never leave a half-\n * written file on a crash mid-update. The caller ensures the parent directory\n * exists.\n *\n * @param absPath Absolute target path.\n * @param body File contents (UTF-8).\n */\nlet atomicWriteCounter = 0;\nexport async function atomicWriteFile(absPath: string, body: string): Promise<void> {\n const tmp = `${absPath}.tmp-${process.pid}-${atomicWriteCounter++}`;\n try {\n await writeFile(tmp, body, { encoding: \"utf8\" });\n await rename(tmp, absPath);\n } catch (e) {\n // Best-effort cleanup of the temp file if the rename never happened.\n try {\n const { rm } = await import(\"node:fs/promises\");\n await rm(tmp, { force: true });\n } catch {\n // ignore — the temp file is named distinctly and harmless if it lingers\n }\n throw e;\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,SAAS,WAAW,aAAa,qBAAqB;AAG/D,IAAM,QAAQ;AACd,IAAM,MAAM;AAUN,SAAU,iBACd,QAAc;AAEd,QAAM,UAAU,OAAO,WAAW,GAAG,IAAI,OAAO,MAAM,CAAC,IAAI;AAC3D,QAAM,QAAQ,QAAQ,MAAM,KAAK;AACjC,MAAI,CAAC,OAAO;AACV,WAAO;MACL,aAAa,CAAA;MACb,MAAM;;EAEV;AACA,QAAM,OAAO,MAAM,CAAC,KAAK;AACzB,QAAM,OAAO,QAAQ,MAAM,MAAM,CAAC,EAAE,MAAM;AAC1C,MAAI;AACJ,MAAI;AACF,UAAM,QAAiB,UAAU,IAAI;AAKrC,aACE,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAC9D,QACA,CAAA;EACT,QAAQ;AAKN,aAAS,CAAA;EACX;AACA,SAAO,EAAE,aAAa,QAAQ,KAAI;AACpC;AAMM,SAAU,qBACd,KAAsB;AAEtB,QAAM,OAAO,OAAO,KAAK,IAAI,eAAe,CAAA,CAAE;AAC9C,MAAI,KAAK,WAAW;AAAG,WAAO,IAAI;AAClC,QAAM,OAAO,cAAc,IAAI,WAAW,EAAE,QAAO;AACnD,SAAO;EAAQ,IAAI;;EAAU,IAAI,IAAI;AACvC;;;AC3DA,SAAS,SAAS,YAAY;AAQxB,SAAU,YAAY,UAAgB;AAC1C,QAAM,OAAO,QAAQ,QAAQ;AAC7B,SAAO;IACL,UAAU;IACV,UAAU,KAAK,MAAM,QAAQ;IAC7B,SAAS,KAAK,MAAM,MAAM;IAC1B,YAAY,KAAK,MAAM,SAAS;IAChC,YAAY,KAAK,MAAM,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