@hve-squad/mcp 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +46 -0
  3. package/README.md +233 -0
  4. package/dist/src/auth/entra.js +164 -0
  5. package/dist/src/auth/jose-verifier.js +31 -0
  6. package/dist/src/auth/scopes.js +240 -0
  7. package/dist/src/catalog/catalog.js +80 -0
  8. package/dist/src/config/operator-config.js +281 -0
  9. package/dist/src/engine/advisory-pipeline.js +367 -0
  10. package/dist/src/engine/advisory-run-store.js +31 -0
  11. package/dist/src/engine/artifact-store.js +165 -0
  12. package/dist/src/engine/auto-memory.js +207 -0
  13. package/dist/src/engine/backends/azure-blob-artifact-store.js +246 -0
  14. package/dist/src/engine/backends/azure-openai.js +69 -0
  15. package/dist/src/engine/backends/azure-table-run-state.js +319 -0
  16. package/dist/src/engine/backends/azure-table-squad-memory.js +240 -0
  17. package/dist/src/engine/backends/file-squad-memory.js +208 -0
  18. package/dist/src/engine/backends/graph-squad-memory.js +271 -0
  19. package/dist/src/engine/backends/managed-identity-credential.js +33 -0
  20. package/dist/src/engine/backends/overflow-squad-memory.js +151 -0
  21. package/dist/src/engine/backlog-contract.js +200 -0
  22. package/dist/src/engine/business-tools.js +118 -0
  23. package/dist/src/engine/consumption.js +134 -0
  24. package/dist/src/engine/coordinator-engine.js +1 -0
  25. package/dist/src/engine/council.js +204 -0
  26. package/dist/src/engine/delegated.js +190 -0
  27. package/dist/src/engine/dispatch-loop.js +84 -0
  28. package/dist/src/engine/durable-run-state.js +251 -0
  29. package/dist/src/engine/embedded-prompt.js +35 -0
  30. package/dist/src/engine/embedded-roles.js +133 -0
  31. package/dist/src/engine/embedded.js +1023 -0
  32. package/dist/src/engine/federation.js +96 -0
  33. package/dist/src/engine/field-cipher.js +84 -0
  34. package/dist/src/engine/gates.js +241 -0
  35. package/dist/src/engine/markdown-table.js +43 -0
  36. package/dist/src/engine/model-backend.js +16 -0
  37. package/dist/src/engine/persona-loader.js +132 -0
  38. package/dist/src/engine/persona.js +287 -0
  39. package/dist/src/engine/profiles.js +237 -0
  40. package/dist/src/engine/render/pptx-render-service.js +60 -0
  41. package/dist/src/engine/render/python-pptx-render-backend.js +117 -0
  42. package/dist/src/engine/render/render-backend.js +25 -0
  43. package/dist/src/engine/render-embedded.js +69 -0
  44. package/dist/src/engine/routing.js +275 -0
  45. package/dist/src/engine/run-params.js +70 -0
  46. package/dist/src/engine/run-state.js +132 -0
  47. package/dist/src/engine/run-worker.js +60 -0
  48. package/dist/src/engine/squad-history.js +136 -0
  49. package/dist/src/engine/squad-ledger.js +215 -0
  50. package/dist/src/engine/squad-memory-resources.js +218 -0
  51. package/dist/src/engine/squad-memory-state.js +57 -0
  52. package/dist/src/engine/squad-run-recorder.js +212 -0
  53. package/dist/src/engine/targeted-squad-memory.js +94 -0
  54. package/dist/src/engine/workspace.js +68 -0
  55. package/dist/src/observability/logger.js +75 -0
  56. package/dist/src/observability/redact.js +77 -0
  57. package/dist/src/paths.js +108 -0
  58. package/dist/src/router/router.js +88 -0
  59. package/dist/src/server-http.js +304 -0
  60. package/dist/src/server.js +237 -0
  61. package/dist/src/transports/http-core.js +1240 -0
  62. package/dist/src/transports/http.js +90 -0
  63. package/dist/src/transports/session-store.js +78 -0
  64. package/dist/src/transports/stdio.js +12 -0
  65. package/dist/src/worker-main.js +87 -0
  66. package/generated/copilot-studio-connector/README.md +44 -0
  67. package/generated/copilot-studio-connector/agent-instructions.md +90 -0
  68. package/generated/copilot-studio-connector/apiDefinition.swagger.json +60 -0
  69. package/generated/copilot-studio-connector/apiProperties.json +35 -0
  70. package/generated/copilot-studio-connector/connector.manifest.json +86 -0
  71. package/generated/mcp-tools.schema.json +462 -0
  72. package/package.json +61 -0
  73. package/tools.catalog.yml +397 -0
