@letra-ai/cli 0.6.2 → 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 (52) 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-URUC6ZZP.js → chunk-MUCIMQAU.js} +1735 -861
  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-UPFERQMD.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 +81 -3
  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 +1 -0
  28. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +1 -0
  29. package/dist/{health-record-YDVXEVLR.js → health-record-JO2ZTIMR.js} +2 -2
  30. package/dist/index.js +2284 -1168
  31. package/dist/{push-VJRSQGUD.js → push-2ZCQSOHF.js} +37 -49
  32. package/dist/server-WUYVNSH7.js +677 -0
  33. package/dist/service-SVEAXQBX.js +28 -0
  34. package/dist/service-TOBY3OHO.js +22 -0
  35. package/dist/service-USTAY5E3.js +62 -0
  36. package/dist/{session-log-WTQ5JBEN.js → session-log-X2Q4XKQN.js} +6 -2
  37. package/dist/specs-CQRB7LPA.js +21 -0
  38. package/dist/sync-LIVPQXEW.js +21 -0
  39. package/package.json +1 -1
  40. package/dist/chunk-DMOLJWWW.js +0 -3321
  41. package/dist/chunk-EDD55PWL.js +0 -119
  42. package/dist/chunk-H64RC3YS.js +0 -254
  43. package/dist/chunk-L6YKDTAQ.js +0 -275
  44. package/dist/chunk-OIHMDOIN.js +0 -1326
  45. package/dist/client/assets/index-EyRsq1SH.css +0 -1
  46. package/dist/client/assets/index-WfKR7Xp6.js +0 -232
  47. package/dist/fallback-MQLGS4KL.js +0 -46
  48. package/dist/flow-serve-G5MSSB3G.js +0 -18
  49. package/dist/focus-sync-3D3XWCTI.js +0 -17
  50. package/dist/server-P6GKRWDX.js +0 -423
  51. package/dist/service-2JN2KI4D.js +0 -29
  52. package/dist/sitrep-OKNZJICV.js +0 -16
