@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,200 @@
1
+ /**
2
+ * The STRUCTURED backlog contract — the business-user bridge between this
3
+ * advisory server (the brain) and the native, certified Azure DevOps / Jira
4
+ * connectors (the hands).
5
+ *
6
+ * Why this exists. The advisory pipeline already ends in a "backlog handoff"
7
+ * stage, but it emits PROSE. To create work items, a Copilot Studio agent must
8
+ * call the native connector once per item with typed fields — so with a prose
9
+ * artifact the orchestrator has to parse English, and that is the dominant
10
+ * failure mode for a non-technical user ("it created one giant work item", "it
11
+ * lost the acceptance criteria", "it invented a parent"). This module makes the
12
+ * hand-off MACHINE-READABLE: the model is asked for JSON, the server VALIDATES
13
+ * and NORMALIZES it, and the agent loops a flat, ready-to-write `workItems[]`.
14
+ *
15
+ * Trust boundary is unchanged (ADR-0001): this server still performs no ADO/Jira
16
+ * write. It produces the plan; the certified connector executes it on the end
17
+ * user's own connection, under that connector's own auth, DLP, and throttles.
18
+ *
19
+ * Robustness. Model output is untrusted text: it may be fenced, prefixed with
20
+ * commentary, or malformed. {@link parseBacklog} therefore extracts the JSON
21
+ * object defensively and validates every field, so the tool either returns a
22
+ * schema-valid contract or a clean, explicit failure — never half-parsed JSON.
23
+ */
24
+ /** Raised when model output cannot be turned into a valid contract. */
25
+ export class BacklogContractError extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = "BacklogContractError";
29
+ }
30
+ }
31
+ /** Hard caps so one call can never emit an unbounded backlog. */
32
+ const MAX_EPICS = 30;
33
+ const MAX_STORIES_PER_EPIC = 30;
34
+ const MAX_TASKS_PER_STORY = 30;
35
+ const MAX_CRITERIA = 20;
36
+ const MAX_TEXT = 4000;
37
+ function text(value, max = MAX_TEXT) {
38
+ if (typeof value !== "string") {
39
+ return "";
40
+ }
41
+ const trimmed = value.trim();
42
+ return trimmed.length > max ? trimmed.slice(0, max) : trimmed;
43
+ }
44
+ function criteria(value) {
45
+ if (!Array.isArray(value)) {
46
+ return [];
47
+ }
48
+ return value
49
+ .map((entry) => text(entry, 600))
50
+ .filter((entry) => entry.length > 0)
51
+ .slice(0, MAX_CRITERIA);
52
+ }
53
+ /**
54
+ * Extract the outermost JSON object from model output. Handles a bare object, a
55
+ * ```json fenced block, and an object preceded/followed by commentary — the three
56
+ * shapes a chat model actually produces. Returns `undefined` when no balanced
57
+ * object is present.
58
+ */
59
+ export function extractJsonObject(raw) {
60
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(raw);
61
+ const candidate = fenced ? fenced[1] : raw;
62
+ const start = candidate.indexOf("{");
63
+ if (start < 0) {
64
+ return undefined;
65
+ }
66
+ // Balance braces while ignoring braces inside strings, so a `{` in a title
67
+ // cannot truncate the object.
68
+ let depth = 0;
69
+ let inString = false;
70
+ let escaped = false;
71
+ for (let i = start; i < candidate.length; i += 1) {
72
+ const ch = candidate[i];
73
+ if (escaped) {
74
+ escaped = false;
75
+ continue;
76
+ }
77
+ if (ch === "\\") {
78
+ escaped = true;
79
+ continue;
80
+ }
81
+ if (ch === '"') {
82
+ inString = !inString;
83
+ continue;
84
+ }
85
+ if (inString) {
86
+ continue;
87
+ }
88
+ if (ch === "{") {
89
+ depth += 1;
90
+ }
91
+ else if (ch === "}") {
92
+ depth -= 1;
93
+ if (depth === 0) {
94
+ return candidate.slice(start, i + 1);
95
+ }
96
+ }
97
+ }
98
+ return undefined;
99
+ }
100
+ /** Depth-first flattening with stable refs, so parents always precede children. */
101
+ export function flattenBacklog(epics) {
102
+ const items = [];
103
+ epics.forEach((epic, epicIndex) => {
104
+ const epicRef = `E${epicIndex + 1}`;
105
+ items.push({
106
+ ref: epicRef,
107
+ type: "Epic",
108
+ title: epic.title,
109
+ description: epic.description,
110
+ acceptanceCriteria: epic.acceptanceCriteria,
111
+ });
112
+ epic.stories.forEach((story, storyIndex) => {
113
+ const storyRef = `${epicRef}-S${storyIndex + 1}`;
114
+ items.push({
115
+ ref: storyRef,
116
+ parentRef: epicRef,
117
+ type: "User Story",
118
+ title: story.title,
119
+ description: story.description,
120
+ acceptanceCriteria: story.acceptanceCriteria,
121
+ estimate: story.estimate,
122
+ });
123
+ story.tasks.forEach((task, taskIndex) => {
124
+ items.push({
125
+ ref: `${storyRef}-T${taskIndex + 1}`,
126
+ parentRef: storyRef,
127
+ type: "Task",
128
+ title: task.title,
129
+ description: task.description,
130
+ acceptanceCriteria: [],
131
+ });
132
+ });
133
+ });
134
+ });
135
+ return items;
136
+ }
137
+ /**
138
+ * Parse and validate model output into a {@link BacklogContract}.
139
+ *
140
+ * Throws {@link BacklogContractError} when no JSON object can be extracted, the
141
+ * JSON is malformed, or it contains no usable epic. Anything structurally present
142
+ * but individually invalid (an untitled story, a non-string criterion) is DROPPED
143
+ * rather than failing the whole call — a business user is better served by a
144
+ * slightly smaller correct backlog than by an error.
145
+ */
146
+ export function parseBacklog(raw) {
147
+ const json = extractJsonObject(raw);
148
+ if (!json) {
149
+ throw new BacklogContractError("The backlog stage did not return a JSON object.");
150
+ }
151
+ let parsed;
152
+ try {
153
+ parsed = JSON.parse(json);
154
+ }
155
+ catch {
156
+ throw new BacklogContractError("The backlog stage returned malformed JSON.");
157
+ }
158
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
159
+ throw new BacklogContractError("The backlog stage returned a non-object payload.");
160
+ }
161
+ const record = parsed;
162
+ const rawEpics = Array.isArray(record.epics) ? record.epics : [];
163
+ const epics = rawEpics
164
+ .slice(0, MAX_EPICS)
165
+ .map((rawEpic) => {
166
+ const epic = (rawEpic ?? {});
167
+ const rawStories = Array.isArray(epic.stories) ? epic.stories : [];
168
+ return {
169
+ title: text(epic.title, 400),
170
+ description: text(epic.description),
171
+ acceptanceCriteria: criteria(epic.acceptanceCriteria),
172
+ stories: rawStories
173
+ .slice(0, MAX_STORIES_PER_EPIC)
174
+ .map((rawStory) => {
175
+ const story = (rawStory ?? {});
176
+ const rawTasks = Array.isArray(story.tasks) ? story.tasks : [];
177
+ const estimate = text(story.estimate, 40);
178
+ return {
179
+ title: text(story.title, 400),
180
+ description: text(story.description),
181
+ acceptanceCriteria: criteria(story.acceptanceCriteria),
182
+ ...(estimate.length > 0 ? { estimate } : {}),
183
+ tasks: rawTasks
184
+ .slice(0, MAX_TASKS_PER_STORY)
185
+ .map((rawTask) => {
186
+ const task = (rawTask ?? {});
187
+ return { title: text(task.title, 400), description: text(task.description) };
188
+ })
189
+ .filter((task) => task.title.length > 0),
190
+ };
191
+ })
192
+ .filter((story) => story.title.length > 0),
193
+ };
194
+ })
195
+ .filter((epic) => epic.title.length > 0);
196
+ if (epics.length === 0) {
197
+ throw new BacklogContractError("The backlog stage returned no usable epics.");
198
+ }
199
+ return { summary: text(record.summary), epics, workItems: flattenBacklog(epics) };
200
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Business-user tool definitions (`squad_business_plan`, `squad_backlog`).
3
+ *
4
+ * These are the surfaces a NON-TECHNICAL user reaches from Copilot Studio or
5
+ * Teams. Everything else the server exposes is engineering-shaped
6
+ * (`squad_research`, `squad_architect`, …) and returns free-form markdown, which
7
+ * a business user cannot act on and an orchestrator cannot reliably map onto
8
+ * work-item writes.
9
+ *
10
+ * Both tools are ADVISORY and land no impactful action: each runs exactly ONE
11
+ * server-side dispatch against a REAL cast persona (resolved from the deployed
12
+ * `*.agent.md` bytes where present — the single-source invariant) and returns a
13
+ * finished artifact. The ADO/Jira WRITE is still performed by the certified
14
+ * native connector on the end user's own connection (ADR-0001).
15
+ *
16
+ * SEC-5 is preserved: each `charter` below becomes the `system` AUTHORITY
17
+ * unchanged, and the caller's request/context are composed separately as
18
+ * delimited DATA by `composeEmbeddedPrompt`. Nothing from the caller is ever
19
+ * concatenated into a charter.
20
+ */
21
+ import { SQUAD_BACKLOG_TOOL, SQUAD_BUSINESS_PLAN_TOOL } from "../auth/scopes.js";
22
+ /**
23
+ * Business-plan charter. Written for a reader with no engineering context: plain
24
+ * language, explicit assumptions, and a fixed section order so successive runs are
25
+ * comparable and the agent can quote a section back to the user.
26
+ */
27
+ export const BUSINESS_PLAN_CHARTER = [
28
+ "You are the **BRD Builder** working directly with a BUSINESS",
29
+ "stakeholder who is not technical. Turn the idea described in the untrusted data",
30
+ "into a clear, decision-ready business plan.",
31
+ "",
32
+ "This is a single advisory turn, not the guided BRD lifecycle: produce the plan",
33
+ "below in one pass and ask no interview questions.",
34
+ "",
35
+ "Write in plain language. No jargon, no framework names, no code. Where the input",
36
+ "is silent, state an explicit assumption rather than inventing a fact, and mark it",
37
+ "as an assumption the stakeholder must confirm.",
38
+ "",
39
+ "Produce EXACTLY these sections, in this order, as markdown headings:",
40
+ "1. `## Summary` — one short paragraph a sponsor could read aloud.",
41
+ "2. `## Problem and Customer` — who has the problem, how it hurts today.",
42
+ "3. `## Proposed Solution` — what we would offer, in outcome terms.",
43
+ "4. `## Value and Success Measures` — the business value and the specific,",
44
+ " measurable indicators that would prove it worked.",
45
+ "5. `## Scope` — what is in, and explicitly what is out of scope.",
46
+ "6. `## Go-to-Market` — who we reach, how, and the first proof point.",
47
+ "7. `## Cost and Effort Outline` — the shape of the investment (ranges and",
48
+ " drivers, not false precision); say plainly when you cannot estimate.",
49
+ "8. `## Risks and Dependencies` — each with a mitigation or an owner decision.",
50
+ "9. `## Milestones` — a short sequence with the decision point at each step.",
51
+ "10. `## Open Questions` — what the stakeholder must decide before work starts.",
52
+ ].join("\n");
53
+ /**
54
+ * Backlog charter. Constrains the model to emit ONLY the JSON object the server
55
+ * validates (`backlog-contract.ts`), because the agent's next step is one native
56
+ * connector call per work item — prose here would force the orchestrator to parse
57
+ * English, which is exactly the failure this tool removes.
58
+ */
59
+ export const BACKLOG_CHARTER = [
60
+ "You are the **Functional Planner**. Turn the request in the untrusted data into",
61
+ "a well-formed delivery backlog for a business stakeholder. Plan only: this turn",
62
+ "reaches no tracker and performs no read-only discovery call.",
63
+ "",
64
+ "Output rules (strict):",
65
+ "- Return ONE JSON object and NOTHING else. No prose before or after, no",
66
+ " markdown fences, no comments.",
67
+ "- Shape:",
68
+ " {",
69
+ ' "summary": "one plain-language paragraph for the stakeholder",',
70
+ ' "epics": [',
71
+ " {",
72
+ ' "title": "...",',
73
+ ' "description": "...",',
74
+ ' "acceptanceCriteria": ["...", "..."],',
75
+ ' "stories": [',
76
+ " {",
77
+ ' "title": "As a <role>, I want <capability>, so that <outcome>",',
78
+ ' "description": "...",',
79
+ ' "acceptanceCriteria": ["Given ... When ... Then ..."],',
80
+ ' "estimate": "S",',
81
+ ' "tasks": [{ "title": "...", "description": "..." }]',
82
+ " }",
83
+ " ]",
84
+ " }",
85
+ " ]",
86
+ " }",
87
+ "",
88
+ "Quality rules:",
89
+ "- Every story title uses the `As a … I want … so that …` form and describes a",
90
+ " user-visible OUTCOME, never an implementation step.",
91
+ "- Every story has at least one testable acceptance criterion in",
92
+ " `Given … When … Then …` form. Criteria are observable, not aspirational.",
93
+ "- Each story is independently valuable and small enough to finish in one",
94
+ " iteration; split it when it is not.",
95
+ "- Do not invent scope. When the request is under-specified, add a story titled",
96
+ " so the gap is obvious and put the missing decision in its description.",
97
+ "- `estimate` is a relative size (`XS`, `S`, `M`, `L`, `XL`) or omitted \u2014 never a",
98
+ " date and never a currency amount.",
99
+ ].join("\n");
100
+ /** The two business tool specifications, keyed by tool id. */
101
+ export const BUSINESS_TOOL_SPECS = {
102
+ [SQUAD_BUSINESS_PLAN_TOOL]: {
103
+ toolId: SQUAD_BUSINESS_PLAN_TOOL,
104
+ role: "BRD Builder",
105
+ charter: BUSINESS_PLAN_CHARTER,
106
+ structured: false,
107
+ },
108
+ [SQUAD_BACKLOG_TOOL]: {
109
+ toolId: SQUAD_BACKLOG_TOOL,
110
+ role: "Functional Planner",
111
+ charter: BACKLOG_CHARTER,
112
+ structured: true,
113
+ },
114
+ };
115
+ /** Resolve a business tool spec by id, or `undefined` when it is not one. */
116
+ export function businessToolSpec(toolId) {
117
+ return BUSINESS_TOOL_SPECS[toolId];
118
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The consumption ledger, from measured tokens rather than estimates.
3
+ *
4
+ * `squad-state.instructions.md` has the Scribe ESTIMATE cost, because a squad
5
+ * running under GitHub Copilot has no per-dispatch token telemetry — it can only
6
+ * model `internal_turns × average_context` and calibrate against a per-user
7
+ * aggregate after the fact. This server is in a better position: the model
8
+ * backend returns real input and output token counts for every dispatch, so the
9
+ * ledger reports what was actually consumed and marks its basis `measured`.
10
+ *
11
+ * The file REPLACES but its rows ACCUMULATE: each rewrite is derived from every
12
+ * consumption block recorded in `history/*.md` for the project, summed per role.
13
+ * Deriving it from the turn in hand would drop every earlier role while leaving
14
+ * its history entry intact — and the total would still look right, which is what
15
+ * makes that bug expensive to notice.
16
+ */
17
+ import { SQUAD_STATE_ROOT } from "./artifact-store.js";
18
+ import { CONSUMPTION_PATH } from "./squad-ledger.js";
19
+ /** One credit is one US cent under Copilot usage-based billing. */
20
+ const USD_PER_CREDIT = 0.01;
21
+ const BLOCK = /```json consumption\n([\s\S]*?)```/g;
22
+ /** Render the per-dispatch block appended to `history/<agent>.md`. */
23
+ export function renderConsumptionBlock(record) {
24
+ const payload = {
25
+ role: record.role,
26
+ model: record.model,
27
+ input_tokens: record.inputTokens,
28
+ output_tokens: record.outputTokens,
29
+ est_cost_usd: round(record.costUsd, 6),
30
+ est_credits: round(record.costUsd / USD_PER_CREDIT, 4),
31
+ basis: "measured",
32
+ };
33
+ return ["#### Consumption", "", "```json consumption", JSON.stringify(payload, null, 2), "```"].join("\n");
34
+ }
35
+ /** Recover every consumption block from a history file. */
36
+ export function parseConsumptionBlocks(markdown) {
37
+ const records = [];
38
+ for (const match of markdown.matchAll(BLOCK)) {
39
+ try {
40
+ const parsed = JSON.parse(match[1]);
41
+ records.push({
42
+ role: String(parsed.role ?? "unknown"),
43
+ agentName: String(parsed.agent ?? ""),
44
+ model: String(parsed.model ?? "unknown"),
45
+ inputTokens: Number(parsed.input_tokens ?? 0),
46
+ outputTokens: Number(parsed.output_tokens ?? 0),
47
+ costUsd: Number(parsed.est_cost_usd ?? 0),
48
+ });
49
+ }
50
+ catch {
51
+ // A hand-edited or truncated block contributes nothing rather than
52
+ // poisoning the totals with NaN.
53
+ }
54
+ }
55
+ return records;
56
+ }
57
+ /** Sum per role, preserving first-seen order so the ledger mirrors the roster. */
58
+ export function summarize(records) {
59
+ const byRole = new Map();
60
+ for (const record of records) {
61
+ const total = byRole.get(record.role) ??
62
+ {
63
+ role: record.role,
64
+ models: new Set(),
65
+ dispatches: 0,
66
+ inputTokens: 0,
67
+ outputTokens: 0,
68
+ costUsd: 0,
69
+ };
70
+ total.models.add(record.model);
71
+ total.dispatches += 1;
72
+ total.inputTokens += record.inputTokens;
73
+ total.outputTokens += record.outputTokens;
74
+ total.costUsd += record.costUsd;
75
+ byRole.set(record.role, total);
76
+ }
77
+ return [...byRole.values()];
78
+ }
79
+ /** Render the two role-aligned tables the roster asks for. */
80
+ export function renderConsumptionMarkdown(totals) {
81
+ const costTotal = totals.reduce((sum, t) => sum + t.costUsd, 0);
82
+ const lines = [
83
+ "# Consumption",
84
+ "",
85
+ "Derived from every `#### Consumption` block recorded in `history/*.md` for this",
86
+ "project. Token counts are **measured** by the model backend rather than estimated,",
87
+ "so no calibration factor is applied. Costs are the backend's realized figures and",
88
+ "remain estimates of billing, not an invoice.",
89
+ "",
90
+ "## Attribution",
91
+ "",
92
+ "| Role | Model(s) | Dispatches |",
93
+ "|------|----------|------------|",
94
+ ...totals.map((t) => `| ${t.role} | ${[...t.models].sort().join(", ")} | ${t.dispatches} |`),
95
+ "",
96
+ "## Usage & Cost",
97
+ "",
98
+ "| Role | Input tokens | Output tokens | Cost (USD) | Credits |",
99
+ "|------|--------------|---------------|------------|---------|",
100
+ ...totals.map((t) => `| ${t.role} | ${t.inputTokens} | ${t.outputTokens} | ${round(t.costUsd, 4)} | ` +
101
+ `${round(t.costUsd / USD_PER_CREDIT, 2)} |`),
102
+ `| **total** | ${totals.reduce((s, t) => s + t.inputTokens, 0)} | ` +
103
+ `${totals.reduce((s, t) => s + t.outputTokens, 0)} | ${round(costTotal, 4)} | ` +
104
+ `${round(costTotal / USD_PER_CREDIT, 2)} |`,
105
+ "",
106
+ ];
107
+ return lines.join("\n");
108
+ }
109
+ function round(value, places) {
110
+ const factor = 10 ** places;
111
+ return Math.round(value * factor) / factor;
112
+ }
113
+ /**
114
+ * Rebuild `consumption.md` from the project's recorded history.
115
+ *
116
+ * Reads every history file rather than accepting a caller-supplied total, so the
117
+ * ledger cannot disagree with the per-dispatch record it claims to summarize.
118
+ */
119
+ export async function rebuildConsumption(store, tenantId, project) {
120
+ const entries = await store.list(tenantId, project, `${SQUAD_STATE_ROOT}/history`);
121
+ const records = [];
122
+ for (const entry of entries) {
123
+ if (entry.path.includes("autopilot-run-")) {
124
+ continue; // The run summary references dispatches; it does not record them.
125
+ }
126
+ const file = await store.get(tenantId, project, entry.path);
127
+ if (file) {
128
+ records.push(...parseConsumptionBlocks(file.content));
129
+ }
130
+ }
131
+ const totals = summarize(records);
132
+ await store.put(tenantId, project, CONSUMPTION_PATH, renderConsumptionMarkdown(totals));
133
+ return totals;
134
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Pre-implementation council stage with most-restrictive-wins synthesis.
3
+ *
4
+ * This module dispatches each council member's persona charter over the plan
5
+ * artifact and synthesizes ONE durable `## Council Verdict` from the members'
6
+ * findings, following the advisory subset of
7
+ * `squad-src/.github/instructions/squad/squad-council.instructions.md`:
8
+ *
9
+ * * Each member is dispatched against the SAME scoped input (the plan
10
+ * artifact), never threaded member-to-member — the council is a parallel
11
+ * go/no-go over one proposal, not a pipeline.
12
+ * * The verdict is synthesized MOST-RESTRICTIVE-WINS: any `Stop` (or a member
13
+ * `Block` / `Risk: High`) drives the verdict to `Stop`; else any
14
+ * `Go-With-Conditions` (a member `Conditional` or one that raised explicit
15
+ * conditions) drives it to `Go-With-Conditions` with the conditions
16
+ * aggregated and role-attributed; else `Go`.
17
+ * * A `Stop` verdict halts the advisory pipeline — there is no implement stage
18
+ * to gate in the advisory (v1) scope, so the compiled artifact simply ends
19
+ * with the verdict.
20
+ *
21
+ * SEC-5 is preserved by construction: every member's `system` is that member's
22
+ * persona charter ONLY (AUTHORITY); the caller request/context and the plan
23
+ * artifact are carried as delimited DATA via `composeEmbeddedPrompt`.
24
+ */
25
+ import { composeEmbeddedPrompt } from "./embedded-prompt.js";
26
+ import { resolvePersonaForRole } from "./embedded-roles.js";
27
+ // ---------------------------------------------------------------------------
28
+ // Member-finding parsing.
29
+ // ---------------------------------------------------------------------------
30
+ /**
31
+ * Extract the conditions a member raised. Supports both an inline
32
+ * `Conditions: <text>` label and a `Conditions:` section header followed by a
33
+ * bullet list. A literal `none` is treated as no condition.
34
+ */
35
+ function extractConditions(text) {
36
+ const lines = text.split(/\r?\n/);
37
+ const conditions = [];
38
+ let inSection = false;
39
+ for (const raw of lines) {
40
+ const line = raw.trim();
41
+ const header = /^#{0,6}\s*conditions?\b\s*:?\s*(.*)$/i.exec(line);
42
+ if (header) {
43
+ inSection = true;
44
+ const inline = header[1].trim().replace(/^[-*]\s*/, "");
45
+ if (inline.length > 0 && !/^none\b/i.test(inline)) {
46
+ conditions.push(inline);
47
+ }
48
+ continue;
49
+ }
50
+ if (inSection) {
51
+ const bullet = /^[-*]\s+(.*)$/.exec(line);
52
+ if (bullet) {
53
+ const value = bullet[1].trim();
54
+ if (value.length > 0 && !/^none\b/i.test(value)) {
55
+ conditions.push(value);
56
+ }
57
+ continue;
58
+ }
59
+ // A blank line or a new header/label ends the conditions section.
60
+ if (line.length === 0 || /^#{1,6}\s/.test(line) || /\w:\s*$/.test(line)) {
61
+ inSection = false;
62
+ }
63
+ }
64
+ }
65
+ return conditions;
66
+ }
67
+ /**
68
+ * Parse a single member's finding text into a verdict class + conditions. The
69
+ * member level itself applies most-restrictive-wins: a `Block` / `Risk: High` /
70
+ * `Stop` marker yields `Stop`; a `Conditional` / `Go-With-Conditions` marker or
71
+ * any raised condition yields `Go-With-Conditions`; otherwise `Go`.
72
+ *
73
+ * Accepts BOTH the council-member label vocabulary (`Approve` / `Conditional` /
74
+ * `Concern` / `Block` with `Risk: Low|Medium|High`) and the direct verdict-class
75
+ * vocabulary (`Go` / `Go-With-Conditions` / `Stop`), so a persona finding in
76
+ * either form is classified consistently.
77
+ */
78
+ export function parseMemberVerdict(text) {
79
+ const conditions = extractConditions(text);
80
+ // Stop-drivers win first (Risk: High blocks even under a softer own-label).
81
+ if (/\brisk:\s*high\b/i.test(text) || /\bblock\b/i.test(text) || /(^|[^a-z])stop\b/i.test(text)) {
82
+ return { verdict: "Stop", conditions };
83
+ }
84
+ if (/go[-\s]with[-\s]conditions/i.test(text) ||
85
+ /\bconditional\b/i.test(text) ||
86
+ conditions.length > 0) {
87
+ return { verdict: "Go-With-Conditions", conditions };
88
+ }
89
+ return { verdict: "Go", conditions: [] };
90
+ }
91
+ // ---------------------------------------------------------------------------
92
+ // Synthesis + rendering.
93
+ // ---------------------------------------------------------------------------
94
+ /** Aggregate + de-duplicate member conditions with inline role attribution. */
95
+ function aggregateConditions(opinions) {
96
+ const seen = new Set();
97
+ const out = [];
98
+ for (const opinion of opinions) {
99
+ for (const condition of opinion.conditions) {
100
+ const attributed = `(${opinion.agentName}) ${condition}`;
101
+ const key = attributed.toLowerCase();
102
+ if (!seen.has(key)) {
103
+ seen.add(key);
104
+ out.push(attributed);
105
+ }
106
+ }
107
+ }
108
+ return out;
109
+ }
110
+ /**
111
+ * Synthesize the single council verdict from member opinions by
112
+ * most-restrictive-wins. Conditions are aggregated for a `Go-With-Conditions`
113
+ * (and carried on a `Stop` for the audit trail); a `Go` carries none.
114
+ */
115
+ export function synthesizeVerdict(opinions) {
116
+ const conditions = aggregateConditions(opinions);
117
+ if (opinions.some((opinion) => opinion.verdict === "Stop")) {
118
+ return { verdict: "Stop", conditions };
119
+ }
120
+ if (opinions.some((opinion) => opinion.verdict === "Go-With-Conditions")) {
121
+ return { verdict: "Go-With-Conditions", conditions };
122
+ }
123
+ return { verdict: "Go", conditions: [] };
124
+ }
125
+ /** Render the `## Council Verdict` markdown section (advisory subset of the schema). */
126
+ function renderVerdict(verdict, conditions, opinions) {
127
+ const lines = ["## Council Verdict", ""];
128
+ lines.push(`* Verdict: ${verdict}`);
129
+ lines.push(`* Council Members Dispatched: ${opinions.map((o) => o.agentName).join(", ")}`);
130
+ lines.push("", "### Findings by Member", "");
131
+ lines.push("| Member | Verdict | Conditions |");
132
+ lines.push("| --- | --- | --- |");
133
+ for (const opinion of opinions) {
134
+ const conds = opinion.conditions.length > 0 ? opinion.conditions.join("; ") : "none";
135
+ lines.push(`| ${opinion.agentName} | ${opinion.verdict} | ${conds} |`);
136
+ }
137
+ lines.push("", "### Conditions", "");
138
+ if (conditions.length > 0) {
139
+ for (const condition of conditions) {
140
+ lines.push(`- ${condition}`);
141
+ }
142
+ }
143
+ else {
144
+ lines.push("- none");
145
+ }
146
+ lines.push("", "### Implementation Gate", "");
147
+ lines.push(`* Permits Implementation Dispatch: ${verdict === "Stop" ? "no (Stop)" : `yes (${verdict})`}`);
148
+ return lines.join("\n");
149
+ }
150
+ // ---------------------------------------------------------------------------
151
+ // Member resolution + dispatch.
152
+ // ---------------------------------------------------------------------------
153
+ /**
154
+ * Resolve a routed {@link RoutePlan}'s council member `agentName`s into ordered
155
+ * {@link PersonaRecord}s via the Phase 1 loader (`resolvePersonaForRole`, real
156
+ * `*.agent.md` bytes first, hero paraphrase fallback only for the two
157
+ * deterministic hero agents). Members whose persona cannot be resolved are
158
+ * dropped (never a silent wrong persona) — mirrors `resolveRoutedStages`.
159
+ */
160
+ export function resolveCouncilMembers(plan, roots) {
161
+ const members = [];
162
+ for (const agentName of plan.council.members) {
163
+ const persona = resolvePersonaForRole(agentName, roots);
164
+ if (persona) {
165
+ members.push(persona);
166
+ }
167
+ }
168
+ return members;
169
+ }
170
+ /**
171
+ * Dispatch the council members over the plan artifact and synthesize the
172
+ * verdict. Each member is dispatched independently against the SAME plan
173
+ * artifact (parallel go/no-go, not a pipeline); the plan artifact and the caller
174
+ * request/context are DATA, the member charter is the only AUTHORITY (SEC-5).
175
+ * Returns the structured verdict plus the rendered `## Council Verdict` block.
176
+ */
177
+ export async function runCouncil(members, planArtifact, request, deps) {
178
+ const opinions = await Promise.all(members.map(async (member) => {
179
+ // SEC-5 — member charter is the ONLY authority; plan + caller input are DATA.
180
+ const prompt = composeEmbeddedPrompt({
181
+ systemAuthority: member.charter,
182
+ request: request.request,
183
+ context: request.context,
184
+ priorArtifact: planArtifact,
185
+ });
186
+ const completion = await deps.backend.complete({
187
+ system: prompt.system,
188
+ messages: prompt.messages,
189
+ });
190
+ const parsed = parseMemberVerdict(completion.text);
191
+ return {
192
+ agentName: member.role,
193
+ verdict: parsed.verdict,
194
+ conditions: parsed.conditions,
195
+ text: completion.text,
196
+ backendId: completion.backendId,
197
+ usage: completion.usage,
198
+ };
199
+ }));
200
+ const synth = synthesizeVerdict(opinions);
201
+ const usage = opinions.map((o) => o.usage).filter((u) => Boolean(u));
202
+ const markdown = renderVerdict(synth.verdict, synth.conditions, opinions);
203
+ return { verdict: synth.verdict, conditions: synth.conditions, members: opinions, usage, markdown };
204
+ }