@aaac/runtime 0.1.44 → 0.1.49

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.
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  buildGuardrailContext,
6
6
  loadProjectConfig
7
- } from "./chunk-735UA5HV.js";
7
+ } from "./chunk-YZQRSVDZ.js";
8
8
  import {
9
9
  DslValidationError,
10
10
  buildCandidateAgents,
@@ -35,17 +35,10 @@ import {
35
35
  shouldInjectAnalyzerExplorationMandate,
36
36
  zodSchemaToPromptDescription,
37
37
  zodSchemaToYamlExample
38
- } from "./chunk-IGSKPSU3.js";
38
+ } from "./chunk-C6XCN33A.js";
39
39
  import {
40
- PluginRegistry,
41
- createGuardrailHooks,
42
- createGuardrailHooksForAgent,
43
- createGuardrailHooksFromRules,
44
- getBlockingViolations,
45
- getWarnings,
46
- hasBlockingViolation,
47
- pluginRegistry
48
- } from "./chunk-EH5VFZYJ.js";
40
+ jsonSchemaToZod
41
+ } from "./chunk-ET6TGQRT.js";
49
42
  import {
50
43
  OBSERVABILITY_ENV_VARS,
51
44
  buildObservabilityEnv,
@@ -66,8 +59,15 @@ import {
66
59
  serializeObserverEmit
67
60
  } from "./chunk-KXGUWBGK.js";
68
61
  import {
69
- jsonSchemaToZod
70
- } from "./chunk-ET6TGQRT.js";
62
+ PluginRegistry,
63
+ createGuardrailHooks,
64
+ createGuardrailHooksForAgent,
65
+ createGuardrailHooksFromRules,
66
+ getBlockingViolations,
67
+ getWarnings,
68
+ hasBlockingViolation,
69
+ pluginRegistry
70
+ } from "./chunk-EH5VFZYJ.js";
71
71
 
72
72
  // src/index.ts
73
73
  import { createRequire } from "module";
@@ -2470,31 +2470,692 @@ async function guardStatus(opts = {}) {
2470
2470
  }
2471
2471
 
2472
2472
  // src/lib/claude-materialize/config.ts
2473
+ import { basename as basename2 } from "path";
2473
2474
  import { z as z2 } from "zod";
2475
+ var WorkspaceMemberBindingSchema = z2.object({
2476
+ /**
2477
+ * Workspace-relative path to the member directory
2478
+ * (e.g. `"./aaac"`). The member's agent-contracts.yaml is resolved
2479
+ * relative to this directory using `config_path`.
2480
+ */
2481
+ path: z2.string(),
2482
+ /**
2483
+ * Path to the member's agent-contracts DSL, relative to the member
2484
+ * root. Defaults to `"./agent-contracts.yaml"`.
2485
+ */
2486
+ config_path: z2.string().optional()
2487
+ });
2488
+ var WorkspaceBindingConfigSchema = z2.object({
2489
+ members: z2.array(WorkspaceMemberBindingSchema),
2490
+ /**
2491
+ * @deprecated Since #241 the generated hook bins are bundled into
2492
+ * self-contained ESM (`@aaac/runtime` inlined) at `claude sync` time, so no
2493
+ * `node_modules` resolution — and thus no `NODE_PATH` export — is needed at
2494
+ * runtime. This field is still accepted for config backward-compatibility but
2495
+ * is ignored (no-op). Remove it from your binding config at your convenience.
2496
+ */
2497
+ resolve_from: z2.string().optional()
2498
+ });
2499
+ var ClaudeEmitSchema = z2.object({
2500
+ /** When true, materialize `<output_dir>/workflows/<id>.js` per workflow. */
2501
+ workflows: z2.boolean().default(false)
2502
+ }).strip();
2474
2503
  var ClaudeConfigSchema = z2.object({
2475
2504
  /** Root directory for Claude artifacts (relative to the project root). */
2476
2505
  output_dir: z2.string().default(".claude"),
2477
2506
  /** Path to agent-contracts.yaml (relative to the project root). */
2478
2507
  config_path: z2.string().default("./agent-contracts.yaml"),
2508
+ /**
2509
+ * Additive-artifact emission toggles. Defaults keep the historical
2510
+ * behavior (no workflow scripts) so existing output is byte-preserved.
2511
+ */
2512
+ emit: ClaudeEmitSchema.default({ workflows: false }),
2479
2513
  /**
2480
2514
  * Command wired into guardrail hooks (e.g. "dev-team guard evaluate").
2481
2515
  * Reserved for future hook integration; validated for config parity.
2482
2516
  */
2483
2517
  guard_command: z2.string().optional(),
2484
2518
  /** Override component id; defaults to `dsl.system.id`. */
2485
- component_id: z2.string().optional()
2519
+ component_id: z2.string().optional(),
2520
+ /**
2521
+ * Workspace binding configuration. When present the generator emits
2522
+ * workspace-router bins instead of single-component bins (AC3).
2523
+ */
2524
+ workspace: WorkspaceBindingConfigSchema.optional()
2486
2525
  }).strip();
2526
+ function resolveWorkspaceMembers(ws) {
2527
+ return ws.members.map((m) => {
2528
+ const name = basename2(m.path.replace(/\/+$/, "")) || m.path;
2529
+ const configPath = m.config_path ?? "./agent-contracts.yaml";
2530
+ return {
2531
+ name,
2532
+ path: m.path,
2533
+ configPath,
2534
+ cacheKey: `navigation-index.${name}`
2535
+ };
2536
+ });
2537
+ }
2487
2538
  function parseClaudeConfig(raw) {
2488
2539
  return ClaudeConfigSchema.parse(raw ?? {});
2489
2540
  }
