@outerlayer/cli 0.1.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +202 -0
  3. package/README.md +320 -0
  4. package/dist/build-info.json +1 -0
  5. package/dist/chunk-4H56Y7O6.js +589 -0
  6. package/dist/chunk-A3WLZX2F.js +120 -0
  7. package/dist/chunk-A6NNKRJU.js +650 -0
  8. package/dist/chunk-D77LS3UI.js +42 -0
  9. package/dist/chunk-DEDV5V4U.js +87324 -0
  10. package/dist/chunk-ECSYRPCC.js +334 -0
  11. package/dist/chunk-IWIUYLDR.js +472 -0
  12. package/dist/chunk-JJP7YLMN.js +25 -0
  13. package/dist/chunk-KFYJV2ZG.js +7978 -0
  14. package/dist/chunk-OZ7C3XUE.js +34 -0
  15. package/dist/chunk-RCQXYLMO.js +96 -0
  16. package/dist/chunk-TFUIDMOB.js +34 -0
  17. package/dist/chunk-VNVZDWO3.js +10 -0
  18. package/dist/chunk-VU34RWDU.js +339 -0
  19. package/dist/chunk-WQ6VGRGZ.js +150 -0
  20. package/dist/chunk-XN2XZFTK.js +165 -0
  21. package/dist/chunk-YMTXR7PJ.js +200 -0
  22. package/dist/chunk-YRYMNBGQ.js +54 -0
  23. package/dist/chunk-Z5GEFMRW.js +45 -0
  24. package/dist/chunk-ZJSNLVCE.js +58 -0
  25. package/dist/cli-3JYGL2OB.js +5311 -0
  26. package/dist/config-POF7DEQW.js +7 -0
  27. package/dist/context-materialize-J6CRQ7O7.js +589 -0
  28. package/dist/emit-artifact-cmd-23F4YKQ3.js +339 -0
  29. package/dist/emit-cmd-TWSYYEZI.js +208 -0
  30. package/dist/emit-commit-credit-cmd-2GX5M2BR.js +121 -0
  31. package/dist/emit-finding-cmd-6K7ERPKG.js +235 -0
  32. package/dist/emit-result-cmd-NDFHMJX7.js +225 -0
  33. package/dist/hook-fast-CBW4ZETX.js +8 -0
  34. package/dist/hook-wrap-fast-36WGE6EX.js +8 -0
  35. package/dist/import-capture-cmd-EUMBGIV3.js +176 -0
  36. package/dist/import-ruler-cmd-7LH2QOMG.js +173 -0
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.js +25 -0
  39. package/dist/init-PTBITAUO.js +103 -0
  40. package/dist/login-cmd-IRX6LZT7.js +62 -0
  41. package/dist/logs-TRNPQM42.js +63 -0
  42. package/dist/loop-NFSOBUUJ.js +646 -0
  43. package/dist/mcp-install-cmd-FDQH6SEN.js +75 -0
  44. package/dist/mcp-serve-cmd-57EZZOTL.js +123 -0
  45. package/dist/paths-D2VGWWFI.js +6 -0
  46. package/dist/pidfile-PTW76F56.js +8 -0
  47. package/dist/status-WGOJTXZF.js +94 -0
  48. package/dist/statusline-fast-Z5U5CEC6.js +8 -0
  49. package/dist/sync-cmd-C5UGI4SF.js +15 -0
  50. package/dist/watch-V3K4PESQ.js +70 -0
  51. package/dist/work-claim-cmd-FQDWQVT2.js +98 -0
  52. package/dist/work-cmd-CW26EZZO.js +16 -0
  53. package/dist/work-launch-YNNCKIH3.js +6 -0
  54. package/dist/work-pr-cmd-W2QNMWXP.js +115 -0
  55. package/package.json +58 -0
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+ import { decodeWrappedCommand } from './chunk-ECSYRPCC.js';
4
+ import { homeFromEnv } from './chunk-VNVZDWO3.js';
5
+ import { readFileSync } from 'fs';
6
+ import { spawn } from 'child_process';
7
+ import { join } from 'path';
8
+
9
+ createRequire(import.meta.url);
10
+ var STATE_FRESH_MS = 15 * 60 * 1e3;
11
+ var WRAP_TIMEOUT_MS = 750;
12
+ function statuslineStatePath(home = homeFromEnv()) {
13
+ return join(home, ".outerlayer", "statusline.json");
14
+ }
15
+ var DIM = "\x1B[2m";
16
+ var RESET = "\x1B[0m";
17
+ function dim(s) {
18
+ return `${DIM}${s}${RESET}`;
19
+ }
20
+ function localDateString(ms) {
21
+ const d = new Date(ms);
22
+ const pad = (n) => String(n).padStart(2, "0");
23
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
24
+ }
25
+ function fmtUsd(n) {
26
+ if (n >= 100) return `$${Math.round(n).toLocaleString("en-US")}`;
27
+ return `$${n.toFixed(2)}`;
28
+ }
29
+ function parseStatuslineStdin(text) {
30
+ try {
31
+ const parsed = text ? JSON.parse(text) : {};
32
+ return parsed && typeof parsed === "object" ? parsed : {};
33
+ } catch {
34
+ return {};
35
+ }
36
+ }
37
+ function readStatuslineState(home = homeFromEnv()) {
38
+ try {
39
+ const parsed = JSON.parse(readFileSync(statuslineStatePath(home), "utf8"));
40
+ if (!parsed || parsed.v !== 1 || typeof parsed.generatedAt !== "string") return null;
41
+ if (!parsed.today || typeof parsed.today.date !== "string" || typeof parsed.today.byAgent !== "object") return null;
42
+ return parsed;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+ function stateFresh(state, now) {
48
+ const generated = Date.parse(state.generatedAt);
49
+ return Number.isFinite(generated) && now - generated <= STATE_FRESH_MS;
50
+ }
51
+ function renderStatusline(stdin, state, now) {
52
+ const segments = [];
53
+ const sessionCost = stdin.cost?.total_cost_usd;
54
+ if (Number.isFinite(sessionCost)) {
55
+ segments.push(`${fmtUsd(sessionCost)} session`);
56
+ }
57
+ const fresh = state !== null && stateFresh(state, now);
58
+ if (fresh && state.today.date === localDateString(now)) {
59
+ const costs = Object.values(state.today.byAgent).filter((c) => typeof c === "number" && c > 0);
60
+ if (costs.length > 0) {
61
+ const total = costs.reduce((sum, c) => sum + c, 0);
62
+ const sessionCount = state.today.sessionCount;
63
+ const scope = costs.length >= 2 ? ` across ${costs.length} agents` : typeof sessionCount === "number" && sessionCount >= 2 ? ` across ${sessionCount} sessions` : "";
64
+ segments.push(`${fmtUsd(total)} today${scope}`);
65
+ }
66
+ }
67
+ if (fresh && typeof state.unsynced === "number" && state.unsynced > 0) {
68
+ segments.push(`${state.unsynced} unsynced`);
69
+ }
70
+ if (!fresh) {
71
+ segments.push(dim("outerlayer doctor"));
72
+ }
73
+ const prefix = "\u2B22 OL";
74
+ return segments.length === 0 ? prefix : `${prefix} ${segments.join(dim(" \xB7 "))}`;
75
+ }
76
+ var readStdin = () => {
77
+ try {
78
+ if (process.stdin.isTTY) return "";
79
+ return readFileSync(0, "utf8");
80
+ } catch {
81
+ return "";
82
+ }
83
+ };
84
+ var spawnWrapped = (command, args) => spawn(command, args, { stdio: ["pipe", "pipe", "ignore"] });
85
+ function runWrappedStatusline(original, stdinText, opts = {}) {
86
+ const spawnImpl = opts.spawnImpl ?? spawnWrapped;
87
+ const timeoutMs = opts.timeoutMs ?? WRAP_TIMEOUT_MS;
88
+ return new Promise((resolve) => {
89
+ let child;
90
+ try {
91
+ child = spawnImpl("/bin/sh", ["-c", original]);
92
+ } catch {
93
+ resolve(null);
94
+ return;
95
+ }
96
+ let out = "";
97
+ let done = false;
98
+ const finish = (value) => {
99
+ if (done) return;
100
+ done = true;
101
+ clearTimeout(timer);
102
+ resolve(value);
103
+ };
104
+ const timer = setTimeout(() => {
105
+ try {
106
+ child.kill("SIGKILL");
107
+ } catch {
108
+ }
109
+ finish(null);
110
+ }, timeoutMs);
111
+ try {
112
+ child.stdout?.on("data", (chunk) => {
113
+ out += chunk.toString("utf8");
114
+ });
115
+ child.stdin?.on("error", () => {
116
+ });
117
+ child.stdin?.write(stdinText);
118
+ child.stdin?.end();
119
+ } catch {
120
+ }
121
+ child.on("error", () => finish(null));
122
+ child.on("close", (code) => finish(code === 0 ? out : null));
123
+ });
124
+ }
125
+ function parseStatuslineArgs(args) {
126
+ const idx = args.indexOf("--wrap-id");
127
+ return idx === -1 ? {} : { wrapId: args[idx + 1] };
128
+ }
129
+ async function runStatuslineFast(args, opts = {}) {
130
+ const write = opts.write ?? ((s) => process.stdout.write(s));
131
+ try {
132
+ const home = opts.home ?? homeFromEnv();
133
+ const now = (opts.now ?? Date.now)();
134
+ const stdinText = (opts.read ?? readStdin)();
135
+ const stdin = parseStatuslineStdin(stdinText);
136
+ const state = readStatuslineState(home);
137
+ const ourLine = renderStatusline(stdin, state, now);
138
+ const { wrapId } = parseStatuslineArgs(args);
139
+ if (wrapId) {
140
+ let original = null;
141
+ try {
142
+ original = decodeWrappedCommand(wrapId);
143
+ } catch {
144
+ original = null;
145
+ }
146
+ if (original) {
147
+ const theirOutput = await runWrappedStatusline(original, stdinText, {
148
+ spawnImpl: opts.spawnImpl,
149
+ timeoutMs: opts.wrapTimeoutMs
150
+ });
151
+ if (theirOutput !== null && theirOutput.length > 0) {
152
+ write(theirOutput.replace(/\n$/, "") + "\n");
153
+ }
154
+ }
155
+ }
156
+ write(ourLine + "\n");
157
+ } catch {
158
+ try {
159
+ write("\u2B22 OL\n");
160
+ } catch {
161
+ }
162
+ }
163
+ }
164
+
165
+ export { STATE_FRESH_MS, WRAP_TIMEOUT_MS, localDateString, parseStatuslineArgs, parseStatuslineStdin, readStatuslineState, renderStatusline, runStatuslineFast, runWrappedStatusline, statuslineStatePath };
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+ import { decodeWrappedCommand } from './chunk-ECSYRPCC.js';
4
+ import { homeFromEnv } from './chunk-VNVZDWO3.js';
5
+ import { readFileSync, mkdirSync, appendFileSync, writeFileSync } from 'fs';
6
+ import { spawn } from 'child_process';
7
+ import { randomUUID, createHash } from 'crypto';
8
+ import { join } from 'path';
9
+
10
+ createRequire(import.meta.url);
11
+ function spoolDir(home = homeFromEnv()) {
12
+ return join(home, ".outerlayer", "spool");
13
+ }
14
+ function hookExecSpoolPath(home = homeFromEnv()) {
15
+ return join(spoolDir(home), "hook-exec.jsonl");
16
+ }
17
+ var MAX_CMD_LEN = 300;
18
+ var MAX_TAIL_BYTES = 4096;
19
+ var readStdin = () => {
20
+ try {
21
+ return readFileSync(0);
22
+ } catch {
23
+ return Buffer.alloc(0);
24
+ }
25
+ };
26
+ function hookWrapStdio(captureOutput) {
27
+ return captureOutput ? ["pipe", "pipe", "pipe"] : ["pipe", "inherit", "inherit"];
28
+ }
29
+ var spawnChild = (command, args, stdio) => spawn(command, args, { stdio });
30
+ function makeSpoolWriter(home) {
31
+ return (record) => {
32
+ try {
33
+ mkdirSync(spoolDir(home), { recursive: true });
34
+ appendFileSync(hookExecSpoolPath(home), JSON.stringify(record) + "\n");
35
+ } catch {
36
+ }
37
+ };
38
+ }
39
+ function logError(home, err) {
40
+ try {
41
+ mkdirSync(spoolDir(home), { recursive: true });
42
+ writeFileSync(
43
+ join(spoolDir(home), "hook-errors.log"),
44
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${err instanceof Error ? err.message : String(err)}
45
+ `,
46
+ { flag: "a" }
47
+ );
48
+ } catch {
49
+ }
50
+ }
51
+ function parsePayload(bytes) {
52
+ try {
53
+ if (bytes.length === 0) return {};
54
+ return JSON.parse(bytes.toString("utf8"));
55
+ } catch {
56
+ return {};
57
+ }
58
+ }
59
+ function makeTailCollector(max = MAX_TAIL_BYTES) {
60
+ let buf = Buffer.alloc(0);
61
+ return {
62
+ push(chunk) {
63
+ buf = Buffer.concat([buf, chunk]);
64
+ if (buf.length > max) buf = buf.subarray(buf.length - max);
65
+ },
66
+ value: () => buf.toString("utf8")
67
+ };
68
+ }
69
+ var ABORT_SIGNALS = ["SIGTERM", "SIGINT"];
70
+ function installAbortForwarding(child, spool, execId, startedAt, now, proc) {
71
+ const handlers = [];
72
+ const cleanup = () => {
73
+ for (const [sig, handler] of handlers) proc.removeListener(sig, handler);
74
+ };
75
+ for (const sig of ABORT_SIGNALS) {
76
+ const handler = (signal) => {
77
+ cleanup();
78
+ try {
79
+ child.kill(signal);
80
+ } catch {
81
+ }
82
+ try {
83
+ spool({ rec: "aborted", execId, durationMs: now() - startedAt, signal });
84
+ } catch {
85
+ }
86
+ try {
87
+ proc.kill(proc.pid, signal);
88
+ } catch {
89
+ }
90
+ };
91
+ handlers.push([sig, handler]);
92
+ proc.once(sig, handler);
93
+ }
94
+ return cleanup;
95
+ }
96
+ function parseHookWrapArgs(args) {
97
+ let id;
98
+ let captureOutput = false;
99
+ for (let i = 0; i < args.length; i++) {
100
+ if (args[i] === "--id") id = args[++i];
101
+ else if (args[i] === "--capture-output") captureOutput = true;
102
+ }
103
+ return { id, captureOutput };
104
+ }
105
+ async function runHookWrapFast(id, opts = {}) {
106
+ const home = opts.home ?? homeFromEnv();
107
+ const read = opts.read ?? readStdin;
108
+ const spawnImpl = opts.spawnImpl ?? spawnChild;
109
+ const spool = opts.spool ?? makeSpoolWriter(home);
110
+ const now = opts.now ?? Date.now;
111
+ const captureOutput = opts.captureOutput ?? false;
112
+ const proc = opts.proc ?? process;
113
+ if (!id) {
114
+ logError(home, new Error("hook-wrap: missing --id"));
115
+ return 0;
116
+ }
117
+ let original;
118
+ try {
119
+ original = decodeWrappedCommand(id);
120
+ } catch (err) {
121
+ logError(home, err);
122
+ return 0;
123
+ }
124
+ let stdinBytes;
125
+ try {
126
+ stdinBytes = read();
127
+ } catch {
128
+ stdinBytes = Buffer.alloc(0);
129
+ }
130
+ const payload = parsePayload(stdinBytes);
131
+ const execId = randomUUID();
132
+ const startedAt = now();
133
+ try {
134
+ spool({
135
+ rec: "started",
136
+ execId,
137
+ t: new Date(startedAt).toISOString(),
138
+ sessionId: payload.session_id ?? null,
139
+ hookEvent: payload.hook_event_name ?? null,
140
+ toolUseId: payload.tool_use_id ?? null,
141
+ // Costs a few bytes; makes an orphaned started-only record
142
+ // self-describing ("PostToolUse Edit hung" vs. a bare uuid).
143
+ toolName: payload.tool_name ?? null,
144
+ cmdSha: createHash("sha256").update(original).digest("hex"),
145
+ cmd: original.slice(0, MAX_CMD_LEN),
146
+ pid: process.pid
147
+ });
148
+ } catch {
149
+ }
150
+ let child;
151
+ try {
152
+ child = spawnImpl("/bin/sh", ["-c", original], hookWrapStdio(captureOutput));
153
+ } catch (err) {
154
+ logError(home, err);
155
+ return 0;
156
+ }
157
+ try {
158
+ child.stdin?.on("error", () => {
159
+ });
160
+ child.stdin?.write(stdinBytes);
161
+ child.stdin?.end();
162
+ } catch {
163
+ }
164
+ const stdoutTail = makeTailCollector();
165
+ const stderrTail = makeTailCollector();
166
+ if (captureOutput) {
167
+ try {
168
+ child.stdout?.on("data", (chunk) => stdoutTail.push(chunk));
169
+ child.stderr?.on("data", (chunk) => stderrTail.push(chunk));
170
+ } catch {
171
+ }
172
+ }
173
+ let stopAbortForwarding = () => {
174
+ };
175
+ try {
176
+ stopAbortForwarding = installAbortForwarding(child, spool, execId, startedAt, now, proc);
177
+ } catch {
178
+ }
179
+ const { exitCode, signal } = await new Promise(
180
+ (resolve) => {
181
+ child.on("close", (code, sig) => resolve({ exitCode: code, signal: sig }));
182
+ child.on("error", () => resolve({ exitCode: null, signal: null }));
183
+ }
184
+ );
185
+ stopAbortForwarding();
186
+ try {
187
+ spool({
188
+ rec: "finished",
189
+ execId,
190
+ durationMs: now() - startedAt,
191
+ exitCode,
192
+ signal: signal ?? void 0,
193
+ ...captureOutput ? { stdoutTail: stdoutTail.value(), stderrTail: stderrTail.value() } : {}
194
+ });
195
+ } catch {
196
+ }
197
+ return exitCode ?? 1;
198
+ }
199
+
200
+ export { hookExecSpoolPath, hookWrapStdio, installAbortForwarding, makeTailCollector, parseHookWrapArgs, runHookWrapFast, spoolDir };
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+
4
+ createRequire(import.meta.url);
5
+
6
+ // src/output.ts
7
+ var NO_COLOR_FLAG = "--no-color";
8
+ var CODES = {
9
+ green: "\x1B[32m",
10
+ yellow: "\x1B[33m",
11
+ red: "\x1B[31m",
12
+ dim: "\x1B[2m",
13
+ reset: "\x1B[0m"
14
+ };
15
+ function colorEnabled(input = {}) {
16
+ const env = input.env ?? process.env;
17
+ const argv = input.argv ?? process.argv;
18
+ if (argv.includes(NO_COLOR_FLAG)) return false;
19
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
20
+ if (env.FORCE_COLOR !== void 0 && env.FORCE_COLOR !== "" && env.FORCE_COLOR !== "0") return true;
21
+ if (env.TERM === "dumb") return false;
22
+ return Boolean((input.stream ?? process.stdout).isTTY);
23
+ }
24
+ function palette(enabled) {
25
+ return enabled ? CODES : { green: "", yellow: "", red: "", dim: "", reset: "" };
26
+ }
27
+ var C = {
28
+ get green() {
29
+ return palette(colorEnabled()).green;
30
+ },
31
+ get yellow() {
32
+ return palette(colorEnabled()).yellow;
33
+ },
34
+ get red() {
35
+ return palette(colorEnabled()).red;
36
+ },
37
+ get dim() {
38
+ return palette(colorEnabled()).dim;
39
+ },
40
+ get reset() {
41
+ return palette(colorEnabled()).reset;
42
+ }
43
+ };
44
+ function stripNoColor(argv) {
45
+ const noColor = argv.includes(NO_COLOR_FLAG);
46
+ return { argv: noColor ? argv.filter((a) => a !== NO_COLOR_FLAG) : argv, noColor };
47
+ }
48
+ function warnDeprecated(message) {
49
+ process.stderr.write(`${C.yellow}!${C.reset} ${message}
50
+ `);
51
+ }
52
+ var API_KEY_FLAG_DEPRECATION = "--api-key is deprecated: a key on the command line lands in shell history and process lists. Run `outerlayer login` once, or set OUTERLAYER_API_KEY.";
53
+
54
+ export { API_KEY_FLAG_DEPRECATION, C, NO_COLOR_FLAG, stripNoColor, warnDeprecated };
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+
4
+ const require$1 = createRequire(import.meta.url);
5
+ var __create = Object.create;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __require = /* @__PURE__ */ ((x) => typeof require$1 !== "undefined" ? require$1 : typeof Proxy !== "undefined" ? new Proxy(x, {
12
+ get: (a, b) => (typeof require$1 !== "undefined" ? require$1 : a)[b]
13
+ }) : x)(function(x) {
14
+ if (typeof require$1 !== "undefined") return require$1.apply(this, arguments);
15
+ throw Error('Dynamic require of "' + x + '" is not supported');
16
+ });
17
+ var __commonJS = (cb, mod) => function __require2() {
18
+ try {
19
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
20
+ } catch (e) {
21
+ throw mod = 0, e;
22
+ }
23
+ };
24
+ var __export = (target, all) => {
25
+ for (var name in all)
26
+ __defProp(target, name, { get: all[name], enumerable: true });
27
+ };
28
+ var __copyProps = (to, from, except, desc) => {
29
+ if (from && typeof from === "object" || typeof from === "function") {
30
+ for (let key of __getOwnPropNames(from))
31
+ if (!__hasOwnProp.call(to, key) && key !== except)
32
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
+ }
34
+ return to;
35
+ };
36
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
37
+ // If the importer is in node compatibility mode or this is not an ESM
38
+ // file that has been converted to a CommonJS file using a Babel-
39
+ // compatible transform (i.e. "__esModule" has not been set), then set
40
+ // "default" to the CommonJS "module.exports" for node compatibility.
41
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
42
+ mod
43
+ ));
44
+
45
+ export { __commonJS, __export, __require, __toESM };
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+ import { homeFromEnv } from './chunk-VNVZDWO3.js';
4
+ import { mkdirSync, statSync, renameSync, appendFileSync, readFileSync } from 'fs';
5
+ import { dirname, join } from 'path';
6
+
7
+ createRequire(import.meta.url);
8
+ function contextProvenancePath(home = homeFromEnv()) {
9
+ return join(home, ".outerlayer", "spool", "context-source.jsonl");
10
+ }
11
+ var MAX_BYTES = 1024 * 1024;
12
+ function appendContextProvenance(record, home = homeFromEnv()) {
13
+ const path = contextProvenancePath(home);
14
+ mkdirSync(dirname(path), { recursive: true });
15
+ try {
16
+ if (statSync(path).size > MAX_BYTES) {
17
+ renameSync(path, `${path}.1`);
18
+ }
19
+ } catch {
20
+ }
21
+ appendFileSync(path, JSON.stringify(record) + "\n");
22
+ }
23
+ function parseLine(text) {
24
+ try {
25
+ const parsed = JSON.parse(text);
26
+ if (typeof parsed.sessionId === "string" && typeof parsed.repoRoot === "string" && typeof parsed.t === "string" && (parsed.verification === "verified" || parsed.verification === "unverified" || parsed.verification === "none") && (typeof parsed.sha === "string" || parsed.sha === null)) {
27
+ return parsed;
28
+ }
29
+ return void 0;
30
+ } catch {
31
+ return void 0;
32
+ }
33
+ }
34
+ function readContextProvenance(home = homeFromEnv()) {
35
+ let raw;
36
+ try {
37
+ raw = readFileSync(contextProvenancePath(home), "utf8");
38
+ } catch {
39
+ return [];
40
+ }
41
+ const records = [];
42
+ for (const line of raw.split("\n")) {
43
+ const trimmed = line.trim();
44
+ if (!trimmed) continue;
45
+ const record = parseLine(trimmed);
46
+ if (record) records.push(record);
47
+ }
48
+ return records;
49
+ }
50
+ function readLatestProvenanceForSession(sessionId, home = homeFromEnv()) {
51
+ const records = readContextProvenance(home);
52
+ for (let i = records.length - 1; i >= 0; i--) {
53
+ if (records[i].sessionId === sessionId) return records[i];
54
+ }
55
+ return void 0;
56
+ }
57
+
58
+ export { appendContextProvenance, readContextProvenance, readLatestProvenanceForSession };