@@ -0,0 +1,117 @@
1
+ /**
2
+ * In-image `python-pptx` render backend (Phase 1 implementation of
3
+ * {@link RenderBackend}).
4
+ *
5
+ * Runs the `powerpoint` skill's `build_deck.py` in a BOUNDED EPHEMERAL workspace:
6
+ * a fresh `mkdtemp` directory is populated with only the caller's DATA YAML
7
+ * (`content/slide-NNN/content.yaml` + `content/global/style.yaml`), the build step
8
+ * is invoked as an argv array (never a shell string), the `.pptx` bytes are read
9
+ * back, and the workspace is ALWAYS removed in a `finally`. No state persists.
10
+ *
11
+ * Security posture:
12
+ * * SEC-5 — the workspace contains ONLY data files this backend writes; a
13
+ * `content-extra.py` is never materialized and `--allow-scripts` is never
14
+ * passed, so python-pptx cannot execute caller-supplied Python.
15
+ * * SEC-3 — `pythonPath`, `scriptsDir`, and `templatePath` come from operator
16
+ * config, never a tool input.
17
+ *
18
+ * The command runner is injectable so unit tests never spawn a real Python.
19
+ */
20
+ import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
21
+ import { execFile } from "node:child_process";
22
+ import { tmpdir } from "node:os";
23
+ import { join } from "node:path";
24
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
25
+ import { RenderInputError, } from "./render-backend.js";
26
+ /** The default `execFile`-based runner (never a shell; argv array only). */
27
+ const defaultRunCommand = (command, args, options) => new Promise((resolve, reject) => {
28
+ execFile(command, args, { cwd: options.cwd, timeout: options.timeoutMs, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
29
+ if (error) {
30
+ // Preserve the build step's stderr for observability; the logger scrubs
31
+ // the message before it is written, so including it is safe (SEC-10).
32
+ reject(new Error(`${error.message}${stderr ? ` (stderr: ${String(stderr)})` : ""}`));
33
+ return;
34
+ }
35
+ resolve({ stdout: String(stdout), stderr: String(stderr) });
36
+ });
37
+ });
38
+ function padSlide(index) {
39
+ return `slide-${String(index + 1).padStart(3, "0")}`;
40
+ }
41
+ /** Extract the caller's `slides` array from the content YAML (validated, DATA-only). */
42
+ function parseSlides(contentYaml) {
43
+ let doc;
44
+ try {
45
+ doc = parseYaml(contentYaml);
46
+ }
47
+ catch {
48
+ throw new RenderInputError("contentYaml is not valid YAML.");
49
+ }
50
+ const slides = doc && typeof doc === "object" ? doc.slides : undefined;
51
+ if (!Array.isArray(slides) || slides.length === 0) {
52
+ throw new RenderInputError("contentYaml must contain a non-empty top-level 'slides' array.");
53
+ }
54
+ return slides;
55
+ }
56
+ export class PythonPptxRenderBackend {
57
+ pythonPath;
58
+ scriptsDir;
59
+ defaultTemplatePath;
60
+ timeoutMs;
61
+ runCommand;
62
+ constructor(options) {
63
+ this.pythonPath = options.pythonPath;
64
+ this.scriptsDir = options.scriptsDir;
65
+ this.defaultTemplatePath = options.defaultTemplatePath;
66
+ this.timeoutMs = options.timeoutMs ?? 120_000;
67
+ this.runCommand = options.runCommand ?? defaultRunCommand;
68
+ }
69
+ async renderPptx(input) {
70
+ // Validate + split BEFORE any workspace/process is created (fail fast, no cleanup owed).
71
+ const slides = parseSlides(input.contentYaml);
72
+ if (typeof input.styleYaml !== "string" || input.styleYaml.trim().length === 0) {
73
+ throw new RenderInputError("styleYaml must be a non-empty YAML string.");
74
+ }
75
+ const templatePath = input.templatePath ?? this.defaultTemplatePath;
76
+ const workspace = await mkdtemp(join(tmpdir(), "squad-render-"));
77
+ try {
78
+ const contentDir = join(workspace, "content");
79
+ const globalDir = join(contentDir, "global");
80
+ await mkdir(globalDir, { recursive: true });
81
+ // style.yaml written verbatim (caller DATA).
82
+ await writeFile(join(globalDir, "style.yaml"), input.styleYaml, "utf8");
83
+ // Each slide re-serialized into its own slide-NNN/content.yaml (DATA only;
84
+ // never a content-extra.py, so python-pptx cannot execute caller Python).
85
+ for (let i = 0; i < slides.length; i += 1) {
86
+ const slideDir = join(contentDir, padSlide(i));
87
+ await mkdir(slideDir, { recursive: true });
88
+ await writeFile(join(slideDir, "content.yaml"), stringifyYaml(slides[i]), "utf8");
89
+ }
90
+ const outputPath = join(workspace, "out.pptx");
91
+ const args = [
92
+ join(this.scriptsDir, "build_deck.py"),
93
+ "--content-dir",
94
+ contentDir,
95
+ "--style",
96
+ join(globalDir, "style.yaml"),
97
+ "--output",
98
+ outputPath,
99
+ ];
100
+ // SEC-5: NEVER `--allow-scripts`. Brand template is operator config only.
101
+ if (templatePath) {
102
+ args.push("--template", templatePath);
103
+ }
104
+ await this.runCommand(this.pythonPath, args, { cwd: this.scriptsDir, timeoutMs: this.timeoutMs });
105
+ const bytes = await readFile(outputPath);
106
+ return {
107
+ pptxBytes: new Uint8Array(bytes),
108
+ slideCount: slides.length,
109
+ usedDefaultTemplate: !templatePath,
110
+ };
111
+ }
112
+ finally {
113
+ // Bounded ephemeral workspace: always removed, even on failure.
114
+ await rm(workspace, { recursive: true, force: true });
115
+ }
116
+ }
117
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Deterministic PowerPoint render backend (the swap seam).
3
+ *
4
+ * `squad_render_pptx` performs ONE known transform — deck content YAML in, a
5
+ * `.pptx` byte buffer out — via the `powerpoint` skill's `python-pptx` build step.
6
+ * This interface is the seam that keeps the execution strategy swappable with no
7
+ * rip-out: the Phase 1 implementation ({@link import("./python-pptx-render-backend.js").PythonPptxRenderBackend})
8
+ * runs Python in-process in a bounded ephemeral workspace; a later sidecar service
9
+ * or ACA Job can implement the same contract without touching the tool surface.
10
+ *
11
+ * Security posture (SEC-5 — the caller YAML is DATA, never code):
12
+ * * The input is text-only YAML; an implementation MUST materialize only data
13
+ * files (`content.yaml` / `style.yaml`), never an executable `content-extra.py`,
14
+ * and MUST NOT pass `--allow-scripts` to the build step, so no caller-supplied
15
+ * Python can execute inside python-pptx.
16
+ * * The interpreter path, scripts directory, and any brand template come from
17
+ * OPERATOR config (SEC-3), never from a tool input.
18
+ */
19
+ /** A render input that fails validation before any workspace or process is created. */
20
+ export class RenderInputError extends Error {
21
+ constructor(message) {
22
+ super(message);
23
+ this.name = "RenderInputError";
24
+ }
25
+ }
@@ -0,0 +1,69 @@
1
+ /** The locked fidelity claim (PROD-2). */
2
+ export const SQUAD_GUIDED_BANNER = "squad-guided / embedded";
3
+ function routingLines(result) {
4
+ const r = result.matchedRouting;
5
+ return [
6
+ "## matchedRouting",
7
+ "",
8
+ `- intent: ${r.routingIntent}`,
9
+ `- role: ${r.role}`,
10
+ `- tier: ${r.tier}`,
11
+ `- council: ${r.council.length > 0 ? r.council.join(", ") : "(none)"}`,
12
+ ];
13
+ }
14
+ export function renderEmbeddedResult(result) {
15
+ if (result.outcome === "denied") {
16
+ return {
17
+ isError: true,
18
+ content: [
19
+ {
20
+ type: "text",
21
+ text: `The squad declined this request (${result.reason ?? "denied"}). ` +
22
+ "No model call was made.",
23
+ },
24
+ ],
25
+ };
26
+ }
27
+ if (result.outcome === "held") {
28
+ const text = [
29
+ `<!-- hve-squad MCP (${SQUAD_GUIDED_BANNER}): paused at a Human Gate. -->`,
30
+ "",
31
+ "## Human Gate — approval required",
32
+ "",
33
+ result.approvalRequest ??
34
+ "This action is paused for human approval and will not proceed until approved out-of-band.",
35
+ "",
36
+ ...routingLines(result),
37
+ "",
38
+ "## machine-readable",
39
+ "",
40
+ "```json",
41
+ JSON.stringify({ mode: "embedded", outcome: "held", reason: result.reason, runId: result.runId }, null, 2),
42
+ "```",
43
+ ].join("\n");
44
+ return { content: [{ type: "text", text }] };
45
+ }
46
+ // completed
47
+ const text = [
48
+ `<!-- hve-squad MCP (${SQUAD_GUIDED_BANNER}). Produced server-side under the squad's gates. -->`,
49
+ "",
50
+ `## Result (${SQUAD_GUIDED_BANNER})`,
51
+ "",
52
+ result.artifact ?? "",
53
+ "",
54
+ ...routingLines(result),
55
+ "",
56
+ "## machine-readable",
57
+ "",
58
+ "```json",
59
+ JSON.stringify({
60
+ mode: "embedded",
61
+ outcome: "completed",
62
+ backendId: result.backendId,
63
+ runId: result.runId,
64
+ usage: result.usage,
65
+ }, null, 2),
66
+ "```",
67
+ ].join("\n");
68
+ return { content: [{ type: "text", text }] };
69
+ }
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Server-side routing engine (advisory stage planning).
3
+ *
4
+ * The dispatch loop shipped a FIXED order (Squad Researcher -> Squad Reviewer).
5
+ * This module replaces that hard-coded pair with a data-driven `route()` that
6
+ * turns a caller request into an ordered advisory stage plan, reading the
7
+ * deployed squad conventions READ-ONLY:
8
+ *
9
+ * * squad-src/.github/instructions/squad/squad-routing.instructions.md
10
+ * — the "Default Routing Rules" table (intent keyword -> role, autonomy
11
+ * tier, parallel-eligibility) used for classification and per-stage
12
+ * tier/parallel resolution.
13
+ * * squad-src/.github/instructions/squad/squad-roster.instructions.md
14
+ * — the "Cast Catalog" table (role KEY -> Primary Agent `name:`) used as
15
+ * the role -> agentName resolver. This is exactly the injectable map the
16
+ * Phase 1 persona loader helpers (`loadPersonaForRosterRole` /
17
+ * `resolvePersonaForRosterRole`) consume.
18
+ *
19
+ * The markdown-table parsing MIRRORS the read-only parser already used by
20
+ * `generators/build-manifests.ts` (fence-skipping table reader + keyword split),
21
+ * so the routing engine and the drift generator read these same files the same
22
+ * way — no new parser is invented.
23
+ *
24
+ * Advisory stage order (VF-08) — the explicit, documented order this router
25
+ * plans and Phase 3 will execute:
26
+ *
27
+ * research (`researcher`)
28
+ * -> plan (`lead`)
29
+ * -> council (`architect`, `security`, `cost-manager`, `product-owner`,
30
+ * +`rai` when the request touches the RAI domain)
31
+ * -> review (`tester`)
32
+ * -> backlog-handoff
33
+ *
34
+ * The linear pipeline stages returned in {@link RoutePlan.stages} are
35
+ * research -> plan -> review; the council is surfaced separately in
36
+ * {@link RoutePlan.council} (engaged only when the request crosses two or more
37
+ * council domains) so Phase 3 can interleave it between plan and review without
38
+ * this Phase re-planning. A single research-type request routes to the single
39
+ * `researcher` stage only.
40
+ *
41
+ * This module is PARSING + CLASSIFICATION only. It calls no model and wires no
42
+ * orchestrator or council dispatch (that is Phase 3); it only makes the stage
43
+ * list ROUTED and consumable by the dispatch loop.
44
+ */
45
+ import { readFileSync } from "node:fs";
46
+ import { join } from "node:path";
47
+ import { resolveSquadGithubRoot } from "../paths.js";
48
+ import { defaultProfileTables, INTAKE_VALIDATOR_ROLE, resolveProfile, } from "./profiles.js";
49
+ // ---------------------------------------------------------------------------
50
+ // Markdown table parsing lives in `markdown-table.ts` so the router, the profile
51
+ // resolver, and the drift generator all read these instruction files the same
52
+ // way — no parser is invented per consumer.
53
+ // ---------------------------------------------------------------------------
54
+ export { parseTables } from "./markdown-table.js";
55
+ import { parseTables } from "./markdown-table.js";
56
+ function splitKeywords(cell) {
57
+ return cell
58
+ .split(",")
59
+ .map((token) => token.trim().toLowerCase())
60
+ .filter((token) => token.length > 0);
61
+ }
62
+ function cleanAgentCell(cell) {
63
+ return (cell ?? "").replace(/`/g, "").trim();
64
+ }
65
+ /** Parse the "Default Routing Rules" table into intent rows. */
66
+ export function parseRoutingIntents(markdown) {
67
+ const table = parseTables(markdown).find((t) => (t.headers[0] ?? "").toLowerCase().includes("pattern"));
68
+ if (!table) {
69
+ throw new Error("Could not find the routing table (Pattern / Keyword) in squad-routing.instructions.md.");
70
+ }
71
+ const roleIdx = table.headers.findIndex((h) => h.toLowerCase().includes("role"));
72
+ const tierIdx = table.headers.findIndex((h) => h.toLowerCase().includes("tier"));
73
+ const parallelIdx = table.headers.findIndex((h) => h.toLowerCase().includes("parallel"));
74
+ return table.rows
75
+ .filter((row) => row.length > 0 && (row[0] ?? "").length > 0)
76
+ .map((row) => ({
77
+ patterns: splitKeywords(row[0]),
78
+ roles: roleIdx >= 0 ? splitKeywords(row[roleIdx]).map((r) => cleanAgentCell(r)) : [],
79
+ tier: (tierIdx >= 0 ? row[tierIdx] : "").trim().toLowerCase(),
80
+ parallelEligible: parallelIdx >= 0 && (row[parallelIdx] ?? "").trim().toLowerCase() === "yes",
81
+ }));
82
+ }
83
+ /**
84
+ * Parse the roster "Cast Catalog" table into a role KEY -> Primary Agent `name:`
85
+ * map. Thin-charter roles (Primary is `—`/`-`/empty) are skipped so the map only
86
+ * ever holds installable agents.
87
+ */
88
+ export function parseRosterMap(markdown) {
89
+ const table = parseTables(markdown).find((t) => t.headers.some((h) => h.toLowerCase().includes("primary agent")));
90
+ if (!table) {
91
+ throw new Error("Could not find the roster cast catalog (Primary Agent) in squad-roster.instructions.md.");
92
+ }
93
+ const roleIdx = table.headers.findIndex((h) => h.trim().toLowerCase() === "role");
94
+ const primaryIdx = table.headers.findIndex((h) => h.toLowerCase().includes("primary agent"));
95
+ const map = new Map();
96
+ for (const row of table.rows) {
97
+ const roleKey = cleanAgentCell(row[roleIdx >= 0 ? roleIdx : 0]).toLowerCase();
98
+ const primary = cleanAgentCell(row[primaryIdx]);
99
+ if (!roleKey || !primary || primary === "—" || primary === "-" || /thin charter/i.test(primary)) {
100
+ continue;
101
+ }
102
+ if (!map.has(roleKey)) {
103
+ map.set(roleKey, primary);
104
+ }
105
+ }
106
+ return map;
107
+ }
108
+ /** Load + parse the routing and roster instructions from disk (read-only). */
109
+ export function loadRoutingTables(githubRoot = resolveSquadGithubRoot()) {
110
+ if (!githubRoot) {
111
+ throw new Error("Could not resolve the squad .github root (squad-routing.instructions.md not found).");
112
+ }
113
+ const routingMd = readFileSync(join(githubRoot, "instructions", "squad", "squad-routing.instructions.md"), "utf8");
114
+ const rosterMd = readFileSync(join(githubRoot, "instructions", "squad", "squad-roster.instructions.md"), "utf8");
115
+ return {
116
+ intents: parseRoutingIntents(routingMd),
117
+ rosterMap: parseRosterMap(rosterMd),
118
+ };
119
+ }
120
+ /**
121
+ * Convenience: the role KEY -> Primary Agent `name:` resolver from the roster
122
+ * Cast Catalog. This is the injectable map consumed by the Phase 1 loader
123
+ * helpers `loadPersonaForRosterRole` / `resolvePersonaForRosterRole`.
124
+ */
125
+ export function loadRosterMap(githubRoot = resolveSquadGithubRoot()) {
126
+ return loadRoutingTables(githubRoot).rosterMap;
127
+ }
128
+ /** The advisory role KEYS, in the fixed advisory stage order (VF-08). */
129
+ const RESEARCH_ROLE = "researcher";
130
+ const PLAN_ROLE = "lead";
131
+ const REVIEW_ROLE = "tester";
132
+ /** Council member role KEYS (base four + optional `rai`). */
133
+ const COUNCIL_BASE_ROLES = ["architect", "security", "cost-manager", "product-owner"];
134
+ const RAI_ROLE = "rai";
135
+ /**
136
+ * Council DOMAINS and their trigger keywords. The router engages the council
137
+ * when a request crosses two or more of these domains (mirrors the routing
138
+ * council row + Implementation Gate domains: architecture, security, cost,
139
+ * product-fit, RAI).
140
+ */
141
+ const COUNCIL_DOMAINS = {
142
+ architecture: ["architecture", "architectural", "system design", "component", "design tradeoff"],
143
+ security: ["security", "secure", "threat", "vulnerability", "stride"],
144
+ cost: ["cost", "budget", "pricing", "finops", "spend"],
145
+ product: ["product", "requirement", "backlog", "prd", "brd", "user story", "roadmap", "epic"],
146
+ rai: ["responsible ai", "rai", "fairness", "harm", "bias"],
147
+ };
148
+ /** Keywords that identify the research intent (research-only detection). */
149
+ const RESEARCH_KEYWORDS = ["research", "investigate", "explore", "find out"];
150
+ /**
151
+ * Whole-word-ish keyword presence: matches at a word start so short keywords
152
+ * like `plan` match `plan`/`planning`/`plans` but not `explanation`.
153
+ */
154
+ function keywordPresent(haystack, keyword) {
155
+ const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
156
+ return new RegExp(`(^|[^a-z0-9])${escaped}`, "i").test(haystack);
157
+ }
158
+ /** Find the routing row that owns a canonical keyword (e.g. `research`, `plan`, `review`). */
159
+ function findIntentRow(tables, keyword) {
160
+ return tables.intents.find((row) => row.patterns.includes(keyword));
161
+ }
162
+ /** Resolve a role KEY to its Primary agent `name:`, falling back to the key when absent. */
163
+ function resolveAgent(tables, roleKey) {
164
+ return tables.rosterMap.get(roleKey) ?? roleKey;
165
+ }
166
+ /** Build one advisory stage from a role key and the routing row that owns `keyword`. */
167
+ function buildStage(tables, roleKey, keyword, fallbackTier, fallbackParallel) {
168
+ const row = findIntentRow(tables, keyword);
169
+ return {
170
+ role: roleKey,
171
+ agentName: resolveAgent(tables, roleKey),
172
+ tier: row?.tier || fallbackTier,
173
+ parallelEligible: row ? row.parallelEligible : fallbackParallel,
174
+ };
175
+ }
176
+ /** The council domains a request crosses. */
177
+ function crossedCouncilDomains(request) {
178
+ const lower = request.toLowerCase();
179
+ const domains = [];
180
+ for (const [domain, keywords] of Object.entries(COUNCIL_DOMAINS)) {
181
+ if (keywords.some((keyword) => keywordPresent(lower, keyword))) {
182
+ domains.push(domain);
183
+ }
184
+ }
185
+ return domains;
186
+ }
187
+ /**
188
+ * Compute an advisory {@link RoutePlan} from a request against already-parsed
189
+ * {@link RoutingTables}. This is the pure, injectable classifier (no disk I/O)
190
+ * behind {@link route}.
191
+ *
192
+ * Classification (deterministic, data-driven):
193
+ * * A request that triggers ONLY the research intent (and no other routing row,
194
+ * no council domain, no mode/full-profile override) routes to the single
195
+ * `researcher` stage.
196
+ * * Any other request is a full advisory request and routes to
197
+ * research -> plan -> review, with the council engaged when the request
198
+ * crosses two or more council domains.
199
+ */
200
+ export function computeRoutePlan(request, opts = {}, tables, profileTables) {
201
+ const lower = request.toLowerCase();
202
+ const profile = resolveProfile(opts.profile, profileTables ?? defaultProfileTables());
203
+ const researchMatched = RESEARCH_KEYWORDS.some((keyword) => keywordPresent(lower, keyword));
204
+ const councilDomains = crossedCouncilDomains(lower);
205
+ // Any NON-research routing row keyword present -> a broader (advisory) request.
206
+ const nonResearchRowMatched = tables.intents.some((row) => !row.patterns.includes("research") &&
207
+ row.patterns.some((pattern) => keywordPresent(lower, pattern)));
208
+ // A profile whose Implement stage fans out is never a single-stage run: the
209
+ // deliverables it seeds are the point of choosing it.
210
+ const advisoryOverride = Boolean(opts.mode) || profile.fansOut;
211
+ const otherMatched = nonResearchRowMatched || councilDomains.length > 0 || advisoryOverride;
212
+ // A role the profile did not seed cannot be dispatched this run.
213
+ const seeded = (stage) => profile.seeded.has(stage.role);
214
+ const intake = profile.hasIntakeGate
215
+ ? buildStage(tables, INTAKE_VALIDATOR_ROLE, "intake", "confirm", false)
216
+ : undefined;
217
+ const fanOut = profile.fansOut
218
+ ? profile.deliverableRoles.map((role) => buildStage(tables, role, role, "confirm", true))
219
+ : [];
220
+ const researchStage = buildStage(tables, RESEARCH_ROLE, "research", "auto", true);
221
+ // Research-only: a single research intent, nothing broader.
222
+ if (researchMatched && !otherMatched) {
223
+ return {
224
+ stages: [researchStage].filter(seeded),
225
+ council: { engaged: false, members: [], missingQuorum: [] },
226
+ profile: profile.name,
227
+ intake,
228
+ fanOut,
229
+ };
230
+ }
231
+ // Full advisory pipeline: research -> plan -> review (council interleaved by Phase 3).
232
+ const stages = [
233
+ researchStage,
234
+ buildStage(tables, PLAN_ROLE, "plan", "confirm", false),
235
+ buildStage(tables, REVIEW_ROLE, "review", "auto", true),
236
+ ].filter(seeded);
237
+ const councilCrossed = councilDomains.length >= 2;
238
+ const missingQuorum = councilCrossed
239
+ ? COUNCIL_BASE_ROLES.filter((role) => !profile.seeded.has(role))
240
+ : [];
241
+ const memberRoles = councilCrossed && missingQuorum.length === 0
242
+ ? [
243
+ ...COUNCIL_BASE_ROLES,
244
+ ...(councilDomains.includes(RAI_ROLE) && profile.seeded.has(RAI_ROLE) ? [RAI_ROLE] : []),
245
+ ]
246
+ : [];
247
+ const members = memberRoles.map((roleKey) => resolveAgent(tables, roleKey));
248
+ return {
249
+ stages,
250
+ council: { engaged: members.length > 0, members, missingQuorum: [...missingQuorum] },
251
+ profile: profile.name,
252
+ intake,
253
+ fanOut,
254
+ };
255
+ }
256
+ let cachedTables;
257
+ /** The default routing tables, parsed from disk once and cached. */
258
+ function defaultTables() {
259
+ if (!cachedTables) {
260
+ cachedTables = loadRoutingTables();
261
+ }
262
+ return cachedTables;
263
+ }
264
+ /**
265
+ * Route a request into an ordered advisory {@link RoutePlan}, reading the
266
+ * deployed routing + roster instructions from disk (parsed once, cached).
267
+ *
268
+ * Each returned stage's `agentName` is the roster Primary for the stage role and
269
+ * can be passed directly to the Phase 1 persona loader
270
+ * (`resolvePersonaForRole` / `loadPersonaForRole`) or, via the roster map from
271
+ * {@link loadRosterMap}, to `resolvePersonaForRosterRole`.
272
+ */
273
+ export function route(request, opts = {}) {
274
+ return computeRoutePlan(request, opts, defaultTables(), defaultProfileTables());
275
+ }
@@ -0,0 +1,70 @@
1
+ function optionalString(value) {
2
+ return typeof value === "string" && value.length > 0 ? value : undefined;
3
+ }
4
+ /**
5
+ * Serialize the non-request coordinator inputs, or `undefined` when there is
6
+ * nothing to persist (so a plain `squad_run` record is byte-identical to before).
7
+ */
8
+ export function encodeRunParams(request) {
9
+ const params = {};
10
+ if (request.profile)
11
+ params.profile = request.profile;
12
+ if (request.tier)
13
+ params.tier = request.tier;
14
+ if (request.owner)
15
+ params.owner = request.owner;
16
+ if (request.mode)
17
+ params.mode = request.mode;
18
+ if (request.squad)
19
+ params.squad = request.squad;
20
+ if (request.init === true)
21
+ params.init = true;
22
+ if (request.promote === true)
23
+ params.promote = true;
24
+ return Object.keys(params).length === 0 ? undefined : JSON.stringify(params);
25
+ }
26
+ /** Parse a persisted params blob. Never throws; unknown/invalid input yields `{}`. */
27
+ export function decodeRunParams(blob) {
28
+ if (!blob) {
29
+ return {};
30
+ }
31
+ let parsed;
32
+ try {
33
+ parsed = JSON.parse(blob);
34
+ }
35
+ catch {
36
+ return {};
37
+ }
38
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
39
+ return {};
40
+ }
41
+ const record = parsed;
42
+ return {
43
+ profile: optionalString(record.profile),
44
+ tier: optionalString(record.tier),
45
+ owner: optionalString(record.owner),
46
+ mode: optionalString(record.mode),
47
+ squad: optionalString(record.squad),
48
+ init: record.init === true,
49
+ promote: record.promote === true,
50
+ };
51
+ }
52
+ /**
53
+ * Rebuild the full {@link CoordinatorRequest} for a persisted run: the stored
54
+ * request/context plus every input recovered from {@link decodeRunParams}.
55
+ */
56
+ export function coordinatorRequestFromRun(run) {
57
+ const params = decodeRunParams(run.params);
58
+ return {
59
+ toolId: run.toolId,
60
+ request: run.request ?? "",
61
+ context: run.context,
62
+ profile: params.profile,
63
+ tier: params.tier,
64
+ owner: params.owner,
65
+ mode: params.mode,
66
+ squad: params.squad,
67
+ init: params.init,
68
+ promote: params.promote,
69
+ };
70
+ }