2490
2541
 
2542
+ // src/lib/claude-materialize/workflow-render.ts
2543
+ import { resolveSchemaRefs } from "agent-contracts";
2544
+ var GENERATED_MARKER = "// Auto-generated by @aaac/runtime claude-materialize (#235). Do not edit; run `claude sync` instead.";
2545
+ var MODEL_CLASS_MAP = {
2546
+ fast: { model: "haiku" },
2547
+ standard: { model: "sonnet" },
2548
+ thinking: { model: "opus", effort: "high" }
2549
+ };
2550
+ var WorkflowCodegenError = class extends Error {
2551
+ constructor(message) {
2552
+ super(message);
2553
+ this.name = "WorkflowCodegenError";
2554
+ }
2555
+ };
2556
+ function jsString(value) {
2557
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "")}'`;
2558
+ }
2559
+ function jsLiteral(value, indent = 0) {
2560
+ const pad = " ".repeat(indent);
2561
+ const padIn = " ".repeat(indent + 1);
2562
+ if (value === null) return "null";
2563
+ if (typeof value === "boolean") return value ? "true" : "false";
2564
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "null";
2565
+ if (typeof value === "string") return jsString(value);
2566
+ if (Array.isArray(value)) {
2567
+ if (value.length === 0) return "[]";
2568
+ const items = value.map((v) => `${padIn}${jsLiteral(v, indent + 1)}`);
2569
+ return `[
2570
+ ${items.join(",\n")}
2571
+ ${pad}]`;
2572
+ }
2573
+ if (typeof value === "object") {
2574
+ const entries = Object.entries(value).filter(
2575
+ ([, v]) => v !== void 0
2576
+ );
2577
+ if (entries.length === 0) return "{}";
2578
+ const lines = entries.map(
2579
+ ([k, v]) => `${padIn}${jsKey(k)}: ${jsLiteral(v, indent + 1)}`
2580
+ );
2581
+ return `{
2582
+ ${lines.join(",\n")}
2583
+ ${pad}}`;
2584
+ }
2585
+ return "null";
2586
+ }
2587
+ function jsKey(key) {
2588
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : jsString(key);
2589
+ }
2590
+ function stepIdentity(step) {
2591
+ if (step.type === "gate") return `gate:${step.gate_kind ?? ""}`;
2592
+ return step.task ?? "";
2593
+ }
2594
+ function resolveDeps(steps) {
2595
+ return steps.map((step, i) => {
2596
+ if (step.depends_on !== void 0) {
2597
+ return step.depends_on.filter((dep) => dep !== "workflow-input").map((dep) => {
2598
+ const idx = steps.findIndex((s, j) => j < i && stepIdentity(s) === dep);
2599
+ if (idx === -1) {
2600
+ throw new WorkflowCodegenError(
2601
+ `depends_on "${dep}" in step ${i} (${stepIdentity(step)}) not found among preceding steps`
2602
+ );
2603
+ }
2604
+ return idx;
2605
+ });
2606
+ }
2607
+ return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);
2608
+ });
2609
+ }
2610
+ function computeWaves(steps, deps) {
2611
+ const completed = /* @__PURE__ */ new Set();
2612
+ const waves = [];
2613
+ while (completed.size < steps.length) {
2614
+ const ready = [];
2615
+ for (let i = 0; i < steps.length; i++) {
2616
+ if (completed.has(i)) continue;
2617
+ if (deps[i].every((d) => completed.has(d))) ready.push(i);
2618
+ }
2619
+ if (ready.length === 0) {
2620
+ throw new WorkflowCodegenError(
2621
+ "Dependency cycle detected: no steps are ready to schedule"
2622
+ );
2623
+ }
2624
+ waves.push(ready);
2625
+ for (const i of ready) completed.add(i);
2626
+ }
2627
+ return waves;
2628
+ }
2629
+ function renderDelegatePrompt(agent, task, step) {
2630
+ const userRequest = (step.instruction ?? step.description ?? "").trim() || "Perform the task described above.";
2631
+ return buildTaskPrompt(agent, task, { user_request: userRequest });
2632
+ }
2633
+ var PRIOR_CONTEXT_PREFIX = "\n\n---\n\n## Prior Context\n";
2634
+ var GATE_SCHEMA = {
2635
+ type: "object",
2636
+ properties: {
2637
+ approved: { type: "boolean" },
2638
+ reason: { type: "string" }
2639
+ },
2640
+ required: ["approved"]
2641
+ };
2642
+ function resolveHandoffSchema(task, handoffTypes, components) {
2643
+ const id = task.result_handoff;
2644
+ if (!id) return void 0;
2645
+ const ht = handoffTypes[id];
2646
+ if (!ht?.schema) return void 0;
2647
+ return resolveSchemaRefs(ht.schema, components);
2648
+ }
2649
+ function toAgentContract(id, raw) {
2650
+ const rawMode = raw.mode ?? "read-only";
2651
+ return {
2652
+ id,
2653
+ role_name: raw.role_name ?? id,
2654
+ purpose: raw.purpose ?? "",
2655
+ mode: rawMode === "read-write" ? "read-write" : "read-only",
2656
+ responsibilities: raw.responsibilities ?? [],
2657
+ constraints: raw.constraints ?? [],
2658
+ rules: raw.rules ?? []
2659
+ };
2660
+ }
2661
+ function toTaskContract(id, raw) {
2662
+ return {
2663
+ id,
2664
+ description: raw.description ?? "",
2665
+ target_agent: raw.target_agent ?? "",
2666
+ result_handoff: raw.result_handoff ?? "",
2667
+ completion_criteria: raw.completion_criteria ?? [],
2668
+ model_class: raw.model_class
2669
+ };
2670
+ }
2671
+ function buildRegistries(dsl) {
2672
+ const rawAgents = dsl.agents ?? {};
2673
+ const rawTasks = dsl.tasks ?? {};
2674
+ const agents = {};
2675
+ for (const [id, a] of Object.entries(rawAgents)) agents[id] = toAgentContract(id, a);
2676
+ const tasks = {};
2677
+ for (const [id, t] of Object.entries(rawTasks)) tasks[id] = toTaskContract(id, t);
2678
+ const componentsRoot = dsl.components ?? {};
2679
+ const components = componentsRoot.schemas ?? componentsRoot;
2680
+ return {
2681
+ agents,
2682
+ tasks,
2683
+ handoffTypes: dsl.handoff_types ?? {},
2684
+ components
2685
+ };
2686
+ }
2687
+ function phaseTitle(step) {
2688
+ if (step.type === "gate") return "Gate";
2689
+ return step.task ?? "Step";
2690
+ }
2691
+ function buildMeta(id, wf, steps) {
2692
+ const seen = /* @__PURE__ */ new Set();
2693
+ const phases = [];
2694
+ for (const step of steps) {
2695
+ const title = phaseTitle(step);
2696
+ if (seen.has(title)) continue;
2697
+ seen.add(title);
2698
+ const detail = (step.description ?? "").trim().split("\n")[0]?.trim();
2699
+ phases.push(detail ? { title, detail } : { title });
2700
+ }
2701
+ const meta = {
2702
+ name: id,
2703
+ description: (wf.description ?? "").trim() || id
2704
+ };
2705
+ if (wf.trigger) meta.whenToUse = wf.trigger.trim();
2706
+ if (phases.length > 0) meta.phases = phases;
2707
+ return meta;
2708
+ }
2709
+ function agentOpts(task, step, handoffSchema, indent) {
2710
+ const opts = {};
2711
+ if (handoffSchema) opts.schema = handoffSchema;
2712
+ opts.label = task.id;
2713
+ opts.phase = phaseTitle(step);
2714
+ const mc = task.model_class ? MODEL_CLASS_MAP[task.model_class] : void 0;
2715
+ if (mc) {
2716
+ opts.model = mc.model;
2717
+ if (mc.effort) opts.effort = mc.effort;
2718
+ }
2719
+ return jsLiteral(opts, indent);
2720
+ }
2721
+ function resultVar(i) {
2722
+ return `step${i}Result`;
2723
+ }
2724
+ function priorContextExpr(i, steps, deps) {
2725
+ const fragments = [];
2726
+ if (stepDependsOnWorkflowInput(steps[i].depends_on)) {
2727
+ fragments.push("_wfInput(args)");
2728
+ }
2729
+ const contribs = deps[i].filter((d) => steps[d].type !== "gate");
2730
+ for (const d of contribs) {
2731
+ fragments.push(`_ctx(${d + 1}, ${jsString(stepIdentity(steps[d]))}, ${resultVar(d)})`);
2732
+ }
2733
+ if (fragments.length === 0) return "";
2734
+ return fragments.join(" + ");
2735
+ }
2736
+ function emitWorkflowInputHelper(pad) {
2737
+ const id = WORKFLOW_INPUT_STEP_ID;
2738
+ return [
2739
+ `${pad}const _wfInput = (args) => {`,
2740
+ `${pad} if (args === undefined || args === null) return ''`,
2741
+ `${pad} let output`,
2742
+ `${pad} if (typeof args === 'string') {`,
2743
+ `${pad} output = { user_request: args }`,
2744
+ `${pad} } else if (typeof args === 'object' && ('user_request' in args || 'handoff' in args)) {`,
2745
+ `${pad} const h = args.handoff`,
2746
+ `${pad} const userRequest = typeof args.user_request === 'string'`,
2747
+ `${pad} ? args.user_request`,
2748
+ `${pad} : h`,
2749
+ `${pad} ? (typeof h.payload === 'string' ? h.payload : JSON.stringify(h.payload, null, 2))`,
2750
+ `${pad} : ''`,
2751
+ `${pad} output = h`,
2752
+ `${pad} ? { user_request: userRequest, handoff: (h.version !== undefined ? { type: h.type, version: h.version, payload: h.payload } : { type: h.type, payload: h.payload }) }`,
2753
+ `${pad} : { user_request: userRequest }`,
2754
+ `${pad} } else {`,
2755
+ `${pad} output = { user_request: JSON.stringify(args, null, 2), handoff: { type: ${jsString(id)}, payload: args } }`,
2756
+ `${pad} }`,
2757
+ `${pad} return '\\n\\n--- Step: ${id} ---\\n' + JSON.stringify(output, null, 2)`,
2758
+ `${pad}}`
2759
+ ];
2760
+ }
2761
+ function withPriorContext(basePromptLiteral, ctxExpr, feedback) {
2762
+ let expr = basePromptLiteral;
2763
+ if (ctxExpr) {
2764
+ expr = `${expr} + ((${ctxExpr}) ? ${jsString(PRIOR_CONTEXT_PREFIX)} + (${ctxExpr}) : '')`;
2765
+ }
2766
+ if (feedback) {
2767
+ const varSection = `${jsString(`
2768
+
2769
+ ---
2770
+
2771
+ ## Context Variables
2772
+
2773
+ - ${feedback.injectAs}: `)} + ${feedback.feedbackVar}`;
2774
+ expr = `${expr} + (${feedback.feedbackVar} !== undefined ? ${varSection} : '')`;
2775
+ }
2776
+ return expr;
2777
+ }
2778
+ function resolveStepAgentTask(step, reg, kind) {
2779
+ const taskId = step.task ?? "";
2780
+ const task = reg.tasks[taskId];
2781
+ if (!task) {
2782
+ throw new WorkflowCodegenError(`${kind} step references unknown task "${taskId}"`);
2783
+ }
2784
+ const agent = reg.agents[task.target_agent] ?? reg.agents[step.from_agent ?? ""];
2785
+ if (!agent) {
2786
+ throw new WorkflowCodegenError(
2787
+ `${kind} task "${taskId}" targets unknown agent "${task.target_agent}"`
2788
+ );
2789
+ }
2790
+ return { agent, task, taskId };
2791
+ }
2792
+ function emitDelegateExpr(step, reg, i, steps, deps, indent, feedback) {
2793
+ const { agent, task } = resolveStepAgentTask(step, reg, "delegate");
2794
+ const prompt = renderDelegatePrompt(agent, task, step);
2795
+ const schema = resolveHandoffSchema(task, reg.handoffTypes, reg.components);
2796
+ const promptExpr = withPriorContext(jsLiteral(prompt), priorContextExpr(i, steps, deps), feedback);
2797
+ const opts = agentOpts(task, step, schema, indent);
2798
+ return `agent(${promptExpr}, ${opts})`;
2799
+ }
2800
+ function emitGateStatements(step, i, steps, deps, pad, feedback) {
2801
+ const gateStep = {
2802
+ type: "gate",
2803
+ gate_kind: step.gate_kind ?? "",
2804
+ description: step.description ?? ""
2805
+ };
2806
+ const marker = "## Prior Step Results\n";
2807
+ const full = buildGateEvaluationPrompt(gateStep, "__PRIOR__");
2808
+ const at = full.indexOf(marker) + marker.length;
2809
+ const head = full.slice(0, at);
2810
+ const tail = full.slice(at).replace(/^__PRIOR__/, "");
2811
+ const ctxExpr = priorContextExpr(i, steps, deps);
2812
+ let promptExpr = ctxExpr ? `${jsLiteral(head)} + (${ctxExpr}) + ${jsLiteral(tail)}` : jsLiteral(full.replace("__PRIOR__", "(no prior results)"));
2813
+ if (feedback) {
2814
+ const varSection = `${jsString(`
2815
+
2816
+ ## Context Variables
2817
+
2818
+ - ${feedback.injectAs}: `)} + ${feedback.feedbackVar}`;
2819
+ promptExpr = `${promptExpr} + (${feedback.feedbackVar} !== undefined ? ${varSection} : '')`;
2820
+ }
2821
+ const label = `gate:${gateStep.gate_kind}`;
2822
+ const lines = [];
2823
+ lines.push(`${pad}const gate = await agent(${promptExpr}, {`);
2824
+ lines.push(`${pad} schema: ${jsLiteral(GATE_SCHEMA, 0).replace(/\n/g, `
2825
+ ${pad} `)},`);
2826
+ lines.push(`${pad} label: ${jsString(label)},`);
2827
+ lines.push(`${pad} phase: 'Gate',`);
2828
+ lines.push(`${pad}})`);
2829
+ lines.push(`${pad}if (!gate.approved) {`);
2830
+ lines.push(`${pad} return { blocked: true, gate: ${jsString(gateStep.gate_kind)}, reason: gate.reason }`);
2831
+ lines.push(`${pad}}`);
2832
+ return lines;
2833
+ }
2834
+ function emitEvaluateAgentCall(step, reg, i, steps, deps, pad, feedback) {
2835
+ const { agent, task } = resolveStepAgentTask(step, reg, "evaluate");
2836
+ const prompt = renderDelegatePrompt(agent, task, step);
2837
+ const schema = resolveHandoffSchema(task, reg.handoffTypes, reg.components);
2838
+ const promptExpr = withPriorContext(jsLiteral(prompt), priorContextExpr(i, steps, deps), feedback);
2839
+ const opts = {};
2840
+ if (schema) opts.schema = schema;
2841
+ opts.label = task.id;
2842
+ opts.phase = phaseTitle(step);
2843
+ const mc = task.model_class ? MODEL_CLASS_MAP[task.model_class] : void 0;
2844
+ if (mc) {
2845
+ opts.model = mc.model;
2846
+ if (mc.effort) opts.effort = mc.effort;
2847
+ }
2848
+ const optsLiteral = jsLiteral(opts, 0).replace(/\n/g, `
2849
+ ${pad}`);
2850
+ return `await agent(${promptExpr}, ${optsLiteral})`;
2851
+ }
2852
+ function emitStepStatements(i, reg, steps, deps, pad, opts) {
2853
+ const step = steps[i];
2854
+ const feedback = opts?.feedback;
2855
+ if (step.type === "delegate") {
2856
+ const expr = emitDelegateExpr(step, reg, i, steps, deps, pad.length / 2 + 1, feedback);
2857
+ const lhs = opts?.assign ? resultVar(i) : `const ${resultVar(i)}`;
2858
+ return [`${pad}${lhs} = await ${expr}`];
2859
+ }
2860
+ if (step.type === "gate") {
2861
+ return emitGateStatements(step, i, steps, deps, pad, feedback);
2862
+ }
2863
+ throw new WorkflowCodegenError(`emitStepStatements called with non-simple step type "${step.type}"`);
2864
+ }
2865
+ function emitEvaluateLoop(evalIdx, reg, steps, deps) {
2866
+ const step = steps[evalIdx];
2867
+ const taskId = step.task ?? "";
2868
+ const loopTo = step.loop_to ?? "";
2869
+ const maxIter = step.max_iterations ?? 1;
2870
+ const onExhausted = step.on_exhausted ?? "escalate";
2871
+ const injectAs = step.inject_as;
2872
+ const loopToIdx = steps.findIndex((s, j) => j < evalIdx && stepIdentity(s) === loopTo);
2873
+ if (loopToIdx === -1) {
2874
+ throw new WorkflowCodegenError(
2875
+ `evaluate step "${taskId}" references unknown loop_to "${loopTo}"`
2876
+ );
2877
+ }
2878
+ const spanIndices = [];
2879
+ for (let k = loopToIdx; k < evalIdx; k++) spanIndices.push(k);
2880
+ const iterVar = `${resultVar(evalIdx)}Iteration`;
2881
+ const feedbackVar = injectAs ? `${resultVar(evalIdx)}Feedback` : void 0;
2882
+ const feedback = injectAs && feedbackVar ? { injectAs, feedbackVar } : void 0;
2883
+ const lines = [];
2884
+ lines.push(` // evaluate: ${taskId} \u2014 bounded convergence loop, re-runs steps ${loopTo}..${taskId} (max ${maxIter})`);
2885
+ for (const k of spanIndices) {
2886
+ if (steps[k].type !== "gate") lines.push(` let ${resultVar(k)}`);
2887
+ }
2888
+ lines.push(` let ${resultVar(evalIdx)}`);
2889
+ lines.push(` let ${iterVar} = 0`);
2890
+ if (feedbackVar) lines.push(` let ${feedbackVar}`);
2891
+ lines.push(` while (true) {`);
2892
+ lines.push(` ${iterVar} = ${iterVar} + 1`);
2893
+ for (const k of spanIndices) {
2894
+ for (const stmt of emitStepStatements(k, reg, steps, deps, " ", { assign: true, feedback })) {
2895
+ lines.push(stmt);
2896
+ }
2897
+ }
2898
+ const evalCall = emitEvaluateAgentCall(step, reg, evalIdx, steps, deps, " ", feedback);
2899
+ lines.push(` ${resultVar(evalIdx)} = ${evalCall}`);
2900
+ lines.push(` if (${resultVar(evalIdx)}.verdict === 'pass') break`);
2901
+ lines.push(` if (${iterVar} >= ${maxIter}) {`);
2902
+ if (onExhausted === "abort") {
2903
+ lines.push(` throw new Error('evaluate "${taskId}" exhausted ${maxIter} iterations without passing')`);
2904
+ } else if (onExhausted === "fail_partial") {
2905
+ lines.push(` log('evaluate "${taskId}" exhausted iterations \u2014 proceeding with partial result')`);
2906
+ lines.push(` break`);
2907
+ } else {
2908
+ lines.push(` return { escalated: true, evaluate: ${jsString(taskId)}, reason: 'exhausted ' + ${iterVar} + ' iterations without passing' }`);
2909
+ }
2910
+ lines.push(` }`);
2911
+ if (feedbackVar) {
2912
+ lines.push(` ${feedbackVar} = typeof ${resultVar(evalIdx)}.feedback === 'string' ? ${resultVar(evalIdx)}.feedback : JSON.stringify(${resultVar(evalIdx)})`);
2913
+ lines.push(` log('evaluate "${taskId}" failed \u2014 re-running ${loopTo}..${taskId} with feedback as ${injectAs} (' + ${iterVar} + '/' + ${maxIter} + ')')`);
2914
+ } else {
2915
+ lines.push(` log('evaluate "${taskId}" failed \u2014 re-running ${loopTo}..${taskId} (' + ${iterVar} + '/' + ${maxIter} + ')')`);
2916
+ }
2917
+ lines.push(` }`);
2918
+ return lines;
2919
+ }
2920
+ function assertInScope(step) {
2921
+ if (step.type === "decision" || step.type === "team_task") {
2922
+ throw new WorkflowCodegenError(
2923
+ `Step type "${step.type}" is out of scope for #235 (only delegate/gate/evaluate are supported). Remove it from the workflow or extend the codegen before enabling workflow output.`
2924
+ );
2925
+ }
2926
+ if (step.type !== "delegate" && step.type !== "gate" && step.type !== "evaluate") {
2927
+ throw new WorkflowCodegenError(`Unknown workflow step type "${step.type}"`);
2928
+ }
2929
+ }
2930
+ function renderWorkflowScript(id, wf, dsl) {
2931
+ const reg = buildRegistries(dsl);
2932
+ const steps = wf.steps ?? [];
2933
+ for (const step of steps) assertInScope(step);
2934
+ const deps = resolveDeps(steps);
2935
+ const waves = computeWaves(steps, deps);
2936
+ const meta = buildMeta(id, wf, steps);
2937
+ const waveOf = /* @__PURE__ */ new Map();
2938
+ waves.forEach((wave, w) => wave.forEach((i) => waveOf.set(i, w)));
2939
+ const spanOwner = /* @__PURE__ */ new Map();
2940
+ for (let e = 0; e < steps.length; e++) {
2941
+ if (steps[e].type !== "evaluate") continue;
2942
+ const loopTo = steps[e].loop_to ?? "";
2943
+ const loopToIdx = steps.findIndex((s, j) => j < e && stepIdentity(s) === loopTo);
2944
+ if (loopToIdx === -1) {
2945
+ throw new WorkflowCodegenError(
2946
+ `evaluate step "${steps[e].task ?? ""}" references unknown loop_to "${loopTo}"`
2947
+ );
2948
+ }
2949
+ for (let k = loopToIdx; k <= e; k++) spanOwner.set(k, e);
2950
+ }
2951
+ const usesStepContext = steps.some(
2952
+ (_, i) => deps[i].some((d) => steps[d].type !== "gate")
2953
+ );
2954
+ const usesWorkflowInput = steps.some(
2955
+ (step) => stepDependsOnWorkflowInput(step.depends_on)
2956
+ );
2957
+ const body = [];
2958
+ if (usesStepContext) {
2959
+ body.push(
2960
+ " const _ctx = (n, id, r) => '\\n\\n--- Step ' + n + ': ' + id + ' ---\\n' + (typeof r === 'string' ? r : JSON.stringify(r, null, 2))"
2961
+ );
2962
+ }
2963
+ if (usesWorkflowInput) {
2964
+ body.push(...emitWorkflowInputHelper(" "));
2965
+ }
2966
+ const emittedWaves = /* @__PURE__ */ new Set();
2967
+ for (let i = 0; i < steps.length; i++) {
2968
+ if (spanOwner.has(i) && spanOwner.get(i) !== i) continue;
2969
+ const step = steps[i];
2970
+ if (step.type === "evaluate") {
2971
+ body.push(...emitEvaluateLoop(i, reg, steps, deps));
2972
+ continue;
2973
+ }
2974
+ const w = waveOf.get(i);
2975
+ const wave = waves[w];
2976
+ const batchable = wave.length > 1 && wave.every((j) => steps[j].type === "delegate" && !spanOwner.has(j));
2977
+ if (batchable) {
2978
+ if (emittedWaves.has(w)) continue;
2979
+ emittedWaves.add(w);
2980
+ const lhs = wave.map((j) => resultVar(j)).join(", ");
2981
+ body.push(` const [${lhs}] = await parallel([`);
2982
+ for (const j of wave) {
2983
+ const expr = emitDelegateExpr(steps[j], reg, j, steps, deps, 2);
2984
+ body.push(` () => ${expr},`);
2985
+ }
2986
+ body.push(" ])");
2987
+ continue;
2988
+ }
2989
+ {
2990
+ if (step.type === "delegate") {
2991
+ body.push(...emitStepStatements(i, reg, steps, deps, " "));
2992
+ } else if (step.type === "gate") {
2993
+ body.push(...emitGateStatements(step, i, steps, deps, " "));
2994
+ }
2995
+ }
2996
+ }
2997
+ body.push(" return { completed: true, workflow: " + jsString(id) + " }");
2998
+ const metaLiteral = jsLiteral(meta, 0);
2999
+ const topLevelBody = body.map((line) => line.startsWith(" ") ? line.slice(2) : line).join("\n");
3000
+ return `${GENERATED_MARKER}
3001
+
3002
+ export const meta = ${metaLiteral}
3003
+
3004
+ ${topLevelBody}
3005
+ `;
3006
+ }
3007
+ function renderWorkflowFiles(dsl, outputDir) {
3008
+ const workflows = dsl.workflow ?? {};
3009
+ const root = outputDir.replace(/\/+$/, "");
3010
+ const files = [];
3011
+ for (const [id, wf] of Object.entries(workflows)) {
3012
+ const content = renderWorkflowScript(id, wf, dsl);
3013
+ files.push({ path: `${root}/workflows/${id}.js`, content });
3014
+ }
3015
+ return files;
3016
+ }
3017
+
2491
3018
  // src/lib/claude-materialize/materialize.ts
