@crewhaus/target-crew 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -22,4 +22,18 @@ export declare class TargetEmitError extends CrewhausError {
22
22
  readonly name = "TargetEmitError";
23
23
  constructor(message: string, cause?: unknown);
24
24
  }
25
- export declare function emitCrew(ir: IrCrewV0, opts?: EmitReadmeOptions): Bundle;
25
+ /**
26
+ * Evals Wave 4, cluster S (D36 + NEW-shape-1) — `emitCrew` options.
27
+ * `evalEntry: true` (set only by `crewhaus compile --with-eval-harness`)
28
+ * additionally emits an `eval-entry.ts` file exporting
29
+ * `runForEval(input, opts)`: one crew run through the SAME compiled
30
+ * orchestrator + role definitions, with the SAME run options the daemon
31
+ * assembles (permissions/taxonomy/caps/limits/budget/hooks/MCP/memory),
32
+ * minus the stdin/stdout framing — the `crew_done` finalOutput is returned
33
+ * for grading. Purely ADDITIVE: the existing daemon/orchestrator/role files
34
+ * stay byte-identical with or without the option.
35
+ */
36
+ export type EmitCrewOptions = EmitReadmeOptions & {
37
+ readonly evalEntry?: boolean;
38
+ };
39
+ export declare function emitCrew(ir: IrCrewV0, opts?: EmitCrewOptions): Bundle;
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@
17
17
  * future shell pipeline consumer) can parse them deterministically.
18
18
  */
19
19
  import { CrewhausError } from "@crewhaus/errors";
20
+ import { renderControlDrain, renderControlImports, renderControlPlaneBoot, renderControlStart, } from "@crewhaus/gateway-protocol/control-codegen";
20
21
  import { escapeJsonString } from "@crewhaus/infra-utils";
21
22
  import { renderBundleReadme, } from "@crewhaus/ir";
22
23
  import { memoryFragmentFromIr } from "@crewhaus/memory-service";
@@ -80,6 +81,9 @@ export function emitCrew(ir, opts = {}) {
80
81
  { path: "orchestrator.ts", content: renderOrchestrator(ir, entryRole) },
81
82
  { path: "daemon.ts", content: renderDaemon(ir) },
82
83
  ];
84
+ if (opts.evalEntry === true) {
85
+ files.push({ path: "eval-entry.ts", content: renderEvalEntry(ir) });
86
+ }
83
87
  for (const role of ir.roles) {
84
88
  files.push({ path: `agent_${safeFileName(role.name)}.ts`, content: renderRoleAgent(ir, role) });
85
89
  }
@@ -151,6 +155,53 @@ function renderPermissionsField(ir) {
151
155
  }
152
156
  return `\n${lines.join("\n")}`;
153
157
  }
