@letra-ai/cli 0.6.1 → 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.
@@ -26,8 +26,8 @@ import {
26
26
  } from "./chunk-PDX44BCA.js";
27
27
 
28
28
  // src/adapters/generate.ts
29
- import { existsSync as existsSync16, mkdirSync as mkdirSync5, readFileSync as readFileSync12, writeFileSync as writeFileSync5 } from "fs";
30
- import { join as join15 } from "path";
29
+ import { existsSync as existsSync18, mkdirSync as mkdirSync6, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
30
+ import { join as join17 } from "path";
31
31
  import chalk2 from "chalk";
32
32
 
33
33
  // src/security/workspace-boundary.ts
@@ -71,8 +71,8 @@ function createWorkspaceBoundary(root) {
71
71
  }
72
72
 
73
73
  // src/adapters/builder.ts
74
- import { existsSync as existsSync15, readFileSync as readFileSync11 } from "fs";
75
- import { join as join14 } from "path";
74
+ import { existsSync as existsSync16, readFileSync as readFileSync12 } from "fs";
75
+ import { join as join15 } from "path";
76
76
  import { pathToFileURL } from "url";
77
77
 
78
78
  // src/harness/loader.ts
@@ -1527,7 +1527,7 @@ var harnessStaleDetector = {
1527
1527
  });
1528
1528
  }
1529
1529
  }