2492
3019
  import { existsSync as existsSync4 } from "fs";
2493
3020
  import { mkdir as mkdir3, readFile as readFile7, writeFile as writeFile3 } from "fs/promises";
2494
- import { dirname as dirname3, join as join5, resolve as resolve5 } from "path";
3021
+ import { dirname as dirname5, join as join7, resolve as resolve5 } from "path";
2495
3022
  import {
2496
3023
  claudeGenerator
2497
3024
  } from "@aaac/contracts";
3025
+
3026
+ // src/lib/claude-materialize/bundle-bins.ts
3027
+ import { createHash } from "crypto";
3028
+ import { readFileSync as readFileSync2 } from "fs";
3029
+ import { dirname as dirname4, join as join6, parse as parse2 } from "path";
3030
+ import { fileURLToPath as fileURLToPath2 } from "url";
3031
+
3032
+ // src/lib/claude-materialize/claude-bundle-assets.ts
3033
+ import { readFileSync } from "fs";
3034
+ import { dirname as dirname3, join as join5, parse } from "path";
3035
+ import { fileURLToPath } from "url";
3036
+ function resolveRuntimeDistDir() {
3037
+ let dir = dirname3(fileURLToPath(import.meta.url));
3038
+ const root = parse(dir).root;
3039
+ while (true) {
3040
+ try {
3041
+ const pkg2 = JSON.parse(readFileSync(join5(dir, "package.json"), "utf8"));
3042
+ if (pkg2.name === "@aaac/runtime") {
3043
+ return join5(dir, "dist", "claude-bundles");
3044
+ }
3045
+ } catch {
3046
+ }
3047
+ if (dir === root) break;
3048
+ dir = dirname3(dir);
3049
+ }
3050
+ return join5(dirname3(fileURLToPath(import.meta.url)), "claude-bundles");
3051
+ }
3052
+ function loadPrebuiltBundle(kind) {
3053
+ const path = join5(resolveRuntimeDistDir(), `${kind}.js`);
3054
+ try {
3055
+ return readFileSync(path, "utf8");
3056
+ } catch {
3057
+ throw new Error(
3058
+ `Missing pre-built Claude runtime bundle: ${path}. Run \`npm run build\` in @aaac/runtime (build-claude-bundles.mjs) first.`
3059
+ );
3060
+ }
3061
+ }
3062
+
3063
+ // src/lib/claude-materialize/bundle-bins.ts
3064
+ var RUNTIME_GLOBAL = "__aaac_runtime";
3065
+ function resolveRuntimeVersion() {
3066
+ let dir = dirname4(fileURLToPath2(import.meta.url));
3067
+ const root = parse2(dir).root;
3068
+ while (true) {
3069
+ try {
3070
+ const pkg2 = JSON.parse(readFileSync2(join6(dir, "package.json"), "utf8"));
3071
+ if (pkg2.name === "@aaac/runtime" && pkg2.version) return pkg2.version;
3072
+ } catch {
3073
+ }
3074
+ if (dir === root) break;
3075
+ dir = dirname4(dir);
3076
+ }
3077
+ return "bundled";
3078
+ }
3079
+ var RUNTIME_VERSION = resolveRuntimeVersion();
3080
+ var bundleCache = /* @__PURE__ */ new Map();
3081
+ function readPrebuiltBundle(kind) {
3082
+ const cached = bundleCache.get(kind);
3083
+ if (cached !== void 0) return cached;
3084
+ const content = loadPrebuiltBundle(kind);
3085
+ bundleCache.set(kind, content);
3086
+ return content;
3087
+ }
3088
+ var MARKER_PREFIX = "//__aaac_bundle__:";
3089
+ function isHookBin(targetDir, path) {
3090
+ return targetDir === ".claude/bin" && !path.includes("/");
3091
+ }
3092
+ function bundleKindFor(source) {
3093
+ return /@aaac\/runtime\/claude-native\/hooks-lite/.test(source) ? "lean" : "full";
3094
+ }
3095
+ function extractRuntimeImport(source) {
3096
+ const re = /import\s*\{([^}]*)\}\s*from\s*["']@aaac\/runtime\/claude-native(?:\/hooks-lite)?["'];?/;
3097
+ const match = source.match(re);
3098
+ if (!match) {
3099
+ throw new Error(
3100
+ "Could not find the @aaac/runtime/claude-native import in the generated hook bin."
3101
+ );
3102
+ }
3103
+ const names = match[1].split(",").map((s) => s.trim()).filter((s) => s.length > 0);
3104
+ return { statement: match[0], names };
3105
+ }
3106
+ function assembleHookBin(source) {
3107
+ const kind = bundleKindFor(source);
3108
+ const bundle = readPrebuiltBundle(kind);
3109
+ const withoutShebang = source.replace(/^#![^\n]*\n/, "");
3110
+ const { statement, names } = extractRuntimeImport(withoutShebang);
3111
+ const rebind = `const { ${names.join(", ")} } = ${RUNTIME_GLOBAL};`;
3112
+ const binBody = withoutShebang.replace(statement, rebind);
3113
+ const requireShim = [
3114
+ "import { createRequire as __aaacCreateRequire } from 'node:module';",
3115
+ "const require = __aaacCreateRequire(import.meta.url);",
3116
+ "const __aaacImportMetaUrl = import.meta.url;",
3117
+ "const __aaacImportMetaResolve = (s) => import.meta.resolve(s);"
3118
+ ].join("\n");
3119
+ const bodyWithoutMarker = [
3120
+ "#!/usr/bin/env node",
3121
+ "// Auto-generated by @aaac/runtime claude sync (#241). Do not edit \u2014 self-contained bundle.",
3122
+ requireShim,
3123
+ bundle.trimEnd(),
3124
+ binBody.trimStart()
3125
+ ].join("\n");
3126
+ const marker = markerFor(bodyWithoutMarker);
3127
+ const shebangEnd = bodyWithoutMarker.indexOf("\n");
3128
+ return bodyWithoutMarker.slice(0, shebangEnd + 1) + marker + "\n" + bodyWithoutMarker.slice(shebangEnd + 1);
3129
+ }
3130
+ function markerFor(fullFileMinusMarker) {
3131
+ const hash = createHash("sha256").update(fullFileMinusMarker).digest("hex").slice(0, 16);
3132
+ return `${MARKER_PREFIX}${RUNTIME_VERSION}:${hash}`;
3133
+ }
3134
+ function readBundleMarker(content) {
3135
+ const nl = content.indexOf("\n");
3136
+ if (nl === -1) return void 0;
3137
+ const secondNl = content.indexOf("\n", nl + 1);
3138
+ const line = content.slice(nl + 1, secondNl === -1 ? void 0 : secondNl);
3139
+ return line.startsWith(MARKER_PREFIX) ? line : void 0;
3140
+ }
3141
+ function expectedBundleMarker(source) {
3142
+ const assembled = assembleHookBin(source);
3143
+ return readBundleMarker(assembled) ?? "";
3144
+ }
3145
+ function recomputeMarkerFromDisk(content) {
3146
+ const nl = content.indexOf("\n");
3147
+ if (nl === -1) return void 0;
3148
+ const secondNl = content.indexOf("\n", nl + 1);
3149
+ if (secondNl === -1) return void 0;
3150
+ const markerLine = content.slice(nl + 1, secondNl);
3151
+ if (!markerLine.startsWith(MARKER_PREFIX)) return void 0;
3152
+ const shebang = content.slice(0, nl + 1);
3153
+ const rest = content.slice(secondNl + 1);
3154
+ const bodyWithoutMarker = shebang + rest;
3155
+ return markerFor(bodyWithoutMarker);
3156
+ }
3157
+
3158
+ // src/lib/claude-materialize/materialize.ts
2498
3159
  var CLAUDE_BLOCK_BEGIN = "<!-- aaac:claude-native:begin -->";
2499
3160
  var CLAUDE_BLOCK_END = "<!-- aaac:claude-native:end -->";
2500
3161
  function buildComponentIR(dsl, config) {
@@ -2513,12 +3174,12 @@ function buildComponentIR(dsl, config) {
2513
3174
  }
2514
3175
  function relPath(file) {
2515
3176
  if (file.targetDir && file.targetDir !== ".") {
2516
- return join5(file.targetDir, file.path);
3177
+ return join7(file.targetDir, file.path);
2517
3178
  }
2518
3179
  return file.path;
2519
3180
  }
2520
3181
  function absPath(root, file) {
2521
- return join5(root, relPath(file));
3182
+ return join7(root, relPath(file));
2522
3183
  }
2523
3184
  async function readIfExists(path) {
2524
3185
  if (!existsSync4(path)) return void 0;
@@ -2526,7 +3187,15 @@ async function readIfExists(path) {
2526
3187
  }
2527
3188
  function renderFiles(dsl, config) {
2528
3189
  const ir = buildComponentIR(dsl, config);
2529
- return claudeGenerator.generate(ir, { outputDir: "", componentPath: "" });
3190
+ const workspaceOptions = config.workspace ? {
3191
+ members: resolveWorkspaceMembers(config.workspace),
3192
+ resolve_from: config.workspace.resolve_from
3193
+ } : void 0;
3194
+ return claudeGenerator.generate(ir, {
3195
+ outputDir: "",
3196
+ componentPath: "",
3197
+ workspace: workspaceOptions
3198
+ });
2530
3199
  }
2531
3200
  function mergeClaudeMdBlock(existing, block) {
2532
3201
  const normalizedBlock = block.trimStart();
@@ -2588,6 +3257,14 @@ function checkContent(file, existing) {
2588
3257
  if (existing !== file.content) return "changed";
2589
3258
  return null;
2590
3259
  }
3260
+ function workflowFiles(dsl, config) {
3261
+ if (!config.emit.workflows) return [];
3262
+ return renderWorkflowFiles(dsl, config.output_dir);
3263
+ }
3264
+ function actionForOverwrite(existing, next) {
3265
+ if (existing === void 0) return "created";
3266
+ return existing === next ? "unchanged" : "updated";
3267
+ }
2591
3268
  async function syncClaude(opts) {
2592
3269
  const config = parseClaudeConfig(opts.config);
2593
3270
  const root = resolve5(opts.projectRoot);
@@ -2596,13 +3273,37 @@ async function syncClaude(opts) {
2596
3273
  const rel = relPath(file);
2597
3274
  const abs = absPath(root, file);
2598
3275
  const existing = await readIfExists(abs);
3276
+ if (isHookBin(file.targetDir, file.path)) {
3277
+ const expected = expectedBundleMarker(file.content);
3278
+ const stored = existing === void 0 ? void 0 : readBundleMarker(existing);
3279
+ const onDisk = existing === void 0 ? void 0 : recomputeMarkerFromDisk(existing);
3280
+ const upToDate = existing !== void 0 && stored === expected && stored === onDisk;
3281
+ const action2 = existing === void 0 ? "created" : upToDate ? "unchanged" : "updated";
3282
+ if (action2 !== "unchanged" && !opts.dryRun) {
3283
+ const assembled = assembleHookBin(file.content);
3284
+ await mkdir3(dirname5(abs), { recursive: true });
3285
+ await writeFile3(abs, assembled, "utf8");
3286
+ }
3287
+ result.files.push({ path: rel, action: action2 });
3288
+ continue;
3289
+ }
2599
3290
  const { content, action } = resolveContent(file, existing);
2600
3291
  if (action !== "unchanged" && !opts.dryRun) {
2601
- await mkdir3(dirname3(abs), { recursive: true });
3292
+ await mkdir3(dirname5(abs), { recursive: true });
2602
3293
  await writeFile3(abs, content, "utf8");
2603
3294
  }
2604
3295
  result.files.push({ path: rel, action });
2605
3296
  }
3297
+ for (const file of workflowFiles(opts.dsl, config)) {
3298
+ const abs = join7(root, file.path);
3299
+ const existing = await readIfExists(abs);
3300
+ const action = actionForOverwrite(existing, file.content);
3301
+ if (action !== "unchanged" && !opts.dryRun) {
3302
+ await mkdir3(dirname5(abs), { recursive: true });
3303
+ await writeFile3(abs, file.content, "utf8");
3304
+ }
3305
+ result.files.push({ path: file.path, action });
3306
+ }
2606
3307
  return result;
2607
3308
  }
2608
3309
  async function checkClaude(opts) {
@@ -2612,11 +3313,32 @@ async function checkClaude(opts) {
2612
3313
  for (const file of renderFiles(opts.dsl, config)) {
2613
3314
  const rel = relPath(file);
2614
3315
  const existing = await readIfExists(absPath(root, file));
3316
+ if (isHookBin(file.targetDir, file.path)) {
3317
+ if (existing === void 0) {
3318
+ drift.push({ path: rel, reason: "missing" });
3319
+ } else {
3320
+ const stored = readBundleMarker(existing);
3321
+ const expected = expectedBundleMarker(file.content);
3322
+ const onDisk = recomputeMarkerFromDisk(existing);
3323
+ if (stored !== expected || stored !== onDisk) {
3324
+ drift.push({ path: rel, reason: "changed" });
3325
+ }
3326
+ }
3327
+ continue;
3328
+ }
2615
3329
  const reason = checkContent(file, existing);
2616
3330
  if (reason) {
2617
3331
  drift.push({ path: rel, reason });
2618
3332
  }
2619
3333
  }
3334
+ for (const file of workflowFiles(opts.dsl, config)) {
3335
+ const existing = await readIfExists(join7(root, file.path));
3336
+ if (existing === void 0) {
3337
+ drift.push({ path: file.path, reason: "missing" });
3338
+ } else if (existing !== file.content) {
3339
+ drift.push({ path: file.path, reason: "changed" });
3340
+ }
3341
+ }
2620
3342
  return { inSync: drift.length === 0, drift };
2621
3343
  }
2622
3344