158
+ /**
159
+ * Loop contract 0.4 (Batch C, G11) — the `askMode` + `approvals` crew
160
+ * RunOptions fields (the orchestrator forwards both to every role turn,
161
+ * primary activations and inline A2A peer turns alike). Unlike the CLI's
162
+ * `approvalRunOptions`, a bundle parses no `--ask-mode`, so the spec value is
163
+ * FIXED here at emit time.
164
+ *
165
+ * Deliberately NOT folded into {@link renderPermissionsField}: that renderer
166
+ * early-returns "" when the spec declares neither a mode nor rules — which is
167
+ * exactly the bundle where parking matters MOST, because with no block every
168
+ * unmatched tool resolves to `ask`. So this one is unconditional, including
169
+ * under `"deny"` where it never parks: runtime-core picks its denial wording
170
+ * by testing `approvals === undefined`, so handing it the store lets it
171
+ * honestly report `ask_mode: "deny"` instead of blaming absent plumbing.
172
+ */
173
+ function renderApprovalFields(ir, indent) {
174
+ return (`\n${indent}askMode: ${escapeJsonString(ir.permissions.askMode ?? "pause")},` +
175
+ `\n${indent}approvals: { store: __approvals, surface: "crew" },`);
176
+ }
177
+ /**
178
+ * G11 — the park store the fields above reference, emitted unconditionally
179
+ * into every file that assembles `crew.run` opts. Constructing it does no I/O;
180
+ * the first write happens at a park.
181
+ *
182
+ * `rootArg` is what the file can offer `resolveSessionRootDir`: the daemon has
183
+ * nothing (`undefined` → tenant root, else `CREWHAUS_SESSION_DIR`, else the
184
+ * store's own default), while the eval bridge passes its caller's per-sample
185
+ * directory so a parked sample's record — which embeds the raw tool input —
186
+ * lands in that sample's artifacts instead of the operator's working tree.
187
+ */
188
+ function renderApprovalStoreBoot(rootArg, indent = "") {
189
+ return `
190
+ ${indent}// G11 — a compiled bundle is NON-INTERACTIVE: a tool that lands on \`ask\`
191
+ ${indent}// has nobody to prompt, so without this it collapsed to a deny. Rooted
192
+ ${indent}// where the run's session files land, so parks live beside them (and
193
+ ${indent}// inside a tenant's rebased root when one is active). No I/O until a park.
194
+ ${indent}const __approvalRoot = resolveSessionRootDir(${rootArg});
195
+ ${indent}const __approvals = createPendingApprovalStore(
196
+ ${indent} __approvalRoot !== undefined ? { rootDir: __approvalRoot } : {},
197
+ ${indent});
198
+ `;
199
+ }
200
+ /** The store's imports. A SEPARATE line from any other runtime-core import
201
+ * the file may already carry — duplicate specifiers are already normal in
202
+ * emitted output, and one dedicated line keeps exact-import-line assertions
203
+ * (and diffs) stable. */
204
+ const APPROVAL_STORE_IMPORT = `import { createPendingApprovalStore, resolveSessionRootDir } from "@crewhaus/runtime-core";\n`;
154
205
  /**
155
206
  * Section 55 / item 23 — render the `failureTaxonomy` crew RunOptions field.
156
207
  * The orchestrator threads it into every role's runChatLoop (same crew-wide
@@ -255,8 +306,23 @@ function renderHooksField(ir) {
255
306
  * daemon's stdout is the JSON-per-line event stream and must stay
256
307
  * machine-parseable.
257
308
  */
