@letra-ai/cli 0.6.1 → 0.7.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/dist/chunk-2GRNAFBQ.js +5305 -0
  2. package/dist/{chunk-MJ2QXNH6.js → chunk-42RST74I.js} +1 -1
  3. package/dist/chunk-HC24XMPZ.js +269 -0
  4. package/dist/chunk-LUPN3TRC.js +554 -0
  5. package/dist/{chunk-KGQLHMGZ.js → chunk-MUCIMQAU.js} +1918 -757
  6. package/dist/chunk-POGWTSEA.js +125 -0
  7. package/dist/chunk-TNF7XTFG.js +6178 -0
  8. package/dist/{chunk-BKAUN5QH.js → chunk-UMC5PDL2.js} +227 -33
  9. package/dist/{chunk-6HSUVCTR.js → chunk-YAQ2TKSK.js} +82 -30
  10. package/dist/client/assets/index-C-6kWNFi.js +232 -0
  11. package/dist/client/assets/index-QV-zN0V8.css +1 -0
  12. package/dist/client/index.html +2 -2
  13. package/dist/fallback-CXCCKHBA.js +56 -0
  14. package/dist/flow-serve-LFILD3EV.js +19 -0
  15. package/dist/{generate-N22QOXUF.js → generate-3R7POT7L.js} +4 -5
  16. package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +1 -0
  17. package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +1 -0
  18. package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +1 -0
  19. package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +1 -0
  20. package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +1 -0
  21. package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +1 -0
  22. package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +1 -0
  23. package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +1 -0
  24. package/dist/harness/default/v0.2.0/executors/registry.yaml +17 -0
  25. package/dist/harness/default/v0.2.0/flows/flow-main.yaml +84 -4
  26. package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +1 -0
  27. package/dist/harness/default/v0.2.0/gates/human-approved.yaml +4 -3
  28. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +1 -0
  29. package/dist/harness/default/v0.2.0/gates/spec-approved.yaml +3 -3
  30. package/dist/{health-record-YDVXEVLR.js → health-record-JO2ZTIMR.js} +2 -2
  31. package/dist/index.js +2237 -1104
  32. package/dist/{push-5JEYSXBY.js → push-2ZCQSOHF.js} +37 -49
  33. package/dist/server-WUYVNSH7.js +677 -0
  34. package/dist/service-SVEAXQBX.js +28 -0
  35. package/dist/service-TOBY3OHO.js +22 -0
  36. package/dist/service-USTAY5E3.js +62 -0
  37. package/dist/{session-log-WTQ5JBEN.js → session-log-X2Q4XKQN.js} +6 -2
  38. package/dist/specs-CQRB7LPA.js +21 -0
  39. package/dist/sync-LIVPQXEW.js +21 -0
  40. package/package.json +1 -1
  41. package/dist/chunk-4QDEU6KP.js +0 -2765
  42. package/dist/chunk-BTPFUKHG.js +0 -275
  43. package/dist/chunk-EDD55PWL.js +0 -119
  44. package/dist/chunk-ELBTIPYN.js +0 -256
  45. package/dist/chunk-IEFSLCJL.js +0 -837
  46. package/dist/chunk-MSF44WWE.js +0 -443
  47. package/dist/chunk-QIVKP3EY.js +0 -362
  48. package/dist/client/assets/index-BuABgOyz.js +0 -232
  49. package/dist/client/assets/index-CpseCZh9.css +0 -1
  50. package/dist/fallback-UXSZ4LNR.js +0 -47
  51. package/dist/flow-serve-MTB6KZMR.js +0 -19
  52. package/dist/focus-sync-3D3XWCTI.js +0 -17
  53. package/dist/server-FUP3APZA.js +0 -415
  54. package/dist/service-OGF7BMCQ.js +0 -21
  55. package/dist/sitrep-DJXTP3JO.js +0 -16
@@ -1,22 +1,202 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  getLetraDir2 as getLetraDir
4
- } from "./chunk-6HSUVCTR.js";
4
+ } from "./chunk-YAQ2TKSK.js";
5
5
 
