@letra-ai/cli 0.5.3 → 0.6.2

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 (98) hide show
  1. package/dist/chunk-6HSUVCTR.js +363 -0
  2. package/dist/chunk-BKAUN5QH.js +300 -0
  3. package/dist/chunk-DMOLJWWW.js +3321 -0
  4. package/dist/chunk-EDD55PWL.js +119 -0
  5. package/dist/chunk-H64RC3YS.js +254 -0
  6. package/dist/chunk-JMIC5NKB.js +235 -0
  7. package/dist/chunk-L6YKDTAQ.js +275 -0
  8. package/dist/chunk-MJ2QXNH6.js +130 -0
  9. package/dist/chunk-OIHMDOIN.js +1326 -0
  10. package/dist/chunk-PDX44BCA.js +11 -0
  11. package/dist/chunk-URUC6ZZP.js +4781 -0
  12. package/dist/client/assets/index-EyRsq1SH.css +1 -0
  13. package/dist/client/assets/index-WfKR7Xp6.js +232 -0
  14. package/dist/client/favicon.svg +16 -4
  15. package/dist/client/index.html +25 -20
  16. package/dist/fallback-MQLGS4KL.js +46 -0
  17. package/dist/flow-serve-G5MSSB3G.js +18 -0
  18. package/dist/focus-sync-3D3XWCTI.js +17 -0
  19. package/dist/generate-UPFERQMD.js +20 -0
  20. package/dist/harness/default/v0.1.0/flows/sdlc.yaml +179 -0
  21. package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +8 -0
  22. package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +7 -0
  23. package/dist/harness/default/v0.1.0/gates/human-approved-code.yaml +8 -0
  24. package/dist/harness/default/v0.1.0/gates/human-approved-spec.yaml +8 -0
  25. package/dist/harness/default/v0.1.0/gates/security-clear.yaml +8 -0
  26. package/dist/harness/default/v0.1.0/policies/sdlc-default.json +20 -0
  27. package/dist/harness/default/v0.1.0/roles/analyst.yaml +9 -0
  28. package/dist/harness/default/v0.1.0/roles/builder.yaml +9 -0
  29. package/dist/harness/default/v0.1.0/roles/pr-bot.yaml +8 -0
  30. package/dist/harness/default/v0.1.0/roles/reviewer.yaml +10 -0
  31. package/dist/harness/default/v0.1.0/roles/security.yaml +8 -0
  32. package/dist/harness/default/v0.1.1/flows/flow-main.yaml +61 -0
  33. package/dist/harness/default/v0.1.1/flows/sdlc.yaml +179 -0
  34. package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +8 -0
  35. package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +7 -0
  36. package/dist/harness/default/v0.1.1/gates/human-approved-code.yaml +8 -0
  37. package/dist/harness/default/v0.1.1/gates/human-approved-spec.yaml +8 -0
  38. package/dist/harness/default/v0.1.1/gates/security-clear.yaml +8 -0
  39. package/dist/harness/default/v0.1.1/policies/sdlc-default.json +20 -0
  40. package/dist/harness/default/v0.1.1/roles/analyst.yaml +9 -0
  41. package/dist/harness/default/v0.1.1/roles/builder.yaml +9 -0
  42. package/dist/harness/default/v0.1.1/roles/pr-bot.yaml +8 -0
  43. package/dist/harness/default/v0.1.1/roles/reviewer.yaml +10 -0
  44. package/dist/harness/default/v0.1.1/roles/security.yaml +8 -0
  45. package/dist/harness/default/v0.1.2/flows/flow-main.yaml +86 -0
  46. package/dist/harness/default/v0.1.2/flows/sdlc.yaml +179 -0
  47. package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +8 -0
  48. package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +7 -0
  49. package/dist/harness/default/v0.1.2/gates/human-approved-code.yaml +8 -0
  50. package/dist/harness/default/v0.1.2/gates/human-approved-spec.yaml +8 -0
  51. package/dist/harness/default/v0.1.2/gates/security-clear.yaml +8 -0
  52. package/dist/harness/default/v0.1.2/policies/sdlc-default.json +20 -0
  53. package/dist/harness/default/v0.1.2/roles/analyst.yaml +9 -0
  54. package/dist/harness/default/v0.1.2/roles/builder.yaml +9 -0
  55. package/dist/harness/default/v0.1.2/roles/pr-bot.yaml +8 -0
  56. package/dist/harness/default/v0.1.2/roles/reviewer.yaml +10 -0
  57. package/dist/harness/default/v0.1.2/roles/security.yaml +8 -0
  58. package/dist/harness/default/v0.1.3/flows/flow-main.yaml +90 -0
  59. package/dist/harness/default/v0.1.3/flows/sdlc.yaml +179 -0
  60. package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +8 -0
  61. package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +7 -0
  62. package/dist/harness/default/v0.1.3/gates/human-approved-code.yaml +9 -0
  63. package/dist/harness/default/v0.1.3/gates/human-approved-spec.yaml +9 -0
  64. package/dist/harness/default/v0.1.3/gates/security-clear.yaml +8 -0
  65. package/dist/harness/default/v0.1.3/policies/sdlc-default.json +20 -0
  66. package/dist/harness/default/v0.1.3/roles/analyst.yaml +9 -0
  67. package/dist/harness/default/v0.1.3/roles/builder.yaml +9 -0
  68. package/dist/harness/default/v0.1.3/roles/pr-bot.yaml +8 -0
  69. package/dist/harness/default/v0.1.3/roles/reviewer.yaml +10 -0
  70. package/dist/harness/default/v0.1.3/roles/security.yaml +8 -0
  71. package/dist/harness/default/v0.2.0/executors/registry.yaml +51 -0
  72. package/dist/harness/default/v0.2.0/flows/flow-main.yaml +249 -0
  73. package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +7 -0
  74. package/dist/harness/default/v0.2.0/gates/human-approved.yaml +10 -0
  75. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +7 -0
  76. package/dist/harness/default/v0.2.0/gates/spec-approved.yaml +10 -0
  77. package/dist/harness/default/v0.2.0/policies/sdlc-default.json +20 -0
  78. package/dist/harness/default/v0.2.0/roles/analyst.yaml +16 -0
  79. package/dist/harness/default/v0.2.0/roles/implementer.yaml +17 -0
  80. package/dist/harness/default/v0.2.0/roles/reviewer.yaml +17 -0
  81. package/dist/harness/default/v0.2.0/roles/security.yaml +17 -0
  82. package/dist/health-record-YDVXEVLR.js +21 -0
  83. package/dist/index.js +1951 -2530
  84. package/dist/init-wizard-NODBBNKO.js +178 -0
  85. package/dist/push-VJRSQGUD.js +116 -0
  86. package/dist/registry-6VPIA3EG.js +18 -0
  87. package/dist/server-P6GKRWDX.js +423 -0
  88. package/dist/service-2JN2KI4D.js +29 -0
  89. package/dist/session-log-WTQ5JBEN.js +21 -0
  90. package/dist/sitrep-OKNZJICV.js +16 -0
  91. package/package.json +37 -28
  92. package/dist/chunk-56GTTLC4.js +0 -1322
  93. package/dist/chunk-QWT5M4XU.js +0 -643
  94. package/dist/client/assets/index-CuLfFw4K.js +0 -85
  95. package/dist/client/assets/index-iyLqZcWx.css +0 -1
  96. package/dist/generate-BF5R5GGA.js +0 -7
  97. package/dist/sitrep-SI6ZFIAM.js +0 -10
  98. package/tsup.config.ts +0 -11