309
+ /** The `mcp_servers` keys that carry a synthesized Thredz server for this
310
+ * crew: the crew-wide `"thredz"` plus one `"thredz-<slug>"` per role that
311
+ * owns its own key. They are spawned on the shared host but deliberately
312
+ * kept OUT of the namespaced `registerMcpServer` pass — their tools are
313
+ * registered as BARE names into per-role catalogs by `connectThredz`, which
314
+ * is what makes `wiki_write` mean "my wiki" to each role. Namespacing them
315
+ * too would double-register the whole vocabulary as `thredz__wiki_write`. */
316
+ function thredzServerNames(ir) {
317
+ const names = new Set();
318
+ for (const role of ir.roles)
319
+ if (role.thredzServer !== undefined)
320
+ names.add(role.thredzServer);
321
+ return names;
322
+ }
258
323
  function renderMcpServers(ir) {
259
- const entries = Object.entries(ir.mcp_servers);
324
+ const thredzNames = thredzServerNames(ir);
325
+ const entries = Object.entries(ir.mcp_servers).filter(([name]) => !thredzNames.has(name));
260
326
  if (entries.length === 0) {
261
327
  return { imports: [], bootBlock: "", hasAny: false };
262
328
  }
@@ -571,10 +637,20 @@ function memoryFabric(ir) {
571
637
  const memoryOn = ir.memory !== undefined && ir.memory.enabled !== false;
572
638
  const continuityOn = ir.continuity !== undefined;
573
639
  const wired = memoryOn || continuityOn;
640
+ // 0.5.0 — AMENDS the crew-wide scope stated above: when any role carries its
641
+ // own Thredz config, the WIKI stops being crew-wide. Each role gets its own,
642
+ // scoped to its own space, and the crew-wide fabric must not also register
643
+ // the ten LOCAL wiki twins — a role's tool array would then carry both, and
644
+ // duplicate names in the array advertised to the provider are a 400.
645
+ // Facts, continuity, plan and skills stay crew-wide and local.
646
+ const perRoleWiki = ir.roles.some((r) => r.thredz !== undefined);
647
+ const crewMemory = memoryOn && perRoleWiki && ir.memory !== undefined
648
+ ? (({ wiki: _perRole, ...rest }) => rest)(ir.memory)
649
+ : ir.memory;
574
650
  const fragmentJson = wired
575
651
  ? JSON.stringify(memoryFragmentFromIr({
576
652
  name: ir.name,
577
- ...(memoryOn ? { memory: ir.memory } : {}),
653
+ ...(memoryOn ? { memory: crewMemory } : {}),
578
654
  ...(continuityOn ? { continuity: ir.continuity } : {}),
579
655
  // v0.3.0 Goal 2 (PR 17) — learning rides the fragment: wireMemory
580
656
  // renders the learning-loop skill + gates in /study /reflect.
@@ -583,12 +659,107 @@ function memoryFabric(ir) {
583
659
  : "";
584
660
  return { wired, fragmentJson };
585
661
  }
662
+ /**
663
+ * 0.5.0 — the per-role Thredz boot. One `addServer` + one `ToolCatalog` +
664
+ * one `connectThredz` + one `wireWiki` per role that carries a config.
665
+ *
666
+ * The catalog is per role ON PURPOSE: `registerMcpToolAliases` throws on a
667
+ * bare-name collision within the catalog it is handed, so two roles could not
668
+ * both own `wiki_write` in one catalog. A catalog is a boot-time composition
669
+ * device — one Map plus N registrations — and `runChatLoop` never sees one, so
670
+ * this costs essentially nothing and lets every role keep the BARE vocabulary
671
+ * that five prompt sites and four policy surfaces match verbatim.
672
+ */
673
+ function renderRoleThredz(ir) {
674
+ const roles = ir.roles.filter((r) => r.thredz !== undefined && r.thredzServer !== undefined);
675
+ if (roles.length === 0) {
676
+ return {
677
+ imports: [],
678
+ bootBlock: "",
679
+ roleExtraToolsField: "",
680
+ roleMemoryField: "",
681
+ hasAny: false,
682
+ };
683
+ }
684
+ // Distinct servers: roles sharing the crew default share one npx process.
685
+ const servers = new Map();
686
+ for (const r of roles)
687
+ if (!servers.has(r.thredzServer))
688
+ servers.set(r.thredzServer, r);
689
+ const ident = (role) => role.replace(/[^A-Za-z0-9]/g, "_");
690
+ const addLines = [...servers].map(([name, r]) => ` try {
691
+ mcpHost.addServer(${escapeJsonString(name)}, resolveMcpServerConfig(${JSON.stringify(synthesizedThredzServerFor(ir, name))}, { name: ${escapeJsonString(name)} }));
692
+ } catch (__err) {
693
+ const __report = toFailureReport(__err);
694
+ process.stderr.write(\`\${formatRunFailure(__report, { prefix: "[crew]" })}\\n\`);
695
+ process.exit(__report.exitCode);
696
+ }`);
697
+ const connectLines = [...servers].map(([name, r]) => {
698
+ const id = ident(name);
699
+ const agent = r.thredz?.agentName;
700
+ return ` const __thredzCat_${id} = new ToolCatalog();
701
+ const __thredz_${id} = await connectThredz(mcpHost, __thredzCat_${id}, {
702
+ serverName: ${escapeJsonString(name)},${agent !== undefined ? `\n agentName: ${escapeJsonString(agent)},` : ""}
703
+ log: (line) => process.stderr.write(line),
704
+ });`;
705
+ });
706
+ // Per-role wiki seam. With a live connection wireWiki returns
707
+ // { store: null, tools: [] } plus a client-bound recall; on the degrade it
708
+ // returns the ten LOCAL tools — so exactly one of the two arrays is
709
+ // non-empty per role, and both are safe to concatenate.
710
+ const wikiLines = roles.map((r) => {
711
+ const id = ident(r.name);
712
+ const server = ident(r.thredzServer);
713
+ return ` const __wiki_${id} = wireWiki(${JSON.stringify({
714
+ specName: ir.name,
715
+ ...(ir.memory !== undefined ? { memory: ir.memory } : {}),
716
+ thredz: r.thredz,
717
+ })}, { catalog: { register: () => {} }, cwd: process.cwd(), thredz: __thredz_${server} });`;
718
+ });
719
+ const recallK = ir.memory?.wiki?.recallK ?? 5;
720
+ const roleExtraToolsField = `\n roleExtraTools: {${roles
721
+ .map((r) => `\n ${escapeJsonString(r.name)}: [...__thredzCat_${ident(r.thredzServer)}.list(), ...(__wiki_${ident(r.name)}?.tools ?? [])],`)
722
+ .join("")}\n },`;
723
+ const roleMemoryField = `\n roleMemory: {${roles
724
+ .map((r) => `\n ${escapeJsonString(r.name)}: foldWikiRecall(__memWired?.options.memory, __wiki_${ident(r.name)}, ${recallK}),`)
725
+ .join("")}\n },`;
726
+ // The Thredz servers ride the SHARED McpHost. When the crew declares no
727
+ // user MCP servers, `renderMcpServers` emits nothing — so this block owns
728
+ // the host declaration and its imports instead.
729
+ const ownsHost = Object.keys(ir.mcp_servers).every((n) => servers.has(n));
730
+ return {
731
+ imports: [
732
+ `import { connectThredz, wireWiki, foldWikiRecall } from "@crewhaus/memory-service";`,
733
+ ...(ownsHost
734
+ ? [`import { McpHost, resolveMcpServerConfig } from "@crewhaus/mcp-host";`]
735
+ : []),
736
+ ],
737
+ bootBlock: `
738
+ // 0.5.0 — per-role Thredz. One key owns one private wiki space and
739
+ // thredz-mcp reads one key per process, so per-role private memory is one
740
+ // spawned server per role. Each role's vocabulary lands in its OWN catalog.${ownsHost ? "\n const mcpHost = new McpHost();" : ""}
741
+ ${addLines.join("\n")}
742
+ ${connectLines.join("\n")}
743
+ ${wikiLines.join("\n")}`,
744
+ roleExtraToolsField,
745
+ roleMemoryField,
746
+ hasAny: true,
747
+ };
748
+ }
749
+ /** The synthesized server config the compiler put in `ir.mcp_servers`. */
750
+ function synthesizedThredzServerFor(ir, name) {
751
+ const cfg = ir.mcp_servers[name];
752
+ if (cfg === undefined)
753
+ throw new Error(`crew emitter: no mcp_servers entry for ${name}`);
754
+ return cfg;
755
+ }
586
756
  function renderDaemon(ir) {
587
757
  const hasRules = ir.permissions.rules.length > 0;
588
758
  const permImport = hasRules
589
759
  ? `import { BUILTIN_DEFAULT_RULES } from "@crewhaus/permission-engine";\n`
590
760
  : "";
591
761
  const permField = renderPermissionsField(ir);
762
+ const approvalFields = renderApprovalFields(ir, " ");
592
763
  const taxonomyField = renderFailureTaxonomyField(ir);
593
764
  // Loop contract 0.4 (Batch A) — the new crew.run knobs.
594
765
  const crewCapsFields = renderCrewCapsFields(ir);
@@ -597,6 +768,8 @@ function renderDaemon(ir) {
597
768
  const hooksField = renderHooksField(ir);
598
769
  const fabric = memoryFabric(ir);
599
770
  const mcp = renderMcpServers(ir);
771
+ // 0.5.0 — per-role Thredz servers, catalogs and wiki seams.
772
+ const roleThredz = renderRoleThredz(ir);
600
773
  // Section 13 (Batch A, G34) — when any role declares sub-agents, inject
601
774
  // the spawner once at the run level; the orchestrator stamps it (plus the
602
775
  // per-role subAgents map) onto each role's runChatLoop bridge.
@@ -614,7 +787,7 @@ function renderDaemon(ir) {
614
787
  : fabric.wired
615
788
  ? `import type { RegisteredTool } from "@crewhaus/tool-catalog";\n`
616
789
  : "";
617
- const mcpImport = mcp.hasAny ? `${mcp.imports.join("\n")}\n` : "";
790
+ const mcpImport = `${[...(mcp.hasAny ? mcp.imports : []), ...roleThredz.imports].join("\n")}${mcp.hasAny || roleThredz.hasAny ? "\n" : ""}`;
618
791
  const memImport = fabric.wired
619
792
  ? `import { wireMemory } from "@crewhaus/memory-service";
620
793
  import { createSkillTool } from "@crewhaus/skills-registry";
@@ -648,35 +821,69 @@ import { createSkillTool } from "@crewhaus/skills-registry";
648
821
  ...(__memWired.options.continuity !== undefined ? { continuity: __memWired.options.continuity } : {}),
649
822
  ...(__skills.length > 0 ? { skills: __skills } : {}),`
650
823
  : "";
651
- const mcpShutdownOk = mcp.hasAny ? "\n await mcpHost.disconnectAll();" : "";
652
- const mcpShutdownErr = mcp.hasAny ? "\n await mcpHost.disconnectAll().catch(() => {});" : "";
653
- // v0.3.0 Goal 3 — thredz is spec-carried on this shape but not emit-wired
654
- // in this release (the one-knob backend flip ships on cli). Surface it,
655
- // 0.2.3-style, so nobody wonders why their wiki stayed local.
656
- const thredzWarning = ir.thredz !== undefined
657
- ? "// note: thredz configured but ignored on crew in 0.3.0 — the Thredz backend flip is wired on the cli shape (design §4)\n"
658
- : "";
824
+ // The host is shared by user MCP servers and the per-role Thredz servers —
825
+ // disconnect it if EITHER put something on it, or N npx children outlive the
826
+ // run.
827
+ const hostLive = mcp.hasAny || roleThredz.hasAny;
828
+ const mcpShutdownOk = hostLive ? "\n await mcpHost.disconnectAll();" : "";
829
+ const mcpShutdownErr = hostLive ? "\n await mcpHost.disconnectAll().catch(() => {});" : "";
830
+ // 0.5.0 — thredz is EMIT-WIRED on crew. A crew whose roles each carry their
831
+ // own key gets one server, one space and one vocabulary per role; roles that
832
+ // share the crew-wide block share one brain. Nothing is ignored any more.
833
+ const thredzWarning = "";
834
+ // crewhaus.control.v1, from the shared gateway-protocol renderers. The crew
835
+ // daemon is a ONE-SHOT: it consumes stdin, runs the crew and exits, so it
836
+ // arms no pokeable lane — `/control/v1/wake` answers 404 lane_not_armed.
837
+ // What control.v1 gives an operator here is a uniform way to observe the run
838
+ // (`/status`: turns + pid + startedAt) and to ask it to stop taking new work
839
+ // and finish (`/drain`), on exactly the same surface the long-running shapes
840
+ // serve.
841
+ const controlPlaneBoot = renderControlPlaneBoot({
842
+ name: ir.name,
843
+ target: "crew",
844
+ indent: " ",
845
+ auditLogExpr: "__controlAudit",
846
+ });
847
+ const controlDrain = renderControlDrain({
848
+ indent: " ",
849
+ body: `process.stderr.write("[crew] draining — finishing the in-flight run\\n");
850
+ while (__crewRunning) await new Promise((__r) => setTimeout(__r, 100));`,
851
+ });
852
+ const controlStart = renderControlStart({ indent: " " });
659
853
  return `#!/usr/bin/env bun
660
854
  // Generated by crewhaus. DO NOT EDIT.
661
855
  // Source spec: ${escapeJsonString(ir.name)} (target: crew, ir version: ${ir.version}, file: daemon.ts)
662
- ${thredzWarning}import { formatRunFailure, toFailureReport } from "@crewhaus/errors";
663
- ${permImport}${memImport}${mcpImport}${spawnImport}${toolCatalogImport}import { buildCrew } from "./orchestrator.js";
856
+ ${thredzWarning}import { openAuditLog } from "@crewhaus/audit-log";
857
+ import { formatRunFailure, toFailureReport } from "@crewhaus/errors";
858
+ ${renderControlImports()}${APPROVAL_STORE_IMPORT}${permImport}${memImport}${mcpImport}${spawnImport}${toolCatalogImport}import { buildCrew } from "./orchestrator.js";
859
+ ${renderApprovalStoreBoot("undefined")}
860
+ let __crewRunning = false;
664
861
 
665
862
  async function main(): Promise<void> {
666
- const crew = buildCrew();
863
+ // control.v1 — the harness-wide hash-chained audit log every control call
864
+ // appends a \`gateway_request\` record to. CREWHAUS_SECURITY_AUDIT=0 opts out.
865
+ const __controlAudit =
866
+ process.env["CREWHAUS_SECURITY_AUDIT"] === "0"
867
+ ? undefined
868
+ : await openAuditLog({ rootDir: \`\${process.cwd()}/.crewhaus/audit\` });
869
+ ${controlPlaneBoot}${controlDrain}${controlStart} const crew = buildCrew();
667
870
  const input = await readAllStdin();
668
871
  const trimmed = input.trim();
669
872
  if (trimmed.length === 0) {
670
873
  process.stderr.write("[crew] no input on stdin\\n");
671
874
  process.exit(2);
672
- }${mcp.bootBlock}${memBoot}
673
- const opts: Parameters<typeof crew.run>[1] = {${permField}${taxonomyField}${crewCapsFields}${loopLimitsField}${budgetField}${hooksField}${spawnField}${extraToolsField}${memOptsFields}
875
+ }${mcp.bootBlock}${roleThredz.bootBlock}${memBoot}
876
+ const opts: Parameters<typeof crew.run>[1] = {${permField}${approvalFields}${taxonomyField}${crewCapsFields}${loopLimitsField}${budgetField}${hooksField}${spawnField}${extraToolsField}${roleThredz.roleExtraToolsField}${roleThredz.roleMemoryField}${memOptsFields}
674
877
  };
675
878
  let lastFinalOutput = "";
879
+ __crewRunning = true;
676
880
  try {
677
881
  for await (const ev of crew.run(trimmed, opts)) {
678
882
  process.stdout.write(\`\${JSON.stringify(ev)}\\n\`);
679
- if (ev.kind === "crew_done") lastFinalOutput = ev.finalOutput;
883
+ if (ev.kind === "crew_done") {
884
+ lastFinalOutput = ev.finalOutput;
885
+ __control.counters.turns++;
886
+ }
680
887
  }
681
888
  } catch (err) {
682
889
  // v0.3.0 Goal 6 — render the one structured failure report (classified
@@ -684,8 +891,11 @@ async function main(): Promise<void> {
684
891
  // status instead of the bare "[crew] error:" line + exit 1.
685
892
  const __report = toFailureReport(err);
686
893
  process.stderr.write(\`\${formatRunFailure(__report, { prefix: "[crew]" })}\\n\`);${mcpShutdownErr}
894
+ __crewRunning = false;
687
895
  process.exit(__report.exitCode);
688
896
  }${mcpShutdownOk}
897
+ __crewRunning = false;
898
+ await __control.stop();
689
899
  if (lastFinalOutput.length > 0) {
690
900
  const PREVIEW_LIMIT = 200;
691
901
  const preview =
@@ -713,3 +923,128 @@ main().catch((err) => {
713
923
  });
714
924
  `;
715
925
  }
926
+ // ---------------------------------------------------------------------------
927
+ // File (cluster S, D36/NEW-shape-1): eval-entry.ts — the eval bridge's
928
+ // runtime entry. Emitted ONLY under `emitCrew(ir, { evalEntry: true })`.
929
+ // ---------------------------------------------------------------------------
930
+ /**
931
+ * Render `eval-entry.ts`: one crew run through the compiled orchestrator +
932
+ * roles, assembled with the SAME renderers the daemon uses (so the two run-
933
+ * option sets can never drift), minus the stdin/stdout framing. Each eval
934
+ * sample is one crew run; the `crew_done` finalOutput is the graded output.
935
+ * The runner's per-sample `sessionId`/`sessionRootDir` thread into the crew's
936
+ * own session machinery so the crew transcript lands in the sample artifacts
937
+ * (crew trace events stay on the orchestrator's internal bus in this slice —
938
+ * `crew.run` mints its own RunContext).
939
+ */
940
+ function renderEvalEntry(ir) {
941
+ const hasRules = ir.permissions.rules.length > 0;
942
+ const permImport = hasRules
943
+ ? `import { BUILTIN_DEFAULT_RULES } from "@crewhaus/permission-engine";\n`
944
+ : "";
945
+ const permField = renderPermissionsField(ir);
946
+ const approvalFields = renderApprovalFields(ir, " ");
947
+ const taxonomyField = renderFailureTaxonomyField(ir);
948
+ const crewCapsFields = renderCrewCapsFields(ir);
949
+ const loopLimitsField = renderLoopLimitsField(ir);
950
+ const budgetField = renderBudgetField(ir);
951
+ const hooksField = renderHooksField(ir);
952
+ const fabric = memoryFabric(ir);
953
+ const mcp = renderMcpServers(ir);
954
+ const anySubAgents = ir.roles.some((r) => r.subAgents.length > 0);
955
+ const spawnImport = anySubAgents
956
+ ? `import { spawnSubAgent } from "@crewhaus/sub-agent-spawner";\n`
957
+ : "";
958
+ const spawnField = anySubAgents ? "\n spawnSubAgent," : "";
959
+ const toolCatalogImport = mcp.hasAny && fabric.wired
960
+ ? `import { ToolCatalog, type RegisteredTool } from "@crewhaus/tool-catalog";\n`
961
+ : mcp.hasAny
962
+ ? `import { ToolCatalog } from "@crewhaus/tool-catalog";\n`
963
+ : fabric.wired
964
+ ? `import type { RegisteredTool } from "@crewhaus/tool-catalog";\n`
965
+ : "";
966
+ const mcpImport = mcp.hasAny ? `${mcp.imports.join("\n")}\n` : "";
967
+ const memImport = fabric.wired
968
+ ? `import { wireMemory } from "@crewhaus/memory-service";
969
+ import { createSkillTool } from "@crewhaus/skills-registry";
970
+ `
971
+ : "";
972
+ const memBoot = fabric.wired
973
+ ? `
974
+ // v0.3.0 — the memory fabric, wired ONCE through the stable composition-
975
+ // root call (design §1 principle 1): roles share the spec-scoped stores;
976
+ // the orchestrator threads the tools + seams into every role's turn.
977
+ //
978
+ // Cluster S (D36/NEW-shape-1) — the fabric roots at the caller's per-sample
979
+ // directory when one is supplied, so a bridged eval keeps the Pillar-2
980
+ // isolation invariant: sample N's facts/plan/handoff never leak into sample
981
+ // N+1, and nothing is written into the operator's working tree.
982
+ const __memTools: RegisteredTool[] = [];
983
+ const __memWired = await wireMemory(${fabric.fragmentJson}, {
984
+ catalog: { register: (t: RegisteredTool) => { __memTools.push(t); } },
985
+ cwd: __evalOpts.sessionRootDir ?? process.cwd(),
986
+ });
987
+ const __skills = __memWired.options.skills ?? [];
988
+ if (__skills.length > 0) __memTools.push(createSkillTool(__skills));`
989
+ : "";
990
+ const extraToolsField = mcp.hasAny && fabric.wired
991
+ ? "\n extraTools: [...__mcpTools, ...__memTools],"
992
+ : mcp.hasAny
993
+ ? "\n extraTools: __mcpTools,"
994
+ : fabric.wired
995
+ ? "\n extraTools: __memTools,"
996
+ : "";
997
+ const memOptsFields = fabric.wired
998
+ ? `
999
+ ...(__memWired.options.memory !== undefined ? { memory: __memWired.options.memory } : {}),
1000
+ ...(__memWired.options.continuity !== undefined ? { continuity: __memWired.options.continuity } : {}),
1001
+ ...(__skills.length > 0 ? { skills: __skills } : {}),`
1002
+ : "";
1003
+ const runBlock = mcp.hasAny
1004
+ ? ` let __final = "";
1005
+ try {
1006
+ for await (const ev of crew.run(input, opts)) {
1007
+ if (ev.kind === "crew_done") __final = ev.finalOutput;
1008
+ }
1009
+ } finally {
1010
+ await mcpHost.disconnectAll().catch(() => {});
1011
+ }
1012
+ return __final;`
1013
+ : ` let __final = "";
1014
+ for await (const ev of crew.run(input, opts)) {
1015
+ if (ev.kind === "crew_done") __final = ev.finalOutput;
1016
+ }
1017
+ return __final;`;
1018
+ return `// Generated by crewhaus. DO NOT EDIT.
1019
+ // Source spec: ${escapeJsonString(ir.name)} (target: crew, ir version: ${ir.version}, file: eval-entry.ts — the compile --with-eval-harness bridge entry)
1020
+ ${APPROVAL_STORE_IMPORT}${permImport}${memImport}${mcpImport}${spawnImport}${toolCatalogImport}import { buildCrew } from "./orchestrator.js";
1021
+
1022
+ type __CrewRunOpts = NonNullable<Parameters<ReturnType<typeof buildCrew>["run"]>[1]>;
1023
+
1024
+ /**
1025
+ * Eval bridge (cluster S, D36/NEW-shape-1) — run ONE crew turn through the
1026
+ * compiled orchestrator + role definitions with the SAME run options the
1027
+ * daemon assembles, minus the stdin/stdout framing. Each eval sample is one
1028
+ * crew run; the crew_done finalOutput is the graded output. \`sessionId\` /
1029
+ * \`sessionRootDir\` thread into the crew's own session machinery so the crew
1030
+ * transcript lands in the caller's per-sample directory; \`_adapter\` is the
1031
+ * scripted-provider test seam every role turn shares.
1032
+ */
1033
+ export async function runForEval(
1034
+ input: string,
1035
+ __evalOpts: {
1036
+ sessionId?: string;
1037
+ sessionRootDir?: string;
1038
+ _adapter?: __CrewRunOpts["_adapter"];
1039
+ } = {},
1040
+ ): Promise<string> {
1041
+ const crew = buildCrew();${renderApprovalStoreBoot("__evalOpts.sessionRootDir", " ")}${mcp.bootBlock}${memBoot}
1042
+ const opts: __CrewRunOpts = {${permField}${approvalFields}${taxonomyField}${crewCapsFields}${loopLimitsField}${budgetField}${hooksField}${spawnField}${extraToolsField}${memOptsFields}
1043
+ ...(__evalOpts.sessionId !== undefined ? { sessionId: __evalOpts.sessionId } : {}),
1044
+ ...(__evalOpts.sessionRootDir !== undefined ? { sessionRootDir: __evalOpts.sessionRootDir } : {}),
1045
+ ...(__evalOpts._adapter !== undefined ? { _adapter: __evalOpts._adapter } : {}),
1046
+ };
1047
+ ${runBlock}
1048
+ }
1049
+ `;
1050
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/target-crew",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "Codegen for the CRW target — emits a daemon + per-role agent files driven by crew-orchestrator (Section 22)",
6
6
  "main": "dist/index.js",
@@ -15,10 +15,11 @@
15
15
  "test": "bun test src"
16
16
  },
17
17
  "dependencies": {
18
- "@crewhaus/errors": "0.4.0",
19
- "@crewhaus/infra-utils": "0.4.0",
20
- "@crewhaus/ir": "0.4.0",
21
- "@crewhaus/memory-service": "0.4.0"
18
+ "@crewhaus/errors": "0.5.0",
19
+ "@crewhaus/gateway-protocol": "0.5.0",
20
+ "@crewhaus/infra-utils": "0.5.0",
21
+ "@crewhaus/ir": "0.5.0",
22
+ "@crewhaus/memory-service": "0.5.0"
22
23
  },
23
24
  "license": "Apache-2.0",
24
25
  "author": {