6
6
  // src/session-log.ts
7
7
  import {
8
- closeSync,
9
- existsSync,
10
- mkdirSync,
11
- openSync,
12
- readFileSync,
8
+ closeSync as closeSync2,
9
+ existsSync as existsSync2,
10
+ mkdirSync as mkdirSync2,
11
+ openSync as openSync2,
12
+ readFileSync as readFileSync2,
13
13
  readdirSync,
14
- renameSync,
14
+ renameSync as renameSync2,
15
15
  rmSync,
16
- writeFileSync,
17
- writeSync
16
+ writeFileSync as writeFileSync2,
17
+ writeSync as writeSync2
18
18
  } from "fs";
19
- import { dirname, join } from "path";
19
+ import { dirname as dirname2, join as join2 } from "path";
20
+
21
+ // src/domain-operations/workspace-transaction.ts
22
+ import { AsyncLocalStorage } from "async_hooks";
23
+ import { createHash, randomUUID } from "crypto";
24
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, writeSync } from "fs";
25
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
26
+ var owner = new AsyncLocalStorage();
27
+ var failureInjector;
28
+ function rootKey(root) {
29
+ return resolve(getLetraDir(resolve(root)));
30
+ }
31
+ function paths(root) {
32
+ const dataRoot = rootKey(root);
33
+ const runtime = join(dataRoot, "runtime");
34
+ return { dataRoot, runtime, lock: join(runtime, "workspace-transaction.lock"), journal: join(runtime, "workspace-transaction.json") };
35
+ }
36
+ function sha256(value) {
37
+ return createHash("sha256").update(value).digest("hex");
38
+ }
39
+ function safeTarget(dataRoot, target) {
40
+ const absolute = isAbsolute(target) ? resolve(target) : resolve(dataRoot, target);
41
+ const rel = relative(dataRoot, absolute);
42
+ if (!rel || rel === ".." || rel.startsWith(".." + sep)) throw new Error("TRANSACTION_PATH_OUTSIDE_DATA_ROOT");
43
+ return absolute;
44
+ }
45
+ function atomicWrite(path, contents) {
46
+ mkdirSync(dirname(path), { recursive: true });
47
+ const temporary = path + "." + randomUUID() + ".tmp";
48
+ writeFileSync(temporary, contents, { encoding: "utf8", flag: "wx" });
49
+ try {
50
+ renameSync(temporary, path);
51
+ } catch (error) {
52
+ try {
53
+ unlinkSync(temporary);
54
+ } catch {
55
+ }
56
+ throw error;
57
+ }
58
+ }
59
+ function lockOwnerPid(path) {
60
+ try {
61
+ const value = JSON.parse(readFileSync(path, "utf8"));
62
+ return Number.isInteger(value.pid) && value.pid > 0 ? value.pid : null;
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+ function acquire(root) {
68
+ const location = paths(root);
69
+ mkdirSync(location.runtime, { recursive: true });
70
+ for (let attempt = 0; attempt < 2; attempt++) {
71
+ try {
72
+ const fd = openSync(location.lock, "wx", 384);
73
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, createdAt: (/* @__PURE__ */ new Date()).toISOString() }));
74
+ return () => {
75
+ closeSync(fd);
76
+ try {
77
+ unlinkSync(location.lock);
78
+ } catch {
79
+ }
80
+ };
81
+ } catch (error) {
82
+ if (error.code !== "EEXIST") throw error;
83
+ const pid = lockOwnerPid(location.lock);
84
+ if (pid === null) throw new Error("WORKSPACE_TRANSACTION_BUSY");
85
+ try {
86
+ process.kill(pid, 0);
87
+ } catch (probeError) {
88
+ if (probeError.code === "ESRCH") {
89
+ try {
90
+ unlinkSync(location.lock);
91
+ } catch {
92
+ throw new Error("WORKSPACE_TRANSACTION_BUSY");
93
+ }
94
+ continue;
95
+ }
96
+ }
97
+ throw new Error("WORKSPACE_TRANSACTION_BUSY");
98
+ }
99
+ }
100
+ throw new Error("WORKSPACE_TRANSACTION_BUSY");
101
+ }
102
+ function isOwner(root) {
103
+ return owner.getStore() === rootKey(root);
104
+ }
105
+ function withWorkspaceTransactionLockSync(root, action) {
106
+ const key = rootKey(root);
107
+ if (owner.getStore() === key) return action();
108
+ const release = acquire(root);
109
+ try {
110
+ return owner.run(key, action);
111
+ } finally {
112
+ release();
113
+ }
114
+ }
115
+ async function withWorkspaceTransactionLock(root, action) {
116
+ const key = rootKey(root);
117
+ if (owner.getStore() === key) return action();
118
+ const release = acquire(root);
119
+ try {
120
+ return await owner.run(key, action);
121
+ } finally {
122
+ release();
123
+ }
124
+ }
125
+ function readJournal(file) {
126
+ if (!existsSync(file)) return null;
127
+ const value = JSON.parse(readFileSync(file, "utf8"));
128
+ if (value.schemaVersion !== 1 || value.phase !== "prepared" && value.phase !== "committed") throw new Error("INVALID_WORKSPACE_TRANSACTION_JOURNAL");
129
+ return value;
130
+ }
131
+ function project(root, journal) {
132
+ const location = paths(root);
133
+ for (const write of journal.writes) {
134
+ const target = safeTarget(location.dataRoot, write.path);
135
+ const current = existsSync(target) ? readFileSync(target, "utf8") : null;
136
+ if (current === write.contents) continue;
137
+ if (current === null ? write.expectedHash !== null : write.expectedHash === null || sha256(current) !== write.expectedHash) throw new Error("WORKSPACE_TRANSACTION_CAS_CONFLICT:" + relative(location.dataRoot, target));
138
+ if (write.expectedHash === null && current !== null) throw new Error("WORKSPACE_TRANSACTION_CREATE_CONFLICT:" + relative(location.dataRoot, target));
139
+ atomicWrite(target, write.contents);
140
+ }
141
+ for (const append of journal.appends ?? []) {
142
+ const target = safeTarget(location.dataRoot, append.path);
143
+ const existing = existsSync(target) ? readFileSync(target, "utf8") : "";
144
+ if (existing.includes(append.dedupeToken)) continue;
145
+ mkdirSync(dirname(target), { recursive: true });
146
+ const fd = openSync(target, "a");
147
+ try {
148
+ writeSync(fd, append.line.endsWith("\n") ? append.line : append.line + "\n");
149
+ } finally {
150
+ closeSync(fd);
151
+ }
152
+ }
153
+ }
154
+ function recoverUnderLock(root) {
155
+ const location = paths(root);
156
+ const journal = readJournal(location.journal);
157
+ if (!journal) return;
158
+ if (journal.phase === "committed") project(root, journal);
159
+ unlinkSync(location.journal);
160
+ }
161
+ function recoverWorkspaceTransaction(root) {
162
+ if (isOwner(root)) return;
163
+ const location = paths(root);
164
+ if (!existsSync(location.journal)) return;
165
+ withWorkspaceTransactionLockSync(root, () => recoverUnderLock(root));
166
+ }
167
+ function isWorkspaceTransactionCommitted(root, transactionId) {
168
+ const journal = readJournal(paths(root).journal);
169
+ return journal?.phase === "committed" && journal.transactionId === transactionId;
170
+ }
171
+ function commitWorkspaceTransaction(root, plan) {
172
+ withWorkspaceTransactionLockSync(root, () => {
173
+ const location = paths(root);
174
+ recoverUnderLock(root);
175
+ plan.validate();
176
+ for (const write of plan.writes) {
177
+ const target = safeTarget(location.dataRoot, write.path);
178
+ const current = existsSync(target) ? readFileSync(target, "utf8") : null;
179
+ if (current === null ? write.expectedHash !== null : write.expectedHash === null || sha256(current) !== write.expectedHash) {
180
+ throw new Error("WORKSPACE_TRANSACTION_CAS_CONFLICT:" + relative(location.dataRoot, target));
181
+ }
182
+ }
183
+ const journal = { schemaVersion: 1, phase: "prepared", transactionId: plan.transactionId, writes: plan.writes, appends: plan.appends };
184
+ atomicWrite(location.journal, JSON.stringify(journal, null, 2) + "\n");
185
+ try {
186
+ failureInjector?.("after-prepare");
187
+ } catch (error) {
188
+ unlinkSync(location.journal);
189
+ throw error;
190
+ }
191
+ const committed = { ...journal, phase: "committed" };
192
+ atomicWrite(location.journal, JSON.stringify(committed, null, 2) + "\n");
193
+ failureInjector?.("after-commit-marker");
194
+ project(root, committed);
195
+ unlinkSync(location.journal);
196
+ });
197
+ }
198
+
199
+ // src/session-log.ts
20
200
  var LOG_FILE = "session-log.json";
