@contextline/contextline 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,716 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { Command } from "commander";
5
+
6
+ // src/tools/appendFragment.ts
7
+ import fs5 from "fs/promises";
8
+
9
+ // src/config.ts
10
+ import fs from "fs";
11
+ import path from "path";
12
+ function getMemoryRoot() {
13
+ if (process.env.CONTEXTLINE_ROOT) return path.resolve(process.env.CONTEXTLINE_ROOT);
14
+ return path.join(process.cwd(), ".contextline");
15
+ }
16
+ function resolveRoot(folder) {
17
+ if (folder) return path.resolve(folder);
18
+ return getMemoryRoot();
19
+ }
20
+
21
+ // src/paths.ts
22
+ import path2 from "path";
23
+
24
+ // src/core/errors.ts
25
+ var ContextLineError = class extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = "ContextLineError";
29
+ }
30
+ };
31
+ var PathSafetyError = class extends ContextLineError {
32
+ constructor(message) {
33
+ super(message);
34
+ this.name = "PathSafetyError";
35
+ }
36
+ };
37
+
38
+ // src/paths.ts
39
+ var L1_FILE = "L1_Quick.md";
40
+ var L2_DIR = "L2_Deep";
41
+ var L3_DIR = "L3_Details";
42
+ function assertSafeRelative(input) {
43
+ if (!input || input.trim() !== input) {
44
+ throw new PathSafetyError("Path input must be non-empty and contain no leading/trailing whitespace.");
45
+ }
46
+ if (path2.isAbsolute(input)) {
47
+ throw new PathSafetyError("Absolute paths are not allowed in tool inputs.");
48
+ }
49
+ const parts = input.split(/[\\/]+/);
50
+ if (parts.includes("..") || parts.includes("")) {
51
+ throw new PathSafetyError("Path traversal and empty path segments are not allowed.");
52
+ }
53
+ }
54
+ function assertSafeRelativeFile(input) {
55
+ assertSafeRelative(input);
56
+ if (!input.endsWith(".md")) {
57
+ throw new PathSafetyError("Memory file paths must end with .md.");
58
+ }
59
+ }
60
+ function safeJoin(root, ...segments) {
61
+ for (const segment of segments) {
62
+ assertSafeRelative(segment);
63
+ }
64
+ const resolvedRoot = path2.resolve(root);
65
+ const target = path2.resolve(resolvedRoot, ...segments);
66
+ const rel = path2.relative(resolvedRoot, target);
67
+ if (rel.startsWith("..") || path2.isAbsolute(rel)) {
68
+ throw new PathSafetyError("Resolved path escapes ContextLine root.");
69
+ }
70
+ return target;
71
+ }
72
+ function deepPath(root, file) {
73
+ assertSafeRelativeFile(file);
74
+ if (file.includes("/") || file.includes("\\")) {
75
+ throw new PathSafetyError("L2 deep memory files must be flat filenames inside L2_Deep for V1.");
76
+ }
77
+ return safeJoin(root, L2_DIR, file);
78
+ }
79
+ function detailPath(root, file) {
80
+ assertSafeRelativeFile(file);
81
+ return safeJoin(root, L3_DIR, file);
82
+ }
83
+ function l1Path(root) {
84
+ return safeJoin(root, L1_FILE);
85
+ }
86
+
87
+ // src/core/atomicWrite.ts
88
+ import fs2 from "fs/promises";
89
+ import path3 from "path";
90
+ async function atomicWriteFile(filePath, content) {
91
+ await fs2.mkdir(path3.dirname(filePath), { recursive: true });
92
+ const tmp = path3.join(path3.dirname(filePath), `.${path3.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
93
+ const handle = await fs2.open(tmp, "w");
94
+ try {
95
+ await handle.writeFile(content, "utf8");
96
+ await handle.sync();
97
+ } finally {
98
+ await handle.close();
99
+ }
100
+ await fs2.rename(tmp, filePath);
101
+ }
102
+
103
+ // src/core/markdown.ts
104
+ function ensureTrailingNewline(content) {
105
+ return content.endsWith("\n") ? content : `${content}
106
+ `;
107
+ }
108
+ function upsertLineByPrefix(content, prefix, nextLine) {
109
+ const lines = ensureTrailingNewline(content).split("\n");
110
+ const index = lines.findIndex((line) => line.trimStart().startsWith(prefix));
111
+ if (index >= 0) {
112
+ lines[index] = nextLine;
113
+ } else {
114
+ lines.splice(Math.max(0, lines.length - 1), 0, nextLine);
115
+ }
116
+ return ensureTrailingNewline(lines.join("\n").replace(/\n{3,}/g, "\n\n"));
117
+ }
118
+
119
+ // src/core/details.ts
120
+ import { format, parseISO } from "date-fns";
121
+ function detailFilename(dateInput) {
122
+ const date = dateInput ? parseISO(dateInput) : /* @__PURE__ */ new Date();
123
+ if (Number.isNaN(date.getTime())) {
124
+ throw new Error("Invalid date. Expected YYYY-MM-DD.");
125
+ }
126
+ return `L3_${format(date, "yyyy_MM")}.md`;
127
+ }
128
+ function detailHeader(dateInput) {
129
+ const date = dateInput ? parseISO(dateInput) : /* @__PURE__ */ new Date();
130
+ if (Number.isNaN(date.getTime())) {
131
+ throw new Error("Invalid date. Expected YYYY-MM-DD.");
132
+ }
133
+ return `# ${format(date, "MMMM yyyy")} Detailed Memory
134
+
135
+ `;
136
+ }
137
+ function detailLine(text, dateInput) {
138
+ const date = dateInput ? parseISO(dateInput) : /* @__PURE__ */ new Date();
139
+ if (Number.isNaN(date.getTime())) {
140
+ throw new Error("Invalid date. Expected YYYY-MM-DD.");
141
+ }
142
+ const clean = text.replace(/\s+/g, " ").trim();
143
+ if (!clean) {
144
+ throw new Error("Detail text must be non-empty.");
145
+ }
146
+ return `* [${format(date, "yyyy-MM-dd")}]: ${clean}`;
147
+ }
148
+
149
+ // src/core/lock.ts
150
+ import fs3 from "fs/promises";
151
+ import path4 from "path";
152
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
153
+ async function withLock(root, fn) {
154
+ const lockPath = path4.join(root, ".lock");
155
+ const start = Date.now();
156
+ let handle;
157
+ while (!handle) {
158
+ try {
159
+ await fs3.mkdir(root, { recursive: true });
160
+ handle = await fs3.open(lockPath, "wx");
161
+ } catch (error) {
162
+ const code = error.code;
163
+ if (code !== "EEXIST" || Date.now() - start > 5e3) {
164
+ throw error;
165
+ }
166
+ await sleep(50);
167
+ }
168
+ }
169
+ try {
170
+ return await fn();
171
+ } finally {
172
+ await handle.close();
173
+ await fs3.rm(lockPath, { force: true });
174
+ }
175
+ }
176
+
177
+ // src/tools/init.ts
178
+ import fs4 from "fs/promises";
179
+ import path5 from "path";
180
+
181
+ // src/core/instructions.ts
182
+ var CONTEXTLINE_INSTRUCTIONS_FILE = "contextline_instructions.md";
183
+ var DEFAULT_CONTEXTLINE_INSTRUCTIONS = `# ContextLine Instructions
184
+
185
+ CONTEXTLINE-INSTRUCTIONS-V1
186
+ This file contains generic operating instructions for ContextLine memory.
187
+ Use the single MCP tool named "contextline" for all ContextLine reads and writes.
188
+ Do not use shell commands to read or write .contextline files.
189
+ Do not mention memory saving unless the user asks.
190
+
191
+ ## Operating Policy
192
+
193
+ Use the single ContextLine MCP tool "contextline" silently for durable memory. Do not use shell commands to read or write .contextline files. Do not mention memory saving unless asked.
194
+
195
+ Durable memory means stable facts likely to help future sessions: user/project facts, preferences, goals, constraints, decisions, relationships, recurring patterns, and important events. Do not save filler, acknowledgements, or one-off chatter.
196
+
197
+ Do not save every message. Periodically batch-save useful durable memory since the last ContextLine save in this session.
198
+
199
+ Use ContextLine as a human-like cache:
200
+
201
+ - L1_Quick.md stores compact facts, summaries, and active pointers.
202
+ - L2_Deep/ stores deeper facts per important object, person, event, project, preference area, or decision thread.
203
+ - L3_Details/ stores timestamped specifics, receipts, and supporting history.
204
+
205
+ For V1, use flat L2 filenames with semantic prefixes instead of folders. Prefer names like person_user.md, project_contextline.md, area_work.md, place_san_jose.md, preference_media.md, preference_language.md, decision_memory_architecture.md, event_launch.md, or org_meta.md.
206
+
207
+ When saving durable memory, complete the full chain. Do not stop after writing L3_Details:
208
+
209
+ 1. Append one L3_Details receipt when supporting specifics are useful.
210
+ 2. Cross-save extracted meaning into every relevant L2_Deep file.
211
+ 3. Update L1_Quick only for compact high-level facts or active pointers.
212
+ 4. Link every L1 line to relevant L2 files.
213
+ 5. Link every L2 line to relevant L3 details when supporting detail exists.
214
+
215
+ Typical tool sequence:
216
+
217
+ Call "contextline" once with action "save_memory", including:
218
+
219
+ - detail.text for the L3_Details receipt
220
+ - deep[] entries for every relevant L2_Deep file, such as person_user.md, area_work.md, place_san_jose.md, or preference_media.md
221
+ - quick[] entries for compact L1_Quick facts linked to L2 files
222
+
223
+ If you write L3_Details but do not update L2_Deep and L1_Quick, the memory is incomplete. Prefer the bundled "save_memory" action so the full chain is saved together.
224
+ `;
225
+
226
+ // src/tools/init.ts
227
+ var DEFAULT_L1 = `# ContextLine L1 Index
228
+
229
+ This is the quick memory cache: compact facts, summaries, and active pointers.
230
+
231
+ ## Quick Facts
232
+
233
+ `;
234
+ async function initContextLine(root) {
235
+ const created = [];
236
+ await fs4.mkdir(root, { recursive: true });
237
+ for (const dir of [
238
+ L2_DIR,
239
+ L3_DIR,
240
+ "maintenance",
241
+ "maintenance/proposals"
242
+ ]) {
243
+ const target = safeJoin(root, ...dir.split("/"));
244
+ await fs4.mkdir(target, { recursive: true });
245
+ created.push(path5.relative(root, target));
246
+ }
247
+ const files = [
248
+ [L1_FILE, DEFAULT_L1],
249
+ [CONTEXTLINE_INSTRUCTIONS_FILE, DEFAULT_CONTEXTLINE_INSTRUCTIONS],
250
+ ["config.json", `${JSON.stringify({ version: 1, capture: { promotion: "selective" } }, null, 2)}
251
+ `]
252
+ ];
253
+ for (const [file, content] of files) {
254
+ const target = safeJoin(root, file);
255
+ try {
256
+ await fs4.writeFile(target, content, { encoding: "utf8", flag: "wx" });
257
+ created.push(path5.relative(root, target));
258
+ } catch (error) {
259
+ if (error.code !== "EEXIST") {
260
+ throw error;
261
+ }
262
+ }
263
+ }
264
+ return { ok: true, root, created };
265
+ }
266
+
267
+ // src/tools/appendFragment.ts
268
+ async function appendFragment(text, date, rootInput) {
269
+ const root = resolveRoot(rootInput);
270
+ await initContextLine(root);
271
+ return withLock(root, async () => {
272
+ const detail_file = detailFilename(date);
273
+ const filePath = detailPath(root, detail_file);
274
+ let content;
275
+ try {
276
+ content = await fs5.readFile(filePath, "utf8");
277
+ } catch (error) {
278
+ if (error.code !== "ENOENT") {
279
+ throw error;
280
+ }
281
+ content = detailHeader(date);
282
+ }
283
+ const fragment = detailLine(text, date);
284
+ await atomicWriteFile(filePath, `${ensureTrailingNewline(content)}${fragment}
285
+ `);
286
+ return {
287
+ ok: true,
288
+ detail_file,
289
+ fragment,
290
+ next_required_steps: [
291
+ "Call contextline with action save_memory to save L3, L2, and L1 together.",
292
+ "If manually continuing, call contextline action update_deep for every relevant L2_Deep file and action update_index for compact L1_Quick facts."
293
+ ],
294
+ display: `ContextLine L3 detail appended
295
+ - Detail file: ${detail_file}`
296
+ };
297
+ });
298
+ }
299
+
300
+ // src/tools/hydrate.ts
301
+ import fs6 from "fs/promises";
302
+ async function hydrate(rootInput) {
303
+ const root = resolveRoot(rootInput);
304
+ await initContextLine(root);
305
+ const l1_path = l1Path(root);
306
+ const instructions_path = safeJoin(root, CONTEXTLINE_INSTRUCTIONS_FILE);
307
+ const content = await fs6.readFile(l1_path, "utf8");
308
+ const instructions = await fs6.readFile(instructions_path, "utf8");
309
+ return {
310
+ ok: true,
311
+ root,
312
+ l1_path,
313
+ instructions_path,
314
+ content,
315
+ instructions,
316
+ instruction: "Use this L1 content as quick memory. Follow the included ContextLine instructions for reading and saving memory.",
317
+ display: `ContextLine hydrated
318
+ - Quick memory: ${l1_path}
319
+ - Instructions: ${instructions_path}`
320
+ };
321
+ }
322
+
323
+ // src/tools/inspect.ts
324
+ import fs7 from "fs/promises";
325
+ import path6 from "path";
326
+ async function countFiles(dir) {
327
+ try {
328
+ return (await fs7.readdir(dir)).length;
329
+ } catch {
330
+ return 0;
331
+ }
332
+ }
333
+ async function inspect(rootInput) {
334
+ const root = resolveRoot(rootInput);
335
+ return {
336
+ root,
337
+ l1: path6.join(root, L1_FILE),
338
+ l2_deep_files: await countFiles(safeJoin(root, L2_DIR)),
339
+ l3_detail_files: await countFiles(safeJoin(root, L3_DIR))
340
+ };
341
+ }
342
+
343
+ // src/core/topology.ts
344
+ import fs8 from "fs/promises";
345
+ import path7 from "path";
346
+
347
+ // src/core/links.ts
348
+ var WIKI_LINK_RE = /\[\[([^\]]+)\]\]/g;
349
+ function extractWikiLinks(content) {
350
+ return [...content.matchAll(WIKI_LINK_RE)].map((match) => match[1]);
351
+ }
352
+ function hasWikiLink(line, filename) {
353
+ return extractWikiLinks(line).includes(filename);
354
+ }
355
+ function ensureWikiLink(line, filename) {
356
+ return hasWikiLink(line, filename) ? line : `${line.trim()} [[${filename}]]`;
357
+ }
358
+
359
+ // src/core/topology.ts
360
+ async function exists(target) {
361
+ try {
362
+ await fs8.access(target);
363
+ return true;
364
+ } catch {
365
+ return false;
366
+ }
367
+ }
368
+ async function listMarkdown(dir) {
369
+ const out = [];
370
+ try {
371
+ const entries = await fs8.readdir(dir, { withFileTypes: true });
372
+ for (const entry of entries) {
373
+ const full = path7.join(dir, entry.name);
374
+ if (entry.isDirectory()) {
375
+ const nested = await listMarkdown(full);
376
+ out.push(...nested.map((file) => path7.join(entry.name, file)));
377
+ } else if (entry.name.endsWith(".md")) {
378
+ out.push(entry.name);
379
+ }
380
+ }
381
+ return out;
382
+ } catch {
383
+ return [];
384
+ }
385
+ }
386
+ async function validateTopology(root) {
387
+ const errors = [];
388
+ const warnings = [];
389
+ const l1 = l1Path(root);
390
+ const l2 = safeJoin(root, L2_DIR);
391
+ const l3 = safeJoin(root, L3_DIR);
392
+ if (!await exists(l1)) errors.push("L1_Quick.md is missing.");
393
+ if (!await exists(l2)) errors.push("L2_Deep directory is missing.");
394
+ if (!await exists(l3)) errors.push("L3_Details directory is missing.");
395
+ if (errors.length) return { ok: false, errors, warnings };
396
+ const l1Content = await fs8.readFile(l1, "utf8");
397
+ for (const link of extractWikiLinks(l1Content)) {
398
+ if (link.startsWith("L3_")) {
399
+ errors.push(`L1 must not link directly to L3 detail file: ${link}`);
400
+ } else if (!await exists(path7.join(l2, link))) {
401
+ errors.push(`L1 links to missing L2 deep memory file: ${link}`);
402
+ }
403
+ }
404
+ for (const file of await listMarkdown(l2)) {
405
+ const content = await fs8.readFile(path7.join(l2, file), "utf8");
406
+ for (const link of extractWikiLinks(content)) {
407
+ if (link === L1_FILE) {
408
+ errors.push(`L2 deep memory file ${file} must not link upward to L1_Quick.md.`);
409
+ } else if (!link.startsWith("L3_")) {
410
+ warnings.push(`L2 deep memory file ${file} links to non-L3 file: ${link}`);
411
+ } else if (!await exists(path7.join(l3, link))) {
412
+ errors.push(`L2 deep memory file ${file} links to missing L3 detail file: ${link}`);
413
+ }
414
+ }
415
+ }
416
+ for (const file of await listMarkdown(l3)) {
417
+ const content = await fs8.readFile(path7.join(l3, file), "utf8");
418
+ const links = extractWikiLinks(content);
419
+ if (links.length) {
420
+ errors.push(`L3 detail file ${file} must not contain wiki links.`);
421
+ }
422
+ }
423
+ return { ok: errors.length === 0, errors, warnings };
424
+ }
425
+
426
+ // src/tools/validateTopology.ts
427
+ async function validateTopology2(rootInput) {
428
+ const root = resolveRoot(rootInput);
429
+ await initContextLine(root);
430
+ const result = await validateTopology(root);
431
+ return {
432
+ ...result,
433
+ display: result.ok ? "ContextLine topology valid" : `ContextLine topology invalid
434
+ - Errors: ${result.errors.length}
435
+ - Warnings: ${result.warnings.length}`
436
+ };
437
+ }
438
+
439
+ // src/hook.ts
440
+ import path8 from "path";
441
+ async function readStdin() {
442
+ const chunks = [];
443
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
444
+ return Buffer.concat(chunks).toString("utf8");
445
+ }
446
+ async function runHook(rootInput) {
447
+ const raw = await readStdin();
448
+ const event = raw.trim() ? JSON.parse(raw) : {};
449
+ const root = rootInput ? path8.resolve(rootInput) : resolveRoot();
450
+ if (event.hook_event_name === "SessionStart") {
451
+ process.stdout.write(
452
+ JSON.stringify({
453
+ continue: true,
454
+ hookSpecificOutput: {
455
+ hookEventName: "SessionStart",
456
+ additionalContext: `ContextLine memory is available. Call the "contextline" MCP tool with action "hydrate" and root ${JSON.stringify(root)} to load your memory index. This reads only files inside the .contextline folder at that path \u2014 it does not scan or ingest the parent directory. Use that same root for all ContextLine calls this session, then follow the returned instructions.`
457
+ }
458
+ })
459
+ );
460
+ return;
461
+ }
462
+ }
463
+
464
+ // src/setup.ts
465
+ import { cwd } from "process";
466
+
467
+ // src/host/codex.ts
468
+ import fs9 from "fs/promises";
469
+ import path9 from "path";
470
+ import os from "os";
471
+ function contextlineMcpBlock(contextlineRoot) {
472
+ return `[mcp_servers.contextline]
473
+ type = "stdio"
474
+ command = "contextline-mcp"
475
+ args = []
476
+ env = { CONTEXTLINE_ROOT = ${JSON.stringify(contextlineRoot)} }
477
+ startup_timeout_sec = 10
478
+ tool_timeout_sec = 10
479
+ `;
480
+ }
481
+ async function upsertContextlineMcpConfig(configTomlPath, contextlineRoot) {
482
+ let existingConfig = "";
483
+ try {
484
+ existingConfig = await fs9.readFile(configTomlPath, "utf8");
485
+ } catch (error) {
486
+ if (error.code !== "ENOENT") throw error;
487
+ }
488
+ const withoutContextLine = existingConfig.replace(/\n?\[mcp_servers\.contextline\][\s\S]*?(?=\n\[|$)/, "").trim();
489
+ const mcpBlock = contextlineMcpBlock(contextlineRoot);
490
+ await fs9.writeFile(configTomlPath, `${withoutContextLine ? `${withoutContextLine}
491
+
492
+ ` : ""}${mcpBlock}
493
+ `, "utf8");
494
+ }
495
+ async function writeHookScript(scriptPath, contextlineRoot) {
496
+ const script = `#!/usr/bin/env node
497
+ import { spawnSync } from "node:child_process";
498
+ import fs from "node:fs";
499
+
500
+ const input = fs.readFileSync(0, "utf8");
501
+ const result = spawnSync("contextline", ["hook", "--root", ${JSON.stringify(contextlineRoot)}], {
502
+ input,
503
+ encoding: "utf8",
504
+ shell: process.platform === "win32"
505
+ });
506
+
507
+ if (result.stderr) process.stderr.write(result.stderr);
508
+ if (result.stdout) process.stdout.write(result.stdout);
509
+ process.exit(result.status ?? 0);
510
+ `;
511
+ await fs9.writeFile(scriptPath, script, "utf8");
512
+ }
513
+ async function upsertHooksJson(hooksJsonPath, hookScriptPath) {
514
+ let existing = {};
515
+ try {
516
+ const raw = await fs9.readFile(hooksJsonPath, "utf8");
517
+ existing = JSON.parse(raw);
518
+ } catch {
519
+ }
520
+ if (!existing.hooks || typeof existing.hooks !== "object") {
521
+ existing.hooks = {};
522
+ }
523
+ const hooks = existing.hooks;
524
+ const sessionStart = Array.isArray(hooks.SessionStart) ? hooks.SessionStart : [];
525
+ const filtered = sessionStart.filter((entry) => {
526
+ if (!entry || typeof entry !== "object") return true;
527
+ const e = entry;
528
+ return !e.hooks?.some((h) => h.command?.includes("contextline"));
529
+ });
530
+ const contextlineEntry = {
531
+ matcher: "startup|resume|clear|compact",
532
+ hooks: [{ type: "command", command: `node ${JSON.stringify(hookScriptPath)}` }]
533
+ };
534
+ hooks.SessionStart = [contextlineEntry, ...filtered];
535
+ await fs9.writeFile(hooksJsonPath, `${JSON.stringify(existing, null, 2)}
536
+ `, "utf8");
537
+ }
538
+ async function detectCodex(projectRoot) {
539
+ const details = [];
540
+ const candidates = [
541
+ path9.join(os.homedir(), ".codex"),
542
+ path9.join(projectRoot, ".codex"),
543
+ process.env.CODEX_HOME
544
+ ].filter(Boolean);
545
+ for (const candidate of candidates) {
546
+ try {
547
+ await fs9.access(candidate);
548
+ details.push(`found ${candidate}`);
549
+ } catch {
550
+ }
551
+ }
552
+ if (details.length) return { host: "codex", confidence: "high", details };
553
+ return { host: "none", confidence: "none", details: [] };
554
+ }
555
+ async function setupCodex(projectRoot, contextlineRoot) {
556
+ await initContextLine(contextlineRoot);
557
+ const codexDir = path9.join(projectRoot, ".codex");
558
+ const hooksDir = path9.join(codexDir, "hooks");
559
+ await fs9.mkdir(hooksDir, { recursive: true });
560
+ const hookScriptPath = path9.join(hooksDir, "contextline-hook.mjs");
561
+ await writeHookScript(hookScriptPath, contextlineRoot);
562
+ const hooksJsonPath = path9.join(codexDir, "hooks.json");
563
+ await upsertHooksJson(hooksJsonPath, hookScriptPath);
564
+ const configTomlPath = path9.join(codexDir, "config.toml");
565
+ await upsertContextlineMcpConfig(configTomlPath, contextlineRoot);
566
+ const globalCodexDir = process.env.CODEX_HOME ?? path9.join(os.homedir(), ".codex");
567
+ const globalHooksDir = path9.join(globalCodexDir, "hooks");
568
+ await fs9.mkdir(globalHooksDir, { recursive: true });
569
+ const globalHookScriptPath = path9.join(globalHooksDir, "contextline-hook.mjs");
570
+ await writeHookScript(globalHookScriptPath, contextlineRoot);
571
+ const globalHooksJsonPath = path9.join(globalCodexDir, "hooks.json");
572
+ await upsertHooksJson(globalHooksJsonPath, globalHookScriptPath);
573
+ const globalConfigTomlPath = path9.join(globalCodexDir, "config.toml");
574
+ if (path9.resolve(globalConfigTomlPath) !== path9.resolve(configTomlPath)) {
575
+ await upsertContextlineMcpConfig(globalConfigTomlPath, contextlineRoot);
576
+ }
577
+ const agentsPath = path9.join(projectRoot, "AGENTS.md");
578
+ try {
579
+ const existingAgents = await fs9.readFile(agentsPath, "utf8");
580
+ if (existingAgents.includes("# ContextLine Memory")) {
581
+ const cleanedAgents = existingAgents.slice(0, existingAgents.indexOf("# ContextLine Memory")).trim();
582
+ if (cleanedAgents) {
583
+ await fs9.writeFile(agentsPath, `${cleanedAgents}
584
+ `, "utf8");
585
+ } else {
586
+ await fs9.rm(agentsPath, { force: true });
587
+ }
588
+ }
589
+ } catch (error) {
590
+ if (error.code !== "ENOENT") throw error;
591
+ }
592
+ return { hooksJsonPath, hookScriptPath, configTomlPath, globalHooksJsonPath, globalHookScriptPath, globalConfigTomlPath };
593
+ }
594
+
595
+ // src/setup.ts
596
+ async function runSetup(options = {}) {
597
+ const projectRoot = cwd();
598
+ const root = getMemoryRoot();
599
+ const requestedHost = options.host ?? "auto";
600
+ let host = requestedHost;
601
+ let detectionDetails = [];
602
+ if (requestedHost === "auto") {
603
+ const detected = await detectCodex(projectRoot);
604
+ host = detected.host === "codex" ? "codex" : "none";
605
+ detectionDetails = detected.details;
606
+ }
607
+ await initContextLine(root);
608
+ let hostSetup = null;
609
+ if (host === "codex") {
610
+ hostSetup = await setupCodex(projectRoot, root);
611
+ }
612
+ const validation = await validateTopology2(root);
613
+ return {
614
+ ok: validation.ok,
615
+ root,
616
+ host,
617
+ detectionDetails,
618
+ hostSetup,
619
+ validation,
620
+ mcpConfig: {
621
+ mcpServers: {
622
+ contextline: {
623
+ command: "contextline-mcp",
624
+ args: [],
625
+ env: {
626
+ CONTEXTLINE_ROOT: root
627
+ }
628
+ }
629
+ }
630
+ }
631
+ };
632
+ }
633
+
634
+ // src/tools/updateDeepPointer.ts
635
+ import fs10 from "fs/promises";
636
+ import path10 from "path";
637
+ async function updateDeepPointer(file, factText, detailFile, rootInput) {
638
+ const root = resolveRoot(rootInput);
639
+ await initContextLine(root);
640
+ detailPath(root, detailFile);
641
+ return withLock(root, async () => {
642
+ const filePath = deepPath(root, file);
643
+ let content = "";
644
+ try {
645
+ content = await fs10.readFile(filePath, "utf8");
646
+ } catch (error) {
647
+ if (error.code !== "ENOENT") {
648
+ throw error;
649
+ }
650
+ content = `# ${path10.basename(file, ".md")}
651
+
652
+ `;
653
+ }
654
+ const updated_line = ensureWikiLink(factText, detailFile);
655
+ const next = upsertLineByPrefix(ensureTrailingNewline(content), factText.trim(), updated_line);
656
+ await atomicWriteFile(filePath, next);
657
+ return { ok: true, file, updated_line, display: `ContextLine L2 updated
658
+ - File: ${file}` };
659
+ });
660
+ }
661
+
662
+ // src/tools/updateIndexPointer.ts
663
+ import fs11 from "fs/promises";
664
+ async function updateIndexPointer(indexLine, files, rootInput) {
665
+ if (files.some((file) => file.startsWith("L3_"))) {
666
+ throw new Error("L1 quick memory pointers may only reference L2 deep memory files.");
667
+ }
668
+ const root = resolveRoot(rootInput);
669
+ await initContextLine(root);
670
+ for (const file of files) {
671
+ deepPath(root, file);
672
+ }
673
+ return withLock(root, async () => {
674
+ const filePath = l1Path(root);
675
+ const content = await fs11.readFile(filePath, "utf8");
676
+ const updated_line = files.reduce((line, file) => ensureWikiLink(line, file), indexLine);
677
+ const next = upsertLineByPrefix(ensureTrailingNewline(content), indexLine.trim(), updated_line);
678
+ await atomicWriteFile(filePath, next);
679
+ return { ok: true, updated_line, display: "ContextLine L1 updated" };
680
+ });
681
+ }
682
+
683
+ // src/cli.ts
684
+ function print(data) {
685
+ console.log(JSON.stringify(data, null, 2));
686
+ }
687
+ var program = new Command();
688
+ program.name("contextline").description("Local-first pointer-chain memory for AI agents.").version("0.1.0");
689
+ program.command("init").argument("[root]").description("Create a .contextline memory folder.").action(async (root) => print(await initContextLine(resolveRoot(root))));
690
+ program.command("hydrate").argument("[root]").description("Read L1_Quick.md as the bounded quick memory cache.").action(async (root) => print(await hydrate(root)));
691
+ program.command("validate").argument("[root]").description("Validate ContextLine topology.").action(async (root) => {
692
+ const result = await validateTopology2(root);
693
+ print(result);
694
+ if (!result.ok) process.exitCode = 1;
695
+ });
696
+ program.command("inspect").argument("[root]").description("Inspect ContextLine folder counts and paths.").action(async (root) => print(await inspect(root)));
697
+ program.command("append").argument("<text>").argument("[root]").option("--date <date>", "Date in YYYY-MM-DD format").description("Append an immutable L3 detail fragment.").action(async (text, root, options) => print(await appendFragment(text, options.date, root)));
698
+ program.command("update-deep").argument("<file>").argument("<fact-text>").argument("<detail-file>").argument("[root]").description("Update an L2 deep memory line with a pointer to an L3 detail file.").action(async (file, factText, detailFile, root) => print(await updateDeepPointer(file, factText, detailFile, root)));
699
+ program.command("update-index").argument("<index-line>").argument("<files...>").option("--root <root>", "Memory folder path").description("Update an L1 quick memory line with pointers to L2 deep memory files.").action(async (indexLine, files, options) => print(await updateIndexPointer(indexLine, files, options.root)));
700
+ program.command("setup").option("--host <host>", "Host adapter: auto, codex, none", "auto").option("--verbose", "Print full JSON result").description("Initialize memory and configure supported host integrations.").action(async (options) => {
701
+ const result = await runSetup(options);
702
+ if (options.verbose) {
703
+ print(result);
704
+ } else {
705
+ process.stdout.write(result.ok ? `ContextLine ready at ${result.root}
706
+ ` : `Setup failed.
707
+ `);
708
+ }
709
+ if (!result.ok) process.exitCode = 1;
710
+ });
711
+ program.command("hook").option("--root <root>", "Memory folder path").description("Run ContextLine host hook. Reads hook JSON from stdin.").action(async (options) => runHook(options.root));
712
+ program.parseAsync(process.argv).catch((error) => {
713
+ console.error(error instanceof Error ? error.message : error);
714
+ process.exit(1);
715
+ });
716
+ //# sourceMappingURL=cli.js.map