@@ -0,0 +1,363 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/workspace/index.ts
4
+ import {
5
+ existsSync,
6
+ mkdirSync,
7
+ readdirSync,
8
+ copyFileSync,
9
+ writeFileSync,
10
+ readFileSync
11
+ } from "fs";
12
+ import { join } from "path";
13
+ import { homedir } from "os";
14
+ import { fileURLToPath } from "url";
15
+ import crypto from "crypto";
16
+ function getLetraDir() {
17
+ return join(homedir(), ".letra");
18
+ }
19
+ function getWorkspacesDir() {
20
+ return join(getLetraDir(), "workspaces");
21
+ }
22
+ function getHarnessDir() {
23
+ return join(getLetraDir(), "harness");
24
+ }
25
+ function getWorkspacePath(name) {
26
+ return join(getWorkspacesDir(), name);
27
+ }
28
+ var CANONICAL_WORKSPACE_DIRS = [
29
+ "harness",
30
+ "specs",
31
+ "decisions",
32
+ "memories",
33
+ "adapters",
34
+ "operations",
35
+ "session-log",
36
+ "reports",
37
+ "cache"
38
+ ];
39
+ var CANONICAL_WORKSPACE_FILES = [
40
+ "workflow.json",
41
+ "workspace.json",
42
+ "context.md",
43
+ "focus.md",
44
+ "constitution.md",
45
+ "constraints.md",
46
+ "glossary.md"
47
+ ];
48
+ function ensureLetraDirs() {
49
+ mkdirSync(getWorkspacesDir(), { recursive: true });
50
+ mkdirSync(getHarnessDir(), { recursive: true });
51
+ }
52
+ function copyDir(src, dest) {
53
+ mkdirSync(dest, { recursive: true });
54
+ for (const entry of readdirSync(src, { withFileTypes: true })) {
55
+ const s = join(src, entry.name);
56
+ const d = join(dest, entry.name);
57
+ if (entry.isDirectory()) {
58
+ copyDir(s, d);
59
+ } else {
60
+ copyFileSync(s, d);
61
+ }
62
+ }
63
+ }
64
+ function slugifyWorkspaceName(input) {
65
+ return input.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "workspace";
66
+ }
67
+ function ensureExternalWorkspaceLayout(workspaceDir, defaults) {
68
+ mkdirSync(workspaceDir, { recursive: true });
69
+ for (const dir of CANONICAL_WORKSPACE_DIRS) {
70
+ mkdirSync(join(workspaceDir, dir), { recursive: true });
71
+ }
72
+ const fallbackFiles = {
73
+ "workflow.json": JSON.stringify(
74
+ defaults?.workflow ?? {
75
+ version: "1.0",
76
+ name: "Workspace",
77
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
78
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
79
+ stages: [],
80
+ items: [],
81
+ tools: []
82
+ },
83
+ null,
84
+ 2
85
+ ),
86
+ "workspace.json": JSON.stringify(defaults?.workspace ?? {}, null, 2),
87
+ "context.md": "# Context\n",
88
+ "focus.md": "# Focus\n",
89
+ "constitution.md": "# Constitution\n",
90
+ "constraints.md": "# Constraints\n",
91
+ "glossary.md": "# Glossary\n"
92
+ };
93
+ for (const file of CANONICAL_WORKSPACE_FILES) {
94
+ const path = join(workspaceDir, file);
95
+ if (!existsSync(path)) writeFileSync(path, fallbackFiles[file], "utf-8");
96
+ }
97
+ }
98
+ function harnessDefaultDir(version) {
99
+ const candidates = [
100
+ join(fileURLToPath(new URL(".", import.meta.url)), "..", "harness", "default", version),
101
+ join(fileURLToPath(new URL(".", import.meta.url)), "harness", "default", version)
102
+ ];
103
+ for (const p of candidates) {
104
+ if (existsSync(p)) return p;
105
+ }
106
+ return candidates[0];
107
+ }
108
+ function ensureDefaultHarness(version = "v0.1.0") {
109
+ const dest = join(getHarnessDir(), version);
110
+ if (existsSync(dest)) return dest;
111
+ const src = harnessDefaultDir(version);
112
+ if (!existsSync(src)) {
113
+ throw new Error(`Default harness not found at ${src}`);
114
+ }
115
+ copyDir(src, dest);
116
+ return dest;
117
+ }
118
+ function initWorkspace(name) {
119
+ ensureLetraDirs();
120
+ const workspaceDir = getWorkspacePath(slugifyWorkspaceName(name));
121
+ if (existsSync(workspaceDir)) {
122
+ throw new Error(`Workspace "${name}" already exists at ${workspaceDir}`);
123
+ }
124
+ const workspaceId = `ws_${crypto.randomBytes(4).toString("hex")}`;
125
+ const templateId = "flow-main";
126
+ const harnessVersion = "v0.1.0";
127
+ ensureDefaultHarness(harnessVersion);
128
+ const info = {
129
+ id: workspaceId,
130
+ name,
131
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
132
+ templateId,
133
+ harnessVersion
134
+ };
135
+ ensureExternalWorkspaceLayout(workspaceDir, { workspace: info });
136
+ return { workspaceDir, info };
137
+ }
138
+ function detectManifest(cwd) {
139
+ const candidates = [join(cwd, "letra.manifest.json"), join(cwd, ".letra", "manifest.json")];
140
+ for (const p of candidates) {
141
+ if (existsSync(p)) {
142
+ try {
143
+ const manifest = JSON.parse(readFileSync(p, "utf-8"));
144
+ return { manifest, path: p };
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+ }
150
+ return null;
151
+ }
152
+ function loadWorkspaceInfo(workspaceName) {
153
+ const p = join(getWorkspacePath(workspaceName), "workspace.json");
154
+ if (!existsSync(p)) return null;
155
+ return JSON.parse(readFileSync(p, "utf-8"));
156
+ }
157
+ function listWorkspaces() {
158
+ const dir = getWorkspacesDir();
159
+ if (!existsSync(dir)) return [];
160
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => loadWorkspaceInfo(e.name)).filter((w) => w !== null);
161
+ }
162
+
163
+ // src/workspace/resolver.ts
164
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, statSync, readFileSync as readFileSync2 } from "fs";
165
+ import { join as join2, isAbsolute, resolve, dirname, parse } from "path";
166
+ var ENV_KEY = "LETRA_WORKSPACE";
167
+ var LINK_FILE = ".letra-link";
168
+ var LETRA_FOLDER = ".letra";
169
+ var workspaceRootCache = /* @__PURE__ */ new Map();
170
+ var dataDirCache = /* @__PURE__ */ new Map();
171
+ function getFlagWorkspace() {
172
+ const idx = process.argv.indexOf("--workspace");
173
+ if (idx === -1 || idx + 1 >= process.argv.length) return null;
174
+ const val = process.argv[idx + 1];
175
+ if (val.startsWith("--")) return null;
176
+ return val;
177
+ }
178
+ function getEnvWorkspace() {
179
+ return process.env[ENV_KEY] ?? null;
180
+ }
181
+ function parseLinkTarget(dir, target) {
182
+ return isAbsolute(target) ? target : resolve(dir, target);
183
+ }
184
+ function readLinkTarget(dir) {
185
+ const linkPath = join2(dir, LINK_FILE);
186
+ if (!existsSync2(linkPath)) return null;
187
+ const content = readFileSync2(linkPath, "utf-8").trim();
188
+ const target = content.split("\n")[0].trim();
189
+ if (!target) {
190
+ console.warn(`Letra link at ${linkPath} is empty \u2014 ignoring.`);
191
+ return null;
192
+ }
193
+ const dataPath = parseLinkTarget(dir, target);
194
+ if (!existsSync2(dataPath)) {
195
+ console.warn(
196
+ `Letra link target does not exist (${dataPath}) \u2014 falling back to local .letra/.`
197
+ );
198
+ return null;
199
+ }
200
+ const directWorkflow = join2(dataPath, "workflow.json");
201
+ const legacyHarnessDir = join2(dataPath, LETRA_FOLDER);
202
+ const legacyWorkflow = join2(legacyHarnessDir, "workflow.json");
203
+ if (existsSync2(directWorkflow)) {
204
+ return { path: linkPath, target: dataPath, dataDir: dataPath };
205
+ }
206
+ if (existsSync2(legacyWorkflow)) {
207
+ return { path: linkPath, target: dataPath, dataDir: legacyHarnessDir };
208
+ }
209
+ console.warn(
210
+ `Letra link target (${dataPath}) has no workflow.json \u2014 falling back to local .letra/.`
211
+ );
212
+ return null;
213
+ }
214
+ function resolution(input) {
215
+ return {
216
+ ...input,
217
+ dataDir: input.workspaceDir,
218
+ locationPath: input.targetDir,
219
+ projectRoot: input.projectRoot ?? input.workspaceRoot
220
+ };
221
+ }
222
+ function resolveWorkspaceRoot(cwd) {
223
+ const start = cwd ?? process.cwd();
224
+ if (workspaceRootCache.has(start)) return workspaceRootCache.get(start);
225
+ let dir = start;
226
+ const root = parse(dir).root;
227
+ const originalCwd = start;
228
+ const result = (function walk() {
229
+ while (dir && dir !== root) {
230
+ const envWs = getEnvWorkspace();
231
+ if (envWs) {
232
+ const wsDir = getWorkspacePath(envWs);
233
+ if (existsSync2(join2(wsDir, "workspace.json"))) {
234
+ const workspaceRoot = dirname(wsDir);
235
+ return resolution({
236
+ workspaceDir: wsDir,
237
+ targetDir: originalCwd,
238
+ workspaceRoot,
239
+ type: "env"
240
+ });
241
+ }
242
+ }
243
+ const flagWs = getFlagWorkspace();
244
+ if (flagWs) {
245
+ const wsDir = getWorkspacePath(flagWs);
246
+ if (existsSync2(join2(wsDir, "workspace.json"))) {
247
+ const workspaceRoot = dirname(wsDir);
248
+ return resolution({
249
+ workspaceDir: wsDir,
250
+ targetDir: originalCwd,
251
+ workspaceRoot,
252
+ type: "flag"
253
+ });
254
+ }
255
+ }
256
+ if (existsSync2(join2(dir, "workflow.json"))) {
257
+ return resolution({
258
+ workspaceDir: dir,
259
+ targetDir: originalCwd,
260
+ workspaceRoot: dir,
261
+ type: "direct"
262
+ });
263
+ }
264
+ const linked = readLinkTarget(dir);
265
+ if (linked) {
266
+ return resolution({
267
+ workspaceDir: linked.dataDir,
268
+ targetDir: originalCwd,
269
+ workspaceRoot: linked.target,
270
+ type: "linked"
271
+ });
272
+ }
273
+ const manifest = detectManifest(dir);
274
+ if (manifest) {
275
+ const workspaceRoot = dirname(manifest.path);
276
+ return resolution({
277
+ workspaceDir: join2(workspaceRoot, LETRA_FOLDER),
278
+ targetDir: originalCwd,
279
+ workspaceRoot,
280
+ type: "manifest"
281
+ });
282
+ }
283
+ const localLetra = join2(dir, LETRA_FOLDER);
284
+ if (existsSync2(localLetra) && statSync(localLetra).isDirectory()) {
285
+ return resolution({
286
+ workspaceDir: localLetra,
287
+ targetDir: originalCwd,
288
+ workspaceRoot: dir,
289
+ type: "local"
290
+ });
291
+ }
292
+ dir = dirname(dir);
293
+ }
294
+ return resolution({
295
+ workspaceDir: join2(originalCwd, LETRA_FOLDER),
296
+ targetDir: originalCwd,
297
+ workspaceRoot: originalCwd,
298
+ type: "local"
299
+ });
300
+ })();
301
+ workspaceRootCache.set(start, result);
302
+ return result;
303
+ }
304
+ function clearWorkspaceCache() {
305
+ workspaceRootCache.clear();
306
+ dataDirCache.clear();
307
+ }
308
+ function resolveDataDir(root) {
309
+ const cached = dataDirCache.get(root);
310
+ if (cached !== void 0) return cached;
311
+ let result = null;
312
+ if (existsSync2(join2(root, "workflow.json"))) {
313
+ result = root;
314
+ }
315
+ if (result === null) {
316
+ const linked = readLinkTarget(root);
317
+ if (linked) {
318
+ result = linked.dataDir;
319
+ }
320
+ }
321
+ if (result === null) {
322
+ const localLetra = join2(root, LETRA_FOLDER);
323
+ if (existsSync2(localLetra) && statSync(localLetra).isDirectory()) {
324
+ result = localLetra;
325
+ }
326
+ }
327
+ dataDirCache.set(root, result);
328
+ return result;
329
+ }
330
+ function getLetraDir2(root) {
331
+ const direct = resolveDataDir(root);
332
+ if (direct) return direct;
333
+ try {
334
+ return resolveWorkspaceRoot(root).workspaceDir;
335
+ } catch {
336
+ return join2(root, LETRA_FOLDER);
337
+ }
338
+ }
339
+ function getSpecsDir(root) {
340
+ return join2(getLetraDir2(root), "specs");
341
+ }
342
+ function isWorkspaceMode(resolution2) {
343
+ return resolution2.type === "linked" || resolution2.type === "env" || resolution2.type === "flag" || resolution2.type === "direct";
344
+ }
345
+
346
+ export {
347
+ getLetraDir,
348
+ getWorkspacesDir,
349
+ getWorkspacePath,
350
+ slugifyWorkspaceName,
351
+ ensureExternalWorkspaceLayout,
352
+ ensureDefaultHarness,
353
+ initWorkspace,
354
+ detectManifest,
355
+ loadWorkspaceInfo,
356
+ listWorkspaces,
357
+ LINK_FILE,
358
+ resolveWorkspaceRoot,
359
+ clearWorkspaceCache,
360
+ getLetraDir2,
361
+ getSpecsDir,
362
+ isWorkspaceMode
363
+ };
@@ -0,0 +1,300 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getLetraDir2 as getLetraDir
4
+ } from "./chunk-6HSUVCTR.js";
5
+
6
+ // src/session-log.ts
7
+ import {
8
+ closeSync,
9
+ existsSync,
10
+ mkdirSync,
11
+ openSync,
12
+ readFileSync,
13
+ readdirSync,
14
+ renameSync,
15
+ rmSync,
16
+ writeFileSync,
17
+ writeSync
18
+ } from "fs";
19
+ import { dirname, join } from "path";
20
+ var LOG_FILE = "session-log.json";
21
+ var LOG_DIR = "session-log";
22
+ var SCHEMA_VERSION = 1;
23
+ var WRITE_ATTEMPTS = 5;
24
+ var MAX_ENTRIES = 2e3;
25
+ var RETRYABLE_WRITE_CODES = /* @__PURE__ */ new Set(["UNKNOWN", "EBUSY", "EPERM", "EACCES"]);
26
+ var logCounter = 0;
27
+ var temporaryFileCounter = 0;
28
+ var ensuredDirectories = /* @__PURE__ */ new Set();
29
+ var appendFileDescriptors = /* @__PURE__ */ new Map();
30
+ function logPath(root) {
31
+ return join(getLetraDir(root), LOG_FILE);
32
+ }
33
+ function logDir(root) {
34
+ return join(getLetraDir(root), LOG_DIR);
35
+ }
36
+ function jsonlPathForDate(root, date = /* @__PURE__ */ new Date()) {
37
+ const iso = date.toISOString();
38
+ const year = iso.slice(0, 4);
39
+ const month = iso.slice(5, 7);
40
+ const day = iso.slice(8, 10);
41
+ return join(logDir(root), year, month, `${day}.jsonl`);
42
+ }
43
+ function nextId() {
44
+ logCounter++;
45
+ const ts = Date.now().toString(36).slice(-4);
46
+ return `log-${ts}-${logCounter.toString(36).padStart(3, "0")}`;
47
+ }
48
+ function normalizeLogEntry(entry) {
49
+ if (typeof entry.id !== "string" || typeof entry.timestamp !== "string" || typeof entry.action !== "string" || typeof entry.description !== "string") {
50
+ return null;
51
+ }
52
+ return {
53
+ id: entry.id,
54
+ timestamp: entry.timestamp,
55
+ action: entry.action,
56
+ description: entry.description,
57
+ itemId: typeof entry.itemId === "string" ? entry.itemId : null,
58
+ acId: typeof entry.acId === "string" ? entry.acId : null,
59
+ details: typeof entry.details === "object" && entry.details !== null && !Array.isArray(entry.details) ? entry.details : {},
60
+ level: entry.level === "debug" ? "debug" : "info"
61
+ };
62
+ }
63
+ function readLegacyEntries(root) {
64
+ const file = logPath(root);
65
+ if (!existsSync(file)) return [];
66
+ try {
67
+ const raw = readFileSync(file, "utf-8");
68
+ const log = JSON.parse(raw);
69
+ if (!Array.isArray(log.entries)) return [];
70
+ return log.entries.map((entry) => normalizeLogEntry(entry)).filter((entry) => entry !== null);
71
+ } catch {
72
+ return [];
73
+ }
74
+ }
75
+ function listJsonlFiles(dir) {
76
+ if (!existsSync(dir)) return [];
77
+ const files = [];
78
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
79
+ const fullPath = join(dir, entry.name);
80
+ if (entry.isDirectory()) {
81
+ files.push(...listJsonlFiles(fullPath));
82
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
83
+ files.push(fullPath);
84
+ }
85
+ }
86
+ return files;
87
+ }
88
+ function readJsonlEntries(root) {
89
+ const entries = [];
90
+ for (const file of listJsonlFiles(logDir(root))) {
91
+ let raw = "";
92
+ try {
93
+ raw = readFileSync(file, "utf-8");
94
+ } catch {
95
+ continue;
96
+ }
97
+ for (const line of raw.split(/\r?\n/)) {
98
+ if (!line.trim()) continue;
99
+ try {
100
+ const entry = normalizeLogEntry(JSON.parse(line));
101
+ if (entry) entries.push(entry);
102
+ } catch {
103
+ }
104
+ }
105
+ }
106
+ return entries;
107
+ }
108
+ function ensureDirectory(dir) {
109
+ if (ensuredDirectories.has(dir)) return;
110
+ mkdirSync(dir, { recursive: true });
111
+ ensuredDirectories.add(dir);
112
+ }
113
+ function appendJsonlLine(file, line) {
114
+ const dir = dirname(file);
115
+ ensureDirectory(dir);
116
+ let fd = appendFileDescriptors.get(file);
117
+ if (fd === void 0) {
118
+ fd = openSync(file, "a");
119
+ appendFileDescriptors.set(file, fd);
120
+ }
121
+ writeSync(fd, `${line}
122
+ `);
123
+ }
124
+ function closeAppendDescriptor(file) {
125
+ const fd = appendFileDescriptors.get(file);
126
+ if (fd === void 0) return;
127
+ closeSync(fd);
128
+ appendFileDescriptors.delete(file);
129
+ }
130
+ function closeSessionLogHandles() {
131
+ for (const [, fd] of appendFileDescriptors) closeSync(fd);
132
+ appendFileDescriptors.clear();
133
+ }
134
+ function loadSessionLog(root) {
135
+ return {
136
+ schemaVersion: SCHEMA_VERSION,
137
+ entries: [...readLegacyEntries(root), ...readJsonlEntries(root)]
138
+ };
139
+ }
140
+ function sleepSync(milliseconds) {
141
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
142
+ }
143
+ function isRetryableWriteError(error) {
144
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && RETRYABLE_WRITE_CODES.has(error.code);
145
+ }
146
+ function replaceWithRetry(source, destination, options) {
147
+ const replaceFile = options.replaceFile ?? renameSync;
148
+ const sleep = options.sleep ?? sleepSync;
149
+ for (let attempt = 1; attempt <= WRITE_ATTEMPTS; attempt++) {
150
+ try {
151
+ replaceFile(source, destination);
152
+ return;
153
+ } catch (error) {
154
+ if (!isRetryableWriteError(error) || attempt === WRITE_ATTEMPTS) throw error;
155
+ sleep(20 * 2 ** (attempt - 1));
156
+ }
157
+ }
158
+ }
159
+ function saveSessionLog(root, log, options = {}) {
160
+ const dir = getLetraDir(root);
161
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
162
+ if (log.entries.length > MAX_ENTRIES) {
163
+ log.entries = log.entries.slice(-MAX_ENTRIES);
164
+ }
165
+ const destination = logPath(root);
166
+ const temporaryFile = join(dir, `.${LOG_FILE}.${process.pid}.${++temporaryFileCounter}.tmp`);
167
+ try {
168
+ writeFileSync(temporaryFile, JSON.stringify(log, null, 2), "utf-8");
169
+ replaceWithRetry(temporaryFile, destination, options);
170
+ } finally {
171
+ if (existsSync(temporaryFile)) rmSync(temporaryFile, { force: true });
172
+ }
173
+ }
174
+ function inferLogLevel(action, options) {
175
+ if (options?.level) return options.level;
176
+ if (action === "system" || options?.details?.systemAction === true) return "debug";
177
+ return "info";
178
+ }
179
+ function logEntry(root, action, description, options) {
180
+ const now = /* @__PURE__ */ new Date();
181
+ const entry = {
182
+ id: nextId(),
183
+ timestamp: now.toISOString(),
184
+ action,
185
+ description,
186
+ itemId: options?.itemId ?? null,
187
+ acId: options?.acId ?? null,
188
+ details: options?.details ?? {},
189
+ level: inferLogLevel(action, options)
190
+ };
191
+ const file = jsonlPathForDate(root, now);
192
+ appendJsonlLine(file, JSON.stringify(entry));
193
+ return entry;
194
+ }
195
+ function matchesTextSearch(entry, query) {
196
+ const lower = query.toLowerCase();
197
+ return entry.id.toLowerCase().includes(lower) || entry.action.toLowerCase().includes(lower) || entry.description.toLowerCase().includes(lower) || (entry.itemId ?? "").toLowerCase().includes(lower) || (entry.acId ?? "").toLowerCase().includes(lower) || JSON.stringify(entry.details).toLowerCase().includes(lower);
198
+ }
199
+ function computeFacets(entries) {
200
+ const actions = {};
201
+ const statuses = {};
202
+ for (const e of entries) {
203
+ const action = e.action || "unknown";
204
+ actions[action] = (actions[action] || 0) + 1;
205
+ const outcome = typeof e.details?.outcome === "string" ? e.details.outcome : "completed";
206
+ statuses[outcome] = (statuses[outcome] || 0) + 1;
207
+ }
208
+ return { actions, statuses };
209
+ }
210
+ function queryLog(root, query) {
211
+ const log = loadSessionLog(root);
212
+ return _queryLog(log.entries, query);
213
+ }
214
+ function queryLogWithMeta(root, query) {
215
+ const log = loadSessionLog(root);
216
+ const allEntries = _applyFilters(log.entries, query);
217
+ const total = allEntries.length;
218
+ const limit = query?.limit ?? 50;
219
+ const offset = query?.offset ?? 0;
220
+ const page = query?.all ? allEntries : allEntries.slice(offset, offset + limit);
221
+ return {
222
+ entries: page,
223
+ total,
224
+ facets: computeFacets(allEntries)
225
+ };
226
+ }
227
+ function _applyFilters(allEntries, query) {
228
+ let entries = [...allEntries];
229
+ if (!query?.debug) entries = entries.filter((e) => e.level !== "debug");
230
+ if (query?.itemId) entries = entries.filter((e) => e.itemId === query.itemId);
231
+ if (query?.action) entries = entries.filter((e) => e.action === query.action);
232
+ if (query?.spec) {
233
+ const spec = query.spec.toLowerCase();
234
+ entries = entries.filter((e) => {
235
+ const specVal = typeof e.details?.spec === "string" ? e.details.spec : "";
236
+ return specVal.toLowerCase() === spec;
237
+ });
238
+ }
239
+ if (query?.actor) {
240
+ const actor = query.actor.toLowerCase();
241
+ entries = entries.filter((e) => {
242
+ const by = typeof e.details?.by === "string" ? e.details.by : "";
243
+ return by.toLowerCase() === actor;
244
+ });
245
+ }
246
+ if (query?.q) entries = entries.filter((e) => matchesTextSearch(e, query.q));
247
+ if (query?.since) {
248
+ const sinceDate = new Date(query.since).getTime();
249
+ entries = entries.filter((e) => new Date(e.timestamp).getTime() >= sinceDate);
250
+ }
251
+ if (query?.from) {
252
+ const fromDate = new Date(query.from).getTime();
253
+ entries = entries.filter((e) => new Date(e.timestamp).getTime() >= fromDate);
254
+ }
255
+ if (query?.to) {
256
+ const toDate = new Date(query.to).getTime();
257
+ entries = entries.filter((e) => new Date(e.timestamp).getTime() <= toDate);
258
+ }
259
+ entries.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
260
+ return entries;
261
+ }
262
+ function _queryLog(allEntries, query) {
263
+ const entries = _applyFilters(allEntries, query);
264
+ if (query?.all) return entries;
265
+ const limit = query?.limit ?? 10;
266
+ const offset = query?.offset ?? 0;
267
+ return entries.slice(offset, offset + limit);
268
+ }
269
+ function pruneSessionLog(root, keepDays, now = /* @__PURE__ */ new Date()) {
270
+ if (!Number.isFinite(keepDays) || keepDays < 1) {
271
+ throw new Error("--keep must be a positive number of days");
272
+ }
273
+ const cutoff = Date.UTC(
274
+ now.getUTCFullYear(),
275
+ now.getUTCMonth(),
276
+ now.getUTCDate() - keepDays + 1
277
+ );
278
+ const removed = [];
279
+ for (const file of listJsonlFiles(logDir(root))) {
280
+ const match = file.match(/session-log[\\/](\d{4})[\\/](\d{2})[\\/](\d{2})\.jsonl$/);
281
+ if (!match) continue;
282
+ const fileDay = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
283
+ if (fileDay < cutoff) {
284
+ closeAppendDescriptor(file);
285
+ rmSync(file, { force: true });
286
+ removed.push(file);
287
+ }
288
+ }
289
+ return removed;
290
+ }
291
+
292
+ export {
293
+ closeSessionLogHandles,
294
+ loadSessionLog,
295
+ saveSessionLog,
296
+ logEntry,
297
+ queryLog,
298
+ queryLogWithMeta,
299
+ pruneSessionLog
300
+ };