@letra-ai/cli 0.5.3 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/chunk-4QDEU6KP.js +2765 -0
  2. package/dist/chunk-6HSUVCTR.js +363 -0
  3. package/dist/chunk-BKAUN5QH.js +300 -0
  4. package/dist/chunk-BTPFUKHG.js +275 -0
  5. package/dist/chunk-EDD55PWL.js +119 -0
  6. package/dist/chunk-ELBTIPYN.js +256 -0
  7. package/dist/chunk-IEFSLCJL.js +837 -0
  8. package/dist/chunk-JMIC5NKB.js +235 -0
  9. package/dist/chunk-KGQLHMGZ.js +4494 -0
  10. package/dist/chunk-MJ2QXNH6.js +130 -0
  11. package/dist/chunk-MSF44WWE.js +443 -0
  12. package/dist/chunk-PDX44BCA.js +11 -0
  13. package/dist/chunk-QIVKP3EY.js +362 -0
  14. package/dist/client/assets/index-BuABgOyz.js +232 -0
  15. package/dist/client/assets/index-CpseCZh9.css +1 -0
  16. package/dist/client/favicon.svg +16 -4
  17. package/dist/client/index.html +25 -20
  18. package/dist/fallback-UXSZ4LNR.js +47 -0
  19. package/dist/flow-serve-MTB6KZMR.js +19 -0
  20. package/dist/focus-sync-3D3XWCTI.js +17 -0
  21. package/dist/generate-N22QOXUF.js +20 -0
  22. package/dist/harness/default/v0.1.0/flows/sdlc.yaml +179 -0
  23. package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +8 -0
  24. package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +7 -0
  25. package/dist/harness/default/v0.1.0/gates/human-approved-code.yaml +8 -0
  26. package/dist/harness/default/v0.1.0/gates/human-approved-spec.yaml +8 -0
  27. package/dist/harness/default/v0.1.0/gates/security-clear.yaml +8 -0
  28. package/dist/harness/default/v0.1.0/policies/sdlc-default.json +20 -0
  29. package/dist/harness/default/v0.1.0/roles/analyst.yaml +9 -0
  30. package/dist/harness/default/v0.1.0/roles/builder.yaml +9 -0
  31. package/dist/harness/default/v0.1.0/roles/pr-bot.yaml +8 -0
  32. package/dist/harness/default/v0.1.0/roles/reviewer.yaml +10 -0
  33. package/dist/harness/default/v0.1.0/roles/security.yaml +8 -0
  34. package/dist/harness/default/v0.1.1/flows/flow-main.yaml +61 -0
  35. package/dist/harness/default/v0.1.1/flows/sdlc.yaml +179 -0
  36. package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +8 -0
  37. package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +7 -0
  38. package/dist/harness/default/v0.1.1/gates/human-approved-code.yaml +8 -0
  39. package/dist/harness/default/v0.1.1/gates/human-approved-spec.yaml +8 -0
  40. package/dist/harness/default/v0.1.1/gates/security-clear.yaml +8 -0
  41. package/dist/harness/default/v0.1.1/policies/sdlc-default.json +20 -0
  42. package/dist/harness/default/v0.1.1/roles/analyst.yaml +9 -0
  43. package/dist/harness/default/v0.1.1/roles/builder.yaml +9 -0
  44. package/dist/harness/default/v0.1.1/roles/pr-bot.yaml +8 -0
  45. package/dist/harness/default/v0.1.1/roles/reviewer.yaml +10 -0
  46. package/dist/harness/default/v0.1.1/roles/security.yaml +8 -0
  47. package/dist/harness/default/v0.1.2/flows/flow-main.yaml +86 -0
  48. package/dist/harness/default/v0.1.2/flows/sdlc.yaml +179 -0
  49. package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +8 -0
  50. package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +7 -0
  51. package/dist/harness/default/v0.1.2/gates/human-approved-code.yaml +8 -0
  52. package/dist/harness/default/v0.1.2/gates/human-approved-spec.yaml +8 -0
  53. package/dist/harness/default/v0.1.2/gates/security-clear.yaml +8 -0
  54. package/dist/harness/default/v0.1.2/policies/sdlc-default.json +20 -0
  55. package/dist/harness/default/v0.1.2/roles/analyst.yaml +9 -0
  56. package/dist/harness/default/v0.1.2/roles/builder.yaml +9 -0
  57. package/dist/harness/default/v0.1.2/roles/pr-bot.yaml +8 -0
  58. package/dist/harness/default/v0.1.2/roles/reviewer.yaml +10 -0
  59. package/dist/harness/default/v0.1.2/roles/security.yaml +8 -0
  60. package/dist/harness/default/v0.1.3/flows/flow-main.yaml +90 -0
  61. package/dist/harness/default/v0.1.3/flows/sdlc.yaml +179 -0
  62. package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +8 -0
  63. package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +7 -0
  64. package/dist/harness/default/v0.1.3/gates/human-approved-code.yaml +9 -0
  65. package/dist/harness/default/v0.1.3/gates/human-approved-spec.yaml +9 -0
  66. package/dist/harness/default/v0.1.3/gates/security-clear.yaml +8 -0
  67. package/dist/harness/default/v0.1.3/policies/sdlc-default.json +20 -0
  68. package/dist/harness/default/v0.1.3/roles/analyst.yaml +9 -0
  69. package/dist/harness/default/v0.1.3/roles/builder.yaml +9 -0
  70. package/dist/harness/default/v0.1.3/roles/pr-bot.yaml +8 -0
  71. package/dist/harness/default/v0.1.3/roles/reviewer.yaml +10 -0
  72. package/dist/harness/default/v0.1.3/roles/security.yaml +8 -0
  73. package/dist/harness/default/v0.2.0/executors/registry.yaml +51 -0
  74. package/dist/harness/default/v0.2.0/flows/flow-main.yaml +247 -0
  75. package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +7 -0
  76. package/dist/harness/default/v0.2.0/gates/human-approved.yaml +10 -0
  77. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +7 -0
  78. package/dist/harness/default/v0.2.0/gates/spec-approved.yaml +10 -0
  79. package/dist/harness/default/v0.2.0/policies/sdlc-default.json +20 -0
  80. package/dist/harness/default/v0.2.0/roles/analyst.yaml +16 -0
  81. package/dist/harness/default/v0.2.0/roles/implementer.yaml +17 -0
  82. package/dist/harness/default/v0.2.0/roles/reviewer.yaml +17 -0
  83. package/dist/harness/default/v0.2.0/roles/security.yaml +17 -0
  84. package/dist/health-record-YDVXEVLR.js +21 -0
  85. package/dist/index.js +1932 -2528
  86. package/dist/init-wizard-NODBBNKO.js +178 -0
  87. package/dist/push-5JEYSXBY.js +116 -0
  88. package/dist/registry-6VPIA3EG.js +18 -0
  89. package/dist/server-FUP3APZA.js +415 -0
  90. package/dist/service-OGF7BMCQ.js +21 -0
  91. package/dist/session-log-WTQ5JBEN.js +21 -0
  92. package/dist/sitrep-DJXTP3JO.js +16 -0
  93. package/package.json +37 -28
  94. package/dist/chunk-56GTTLC4.js +0 -1322
  95. package/dist/chunk-QWT5M4XU.js +0 -643
  96. package/dist/client/assets/index-CuLfFw4K.js +0 -85
  97. package/dist/client/assets/index-iyLqZcWx.css +0 -1
  98. package/dist/generate-BF5R5GGA.js +0 -7
  99. package/dist/sitrep-SI6ZFIAM.js +0 -10
  100. package/tsup.config.ts +0 -11
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getLetraDir2 as getLetraDir
4
+ } from "./chunk-6HSUVCTR.js";
5
+
6
+ // src/health-record.ts
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
8
+ import { join } from "path";
9
+ var RECORD_FILE = "health-record.json";
10
+ var SCHEMA_VERSION = 1;
11
+ var CLEANUP_DAYS = 90;
12
+ function recordPath(root) {
13
+ return join(getLetraDir(root), RECORD_FILE);
14
+ }
15
+ function loadHealthRecord(root) {
16
+ const file = recordPath(root);
17
+ if (!existsSync(file)) {
18
+ return { schemaVersion: SCHEMA_VERSION, lastScanAt: (/* @__PURE__ */ new Date()).toISOString(), entries: [] };
19
+ }
20
+ try {
21
+ const raw = readFileSync(file, "utf-8");
22
+ const record = JSON.parse(raw);
23
+ if (!record.entries) record.entries = [];
24
+ return record;
25
+ } catch {
26
+ return { schemaVersion: SCHEMA_VERSION, lastScanAt: (/* @__PURE__ */ new Date()).toISOString(), entries: [] };
27
+ }
28
+ }
29
+ function saveHealthRecord(root, record) {
30
+ const dir = getLetraDir(root);
31
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
32
+ record.lastScanAt = (/* @__PURE__ */ new Date()).toISOString();
33
+ writeFileSync(recordPath(root), JSON.stringify(record, null, 2), "utf-8");
34
+ }
35
+ function hashResult(result) {
36
+ const key = `${result.detector}:${result.title}`;
37
+ let hash = 0;
38
+ for (let i = 0; i < key.length; i++) {
39
+ const char = key.charCodeAt(i);
40
+ hash = (hash << 5) - hash + char;
41
+ hash |= 0;
42
+ }
43
+ return `hr-${Math.abs(hash).toString(16).padStart(6, "0")}`;
44
+ }
45
+ function severityFromType(type) {
46
+ if (type === "error") return "alta";
47
+ if (type === "warning") return "media";
48
+ return "baixa";
49
+ }
50
+ function mergeScanResults(record, results) {
51
+ const now = (/* @__PURE__ */ new Date()).toISOString();
52
+ for (const result of results) {
53
+ const id = hashResult(result);
54
+ const existing = record.entries.find((e) => e.id === id);
55
+ if (!existing) {
56
+ record.entries.push({
57
+ id,
58
+ type: result.type,
59
+ title: result.title,
60
+ status: "novo",
61
+ severity: severityFromType(result.type),
62
+ source: result.detector,
63
+ detectedAt: now,
64
+ resolvedAt: null,
65
+ dismissedAt: null,
66
+ dismissReason: null,
67
+ acknowledgedAt: null
68
+ });
69
+ } else if (existing.status === "resolvido") {
70
+ existing.status = "novo";
71
+ existing.detectedAt = now;
72
+ existing.resolvedAt = null;
73
+ }
74
+ }
75
+ for (const entry of record.entries) {
76
+ if (entry.status === "descartado") continue;
77
+ const stillPresent = results.some((r) => hashResult(r) === entry.id);
78
+ if (!stillPresent && entry.status !== "resolvido") {
79
+ entry.status = "resolvido";
80
+ entry.resolvedAt = now;
81
+ }
82
+ }
83
+ record.entries = cleanupOldEntries(record.entries);
84
+ return record;
85
+ }
86
+ function cleanupOldEntries(entries) {
87
+ const cutoff = Date.now() - CLEANUP_DAYS * 24 * 60 * 60 * 1e3;
88
+ return entries.filter((e) => {
89
+ if (e.status !== "resolvido" && e.status !== "descartado") return true;
90
+ const refDate = e.resolvedAt ?? e.dismissedAt ?? e.detectedAt;
91
+ return new Date(refDate).getTime() > cutoff;
92
+ });
93
+ }
94
+ function ackEntry(record, id) {
95
+ const entry = record.entries.find((e) => e.id === id);
96
+ if (!entry) return false;
97
+ entry.status = "ciente";
98
+ entry.acknowledgedAt = (/* @__PURE__ */ new Date()).toISOString();
99
+ return true;
100
+ }
101
+ function dismissEntry(record, id, reason) {
102
+ const entry = record.entries.find((e) => e.id === id);
103
+ if (!entry) return false;
104
+ entry.status = "descartado";
105
+ entry.dismissedAt = (/* @__PURE__ */ new Date()).toISOString();
106
+ entry.dismissReason = reason ?? null;
107
+ return true;
108
+ }
109
+ function getActiveEntries(record) {
110
+ return record.entries.filter((e) => e.status === "novo" || e.status === "ciente");
111
+ }
112
+ function getSummary(record) {
113
+ return {
114
+ novo: record.entries.filter((e) => e.status === "novo").length,
115
+ ciente: record.entries.filter((e) => e.status === "ciente").length,
116
+ descartado: record.entries.filter((e) => e.status === "descartado").length,
117
+ resolvido: record.entries.filter((e) => e.status === "resolvido").length,
118
+ alta: record.entries.filter((e) => e.status === "novo" && e.severity === "alta").length
119
+ };
120
+ }
121
+
122
+ export {
123
+ loadHealthRecord,
124
+ saveHealthRecord,
125
+ mergeScanResults,
126
+ ackEntry,
127
+ dismissEntry,
128
+ getActiveEntries,
129
+ getSummary
130
+ };
@@ -0,0 +1,443 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ DEFAULT_HARNESS_VERSION,
4
+ loadHarness,
5
+ loadWorkflow,
6
+ resolveHarnessRoot
7
+ } from "./chunk-4QDEU6KP.js";
8
+ import {
9
+ readFocusFile
10
+ } from "./chunk-EDD55PWL.js";
11
+ import {
12
+ getLetraDir2 as getLetraDir
13
+ } from "./chunk-6HSUVCTR.js";
14
+
15
+ // src/flow-definition/resolve.ts
16
+ function resolveTemplate(workflow, harness) {
17
+ if (!workflow?.template || !harness) return null;
18
+ return harness.flows[workflow.template] ?? null;
19
+ }
20
+ function gateIdFromRef(gateRef) {
21
+ return gateRef.replace(/^.*[\\/]/, "").replace(/\.ya?ml$/, "");
22
+ }
23
+ function cloneActivityHint(hint) {
24
+ if (!hint) return void 0;
25
+ return {
26
+ ...hint,
27
+ mustRead: hint.mustRead?.map((reference) => ({ ...reference })),
28
+ mustNotDo: hint.mustNotDo ? [...hint.mustNotDo] : void 0,
29
+ nextActions: hint.nextActions?.map((action) => ({ ...action })),
30
+ commands: hint.commands?.map((command) => ({ ...command }))
31
+ };
32
+ }
33
+ function cloneActivity(activity) {
34
+ if (!activity) return void 0;
35
+ return {
36
+ design: cloneActivityHint(activity.design),
37
+ implement: cloneActivityHint(activity.implement),
38
+ review: cloneActivityHint(activity.review),
39
+ diagnose: cloneActivityHint(activity.diagnose),
40
+ gate: cloneActivityHint(activity.gate)
41
+ };
42
+ }
43
+ function resolveGate(harness, gateRef, warnings, artifactRef) {
44
+ if (!harness || !gateRef) return null;
45
+ const gateId = gateIdFromRef(gateRef);
46
+ const gate = harness.gates[gateId];
47
+ if (!gate) {
48
+ warnings.push({
49
+ code: "GATE_NOT_FOUND",
50
+ message: `Gate "${gateId}" referenced by ${artifactRef} was not found in the harness.`,
51
+ artifactRef
52
+ });
53
+ return null;
54
+ }
55
+ return {
56
+ id: gate.id,
57
+ name: gate.name,
58
+ type: gate.type,
59
+ blocking: gate.blocking,
60
+ policyRef: gate.policyRef,
61
+ description: gate.description,
62
+ decisions: gate.decisions ? { ...gate.decisions } : void 0
63
+ };
64
+ }
65
+ function cloneRole(role) {
66
+ return {
67
+ id: role.id,
68
+ label: role.label,
69
+ description: role.description,
70
+ allowedStages: [...role.allowedStages],
71
+ capabilities: [...role.capabilities]
72
+ };
73
+ }
74
+ function resolveRoles(harness, roleIds, warnings, artifactRef) {
75
+ if (!harness) return [];
76
+ return roleIds.flatMap((roleId) => {
77
+ const role = harness.roles[roleId];
78
+ if (role) return [cloneRole(role)];
79
+ warnings.push({
80
+ code: "ROLE_NOT_FOUND",
81
+ message: `Role "${roleId}" referenced by ${artifactRef} was not found in the harness.`,
82
+ artifactRef
83
+ });
84
+ return [];
85
+ });
86
+ }
87
+ function resolvePhases(harness, phases, warnings, stageId) {
88
+ if (!phases) return void 0;
89
+ return {
90
+ initialState: phases.initialState,
91
+ states: Object.fromEntries(
92
+ Object.entries(phases.states).map(([phaseId, phase]) => [
93
+ phaseId,
94
+ {
95
+ id: phase.id,
96
+ label: phase.label,
97
+ description: phase.description,
98
+ actions: phase.actions?.map((action) => ({ ...action })),
99
+ transitions: phase.transitions?.map((transition) => ({
100
+ target: transition.target,
101
+ gate: resolveGate(
102
+ harness,
103
+ transition.gate,
104
+ warnings,
105
+ `flow stage "${stageId}" phase "${phaseId}" transition to "${transition.target}"`
106
+ ),
107
+ ...transition.gate ? { gateRef: transition.gate } : {},
108
+ ...transition.auto === void 0 ? {} : { auto: transition.auto }
109
+ })),
110
+ harness: phase.harness ? {
111
+ ...phase.harness,
112
+ tools: phase.harness.tools ? [...phase.harness.tools] : void 0,
113
+ checks: phase.harness.checks ? [...phase.harness.checks] : void 0,
114
+ activity: cloneActivity(phase.harness.activity),
115
+ review: cloneActivityHint(phase.harness.review),
116
+ gate: cloneActivityHint(phase.harness.gate)
117
+ } : void 0
118
+ }
119
+ ])
120
+ )
121
+ };
122
+ }
123
+ function mergeTemplateStage(workflow, harness, stageDef, index, warnings) {
124
+ const workflowStage = workflow.stages.find((stage) => stage.id === stageDef.id);
125
+ const artifactRef = `flow stage "${stageDef.id}"`;
126
+ const roleIds = [...stageDef.agents ?? []];
127
+ return {
128
+ id: stageDef.id,
129
+ name: stageDef.name || workflowStage?.name || stageDef.id,
130
+ order: stageDef.order ?? workflowStage?.order ?? index,
131
+ zone: stageDef.zone ?? workflowStage?.zone,
132
+ description: stageDef.description,
133
+ roleIds,
134
+ roles: resolveRoles(harness, roleIds, warnings, artifactRef),
135
+ agents: [...roleIds],
136
+ gate: resolveGate(harness, stageDef.gate, warnings, artifactRef),
137
+ phases: resolvePhases(harness, stageDef.phases, warnings, stageDef.id),
138
+ activity: cloneActivity(stageDef.activity),
139
+ provenance: "harness"
140
+ };
141
+ }
142
+ function workflowStageDefinition(stage, provenance = "workflow-instance") {
143
+ return {
144
+ id: stage.id,
145
+ name: stage.name,
146
+ order: stage.order,
147
+ zone: stage.zone,
148
+ description: void 0,
149
+ roleIds: [],
150
+ roles: [],
151
+ agents: [],
152
+ gate: null,
153
+ phases: resolvePhases(null, stage.phases, [], stage.id),
154
+ activity: void 0,
155
+ provenance
156
+ };
157
+ }
158
+ function resolveFromTemplate(workflow, harness, template) {
159
+ const warnings = [];
160
+ const instanceStageIds = new Set(workflow.stages.map((stage) => stage.id));
161
+ const templateStageIds = new Set(template.stages.map((stage) => stage.id));
162
+ const templateStages = template.stages.map((stageDef, index) => {
163
+ if (!instanceStageIds.has(stageDef.id)) {
164
+ warnings.push({
165
+ code: "TEMPLATE_STAGE_NOT_IN_INSTANCE",
166
+ message: `Harness stage "${stageDef.id}" is not persisted in the workflow instance.`,
167
+ artifactRef: `flow stage "${stageDef.id}"`
168
+ });
169
+ }
170
+ return mergeTemplateStage(workflow, harness, stageDef, index, warnings);
171
+ });
172
+ const extensionStages = workflow.stages.filter((stage) => !templateStageIds.has(stage.id)).map((stage) => {
173
+ warnings.push({
174
+ code: "INSTANCE_STAGE_NOT_IN_TEMPLATE",
175
+ message: `Workflow stage "${stage.id}" is not declared by template "${template.id}".`,
176
+ artifactRef: `workflow stage "${stage.id}"`
177
+ });
178
+ return workflowStageDefinition(stage);
179
+ });
180
+ return {
181
+ id: template.id,
182
+ source: "workflow-template",
183
+ harnessVersion: workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION,
184
+ templateVersion: template.version,
185
+ name: template.name,
186
+ stages: [...templateStages, ...extensionStages].sort(
187
+ (left, right) => left.order - right.order
188
+ ),
189
+ roles: harness ? Object.values(harness.roles).map(cloneRole) : [],
190
+ warnings
191
+ };
192
+ }
193
+ function resolveFromWorkflow(workflow, source, warnings = []) {
194
+ return {
195
+ id: workflow.template ?? null,
196
+ source,
197
+ harnessVersion: workflow.harnessVersion ?? null,
198
+ templateVersion: null,
199
+ name: workflow.name,
200
+ stages: workflow.stages.map((stage) => workflowStageDefinition(stage)).sort((left, right) => left.order - right.order),
201
+ roles: [],
202
+ warnings: warnings.map((warning) => ({ ...warning }))
203
+ };
204
+ }
205
+ function resolveActiveFlowFrom(workflow, harness) {
206
+ const template = resolveTemplate(workflow, harness);
207
+ if (!workflow) {
208
+ return { workflow, harness, template: null, flow: null };
209
+ }
210
+ if (template) {
211
+ return {
212
+ workflow,
213
+ harness,
214
+ template,
215
+ flow: resolveFromTemplate(workflow, harness, template)
216
+ };
217
+ }
218
+ if (workflow.template) {
219
+ const warnings = harness ? [
220
+ {
221
+ code: "TEMPLATE_NOT_FOUND",
222
+ message: `Template "${workflow.template}" was not found in harness "${workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION}".`,
223
+ artifactRef: `harness flow "${workflow.template}"`
224
+ }
225
+ ] : [
226
+ {
227
+ code: "HARNESS_UNAVAILABLE",
228
+ message: `Harness "${workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION}" is unavailable for template "${workflow.template}".`,
229
+ artifactRef: `harness "${workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION}"`
230
+ }
231
+ ];
232
+ return {
233
+ workflow,
234
+ harness,
235
+ template: null,
236
+ flow: resolveFromWorkflow(workflow, "legacy-fallback", warnings)
237
+ };
238
+ }
239
+ return {
240
+ workflow,
241
+ harness,
242
+ template: null,
243
+ flow: resolveFromWorkflow(workflow, "workflow-instance")
244
+ };
245
+ }
246
+ function resolveActiveFlow(root) {
247
+ return resolveActiveFlowFor(root);
248
+ }
249
+ function resolveActiveFlowFor(root, workflow = loadWorkflow(root)) {
250
+ const harness = loadHarnessForWorkflow(root, workflow);
251
+ return resolveActiveFlowFrom(workflow, harness);
252
+ }
253
+ function loadHarnessForWorkflow(root, workflow) {
254
+ const version = workflow?.harnessVersion ?? DEFAULT_HARNESS_VERSION;
255
+ return loadHarness(resolveHarnessRoot(root, version));
256
+ }
257
+
258
+ // src/agent-direction/service.ts
259
+ import { createHash } from "crypto";
260
+ import { existsSync, readFileSync } from "fs";
261
+ import { join, resolve } from "path";
262
+ function slug(value) {
263
+ return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "action";
264
+ }
265
+ function findCurrentItem(workflow, currentItemId) {
266
+ if (currentItemId) {
267
+ const explicit = workflow.items.find((item) => item.id === currentItemId);
268
+ if (explicit) return explicit;
269
+ }
270
+ if (workflow.primaryItemId) {
271
+ const primary = workflow.items.find((item) => item.id === workflow.primaryItemId);
272
+ if (primary) return primary;
273
+ }
274
+ const doingStages = new Set(
275
+ workflow.stages.filter(
276
+ (stage, index) => stage.zone === "doing" || !stage.zone && index > 0 && index < workflow.stages.length - 1
277
+ ).map((stage) => stage.id)
278
+ );
279
+ return workflow.items.find((item) => doingStages.has(item.stage)) ?? null;
280
+ }
281
+ function firstPendingAC(content) {
282
+ if (!content) return null;
283
+ const match = content.match(/-\s*\[ \]\s*\*\*([^*]+)\*\*\s*:?\s*([^\r\n]*)/);
284
+ if (!match) return null;
285
+ const id = match[1].match(/\bAC[\s-]?(\d+)\b/i);
286
+ if (!id) return null;
287
+ return {
288
+ id: `AC${id[1]}`,
289
+ description: match[2].trim() || match[1].replace(/^AC[\s-]?\d+\s*[—-]?\s*/i, "").trim()
290
+ };
291
+ }
292
+ function activeHint(stage) {
293
+ if (!stage?.activity) return null;
294
+ return stage.activity.design ?? stage.activity.implement ?? stage.activity.review ?? stage.activity.diagnose ?? stage.activity.gate ?? null;
295
+ }
296
+ function commandMutates(command) {
297
+ return /\bletra\s+(?:ac\s+done|flow\s+move|focus|sitrep|health\s+(?:ack|dismiss|scan))\b/i.test(
298
+ command
299
+ );
300
+ }
301
+ function resolveCommands(hint, item, pendingAC, nextStageId) {
302
+ return (hint?.commands ?? []).flatMap((entry) => {
303
+ let command = entry.command;
304
+ if (command.includes("<AC-ID>")) {
305
+ if (!pendingAC) return [];
306
+ command = command.replaceAll("<AC-ID>", pendingAC.id);
307
+ }
308
+ if (command.includes("<ITEM-ID>")) {
309
+ if (!item) return [];
310
+ command = command.replaceAll("<ITEM-ID>", item.id);
311
+ }
312
+ if (command.includes("<NEXT-STAGE>")) {
313
+ if (!nextStageId) return [];
314
+ command = command.replaceAll("<NEXT-STAGE>", nextStageId);
315
+ }
316
+ return [
317
+ {
318
+ id: slug(entry.label || command),
319
+ command,
320
+ label: entry.label || command,
321
+ mutates: commandMutates(command)
322
+ }
323
+ ];
324
+ });
325
+ }
326
+ function resolveActions(hint) {
327
+ return (hint?.nextActions ?? []).map((action) => ({
328
+ id: slug(action.label),
329
+ label: action.label,
330
+ reason: action.description
331
+ }));
332
+ }
333
+ function semanticRevision(snapshot) {
334
+ return `sha256:${createHash("sha256").update(JSON.stringify(snapshot)).digest("hex")}`;
335
+ }
336
+ function createAgentDirectionSnapshot(input) {
337
+ const item = input.workflow ? findCurrentItem(input.workflow, input.currentItemId) : null;
338
+ const stage = item ? input.flow?.stages.find((candidate) => candidate.id === item.stage) ?? null : null;
339
+ const sortedStages = input.flow ? [...input.flow.stages].sort((a, b) => a.order - b.order) : [];
340
+ const stageIndex = stage ? sortedStages.findIndex((candidate) => candidate.id === stage.id) : -1;
341
+ const nextStageId = stageIndex >= 0 ? sortedStages[stageIndex + 1]?.id ?? null : null;
342
+ const hint = activeHint(stage);
343
+ const pendingAC = firstPendingAC(input.specContent);
344
+ const warnings = (input.flow?.warnings ?? []).map((warning) => ({
345
+ code: warning.code,
346
+ message: warning.message
347
+ }));
348
+ const mode = !input.workflow ? "unconfigured" : !input.flow || input.flow.source !== "workflow-template" || warnings.length > 0 ? "degraded" : "active";
349
+ const allowedStageIds = [...new Set(stage?.roles.flatMap((role) => role.allowedStages) ?? [])];
350
+ const gateEvidence = stage?.activity?.gate?.evidence;
351
+ const constitutionPath = join(getLetraDir(input.workspaceRoot), "constitution.md");
352
+ const constitutionAvailable = existsSync(constitutionPath);
353
+ const constitutionVersion = input.constitutionVersion ?? (constitutionAvailable ? readConstitutionVersion(input.workspaceRoot) : null);
354
+ const governanceReferences = [];
355
+ if (constitutionAvailable) {
356
+ governanceReferences.push({
357
+ path: "constitution.md",
358
+ version: constitutionVersion ?? "unknown",
359
+ available: true,
360
+ source: "workspace"
361
+ });
362
+ } else {
363
+ governanceReferences.push({
364
+ path: "constitution.md",
365
+ version: "unknown",
366
+ available: false,
367
+ source: "workspace"
368
+ });
369
+ warnings.push({
370
+ code: "CONSTITUTION_MISSING",
371
+ message: "Constitution file not found in workspace"
372
+ });
373
+ }
374
+ const semantic = {
375
+ schemaVersion: "1",
376
+ source: {
377
+ harnessVersion: input.flow?.harnessVersion ?? input.workflow?.harnessVersion ?? null,
378
+ flowId: input.flow?.id ?? null,
379
+ workspaceRoot: resolve(input.workspaceRoot).replace(/\\/g, "/")
380
+ },
381
+ mode,
382
+ item: item ? {
383
+ id: item.id,
384
+ description: item.description,
385
+ stage: item.stage,
386
+ spec: item.spec ?? null
387
+ } : null,
388
+ roleIds: stage ? [...stage.roleIds] : [],
389
+ allowedStageIds,
390
+ objective: hint?.objective ?? null,
391
+ pendingAC,
392
+ commands: resolveCommands(hint, item, pendingAC, nextStageId),
393
+ prohibitions: [...hint?.mustNotDo ?? []],
394
+ requiredEvidence: gateEvidence ? [gateEvidence] : [],
395
+ nextActions: resolveActions(hint),
396
+ warnings,
397
+ governanceReferences,
398
+ constitutionVersion: constitutionVersion ?? void 0
399
+ };
400
+ return {
401
+ ...semantic,
402
+ revision: semanticRevision(semantic),
403
+ generatedAt: input.now ?? (/* @__PURE__ */ new Date()).toISOString()
404
+ };
405
+ }
406
+ function readActiveSpec(root, specName) {
407
+ if (!specName) return null;
408
+ const specDir = join(getLetraDir(root), "specs", specName);
409
+ const acceptancePath = join(specDir, "acceptance.md");
410
+ const specPath = join(specDir, "spec.md");
411
+ if (existsSync(acceptancePath)) return readFileSync(acceptancePath, "utf-8");
412
+ if (existsSync(specPath)) return readFileSync(specPath, "utf-8");
413
+ return null;
414
+ }
415
+ function readConstitutionVersion(root) {
416
+ const constitutionPath = join(getLetraDir(root), "constitution.md");
417
+ if (!existsSync(constitutionPath)) return null;
418
+ const content = readFileSync(constitutionPath, "utf-8");
419
+ const versionMatch = content.match(/\*\*Version:\*\*\s*(.+)/);
420
+ return versionMatch ? versionMatch[1].trim() : null;
421
+ }
422
+ function resolveAgentDirection(root) {
423
+ const resolution = resolveActiveFlow(root);
424
+ const focus = readFocusFile(root);
425
+ const workflow = resolution.workflow;
426
+ const focusedItem = workflow && focus?.itemId ? workflow.items.find((item) => item.id === focus.itemId) ?? null : null;
427
+ const selectedItem = focusedItem ?? (workflow ? findCurrentItem(workflow) : null);
428
+ const specName = selectedItem?.spec ?? focus?.specName ?? null;
429
+ return createAgentDirectionSnapshot({
430
+ workspaceRoot: root,
431
+ workflow,
432
+ flow: resolution.flow,
433
+ specContent: readActiveSpec(root, specName),
434
+ currentItemId: selectedItem?.id ?? null
435
+ });
436
+ }
437
+
438
+ export {
439
+ resolveActiveFlow,
440
+ resolveActiveFlowFor,
441
+ loadHarnessForWorkflow,
442
+ resolveAgentDirection
443
+ };
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ export {
10
+ __require
11
+ };