21
201
  var LOG_DIR = "session-log";
22
202
  var SCHEMA_VERSION = 1;
@@ -28,17 +208,17 @@ var temporaryFileCounter = 0;
28
208
  var ensuredDirectories = /* @__PURE__ */ new Set();
29
209
  var appendFileDescriptors = /* @__PURE__ */ new Map();
30
210
  function logPath(root) {
31
- return join(getLetraDir(root), LOG_FILE);
211
+ return join2(getLetraDir(root), LOG_FILE);
32
212
  }
33
213
  function logDir(root) {
34
- return join(getLetraDir(root), LOG_DIR);
214
+ return join2(getLetraDir(root), LOG_DIR);
35
215
  }
36
216
  function jsonlPathForDate(root, date = /* @__PURE__ */ new Date()) {
37
217
  const iso = date.toISOString();
38
218
  const year = iso.slice(0, 4);
39
219
  const month = iso.slice(5, 7);
40
220
  const day = iso.slice(8, 10);
41
- return join(logDir(root), year, month, `${day}.jsonl`);
221
+ return join2(logDir(root), year, month, `${day}.jsonl`);
42
222
  }
43
223
  function nextId() {
44
224
  logCounter++;
@@ -62,9 +242,9 @@ function normalizeLogEntry(entry) {
62
242
  }
63
243
  function readLegacyEntries(root) {
64
244
  const file = logPath(root);
65
- if (!existsSync(file)) return [];
245
+ if (!existsSync2(file)) return [];
66
246
  try {
67
- const raw = readFileSync(file, "utf-8");
247
+ const raw = readFileSync2(file, "utf-8");
68
248
  const log = JSON.parse(raw);
69
249
  if (!Array.isArray(log.entries)) return [];
70
250
  return log.entries.map((entry) => normalizeLogEntry(entry)).filter((entry) => entry !== null);
@@ -73,10 +253,10 @@ function readLegacyEntries(root) {
73
253
  }
74
254
  }
75
255
  function listJsonlFiles(dir) {
76
- if (!existsSync(dir)) return [];
256
+ if (!existsSync2(dir)) return [];
77
257
  const files = [];
78
258
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
79
- const fullPath = join(dir, entry.name);
259
+ const fullPath = join2(dir, entry.name);
80
260
  if (entry.isDirectory()) {
81
261
  files.push(...listJsonlFiles(fullPath));
82
262
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -90,7 +270,7 @@ function readJsonlEntries(root) {
90
270
  for (const file of listJsonlFiles(logDir(root))) {
91
271
  let raw = "";
92
272
  try {
93
- raw = readFileSync(file, "utf-8");
273
+ raw = readFileSync2(file, "utf-8");
94
274
  } catch {
95
275
  continue;
96
276
  }
@@ -107,31 +287,32 @@ function readJsonlEntries(root) {
107
287
  }
108
288
  function ensureDirectory(dir) {
109
289
  if (ensuredDirectories.has(dir)) return;
110
- mkdirSync(dir, { recursive: true });
290
+ mkdirSync2(dir, { recursive: true });
111
291
  ensuredDirectories.add(dir);
112
292
  }
113
293
  function appendJsonlLine(file, line) {
114
- const dir = dirname(file);
294
+ const dir = dirname2(file);
115
295
  ensureDirectory(dir);
116
296
  let fd = appendFileDescriptors.get(file);
117
297
  if (fd === void 0) {
118
- fd = openSync(file, "a");
298
+ fd = openSync2(file, "a");
119
299
  appendFileDescriptors.set(file, fd);
120
300
  }
121
- writeSync(fd, `${line}
301
+ writeSync2(fd, `${line}
122
302
  `);
123
303
  }
124
304
  function closeAppendDescriptor(file) {
125
305
  const fd = appendFileDescriptors.get(file);
126
306
  if (fd === void 0) return;
127
- closeSync(fd);
307
+ closeSync2(fd);
128
308
  appendFileDescriptors.delete(file);
129
309
  }
130
310
  function closeSessionLogHandles() {
131
- for (const [, fd] of appendFileDescriptors) closeSync(fd);
311
+ for (const [, fd] of appendFileDescriptors) closeSync2(fd);
132
312
  appendFileDescriptors.clear();
133
313
  }
134
314
  function loadSessionLog(root) {
315
+ recoverWorkspaceTransaction(root);
135
316
  return {
136
317
  schemaVersion: SCHEMA_VERSION,
137
318
  entries: [...readLegacyEntries(root), ...readJsonlEntries(root)]
@@ -144,7 +325,7 @@ function isRetryableWriteError(error) {
144
325
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && RETRYABLE_WRITE_CODES.has(error.code);
145
326
  }
146
327
  function replaceWithRetry(source, destination, options) {
147
- const replaceFile = options.replaceFile ?? renameSync;
328
+ const replaceFile = options.replaceFile ?? renameSync2;
148
329
  const sleep = options.sleep ?? sleepSync;
149
330
  for (let attempt = 1; attempt <= WRITE_ATTEMPTS; attempt++) {
150
331
  try {
@@ -158,17 +339,17 @@ function replaceWithRetry(source, destination, options) {
158
339
  }
159
340
  function saveSessionLog(root, log, options = {}) {
160
341
  const dir = getLetraDir(root);
161
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
342
+ if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
162
343
  if (log.entries.length > MAX_ENTRIES) {
163
344
  log.entries = log.entries.slice(-MAX_ENTRIES);
164
345
  }
165
346
  const destination = logPath(root);
166
- const temporaryFile = join(dir, `.${LOG_FILE}.${process.pid}.${++temporaryFileCounter}.tmp`);
347
+ const temporaryFile = join2(dir, `.${LOG_FILE}.${process.pid}.${++temporaryFileCounter}.tmp`);
167
348
  try {
168
- writeFileSync(temporaryFile, JSON.stringify(log, null, 2), "utf-8");
349
+ writeFileSync2(temporaryFile, JSON.stringify(log, null, 2), "utf-8");
169
350
  replaceWithRetry(temporaryFile, destination, options);
170
351
  } finally {
171
- if (existsSync(temporaryFile)) rmSync(temporaryFile, { force: true });
352
+ if (existsSync2(temporaryFile)) rmSync(temporaryFile, { force: true });
172
353
  }
173
354
  }
174
355
  function inferLogLevel(action, options) {
@@ -177,8 +358,16 @@ function inferLogLevel(action, options) {
177
358
  return "info";
178
359
  }
179
360
  function logEntry(root, action, description, options) {
361
+ return withWorkspaceTransactionLockSync(root, () => {
362
+ const entry = createLogEntry(action, description, options);
363
+ const file = jsonlPathForDate(root, new Date(entry.timestamp));
364
+ appendJsonlLine(file, JSON.stringify(entry));
365
+ return entry;
366
+ });
367
+ }
368
+ function createLogEntry(action, description, options) {
180
369
  const now = /* @__PURE__ */ new Date();
181
- const entry = {
370
+ return {
182
371
  id: nextId(),
183
372
  timestamp: now.toISOString(),
184
373
  action,
@@ -188,9 +377,6 @@ function logEntry(root, action, description, options) {
188
377
  details: options?.details ?? {},
189
378
  level: inferLogLevel(action, options)
190
379
  };
191
- const file = jsonlPathForDate(root, now);
192
- appendJsonlLine(file, JSON.stringify(entry));
193
- return entry;
194
380
  }
195
381
  function matchesTextSearch(entry, query) {
196
382
  const lower = query.toLowerCase();
@@ -228,6 +414,7 @@ function _applyFilters(allEntries, query) {
228
414
  let entries = [...allEntries];
229
415
  if (!query?.debug) entries = entries.filter((e) => e.level !== "debug");
230
416
  if (query?.itemId) entries = entries.filter((e) => e.itemId === query.itemId);
417
+ if (query?.runId) entries = entries.filter((e) => e.details?.runId === query.runId);
231
418
  if (query?.action) entries = entries.filter((e) => e.action === query.action);
232
419
  if (query?.spec) {
233
420
  const spec = query.spec.toLowerCase();
@@ -290,10 +477,17 @@ function pruneSessionLog(root, keepDays, now = /* @__PURE__ */ new Date()) {
290
477
  }
291
478
 
292
479
  export {
480
+ withWorkspaceTransactionLockSync,
481
+ withWorkspaceTransactionLock,
482
+ recoverWorkspaceTransaction,
483
+ isWorkspaceTransactionCommitted,
484
+ commitWorkspaceTransaction,
485
+ jsonlPathForDate,
293
486
  closeSessionLogHandles,
294
487
  loadSessionLog,
295
488
  saveSessionLog,
296
489
  logEntry,
490
+ createLogEntry,
297
491
  queryLog,
298
492
  queryLogWithMeta,
299
493
  pruneSessionLog
@@ -84,7 +84,7 @@ function ensureExternalWorkspaceLayout(workspaceDir, defaults) {
84
84
  2
85
85
  ),
86
86
  "workspace.json": JSON.stringify(defaults?.workspace ?? {}, null, 2),
87
- "context.md": "# Context\n",
87
+ "context.md": "# Context\n\nEste arquivo \xE9 mem\xF3ria humana curada. Estado vivo vem de `get_direction` ou `letra direction --json`.\n",
88
88
  "focus.md": "# Focus\n",
89
89
  "constitution.md": "# Constitution\n",
90
90
  "constraints.md": "# Constraints\n",
@@ -105,7 +105,7 @@ function harnessDefaultDir(version) {
105
105
  }
106
106
  return candidates[0];
107
107
  }
108
- function ensureDefaultHarness(version = "v0.1.0") {
108
+ function ensureDefaultHarness(version = "v0.2.0") {
109
109
  const dest = join(getHarnessDir(), version);
110
110
  if (existsSync(dest)) return dest;
111
111
  const src = harnessDefaultDir(version);
@@ -123,7 +123,7 @@ function initWorkspace(name) {
123
123
  }
124
124
  const workspaceId = `ws_${crypto.randomBytes(4).toString("hex")}`;
125
125
  const templateId = "flow-main";
126
- const harnessVersion = "v0.1.0";
126
+ const harnessVersion = "v0.2.0";
127
127
  ensureDefaultHarness(harnessVersion);
128
128
  const info = {
129
129
  id: workspaceId,
@@ -132,7 +132,9 @@ function initWorkspace(name) {
132
132
  templateId,
133
133
  harnessVersion
134
134
  };
135
- ensureExternalWorkspaceLayout(workspaceDir, { workspace: info });
135
+ ensureExternalWorkspaceLayout(workspaceDir, {
136
+ workspace: info
137
+ });
136
138
  return { workspaceDir, info };
137
139
  }
138
140
  function detectManifest(cwd) {
@@ -162,8 +164,23 @@ function listWorkspaces() {
162
164
 
163
165
  // src/workspace/resolver.ts
164
166
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, statSync, readFileSync as readFileSync2 } from "fs";
165
- import { join as join2, isAbsolute, resolve, dirname, parse } from "path";
167
+ import { homedir as homedir2 } from "os";
168
+ import { join as join2, isAbsolute, resolve, dirname, delimiter } from "path";
166
169
  var ENV_KEY = "LETRA_WORKSPACE";
170
+ var CEILING_ENV_KEY = "LETRA_CEILING_DIRECTORIES";
171
+ function ceilingDirectories() {
172
+ const raw = process.env[CEILING_ENV_KEY];
173
+ if (!raw) return /* @__PURE__ */ new Set();
174
+ return new Set(
175
+ raw.split(delimiter).map((entry) => entry.trim()).filter(Boolean).map((entry) => normalizeForCompare(resolve(entry)))
176
+ );
177
+ }
178
+ function normalizeForCompare(path) {
179
+ return process.platform === "win32" ? path.toLowerCase() : path;
180
+ }
181
+ function isHomeDirectory(dir) {
182
+ return normalizeForCompare(resolve(dir)) === normalizeForCompare(resolve(homedir2()));
183
+ }
167
184
  var LINK_FILE = ".letra-link";
168
185
  var LETRA_FOLDER = ".letra";
169
186
  var workspaceRootCache = /* @__PURE__ */ new Map();
@@ -184,32 +201,53 @@ function parseLinkTarget(dir, target) {
184
201
  function readLinkTarget(dir) {
185
202
  const linkPath = join2(dir, LINK_FILE);
186
203
  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;
204
+ let content = "";
205
+ try {
206
+ content = readFileSync2(linkPath, "utf-8").trim();
207
+ } catch {
208
+ return {
209
+ path: linkPath,
210
+ target: dir,
211
+ dataDir: dir,
212
+ valid: false,
213
+ errorMessage: "link unreadable"
214
+ };
192
215
  }
216
+ const target = content.split("\n")[0].trim();
217
+ if (!target)
218
+ return {
219
+ path: linkPath,
220
+ target: dir,
221
+ dataDir: dir,
222
+ valid: false,
223
+ errorMessage: "link is empty"
224
+ };
193
225
  const dataPath = parseLinkTarget(dir, target);
194
226
  if (!existsSync2(dataPath)) {
195
- console.warn(
196
- `Letra link target does not exist (${dataPath}) \u2014 falling back to local .letra/.`
197
- );
198
- return null;
227
+ return {
228
+ path: linkPath,
229
+ target: dataPath,
230
+ dataDir: dataPath,
231
+ valid: false,
232
+ errorMessage: "link target does not exist"
233
+ };
199
234
  }
200
235
  const directWorkflow = join2(dataPath, "workflow.json");
201
236
  const legacyHarnessDir = join2(dataPath, LETRA_FOLDER);
202
237
  const legacyWorkflow = join2(legacyHarnessDir, "workflow.json");
203
238
  if (existsSync2(directWorkflow)) {
204
- return { path: linkPath, target: dataPath, dataDir: dataPath };
239
+ return { path: linkPath, target: dataPath, dataDir: dataPath, valid: true };
205
240
  }
206
241
  if (existsSync2(legacyWorkflow)) {
207
- return { path: linkPath, target: dataPath, dataDir: legacyHarnessDir };
242
+ return { path: linkPath, target: dataPath, dataDir: legacyHarnessDir, valid: true };
208
243
  }
209
- console.warn(
210
- `Letra link target (${dataPath}) has no workflow.json \u2014 falling back to local .letra/.`
211
- );
212
- return null;
244
+ return {
245
+ path: linkPath,
246
+ target: dataPath,
247
+ dataDir: dataPath,
248
+ valid: false,
249
+ errorMessage: "link target has no workflow.json"
250
+ };
213
251
  }
214
252
  function resolution(input) {
215
253
  return {
@@ -220,13 +258,14 @@ function resolution(input) {
220
258
  };
221
259
  }
222
260
  function resolveWorkspaceRoot(cwd) {
223
- const start = cwd ?? process.cwd();
261
+ const start = resolve(cwd ?? process.cwd());
224
262
  if (workspaceRootCache.has(start)) return workspaceRootCache.get(start);
225
263
  let dir = start;
226
- const root = parse(dir).root;
227
264
  const originalCwd = start;
265
+ const ceilings = ceilingDirectories();
228
266
  const result = (function walk() {
229
- while (dir && dir !== root) {
267
+ while (dir) {
268
+ if (dir !== start && ceilings.has(normalizeForCompare(dir))) break;
230
269
  const envWs = getEnvWorkspace();
231
270
  if (envWs) {
232
271
  const wsDir = getWorkspacePath(envWs);
@@ -253,6 +292,12 @@ function resolveWorkspaceRoot(cwd) {
253
292
  });
254
293
  }
255
294
  }
295
+ if (dir !== start && isHomeDirectory(dir)) {
296
+ const parent2 = dirname(dir);
297
+ if (parent2 === dir) break;
298
+ dir = parent2;
299
+ continue;
300
+ }
256
301
  if (existsSync2(join2(dir, "workflow.json"))) {
257
302
  return resolution({
258
303
  workspaceDir: dir,
@@ -267,7 +312,10 @@ function resolveWorkspaceRoot(cwd) {
267
312
  workspaceDir: linked.dataDir,
268
313
  targetDir: originalCwd,
269
314
  workspaceRoot: linked.target,
270
- type: "linked"
315
+ type: "linked",
316
+ errorCode: linked.valid ? void 0 : "WORKSPACE_LINK_INVALID",
317
+ errorMessage: linked.errorMessage,
318
+ linkPath: linked.path
271
319
  });
272
320
  }
273
321
  const manifest = detectManifest(dir);
@@ -281,6 +329,10 @@ function resolveWorkspaceRoot(cwd) {
281
329
  });
282
330
  }
283
331
  const localLetra = join2(dir, LETRA_FOLDER);
332
+ if (resolve(localLetra) === resolve(homedir2(), LETRA_FOLDER)) {
333
+ dir = dirname(dir);
334
+ continue;
335
+ }
284
336
  if (existsSync2(localLetra) && statSync(localLetra).isDirectory()) {
285
337
  return resolution({
286
338
  workspaceDir: localLetra,
@@ -289,7 +341,9 @@ function resolveWorkspaceRoot(cwd) {
289
341
  type: "local"
290
342
  });
291
343
  }
292
- dir = dirname(dir);
344
+ const parent = dirname(dir);
345
+ if (parent === dir) break;
346
+ dir = parent;
293
347
  }
294
348
  return resolution({
295
349
  workspaceDir: join2(originalCwd, LETRA_FOLDER),
@@ -314,7 +368,7 @@ function resolveDataDir(root) {
314
368
  }
315
369
  if (result === null) {
316
370
  const linked = readLinkTarget(root);
317
- if (linked) {
371
+ if (linked?.valid) {
318
372
  result = linked.dataDir;
319
373
  }
320
374
  }
@@ -336,9 +390,6 @@ function getLetraDir2(root) {
336
390
  return join2(root, LETRA_FOLDER);
337
391
  }
338
392
  }
339
- function getSpecsDir(root) {
340
- return join2(getLetraDir2(root), "specs");
341
- }
342
393
  function isWorkspaceMode(resolution2) {
343
394
  return resolution2.type === "linked" || resolution2.type === "env" || resolution2.type === "flag" || resolution2.type === "direct";
344
395
  }
@@ -355,9 +406,10 @@ export {
355
406
  loadWorkspaceInfo,
356
407
  listWorkspaces,
357
408
  LINK_FILE,
409
+ LETRA_FOLDER,
358
410
  resolveWorkspaceRoot,
359
411
  clearWorkspaceCache,
412
+ resolveDataDir,
360
413
  getLetraDir2,
361
- getSpecsDir,
362
414
  isWorkspaceMode
363
415
  };