1530
- const { generateAdapters: generateAdapters2 } = await import("./generate-N22QOXUF.js");
1530
+ const { generateAdapters: generateAdapters2 } = await import("./generate-UPFERQMD.js");
1531
1531
  generateAdapters2(rootDir, tools, {
1532
1532
  source: "flow-move",
1533
1533
  workflow,
@@ -1942,8 +1942,8 @@ var DiagnosticEngine = class {
1942
1942
  const fullPath = join12(dataDir, dir);
1943
1943
  if (!existsSync13(fullPath)) {
1944
1944
  try {
1945
- const { mkdirSync: mkdirSync6 } = __require("fs");
1946
- mkdirSync6(fullPath, { recursive: true });
1945
+ const { mkdirSync: mkdirSync7 } = __require("fs");
1946
+ mkdirSync7(fullPath, { recursive: true });
1947
1947
  } catch {
1948
1948
  }
1949
1949
  }
@@ -1955,12 +1955,12 @@ var DiagnosticEngine = class {
1955
1955
  function askText(query, defaultValue) {
1956
1956
  if (!process.stdin.isTTY) return Promise.resolve(defaultValue);
1957
1957
  const rl = createInterface({ input: process.stdin, output: process.stdout });
1958
- return new Promise((resolve3) => {
1958
+ return new Promise((resolve4) => {
1959
1959
  const formatted = `${chalk.cyan(query)} ${chalk.gray(`(default: ${defaultValue})`)}
1960
1960
  > `;
1961
1961
  rl.question(formatted, (answer) => {
1962
1962
  rl.close();
1963
- resolve3(answer.trim() || defaultValue);
1963
+ resolve4(answer.trim() || defaultValue);
1964
1964
  });
1965
1965
  });
1966
1966
  }
@@ -2199,7 +2199,7 @@ async function writeWorkflow(root, options) {
2199
2199
  }
2200
2200
  if (!skipSitrep) {
2201
2201
  try {
2202
- const { sitrep } = await import("./sitrep-DJXTP3JO.js");
2202
+ const { sitrep } = await import("./sitrep-OKNZJICV.js");
2203
2203
  await sitrep(resolution?.workspaceDir ?? root, { quiet: true, skipLog: true });
2204
2204
  } catch {
2205
2205
  }
@@ -2327,22 +2327,462 @@ async function flowInitAction(targetPath, options) {
2327
2327
  }
2328
2328
  }
2329
2329
 
2330
+ // src/agent-direction/service.ts
2331
+ import { createHash } from "crypto";
2332
+ import { existsSync as existsSync15, readFileSync as readFileSync11 } from "fs";
2333
+ import { join as join14, resolve as resolve3 } from "path";
2334
+
2335
+ // src/flow-definition/resolve.ts
2336
+ function resolveTemplate(workflow, harness) {
2337
+ if (!workflow?.template || !harness) return null;
2338
+ return harness.flows[workflow.template] ?? null;
2339
+ }
2340
+ function gateIdFromRef(gateRef) {
2341
+ return gateRef.replace(/^.*[\\/]/, "").replace(/\.ya?ml$/, "");
2342
+ }
2343
+ function cloneActivityHint(hint) {
2344
+ if (!hint) return void 0;
2345
+ return {
2346
+ ...hint,
2347
+ mustRead: hint.mustRead?.map((reference) => ({ ...reference })),
2348
+ mustNotDo: hint.mustNotDo ? [...hint.mustNotDo] : void 0,
2349
+ nextActions: hint.nextActions?.map((action) => ({ ...action })),
2350
+ commands: hint.commands?.map((command) => ({ ...command }))
2351
+ };
2352
+ }
2353
+ function cloneActivity(activity) {
2354
+ if (!activity) return void 0;
2355
+ return {
2356
+ design: cloneActivityHint(activity.design),
2357
+ implement: cloneActivityHint(activity.implement),
2358
+ review: cloneActivityHint(activity.review),
2359
+ diagnose: cloneActivityHint(activity.diagnose),
2360
+ gate: cloneActivityHint(activity.gate)
2361
+ };
2362
+ }
2363
+ function resolveGate(harness, gateRef, warnings, artifactRef) {
2364
+ if (!harness || !gateRef) return null;
2365
+ const gateId = gateIdFromRef(gateRef);
2366
+ const gate = harness.gates[gateId];
2367
+ if (!gate) {
2368
+ warnings.push({
2369
+ code: "GATE_NOT_FOUND",
2370
+ message: `Gate "${gateId}" referenced by ${artifactRef} was not found in the harness.`,
2371
+ artifactRef
2372
+ });
2373
+ return null;
2374
+ }
2375
+ return {
2376
+ id: gate.id,
2377
+ name: gate.name,
2378
+ type: gate.type,
2379
+ blocking: gate.blocking,
2380
+ policyRef: gate.policyRef,
2381
+ description: gate.description,
2382
+ decisions: gate.decisions ? { ...gate.decisions } : void 0
2383
+ };
2384
+ }
2385
+ function cloneRole(role) {
2386
+ return {
2387
+ id: role.id,
2388
+ label: role.label,
2389
+ description: role.description,
2390
+ allowedStages: [...role.allowedStages],
2391
+ capabilities: [...role.capabilities]
2392
+ };
2393
+ }
2394
+ function resolveRoles(harness, roleIds, warnings, artifactRef) {
2395
+ if (!harness) return [];
2396
+ return roleIds.flatMap((roleId) => {
2397
+ const role = harness.roles[roleId];
2398
+ if (role) return [cloneRole(role)];
2399
+ warnings.push({
2400
+ code: "ROLE_NOT_FOUND",
2401
+ message: `Role "${roleId}" referenced by ${artifactRef} was not found in the harness.`,
2402
+ artifactRef
2403
+ });
2404
+ return [];
2405
+ });
2406
+ }
2407
+ function resolvePhases(harness, phases, warnings, stageId) {
2408
+ if (!phases) return void 0;
2409
+ return {
2410
+ initialState: phases.initialState,
2411
+ states: Object.fromEntries(
2412
+ Object.entries(phases.states).map(([phaseId, phase]) => [
2413
+ phaseId,
2414
+ {
2415
+ id: phase.id,
2416
+ label: phase.label,
2417
+ description: phase.description,
2418
+ actions: phase.actions?.map((action) => ({ ...action })),
2419
+ transitions: phase.transitions?.map((transition) => ({
2420
+ target: transition.target,
2421
+ gate: resolveGate(
2422
+ harness,
2423
+ transition.gate,
2424
+ warnings,
2425
+ `flow stage "${stageId}" phase "${phaseId}" transition to "${transition.target}"`
2426
+ ),
2427
+ ...transition.gate ? { gateRef: transition.gate } : {},
2428
+ ...transition.auto === void 0 ? {} : { auto: transition.auto }
2429
+ })),
2430
+ harness: phase.harness ? {
2431
+ ...phase.harness,
2432
+ tools: phase.harness.tools ? [...phase.harness.tools] : void 0,
2433
+ checks: phase.harness.checks ? [...phase.harness.checks] : void 0,
2434
+ activity: cloneActivity(phase.harness.activity),
2435
+ review: cloneActivityHint(phase.harness.review),
2436
+ gate: cloneActivityHint(phase.harness.gate)
2437
+ } : void 0
2438
+ }
2439
+ ])
2440
+ )
2441
+ };
2442
+ }
2443
+ function mergeTemplateStage(workflow, harness, stageDef, index, warnings) {
2444
+ const workflowStage = workflow.stages.find((stage) => stage.id === stageDef.id);
2445
+ const artifactRef = `flow stage "${stageDef.id}"`;
2446
+ const roleIds = [...stageDef.agents ?? []];
2447
+ return {
2448
+ id: stageDef.id,
2449
+ name: stageDef.name || workflowStage?.name || stageDef.id,
2450
+ order: stageDef.order ?? workflowStage?.order ?? index,
2451
+ zone: stageDef.zone ?? workflowStage?.zone,
2452
+ description: stageDef.description,
2453
+ roleIds,
2454
+ roles: resolveRoles(harness, roleIds, warnings, artifactRef),
2455
+ agents: [...roleIds],
2456
+ gate: resolveGate(harness, stageDef.gate, warnings, artifactRef),
2457
+ preferredExecutor: stageDef.preferredExecutor,
2458
+ phases: resolvePhases(harness, stageDef.phases, warnings, stageDef.id),
2459
+ activity: cloneActivity(stageDef.activity),
2460
+ provenance: "harness"
2461
+ };
2462
+ }
2463
+ function workflowStageDefinition(stage, provenance = "workflow-instance") {
2464
+ return {
2465
+ id: stage.id,
2466
+ name: stage.name,
2467
+ order: stage.order,
2468
+ zone: stage.zone,
2469
+ description: void 0,
2470
+ roleIds: [],
2471
+ roles: [],
2472
+ agents: [],
2473
+ gate: null,
2474
+ preferredExecutor: void 0,
2475
+ phases: resolvePhases(null, stage.phases, [], stage.id),
2476
+ activity: void 0,
2477
+ provenance
2478
+ };
2479
+ }
2480
+ function resolveFromTemplate(workflow, harness, template) {
2481
+ const warnings = [];
2482
+ const instanceStageIds = new Set(workflow.stages.map((stage) => stage.id));
2483
+ const templateStageIds = new Set(template.stages.map((stage) => stage.id));
2484
+ const templateStages = template.stages.map((stageDef, index) => {
2485
+ if (!instanceStageIds.has(stageDef.id)) {
2486
+ warnings.push({
2487
+ code: "TEMPLATE_STAGE_NOT_IN_INSTANCE",
2488
+ message: `Harness stage "${stageDef.id}" is not persisted in the workflow instance.`,
2489
+ artifactRef: `flow stage "${stageDef.id}"`
2490
+ });
2491
+ }
2492
+ return mergeTemplateStage(workflow, harness, stageDef, index, warnings);
2493
+ });
2494
+ const extensionStages = workflow.stages.filter((stage) => !templateStageIds.has(stage.id)).map((stage) => {
2495
+ warnings.push({
2496
+ code: "INSTANCE_STAGE_NOT_IN_TEMPLATE",
2497
+ message: `Workflow stage "${stage.id}" is not declared by template "${template.id}".`,
2498
+ artifactRef: `workflow stage "${stage.id}"`
2499
+ });
2500
+ return workflowStageDefinition(stage);
2501
+ });
2502
+ return {
2503
+ id: template.id,
2504
+ source: "workflow-template",
2505
+ harnessVersion: workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION,
2506
+ templateVersion: template.version,
2507
+ name: template.name,
2508
+ stages: [...templateStages, ...extensionStages].sort(
2509
+ (left, right) => left.order - right.order
2510
+ ),
2511
+ roles: harness ? Object.values(harness.roles).map(cloneRole) : [],
2512
+ warnings
2513
+ };
2514
+ }
2515
+ function resolveFromWorkflow(workflow, source, warnings = []) {
2516
+ return {
2517
+ id: workflow.template ?? null,
2518
+ source,
2519
+ harnessVersion: workflow.harnessVersion ?? null,
2520
+ templateVersion: null,
2521
+ name: workflow.name,
2522
+ stages: (Array.isArray(workflow.stages) ? workflow.stages : []).map((stage) => workflowStageDefinition(stage)).sort((left, right) => left.order - right.order),
2523
+ roles: [],
2524
+ warnings: warnings.map((warning) => ({ ...warning }))
2525
+ };
2526
+ }
2527
+ function resolveActiveFlowFrom(workflow, harness) {
2528
+ const template = resolveTemplate(workflow, harness);
2529
+ if (!workflow) {
2530
+ return { workflow, harness, template: null, flow: null };
2531
+ }
2532
+ if (template) {
2533
+ return {
2534
+ workflow,
2535
+ harness,
2536
+ template,
2537
+ flow: resolveFromTemplate(workflow, harness, template)
2538
+ };
2539
+ }
2540
+ if (workflow.template) {
2541
+ const warnings = harness ? [
2542
+ {
2543
+ code: "TEMPLATE_NOT_FOUND",
2544
+ message: `Template "${workflow.template}" was not found in harness "${workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION}".`,
2545
+ artifactRef: `harness flow "${workflow.template}"`
2546
+ }
2547
+ ] : [
2548
+ {
2549
+ code: "HARNESS_UNAVAILABLE",
2550
+ message: `Harness "${workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION}" is unavailable for template "${workflow.template}".`,
2551
+ artifactRef: `harness "${workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION}"`
2552
+ }
2553
+ ];
2554
+ return {
2555
+ workflow,
2556
+ harness,
2557
+ template: null,
2558
+ flow: resolveFromWorkflow(workflow, "legacy-fallback", warnings)
2559
+ };
2560
+ }
2561
+ return {
2562
+ workflow,
2563
+ harness,
2564
+ template: null,
2565
+ flow: resolveFromWorkflow(workflow, "workflow-instance")
2566
+ };
2567
+ }
2568
+ function resolveActiveFlow(root) {
2569
+ return resolveActiveFlowFor(root);
2570
+ }
2571
+ function resolveActiveFlowFor(root, workflow = loadWorkflow(root)) {
2572
+ const harness = loadHarnessForWorkflow(root, workflow);
2573
+ return resolveActiveFlowFrom(workflow, harness);
2574
+ }
2575
+ function loadHarnessForWorkflow(root, workflow) {
2576
+ const version = workflow?.harnessVersion ?? DEFAULT_HARNESS_VERSION;
2577
+ return loadHarness(resolveHarnessRoot(root, version));
2578
+ }
2579
+
2580
+ // src/agent-direction/service.ts
2581
+ function slug(value) {
2582
+ return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "action";
2583
+ }
2584
+ function findCurrentItem(workflow, currentItemId) {
2585
+ const items = Array.isArray(workflow.items) ? workflow.items : [];
2586
+ const stages = Array.isArray(workflow.stages) ? workflow.stages : [];
2587
+ if (currentItemId) {
2588
+ const explicit = items.find((item) => item.id === currentItemId);
2589
+ if (explicit) return explicit;
2590
+ }
2591
+ if (workflow.primaryItemId) {
2592
+ const primary = items.find((item) => item.id === workflow.primaryItemId);
2593
+ if (primary) return primary;
2594
+ }
2595
+ const doingStages = new Set(
2596
+ stages.filter(
2597
+ (stage, index) => stage.zone === "doing" || !stage.zone && index > 0 && index < stages.length - 1
2598
+ ).map((stage) => stage.id)
2599
+ );
2600
+ return items.find((item) => doingStages.has(item.stage)) ?? null;
2601
+ }
2602
+ function firstPendingAC(content) {
2603
+ if (!content) return null;
2604
+ const match = content.match(/-\s*\[ \]\s*\*\*([^*]+)\*\*\s*:?\s*([^\r\n]*)/);
2605
+ if (!match) return null;
2606
+ const id = match[1].match(/\bAC[\s-]?(\d+)\b/i);
2607
+ if (!id) return null;
2608
+ return {
2609
+ id: `AC${id[1]}`,
2610
+ description: match[2].trim() || match[1].replace(/^AC[\s-]?\d+\s*[—-]?\s*/i, "").trim()
2611
+ };
2612
+ }
2613
+ function activeHint(stage) {
2614
+ if (!stage?.activity) return null;
2615
+ return stage.activity.design ?? stage.activity.implement ?? stage.activity.review ?? stage.activity.diagnose ?? stage.activity.gate ?? null;
2616
+ }
2617
+ function commandMutates(command) {
2618
+ return /\bletra\s+(?:ac\s+done|flow\s+move|focus|sitrep|health\s+(?:ack|dismiss|scan))\b/i.test(
2619
+ command
2620
+ );
2621
+ }
2622
+ function resolveCommands(hint, item, pendingAC, nextStageId) {
2623
+ return (hint?.commands ?? []).flatMap((entry) => {
2624
+ let command = entry.command;
2625
+ if (command.includes("<AC-ID>")) {
2626
+ if (!pendingAC) return [];
2627
+ command = command.replaceAll("<AC-ID>", pendingAC.id);
2628
+ }
2629
+ if (command.includes("<ITEM-ID>")) {
2630
+ if (!item) return [];
2631
+ command = command.replaceAll("<ITEM-ID>", item.id);
2632
+ }
2633
+ if (command.includes("<NEXT-STAGE>")) {
2634
+ if (!nextStageId) return [];
2635
+ command = command.replaceAll("<NEXT-STAGE>", nextStageId);
2636
+ }
2637
+ return [
2638
+ {
2639
+ id: slug(entry.label || command),
2640
+ command,
2641
+ label: entry.label || command,
2642
+ mutates: commandMutates(command)
2643
+ }
2644
+ ];
2645
+ });
2646
+ }
2647
+ function resolveActions(hint) {
2648
+ return (hint?.nextActions ?? []).map((action) => ({
2649
+ id: slug(action.label),
2650
+ label: action.label,
2651
+ reason: action.description
2652
+ }));
2653
+ }
2654
+ function semanticRevision(snapshot) {
2655
+ return `sha256:${createHash("sha256").update(JSON.stringify(snapshot)).digest("hex")}`;
2656
+ }
2657
+ function createAgentDirectionSnapshot(input) {
2658
+ const item = input.workflow ? findCurrentItem(input.workflow, input.currentItemId) : null;
2659
+ const stage = item ? input.flow?.stages.find((candidate) => candidate.id === item.stage) ?? null : null;
2660
+ const sortedStages = input.flow ? [...input.flow.stages].sort((a, b) => a.order - b.order) : [];
2661
+ const stageIndex = stage ? sortedStages.findIndex((candidate) => candidate.id === stage.id) : -1;
2662
+ const nextStageId = stageIndex >= 0 ? sortedStages[stageIndex + 1]?.id ?? null : null;
2663
+ const hint = activeHint(stage);
2664
+ const pendingAC = firstPendingAC(input.specContent);
2665
+ const warnings = (input.flow?.warnings ?? []).map((warning) => ({
2666
+ code: warning.code,
2667
+ message: warning.message
2668
+ }));
2669
+ const mode = !input.workflow ? "unconfigured" : !input.flow || input.flow.source !== "workflow-template" || warnings.length > 0 ? "degraded" : "active";
2670
+ const allowedStageIds = [...new Set(stage?.roles.flatMap((role) => role.allowedStages) ?? [])];
2671
+ const gateEvidence = stage?.activity?.gate?.evidence;
2672
+ const constitutionPath = join14(getLetraDir2(input.workspaceRoot), "constitution.md");
2673
+ const constitutionAvailable = existsSync15(constitutionPath);
2674
+ const constitutionVersion = input.constitutionVersion ?? (constitutionAvailable ? readConstitutionVersion(input.workspaceRoot) : null);
2675
+ const governanceReferences = [];
2676
+ if (constitutionAvailable) {
2677
+ governanceReferences.push({
2678
+ path: "constitution.md",
2679
+ version: constitutionVersion ?? "unknown",
2680
+ available: true,
2681
+ source: "workspace"
2682
+ });
2683
+ } else {
2684
+ governanceReferences.push({
2685
+ path: "constitution.md",
2686
+ version: "unknown",
2687
+ available: false,
2688
+ source: "workspace"
2689
+ });
2690
+ warnings.push({
2691
+ code: "CONSTITUTION_MISSING",
2692
+ message: "Constitution file not found in workspace"
2693
+ });
2694
+ }
2695
+ const semantic = {
2696
+ schemaVersion: "1",
2697
+ source: {
2698
+ harnessVersion: input.flow?.harnessVersion ?? input.workflow?.harnessVersion ?? null,
2699
+ flowId: input.flow?.id ?? null,
2700
+ workspaceRoot: resolve3(input.workspaceRoot).replace(/\\/g, "/")
2701
+ },
2702
+ mode,
2703
+ item: item ? {
2704
+ id: item.id,
2705
+ description: item.description,
2706
+ stage: item.stage,
2707
+ spec: item.spec ?? null,
2708
+ claimedBy: item.claimedBy ?? null,
2709
+ claimedAt: item.claimedAt ?? null,
2710
+ claimExpiresAt: item.claimExpiresAt ?? null,
2711
+ claimExecutorId: item.claimExecutorId ?? null,
2712
+ claimCapability: item.claimCapability ?? null,
2713
+ claimRevision: item.claimRevision ?? null,
2714
+ claimTtlMinutes: item.claimTtlMinutes ?? null,
2715
+ activityStatus: item.activityStatus ?? null,
2716
+ activityStartedAt: item.activityStartedAt ?? null,
2717
+ lastHeartbeatAt: item.lastHeartbeatAt ?? null,
2718
+ lastFailure: item.lastFailure ?? null
2719
+ } : null,
2720
+ roleIds: stage ? [...stage.roleIds] : [],
2721
+ allowedStageIds,
2722
+ objective: hint?.objective ?? null,
2723
+ pendingAC,
2724
+ commands: resolveCommands(hint, item, pendingAC, nextStageId),
2725
+ prohibitions: [...hint?.mustNotDo ?? []],
2726
+ requiredEvidence: gateEvidence ? [gateEvidence] : [],
2727
+ nextActions: resolveActions(hint),
2728
+ warnings,
2729
+ governanceReferences,
2730
+ constitutionVersion: constitutionVersion ?? void 0
2731
+ };
2732
+ return {
2733
+ ...semantic,
2734
+ revision: semanticRevision(semantic),
2735
+ generatedAt: input.now ?? (/* @__PURE__ */ new Date()).toISOString()
2736
+ };
2737
+ }
2738
+ function readActiveSpec(root, specName) {
2739
+ if (!specName) return null;
2740
+ const specDir = join14(getLetraDir2(root), "specs", specName);
2741
+ const acceptancePath = join14(specDir, "acceptance.md");
2742
+ const specPath = join14(specDir, "spec.md");
2743
+ if (existsSync15(acceptancePath)) return readFileSync11(acceptancePath, "utf-8");
2744
+ if (existsSync15(specPath)) return readFileSync11(specPath, "utf-8");
2745
+ return null;
2746
+ }
2747
+ function readConstitutionVersion(root) {
2748
+ const constitutionPath = join14(getLetraDir2(root), "constitution.md");
2749
+ if (!existsSync15(constitutionPath)) return null;
2750
+ const content = readFileSync11(constitutionPath, "utf-8");
2751
+ const versionMatch = content.match(/\*\*Version:\*\*\s*(.+)/);
2752
+ return versionMatch ? versionMatch[1].trim() : null;
2753
+ }
2754
+ function resolveAgentDirection(root) {
2755
+ const resolution = resolveActiveFlow(root);
2756
+ const focus = readFocusFile(root);
2757
+ const workflow = resolution.workflow;
2758
+ const focusedItem = workflow && focus?.itemId && Array.isArray(workflow.items) ? workflow.items.find((item) => item.id === focus.itemId) ?? null : null;
2759
+ const selectedItem = focusedItem ?? (workflow && Array.isArray(workflow.items) ? findCurrentItem(workflow) : null);
2760
+ const specName = selectedItem?.spec ?? focus?.specName ?? null;
2761
+ return createAgentDirectionSnapshot({
2762
+ workspaceRoot: root,
2763
+ workflow,
2764
+ flow: resolution.flow,
2765
+ specContent: readActiveSpec(root, specName),
2766
+ currentItemId: selectedItem?.id ?? null
2767
+ });
2768
+ }
2769
+
2330
2770
  // src/adapters/builder.ts
2331
2771
  function countACs(stateDir, specName) {
2332
2772
  if (!specName) return { pending: 0, total: 0, pendingIds: [] };
2333
- let specDir = join14(stateDir, "specs", specName);
2334
- if (!existsSync15(specDir)) {
2335
- const legacyDir = join14(getLetraDir2(stateDir), "specs", specName);
2336
- if (!existsSync15(legacyDir)) return { pending: 0, total: 0, pendingIds: [] };
2773
+ let specDir = join15(stateDir, "specs", specName);
2774
+ if (!existsSync16(specDir)) {
2775
+ const legacyDir = join15(getLetraDir2(stateDir), "specs", specName);
2776
+ if (!existsSync16(legacyDir)) return { pending: 0, total: 0, pendingIds: [] };
2337
2777
  specDir = legacyDir;
2338
2778
  }
2339
2779
  let content = "";
2340
- const acceptancePath = join14(specDir, "acceptance.md");
2341
- const specPath = join14(specDir, "spec.md");
2342
- if (existsSync15(acceptancePath)) {
2343
- content = readFileSync11(acceptancePath, "utf-8");
2344
- } else if (existsSync15(specPath)) {
2345
- content = readFileSync11(specPath, "utf-8");
2780
+ const acceptancePath = join15(specDir, "acceptance.md");
2781
+ const specPath = join15(specDir, "spec.md");
2782
+ if (existsSync16(acceptancePath)) {
2783
+ content = readFileSync12(acceptancePath, "utf-8");
2784
+ } else if (existsSync16(specPath)) {
2785
+ content = readFileSync12(specPath, "utf-8");
2346
2786
  const acMatch = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
2347
2787
  if (acMatch) content = acMatch[1];
2348
2788
  else return { pending: 0, total: 0, pendingIds: [] };
@@ -2355,14 +2795,14 @@ function countACs(stateDir, specName) {
2355
2795
  return { pending, total, pendingIds };
2356
2796
  }
2357
2797
  function loadLastSession(stateDir) {
2358
- let logPath = join14(stateDir, "session-log.json");
2359
- if (!existsSync15(logPath)) {
2360
- const legacy = join14(getLetraDir2(stateDir), "session-log.json");
2361
- if (!existsSync15(legacy)) return null;
2798
+ let logPath = join15(stateDir, "session-log.json");
2799
+ if (!existsSync16(logPath)) {
2800
+ const legacy = join15(getLetraDir2(stateDir), "session-log.json");
2801
+ if (!existsSync16(legacy)) return null;
2362
2802
  logPath = legacy;
2363
2803
  }
2364
2804
  try {
2365
- const log = JSON.parse(readFileSync11(logPath, "utf-8"));
2805
+ const log = JSON.parse(readFileSync12(logPath, "utf-8"));
2366
2806
  const entries = log.entries || [];
2367
2807
  if (entries.length === 0) return null;
2368
2808
  const lastEntry = entries[0];
@@ -2422,18 +2862,19 @@ function buildHarnessSnapshot(root, options) {
2422
2862
  const isWorkspace = options.workspaceDir !== void 0;
2423
2863
  const stateDir = isWorkspace ? options.workspaceDir ?? root : root;
2424
2864
  const dotLetra = isWorkspace ? stateDir : getLetraDir2(stateDir);
2425
- const hasFocus = existsSync15(join14(dotLetra, "focus.md"));
2865
+ const hasFocus = existsSync16(join15(dotLetra, "focus.md"));
2426
2866
  const buildReferenceLinks = (specName) => ({
2427
- context: pathToFileURL(join14(dotLetra, "context.md")).href,
2428
- constitution: pathToFileURL(join14(dotLetra, "constitution.md")).href,
2429
- glossary: pathToFileURL(join14(dotLetra, "glossary.md")).href,
2430
- constraints: pathToFileURL(join14(dotLetra, "constraints.md")).href,
2431
- focus: hasFocus ? pathToFileURL(join14(dotLetra, "focus.md")).href : null,
2432
- spec: specName ? pathToFileURL(join14(dotLetra, "specs", specName, "spec.md")).href : null,
2433
- workflow: pathToFileURL(join14(dotLetra, "workflow.json")).href
2867
+ context: pathToFileURL(join15(dotLetra, "context.md")).href,
2868
+ constitution: pathToFileURL(join15(dotLetra, "constitution.md")).href,
2869
+ glossary: pathToFileURL(join15(dotLetra, "glossary.md")).href,
2870
+ constraints: pathToFileURL(join15(dotLetra, "constraints.md")).href,
2871
+ focus: hasFocus ? pathToFileURL(join15(dotLetra, "focus.md")).href : null,
2872
+ spec: specName ? pathToFileURL(join15(dotLetra, "specs", specName, "spec.md")).href : null,
2873
+ workflow: pathToFileURL(join15(dotLetra, "workflow.json")).href
2434
2874
  });
2435
2875
  if (!options.workflow || !options.activeStageId) {
2436
2876
  return {
2877
+ direction: resolveAgentDirection(root),
2437
2878
  workflowName: "letra",
2438
2879
  hasWorkflow: false,
2439
2880
  items: [],
@@ -2569,6 +3010,7 @@ function buildHarnessSnapshot(root, options) {
2569
3010
  harnessDirection.primaryItemId = primaryItemId;
2570
3011
  }
2571
3012
  return {
3013
+ direction: resolveAgentDirection(root),
2572
3014
  workflowName: workflow.name,
2573
3015
  hasWorkflow: true,
2574
3016
  activeStage: stage ? { id: stage.id, name: stage.name } : { id: activeStageId, name: activeStageId },
@@ -2675,6 +3117,105 @@ function appendCodexLiveContextInstructions(content) {
2675
3117
  ].join("\n");
2676
3118
  }
2677
3119
 
3120
+ // src/agents/service.ts
3121
+ import { existsSync as existsSync17, mkdirSync as mkdirSync5, readFileSync as readFileSync13, writeFileSync as writeFileSync5 } from "fs";
3122
+ import { join as join16 } from "path";
3123
+ var DEFAULTS = {
3124
+ analyst: { displayName: "Analista", bio: "Analisa contexto e define dire\xE7\xE3o.", avatar: { type: "emoji", value: "\u{1F50E}" }, color: "oklch(0.72 0.14 220)", skills: [{ id: "analysis", label: "An\xE1lise", level: "expert", category: "process" }], status: "offline", stageBindings: ["design"], adapterHints: {} },
3125
+ implementer: { displayName: "Implementador", bio: "Transforma especifica\xE7\xF5es em c\xF3digo.", avatar: { type: "emoji", value: "\u{1F6E0}\uFE0F" }, color: "oklch(0.72 0.16 150)", skills: [{ id: "coding", label: "Implementa\xE7\xE3o", level: "expert", category: "engineering" }], status: "offline", stageBindings: ["code"], adapterHints: {} },
3126
+ reviewer: { displayName: "Revisor", bio: "Confronta c\xF3digo, spec e evid\xEAncias.", avatar: { type: "emoji", value: "\u{1F50D}" }, color: "oklch(0.75 0.15 80)", skills: [{ id: "review", label: "Code review", level: "expert", category: "quality" }], status: "offline", stageBindings: ["review"], adapterHints: {} },
3127
+ security: { displayName: "Seguran\xE7a", bio: "Avalia riscos e controles.", avatar: { type: "emoji", value: "\u{1F6E1}\uFE0F" }, color: "oklch(0.68 0.18 25)", skills: [{ id: "security", label: "Seguran\xE7a", level: "advanced", category: "quality" }], status: "offline", stageBindings: ["review"], adapterHints: {} }
3128
+ };
3129
+ function pathFor(root) {
3130
+ return join16(getLetraDir2(root), "agents.json");
3131
+ }
3132
+ function assertAgent(agent) {
3133
+ if (!agent || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(agent.id)) throw new Error("Agent id inv\xE1lido");
3134
+ if (!agent.displayName?.trim() || !agent.role?.trim()) throw new Error("displayName e role s\xE3o obrigat\xF3rios");
3135
+ if (!agent.avatar || !["emoji", "initials", "image"].includes(agent.avatar.type) || !agent.avatar.value?.trim()) throw new Error("avatar inv\xE1lido");
3136
+ if (typeof agent.color !== "string" || !agent.color.trim()) throw new Error("color deve ser preenchida");
3137
+ if (!["online", "offline", "busy"].includes(agent.status)) throw new Error("status inv\xE1lido");
3138
+ if (!Array.isArray(agent.skills) || agent.skills.some((s) => !s.id || !s.label || !["beginner", "intermediate", "advanced", "expert"].includes(s.level))) throw new Error("skills inv\xE1lidas");
3139
+ if (!Array.isArray(agent.stageBindings) || agent.adapterHints && typeof agent.adapterHints !== "object") throw new Error("stageBindings ou adapterHints inv\xE1lidos");
3140
+ return agent;
3141
+ }
3142
+ function defaults(workflow) {
3143
+ const roles = new Set(workflow.stages.flatMap((s) => s.allow ?? []));
3144
+ return [...roles].map((role) => ({ id: role, role, ...DEFAULTS[role] ?? { displayName: role, bio: "Agente do harness.", avatar: { type: "initials", value: role.slice(0, 2).toUpperCase() }, color: "oklch(0.7 0.12 280)", skills: [], status: "offline", stageBindings: workflow.stages.filter((s) => (s.allow ?? []).includes(role)).map((s) => s.id), adapterHints: {} } }));
3145
+ }
3146
+ function loadAgents(root, workflow) {
3147
+ const file = pathFor(root);
3148
+ if (existsSync17(file)) {
3149
+ try {
3150
+ const parsed = JSON.parse(readFileSync13(file, "utf8"));
3151
+ if (parsed?.version === "1" && Array.isArray(parsed.agents)) {
3152
+ const valid = parsed.agents.filter((a) => {
3153
+ try {
3154
+ assertAgent(a);
3155
+ return true;
3156
+ } catch {
3157
+ return false;
3158
+ }
3159
+ });
3160
+ const known = new Set(valid.map((a) => a.role));
3161
+ const merged = workflow ? [...valid, ...defaults(workflow).filter((a) => !known.has(a.role))] : valid;
3162
+ const registry2 = { ...parsed, agents: merged };
3163
+ if (merged.length !== parsed.agents.length) saveAgents(root, registry2);
3164
+ return registry2;
3165
+ }
3166
+ } catch {
3167
+ }
3168
+ }
3169
+ const registry = { version: "1", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), agents: workflow ? defaults(workflow) : [] };
3170
+ if (workflow) saveAgents(root, registry);
3171
+ return registry;
3172
+ }
3173
+ function saveAgents(root, registry) {
3174
+ const file = pathFor(root);
3175
+ mkdirSync5(join16(file, ".."), { recursive: true });
3176
+ writeFileSync5(file, JSON.stringify({ ...registry, version: "1", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2) + "\n");
3177
+ }
3178
+ function listAgents(root, workflow) {
3179
+ return loadAgents(root, workflow).agents;
3180
+ }
3181
+ function createAgent(root, agent, workflow) {
3182
+ const r = loadAgents(root, workflow);
3183
+ assertAgent(agent);
3184
+ if (r.agents.some((a) => a.id === agent.id)) throw new Error(`Agent ${agent.id} already exists`);
3185
+ r.agents.push(agent);
3186
+ saveAgents(root, r);
3187
+ return agent;
3188
+ }
3189
+ function updateAgent(root, id, patch, workflow) {
3190
+ const r = loadAgents(root, workflow);
3191
+ const i = r.agents.findIndex((a) => a.id === id);
3192
+ if (i < 0) throw new Error(`Agent ${id} not found`);
3193
+ const next = assertAgent({ ...r.agents[i], ...patch, avatar: patch.avatar ?? r.agents[i].avatar, skills: patch.skills ?? r.agents[i].skills, stageBindings: patch.stageBindings ?? r.agents[i].stageBindings, adapterHints: patch.adapterHints ?? r.agents[i].adapterHints, id });
3194
+ r.agents[i] = next;
3195
+ saveAgents(root, r);
3196
+ return next;
3197
+ }
3198
+ function deleteAgent(root, id, workflow) {
3199
+ const r = loadAgents(root, workflow);
3200
+ if (!r.agents.some((a) => a.id === id)) throw new Error(`Agent ${id} not found`);
3201
+ if (workflow?.items.some((item) => item.claimedBy === id)) throw new Error(`Agent ${id} possui claims ativos`);
3202
+ r.agents = r.agents.filter((a) => a.id !== id);
3203
+ saveAgents(root, r);
3204
+ }
3205
+
3206
+ // src/adapters/skill-bridge.ts
3207
+ function buildSkillInstructions(agent, adapter = "generic") {
3208
+ const lines = [`# Agent ${agent.displayName}`, `Role: ${agent.role}`, `Adapter: ${adapter}`];
3209
+ if (agent.bio) lines.push(`Purpose: ${agent.bio}`);
3210
+ if (agent.skills.length) {
3211
+ lines.push("Skills:");
3212
+ for (const skill of agent.skills) lines.push(`- ${skill.label} (${skill.level}${skill.category ? `, ${skill.category}` : ""})`);
3213
+ }
3214
+ const hint = agent.adapterHints?.[adapter] ?? agent.adapterHints?.generic;
3215
+ if (hint) lines.push("Instructions:", hint);
3216
+ return lines.join("\n");
3217
+ }
3218
+
2678
3219
  // src/adapters/generate.ts
2679
3220
  var ADAPTER_HEADER = {
2680
3221
  init: "# Generated by letra init. Do not edit manually.\n",
@@ -2694,11 +3235,18 @@ Execute \`letra health\` para detalhes e \`letra health ack <id>\` para reconhec
2694
3235
  header += warn;
2695
3236
  }
2696
3237
  const files = [];
3238
+ const agents = loadAgents(root).agents;
2697
3239
  for (const artifact of instructionArtifactsForAdapters(tools)) {
2698
3240
  let content = formatAdapterContent(snapshot, artifact.format, {
2699
3241
  source: options.source,
2700
3242
  displayName: artifact.displayName
2701
3243
  });
3244
+ if (agents.length) {
3245
+ content += `
3246
+
3247
+ ## Letra agent identities (registry v1)
3248
+ ${agents.map((agent) => buildSkillInstructions(agent, artifact.tool)).join("\n\n")}`;
3249
+ }
2702
3250
  if (artifact.id === "agents-md-shared" && tools.includes("codex")) {
2703
3251
  content = appendCodexLiveContextInstructions(content);
2704
3252
  }
@@ -2711,8 +3259,8 @@ Execute \`letra health\` para detalhes e \`letra health ack <id>\` para reconhec
2711
3259
  }
2712
3260
  if (tools.includes("codex")) {
2713
3261
  const configArtifact = ADAPTER_ARTIFACTS["codex-project-config"];
2714
- const configPath = join15(root, configArtifact.path);
2715
- const existingConfig = existsSync16(configPath) ? readFileSync12(configPath, "utf-8") : "";
3262
+ const configPath = join17(root, configArtifact.path);
3263
+ const existingConfig = existsSync18(configPath) ? readFileSync14(configPath, "utf-8") : "";
2716
3264
  files.push({
2717
3265
  tool: "codex",
2718
3266
  artifactId: configArtifact.id,
@@ -2733,11 +3281,11 @@ function generateAdapters(root, tools, options) {
2733
3281
  const boundary = options.confineWrites ? createWorkspaceBoundary(root) : null;
2734
3282
  const verb = options.verb ?? (options.source === "init" ? "Created" : "Updated");
2735
3283
  for (const file of renderAdapterFiles(root, tools, options)) {
2736
- const requestedPath = join15(root, file.path);
3284
+ const requestedPath = join17(root, file.path);
2737
3285
  const filePath = boundary?.assertPath(requestedPath) ?? requestedPath;
2738
- const dir = join15(filePath, "..");
2739
- if (!existsSync16(dir)) mkdirSync5(dir, { recursive: true });
2740
- writeFileSync5(filePath, file.content);
3286
+ const dir = join17(filePath, "..");
3287
+ if (!existsSync18(dir)) mkdirSync6(dir, { recursive: true });
3288
+ writeFileSync6(filePath, file.content);
2741
3289
  if (!options.quiet) {
2742
3290
  console.log(` ${chalk2.gray(verb)} ${file.path}`);
2743
3291
  }
@@ -2751,6 +3299,14 @@ export {
2751
3299
  DEFAULT_HARNESS_VERSION,
2752
3300
  resolveHarnessRoot,
2753
3301
  loadHarness,
3302
+ resolveActiveFlow,
3303
+ resolveActiveFlowFor,
3304
+ loadHarnessForWorkflow,
3305
+ resolveAgentDirection,
3306
+ listAgents,
3307
+ createAgent,
3308
+ updateAgent,
3309
+ deleteAgent,
2754
3310
  TOOL_TARGETS,
2755
3311
  renderAdapterFiles,
2756
3312
  generateAdapters,