@@ -0,0 +1,554 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ loadSessionLog
4
+ } from "./chunk-UMC5PDL2.js";
5
+ import {
6
+ getLetraDir2 as getLetraDir
7
+ } from "./chunk-YAQ2TKSK.js";
8
+
9
+ // src/spec-catalog/service.ts
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "fs";
11
+ import { join, relative } from "path";
12
+
13
+ // src/spec-catalog/config.ts
14
+ var DEFAULT_CATALOG_CONFIG = {
15
+ consolidationTargets: {
16
+ "design-system": "design-system-v2",
17
+ "pitagoras-ux": "design-system-v2",
18
+ "ds-catalog": "design-system-v2",
19
+ "design-system-v2-patterns": "design-system-v2",
20
+ "adapter-alerts": "adapter-platform-v2",
21
+ "adapter-claude-code": "adapter-platform-v2",
22
+ "adapter-codex-cli": "adapter-platform-v2",
23
+ "adapter-cursor": "adapter-platform-v2",
24
+ "adapter-hermes": "adapter-platform-v2",
25
+ "adapter-opencode": "adapter-platform-v2",
26
+ "adapter-vscode": "adapter-platform-v2",
27
+ "adapter-windsurf": "adapter-platform-v2",
28
+ "harness-agent-direction": "adapter-platform-v2",
29
+ "architecture-convergence": "architecture-agnostic"
30
+ },
31
+ canonicalIds: [
32
+ "activity-context",
33
+ "architecture-agnostic",
34
+ "adapter-platform-v2",
35
+ "design-system-v2",
36
+ "agent-orchestration",
37
+ "agent-identity",
38
+ "external-executor-protocol",
39
+ "semiautonomous-flow",
40
+ "canonical-operation-gateway",
41
+ "durable-execution-leases",
42
+ "idempotent-runtime-projections",
43
+ "protocol-conformance-reference",
44
+ "security-review-scoped",
45
+ "supervision-signals",
46
+ "tool-adapters",
47
+ "launch-site",
48
+ "spec-governance-hygiene"
49
+ ],
50
+ priorityTiers: [
51
+ { rank: 1, tier: "workspace", specIds: ["canonical-workspace-integrity", "harness-schema-validation", "spec-frontmatter", "canonical-operation-gateway"] },
52
+ { rank: 2, tier: "execution", specIds: ["durable-execution-leases", "idempotent-runtime-projections", "protocol-conformance-reference", "external-executor-protocol", "semiautonomous-flow"] },
53
+ { rank: 3, tier: "governance", specIds: ["security-review-scoped", "supervision-signals", "agent-orchestration", "agent-identity"] },
54
+ { rank: 4, tier: "adapters", specIds: ["adapter-platform-v2", "tool-adapters", "architecture-agnostic"] },
55
+ { rank: 5, tier: "supervision", specIds: ["activity-context", "design-system-v2", "launch-site"] }
56
+ ]
57
+ };
58
+
59
+ // src/spec-catalog/service.ts
60
+ var SPEC_CATALOG_SCHEMA_VERSION = "1";
61
+ var SPEC_CATALOG_FILE = "spec-catalog.json";
62
+ var SPEC_DISPOSITIONS_FILE = "spec-dispositions.json";
63
+ function loadCatalogConfig(root) {
64
+ const configPath = join(getLetraDir(root), "spec-catalog.config.json");
65
+ if (!existsSync(configPath)) return DEFAULT_CATALOG_CONFIG;
66
+ try {
67
+ const raw = JSON.parse(readFileSync(configPath, "utf8"));
68
+ return {
69
+ consolidationTargets: raw.consolidationTargets ?? DEFAULT_CATALOG_CONFIG.consolidationTargets,
70
+ canonicalIds: raw.canonicalIds ?? DEFAULT_CATALOG_CONFIG.canonicalIds,
71
+ priorityTiers: raw.priorityTiers ?? DEFAULT_CATALOG_CONFIG.priorityTiers
72
+ };
73
+ } catch {
74
+ return DEFAULT_CATALOG_CONFIG;
75
+ }
76
+ }
77
+ function readFocusSpec(root) {
78
+ const focusPath = join(getLetraDir(root), "focus.md");
79
+ if (!existsSync(focusPath)) return null;
80
+ const content = readFileSync(focusPath, "utf8");
81
+ return content.match(/^# Focus:\s*([^\r\n]+)/m)?.[1]?.trim() || null;
82
+ }
83
+ function dependenciesIn(content, knownSpecIds, currentId) {
84
+ const references = /* @__PURE__ */ new Set();
85
+ const section = content.match(/^## Dependencies\s*\r?\n([\s\S]*)(?=^## |$)/mi)?.[1] ?? "";
86
+ for (const line of section.split(/\r?\n/)) {
87
+ for (const candidate of knownSpecIds) {
88
+ const escaped = candidate.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
89
+ if (candidate !== currentId && new RegExp(`(?:^|[^a-z0-9-])${escaped}(?![a-z0-9-])`, "i").test(line)) {
90
+ references.add(candidate);
91
+ }
92
+ }
93
+ }
94
+ return [...references].sort();
95
+ }
96
+ function orderByDependencies(specs) {
97
+ const graph = /* @__PURE__ */ new Map();
98
+ for (const spec of specs) graph.set(spec.id, { spec, inDegree: 0 });
99
+ for (const spec of specs) {
100
+ for (const dep of spec.dependencies) {
101
+ const node = graph.get(dep);
102
+ if (node) node.inDegree++;
103
+ }
104
+ }
105
+ const sorted = [];
106
+ const queue = [...graph.entries()].filter(([, n]) => n.inDegree === 0).sort((a, b) => a[1].spec.priority.rank - b[1].spec.priority.rank || a[0].localeCompare(b[0]));
107
+ while (queue.length > 0) {
108
+ const [id, node] = queue.shift();
109
+ sorted.push(node.spec);
110
+ for (const spec of specs) {
111
+ if (spec.dependencies.includes(id)) {
112
+ const neighbor = graph.get(spec.id);
113
+ neighbor.inDegree--;
114
+ if (neighbor.inDegree === 0) queue.push([spec.id, neighbor]);
115
+ }
116
+ }
117
+ queue.sort((a, b) => a[1].spec.priority.rank - b[1].spec.priority.rank || a[0].localeCompare(b[0]));
118
+ }
119
+ return sorted.length === specs.length ? sorted : [...specs];
120
+ }
121
+ function directionMarkers(content) {
122
+ const markers = [
123
+ "governance",
124
+ "human gate",
125
+ "human",
126
+ "agent",
127
+ "handoff",
128
+ "evidence",
129
+ "executor",
130
+ "workspace",
131
+ "workflow"
132
+ ];
133
+ const lower = content.toLocaleLowerCase();
134
+ return markers.filter((marker) => lower.includes(marker));
135
+ }
136
+ function itemStatus(workflow, item) {
137
+ const stage = workflow?.stages.find((candidate) => candidate.id === item.stage);
138
+ return stage?.zone === "done" || item.stage === "done" ? "completed" : "active";
139
+ }
140
+ function pathFor(root) {
141
+ return join(getLetraDir(root), SPEC_CATALOG_FILE);
142
+ }
143
+ function dispositionsPathFor(root) {
144
+ return join(getLetraDir(root), SPEC_DISPOSITIONS_FILE);
145
+ }
146
+ function readDispositions(root) {
147
+ const path = dispositionsPathFor(root);
148
+ if (!existsSync(path)) return {};
149
+ try {
150
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
151
+ return Object.fromEntries((parsed.records ?? []).filter(
152
+ (record) => record && typeof record.specId === "string" && ["active", "consolidated", "archived"].includes(record.disposition)
153
+ ).map((record) => [record.specId, record]));
154
+ } catch {
155
+ return {};
156
+ }
157
+ }
158
+ function defaultDisposition(id, linked, canonicalIds, config) {
159
+ const target = config.consolidationTargets[id];
160
+ if (target) {
161
+ return {
162
+ specId: id,
163
+ disposition: "consolidated",
164
+ canonicalSpecId: target,
165
+ rationale: `Consolidada na capability can\xF4nica ${target}, preservando esta spec como hist\xF3rico rastre\xE1vel.`,
166
+ decidedBy: "spec-governance-hygiene",
167
+ decidedAt: (/* @__PURE__ */ new Date()).toISOString(),
168
+ rollbackRef: `specs/${id}`,
169
+ preservedPaths: [`specs/${id}/spec.md`, `specs/${id}/acceptance.md`]
170
+ };
171
+ }
172
+ const hasActiveItem = linked.some((item) => itemStatus(null, item) === "active" && item.stage !== "done");
173
+ const canonical = canonicalIds.has(id);
174
+ const disposition = hasActiveItem || canonical ? "active" : "archived";
175
+ const rationale = hasActiveItem ? "Mantida porque possui trabalho ativo no workflow vigente." : canonical ? "Mantida como spec can\xF4nica da capability na dire\xE7\xE3o vigente." : "Preservada como hist\xF3rico; n\xE3o h\xE1 trabalho ativo vinculado na dire\xE7\xE3o vigente.";
176
+ return {
177
+ specId: id,
178
+ disposition,
179
+ canonicalSpecId: canonical ? id : null,
180
+ rationale,
181
+ decidedBy: "spec-governance-hygiene",
182
+ decidedAt: (/* @__PURE__ */ new Date()).toISOString(),
183
+ rollbackRef: `specs/${id}`,
184
+ preservedPaths: [`specs/${id}/spec.md`, `specs/${id}/acceptance.md`]
185
+ };
186
+ }
187
+ function priorityFor(id, disposition, config) {
188
+ if (disposition === "archived") return { rank: 6, tier: "history" };
189
+ for (const tier of config.priorityTiers) {
190
+ if (tier.specIds.includes(id)) return { rank: tier.rank, tier: tier.tier };
191
+ }
192
+ return { rank: 5, tier: "supervision" };
193
+ }
194
+ function ensureDispositions(root, ids, linkedItems, config) {
195
+ const existing = readDispositions(root);
196
+ const canonicalIds = new Set(config.canonicalIds);
197
+ const records = { ...existing };
198
+ for (const id of ids) {
199
+ if (!records[id] || records[id].decidedBy === "spec-governance-hygiene") {
200
+ records[id] = defaultDisposition(id, linkedItems.get(id) ?? [], canonicalIds, config);
201
+ }
202
+ }
203
+ return records;
204
+ }
205
+ function writeDispositions(root, records) {
206
+ const path = dispositionsPathFor(root);
207
+ mkdirSync(join(path, ".."), { recursive: true });
208
+ const content = `${JSON.stringify({ schemaVersion: SPEC_CATALOG_SCHEMA_VERSION, records: Object.values(records).sort((a, b) => a.specId.localeCompare(b.specId)) }, null, 2)}
209
+ `;
210
+ const tmpPath = `${path}.tmp.${Date.now()}`;
211
+ try {
212
+ writeFileSync(tmpPath, content, "utf8");
213
+ renameSync(tmpPath, path);
214
+ } catch (err) {
215
+ try {
216
+ unlinkSync(tmpPath);
217
+ } catch {
218
+ }
219
+ throw err;
220
+ }
221
+ }
222
+ function buildSpecCatalog(root, workflow, options) {
223
+ const config = options?.config ?? loadCatalogConfig(root);
224
+ const letraDir = getLetraDir(root);
225
+ const specsDir = join(letraDir, "specs");
226
+ const focusSpec = readFocusSpec(root);
227
+ const focusItem = workflow?.items.find((item) => item.spec === focusSpec)?.id ?? null;
228
+ const items = workflow?.items ?? [];
229
+ const directories = existsSync(specsDir) ? readdirSync(specsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort() : [];
230
+ const knownSpecIds = /* @__PURE__ */ new Set([
231
+ ...directories,
232
+ ...items.map((item) => item.spec).filter((id) => Boolean(id))
233
+ ]);
234
+ const allSpecIds = [...knownSpecIds].sort();
235
+ const lastUseByItem = /* @__PURE__ */ new Map();
236
+ for (const entry of loadSessionLog(root).entries) {
237
+ if (!entry.itemId || !Number.isFinite(Date.parse(entry.timestamp))) continue;
238
+ const previous = lastUseByItem.get(entry.itemId);
239
+ if (!previous || Date.parse(entry.timestamp) > Date.parse(previous)) {
240
+ lastUseByItem.set(entry.itemId, new Date(entry.timestamp).toISOString());
241
+ }
242
+ }
243
+ const linkedItems = /* @__PURE__ */ new Map();
244
+ for (const item of items) {
245
+ if (!item.spec) continue;
246
+ const current = linkedItems.get(item.spec) ?? [];
247
+ current.push(item);
248
+ linkedItems.set(item.spec, current);
249
+ }
250
+ const dispositions = ensureDispositions(root, allSpecIds, linkedItems, config);
251
+ const specs = orderByDependencies(allSpecIds.map((id) => {
252
+ const specPath = join(specsDir, id, "spec.md");
253
+ const valid = existsSync(specPath);
254
+ const content = valid ? readFileSync(specPath, "utf8") : "";
255
+ const linked = linkedItems.get(id) ?? [];
256
+ const stages = [...new Set(linked.map((item) => item.stage))].sort();
257
+ const active = linked.some((item) => itemStatus(workflow, item) === "active");
258
+ const lastUsedCandidates = linked.map((item) => lastUseByItem.get(item.id)).filter((value) => Boolean(value));
259
+ const lastUsedAt = lastUsedCandidates.sort((left, right) => Date.parse(right) - Date.parse(left))[0] ?? null;
260
+ const focus = id === focusSpec;
261
+ const relationship = focus ? "current-focus" : linked.length > 0 ? "workflow-linked" : "unlinked";
262
+ const primaryItemId = linked.length > 0 ? linked.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt))[0].id : null;
263
+ return {
264
+ id,
265
+ path: `specs/${id}/spec.md`,
266
+ status: !valid ? "invalid" : active ? "active" : linked.length > 0 ? "completed" : "unlinked",
267
+ valid,
268
+ itemIds: linked.map((item) => item.id).sort(),
269
+ primaryItemId,
270
+ stages,
271
+ lastUsedAt,
272
+ lastUseSource: lastUsedAt ? "session-log" : "unknown",
273
+ disposition: dispositions[id],
274
+ dependencies: dependenciesIn(content, knownSpecIds, id),
275
+ direction: { relationship, focus, indicators: directionMarkers(content) },
276
+ priority: priorityFor(id, dispositions[id].disposition, config)
277
+ };
278
+ }));
279
+ return {
280
+ schemaVersion: SPEC_CATALOG_SCHEMA_VERSION,
281
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
282
+ source: {
283
+ workflowPath: `workflow.json`,
284
+ specsPath: `specs/`,
285
+ focusPath: `focus.md`
286
+ },
287
+ currentFocus: { spec: focusSpec, itemId: focusItem },
288
+ dispositionsPath: SPEC_DISPOSITIONS_FILE,
289
+ specs,
290
+ items: items.map((item) => {
291
+ const itemSpec = item.spec;
292
+ const disposition = itemSpec ? dispositions[itemSpec] : void 0;
293
+ const resolved = disposition?.canonicalSpecId ?? itemSpec ?? null;
294
+ const isConsolidated = disposition?.disposition === "consolidated" && disposition?.canonicalSpecId;
295
+ const deps = [];
296
+ if (itemSpec && knownSpecIds.has(itemSpec)) deps.push(itemSpec);
297
+ if (isConsolidated && resolved && resolved !== itemSpec && knownSpecIds.has(resolved)) deps.push(resolved);
298
+ return {
299
+ id: item.id,
300
+ description: item.description,
301
+ stage: item.stage,
302
+ status: itemStatus(workflow, item),
303
+ spec: itemSpec ?? null,
304
+ resolvedSpec: resolved,
305
+ consolidatedFrom: isConsolidated ? itemSpec ?? null : null,
306
+ specDisposition: itemSpec ? directories.includes(itemSpec) ? disposition?.disposition ?? "missing" : "missing" : null,
307
+ claimedBy: item.claimedBy ?? null,
308
+ dependencies: deps,
309
+ priorityRank: priorityFor(itemSpec ?? "", itemSpec ? disposition?.disposition ?? "archived" : "archived", config).rank
310
+ };
311
+ })
312
+ };
313
+ }
314
+ function writeSpecCatalog(root, workflow) {
315
+ const config = loadCatalogConfig(root);
316
+ const destination = pathFor(root);
317
+ mkdirSync(join(destination, ".."), { recursive: true });
318
+ const catalog = buildSpecCatalog(root, workflow, { config });
319
+ const letraDir = getLetraDir(root);
320
+ const specsDir = join(letraDir, "specs");
321
+ const directories = existsSync(specsDir) ? readdirSync(specsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort() : [];
322
+ const knownSpecIds = /* @__PURE__ */ new Set([
323
+ ...directories,
324
+ ...(workflow?.items ?? []).map((item) => item.spec).filter((id) => Boolean(id))
325
+ ]);
326
+ const linkedItems = /* @__PURE__ */ new Map();
327
+ for (const item of workflow?.items ?? []) {
328
+ if (!item.spec) continue;
329
+ const current = linkedItems.get(item.spec) ?? [];
330
+ current.push(item);
331
+ linkedItems.set(item.spec, current);
332
+ }
333
+ const dispositions = ensureDispositions(root, [...knownSpecIds].sort(), linkedItems, config);
334
+ writeDispositions(root, dispositions);
335
+ catalog.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
336
+ writeFileSync(destination, `${JSON.stringify(catalog, null, 2)}
337
+ `, "utf8");
338
+ return catalog;
339
+ }
340
+ function readSpecCatalog(root) {
341
+ const path = pathFor(root);
342
+ if (!existsSync(path)) return null;
343
+ try {
344
+ return JSON.parse(readFileSync(path, "utf8"));
345
+ } catch {
346
+ return null;
347
+ }
348
+ }
349
+ function validateSpecCatalog(root, workflow = null) {
350
+ const issues = [];
351
+ const letraDir = getLetraDir(root);
352
+ const specsDir = join(letraDir, "specs");
353
+ const workflowItems = workflow?.items ?? [];
354
+ const directories = existsSync(specsDir) ? readdirSync(specsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name) : [];
355
+ const knownIds = /* @__PURE__ */ new Set([...directories, ...workflowItems.map((item) => item.spec).filter((id) => Boolean(id))]);
356
+ const catalogPath = pathFor(root);
357
+ const catalogExists = existsSync(catalogPath);
358
+ const dispositionPath = dispositionsPathFor(root);
359
+ const dispositionsExist = existsSync(dispositionPath);
360
+ if (!catalogExists && !dispositionsExist) return { valid: true, issues };
361
+ if (!catalogExists) issues.push({ code: "CATALOG_MISSING", message: "spec-catalog.json n\xE3o existe; gere com 'letra spec catalog'." });
362
+ if (!dispositionsExist) issues.push({ code: "DISPOSITIONS_MISSING", message: "spec-dispositions.json n\xE3o existe." });
363
+ let records = [];
364
+ if (existsSync(dispositionPath)) {
365
+ try {
366
+ const parsed = JSON.parse(readFileSync(dispositionPath, "utf8"));
367
+ if (typeof parsed.schemaVersion === "string" && parsed.schemaVersion !== SPEC_CATALOG_SCHEMA_VERSION) {
368
+ issues.push({ code: "SCHEMA_VERSION_UNKNOWN", message: `Vers\xE3o de schema desconhecida: ${parsed.schemaVersion}. Esperado ${SPEC_CATALOG_SCHEMA_VERSION}.` });
369
+ }
370
+ if (!Array.isArray(parsed.records)) {
371
+ issues.push({ code: "DISPOSITIONS_INVALID", message: "Registro de disposi\xE7\xF5es n\xE3o cont\xE9m um array records." });
372
+ } else {
373
+ for (let i = 0; i < parsed.records.length; i++) {
374
+ if (parsed.records[i] === null || parsed.records[i] === void 0) {
375
+ issues.push({ code: "DISPOSITION_NULL_RECORD", message: `Registro nulo ou indefinido no \xEDndice ${i}.` });
376
+ }
377
+ }
378
+ records = parsed.records.filter((r) => r != null);
379
+ }
380
+ } catch {
381
+ issues.push({ code: "DISPOSITIONS_INVALID", message: "Registro de disposi\xE7\xF5es cont\xE9m JSON inv\xE1lido." });
382
+ }
383
+ }
384
+ const seen = /* @__PURE__ */ new Set();
385
+ const canonicalClaims = /* @__PURE__ */ new Map();
386
+ const recordById = /* @__PURE__ */ new Map();
387
+ for (const raw of records) {
388
+ const record = raw;
389
+ const id = typeof record.specId === "string" ? record.specId : "";
390
+ if (!id) {
391
+ issues.push({ code: "DISPOSITION_INVALID", message: "Disposi\xE7\xE3o sem specId." });
392
+ continue;
393
+ }
394
+ if (seen.has(id)) issues.push({ code: "DISPOSITION_DUPLICATE", message: `specId duplicado no registro: ${id}.`, specId: id });
395
+ seen.add(id);
396
+ if (!["active", "consolidated", "archived"].includes(record.disposition ?? "")) {
397
+ issues.push({ code: "DISPOSITION_INVALID", message: `Disposi\xE7\xE3o inv\xE1lida para ${id}.`, specId: id });
398
+ continue;
399
+ }
400
+ const disposition = record.disposition;
401
+ const canonical = typeof record.canonicalSpecId === "string" ? record.canonicalSpecId : null;
402
+ if (canonical && !knownIds.has(canonical)) {
403
+ issues.push({ code: "CANONICAL_REFERENCE_BROKEN", message: `${id} aponta para spec can\xF4nica inexistente: ${canonical}.`, specId: id });
404
+ }
405
+ if (disposition === "consolidated" && canonical) {
406
+ const previous = canonicalClaims.get(canonical);
407
+ if (previous && previous !== id) {
408
+ }
409
+ }
410
+ if (disposition === "active" && canonical) {
411
+ const previous = canonicalClaims.get(canonical);
412
+ if (previous && previous !== id) issues.push({ code: "DUPLICATE_CANONICAL", message: `Specs ativas ${previous} e ${id} declaram a mesma canonical ${canonical}.`, specId: id });
413
+ else canonicalClaims.set(canonical, id);
414
+ }
415
+ if (!record.rollbackRef || !Array.isArray(record.preservedPaths) || record.preservedPaths.length === 0) {
416
+ issues.push({ code: "REVERSIBILITY_MISSING", message: `${id} n\xE3o possui rollbackRef e preservedPaths completos.`, specId: id });
417
+ }
418
+ if (typeof record.specId === "string") recordById.set(id, record);
419
+ }
420
+ for (const id of knownIds) {
421
+ if (!recordById.has(id)) issues.push({ code: "DISPOSITION_INVALID", message: `Spec ${id} n\xE3o possui disposi\xE7\xE3o registrada.`, specId: id });
422
+ }
423
+ for (const record of recordById.values()) {
424
+ if (record.disposition === "consolidated" && record.canonicalSpecId) {
425
+ const target = recordById.get(record.canonicalSpecId);
426
+ if (!target || target.disposition !== "active") issues.push({ code: "CANONICAL_REFERENCE_BROKEN", message: `${record.specId} consolidada sem destino ativo: ${record.canonicalSpecId}.`, specId: record.specId });
427
+ }
428
+ }
429
+ const catalog = readSpecCatalog(root);
430
+ if (catalog && typeof catalog.schemaVersion === "string" && catalog.schemaVersion !== SPEC_CATALOG_SCHEMA_VERSION) {
431
+ issues.push({ code: "SCHEMA_VERSION_UNKNOWN", message: `Cat\xE1logo cont\xE9m vers\xE3o de schema desconhecida: ${catalog.schemaVersion}. Esperado ${SPEC_CATALOG_SCHEMA_VERSION}.` });
432
+ }
433
+ for (const dir of directories) {
434
+ const specFile = join(specsDir, dir, "spec.md");
435
+ if (!existsSync(specFile)) {
436
+ const disposition = recordById.get(dir)?.disposition;
437
+ if (disposition === "archived") continue;
438
+ issues.push({ code: "SPEC_FILE_MISSING", message: `Diret\xF3rio de spec ${dir} existe mas n\xE3o cont\xE9m spec.md.`, specId: dir });
439
+ }
440
+ }
441
+ const consolidationGraph = /* @__PURE__ */ new Map();
442
+ for (const [id, target] of Object.entries(loadCatalogConfig(root).consolidationTargets)) {
443
+ if (id !== target) consolidationGraph.set(id, target);
444
+ }
445
+ for (const [id, target] of consolidationGraph) {
446
+ const visited = /* @__PURE__ */ new Set();
447
+ let current = id;
448
+ while (current) {
449
+ if (visited.has(current)) {
450
+ issues.push({ code: "CONSOLIDATION_CYCLE", message: `Ciclo de consolida\xE7\xE3o detectado come\xE7ando em ${id}.`, specId: id });
451
+ break;
452
+ }
453
+ visited.add(current);
454
+ current = consolidationGraph.get(current);
455
+ if (current === id) {
456
+ issues.push({ code: "CONSOLIDATION_CYCLE", message: `Ciclo de consolida\xE7\xE3o detectado: ${id} \u2192 ... \u2192 ${current}.`, specId: id });
457
+ break;
458
+ }
459
+ }
460
+ }
461
+ if (catalog) {
462
+ const depGraph = /* @__PURE__ */ new Map();
463
+ for (const spec of catalog.specs) depGraph.set(spec.id, spec.dependencies);
464
+ for (const [id, deps] of depGraph) {
465
+ for (const dep of deps) {
466
+ const visited = /* @__PURE__ */ new Set();
467
+ let current = dep;
468
+ while (current) {
469
+ if (current === id) {
470
+ issues.push({ code: "CONSOLIDATION_CYCLE", message: `Ciclo de depend\xEAncias detectado: ${id} \u2192 ... \u2192 ${dep}.`, specId: id });
471
+ break;
472
+ }
473
+ if (visited.has(current)) break;
474
+ visited.add(current);
475
+ current = depGraph.get(current)?.find((d) => d !== current) ?? void 0;
476
+ }
477
+ }
478
+ }
479
+ }
480
+ for (const item of workflowItems) {
481
+ if (!item.spec) continue;
482
+ const record = recordById.get(item.spec);
483
+ if (!record || !knownIds.has(item.spec)) {
484
+ issues.push({ code: "ITEM_SPEC_MISSING", message: `${item.id} aponta para spec ausente ou n\xE3o catalogada: ${item.spec}.`, itemId: item.id, specId: item.spec });
485
+ continue;
486
+ }
487
+ const specDir = join(specsDir, item.spec);
488
+ if (!existsSync(specDir) || !existsSync(join(specDir, "spec.md"))) {
489
+ issues.push({ code: "WORKFLOW_REFERENCE_UNVERIFIED", message: `${item.id} referencia ${item.spec} mas o spec.md n\xE3o existe no disco.`, itemId: item.id, specId: item.spec });
490
+ }
491
+ if (itemStatus(workflow, item) === "active" && record.disposition === "archived") {
492
+ issues.push({ code: "ACTIVE_ARCHIVED_REFERENCE", message: `${item.id} ativo aponta para spec arquivada: ${item.spec}.`, itemId: item.id, specId: item.spec });
493
+ }
494
+ }
495
+ if (catalog) {
496
+ for (const item of catalog.items) {
497
+ if (item.spec && item.specDisposition === "missing") issues.push({ code: "ITEM_SPEC_MISSING", message: `${item.id} est\xE1 sem resolu\xE7\xE3o no cat\xE1logo: ${item.spec}.`, itemId: item.id, specId: item.spec });
498
+ }
499
+ }
500
+ if (catalog && existsSync(dispositionPath)) {
501
+ try {
502
+ const catalogMtime = Date.parse(catalog.generatedAt);
503
+ const dispStat = statSync(dispositionPath);
504
+ const dispMtime = dispStat.mtimeMs;
505
+ const STALE_TOLERANCE_MS = 2e3;
506
+ if (dispMtime > catalogMtime + STALE_TOLERANCE_MS) {
507
+ issues.push({ code: "CATALOG_STALE", message: "spec-dispositions.json foi modificado ap\xF3s a gera\xE7\xE3o do cat\xE1logo. Regenere com 'letra spec catalog'." });
508
+ }
509
+ const workflowPath = join(getLetraDir(root), "workflow.json");
510
+ if (existsSync(workflowPath)) {
511
+ const wfStat = statSync(workflowPath);
512
+ if (wfStat.mtimeMs > catalogMtime + STALE_TOLERANCE_MS) {
513
+ issues.push({ code: "CATALOG_STALE", message: "workflow.json foi modificado ap\xF3s a gera\xE7\xE3o do cat\xE1logo. Regenere com 'letra spec catalog'." });
514
+ }
515
+ }
516
+ } catch {
517
+ }
518
+ }
519
+ return { valid: issues.length === 0, issues };
520
+ }
521
+ function specCatalogPath(root) {
522
+ return relative(root, pathFor(root));
523
+ }
524
+ function restoreDisposition(root, specId) {
525
+ const records = readDispositions(root);
526
+ const record = records[specId];
527
+ if (!record) return null;
528
+ const restored = {
529
+ ...record,
530
+ disposition: "active",
531
+ canonicalSpecId: specId,
532
+ rationale: `Restaurada de ${record.disposition} para active em ${(/* @__PURE__ */ new Date()).toISOString()}.`,
533
+ decidedBy: "spec-governance-hygiene",
534
+ decidedAt: (/* @__PURE__ */ new Date()).toISOString(),
535
+ rollbackRef: record.rollbackRef || `specs/${specId}`,
536
+ preservedPaths: record.preservedPaths.length > 0 ? record.preservedPaths : [`specs/${specId}/spec.md`, `specs/${specId}/acceptance.md`]
537
+ };
538
+ const updated = { ...records, [specId]: restored };
539
+ writeDispositions(root, updated);
540
+ return restored;
541
+ }
542
+
543
+ export {
544
+ SPEC_CATALOG_SCHEMA_VERSION,
545
+ SPEC_CATALOG_FILE,
546
+ SPEC_DISPOSITIONS_FILE,
547
+ loadCatalogConfig,
548
+ buildSpecCatalog,
549
+ writeSpecCatalog,
550
+ readSpecCatalog,
551
+ validateSpecCatalog,
552
+ specCatalogPath,
553
+ restoreDisposition
554
+ };