@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,367 @@
1
+ /**
2
+ * Mode-aware ADVISORY pipeline orchestrator.
3
+ *
4
+ * The dispatch loop runs an ordered list of persona completions; the router
5
+ * turns a request into a routed stage plan. This orchestrator composes the two
6
+ * into the full ADVISORY sequence and runs it as sequential model completions:
7
+ *
8
+ * research (`researcher`)
9
+ * -> plan (`lead`)
10
+ * -> council (`architect`, `security`, `cost-manager`, `product-owner`,
11
+ * +`rai`) — interleaved between plan and review when engaged
12
+ * -> review (`tester`)
13
+ * -> backlog-handoff (`product-owner`)
14
+ *
15
+ * It performs NO code execution and NO impactful action — those are the deferred
16
+ * execution expansion. The advisory scope produces finished TEXT artifacts only,
17
+ * so the only human gate is the existing final hold applied to the compiled
18
+ * artifact before it is returned (modeled here by an injectable
19
+ * {@link AdvisoryFinalHold}; in a deployed run this is the existing
20
+ * `GateKeeper`/approval machinery, unchanged).
21
+ *
22
+ * Mode handling:
23
+ * * default / `interactive` — returns after EACH stage with a resume token so
24
+ * the caller advances stage-by-stage (a turn per stage).
25
+ * * `autopilot` / `autonomous` — advance stage-to-stage without pausing to a
26
+ * single compiled artifact (advisory work has no impactful action, so there
27
+ * is no per-stage human gate).
28
+ *
29
+ * SEC-5 is preserved by construction: every stage's `system` is the resolved
30
+ * persona charter ONLY (AUTHORITY); the caller request/context and every prior
31
+ * artifact (including the council verdict) are carried as delimited DATA via
32
+ * `composeEmbeddedPrompt` / the council dispatch.
33
+ *
34
+ * A per-run cost ceiling ({@link AdvisoryPipelineDeps.costLedger}) is checked
35
+ * BEFORE each stage; exceeding it halts the run with a clear reason and zero
36
+ * further model calls.
37
+ */
38
+ import { composeEmbeddedPrompt } from "./embedded-prompt.js";
39
+ import { resolvePersonaForRole, resolvePersonaForRosterRole } from "./embedded-roles.js";
40
+ import { runCouncil, resolveCouncilMembers } from "./council.js";
41
+ import { loadRosterMap, route } from "./routing.js";
42
+ /** The roster role KEY the backlog-handoff stage resolves to. */
43
+ const BACKLOG_ROLE_KEY = "product-owner";
44
+ /** Normalize a raw `mode` string into an {@link AdvisoryMode} (default interactive). */
45
+ export function normalizeAdvisoryMode(mode) {
46
+ const m = (mode ?? "").trim().toLowerCase();
47
+ if (m === "autopilot") {
48
+ return "autopilot";
49
+ }
50
+ if (m === "autonomous") {
51
+ return "autonomous";
52
+ }
53
+ return "interactive";
54
+ }
55
+ /**
56
+ * Recompile the artifact from persisted stages (Phase 4). Each persisted stage's
57
+ * `artifact` is the fully-rendered section, so recompilation is the same join the
58
+ * in-process {@link compileArtifact} performs — a status poll and the live run
59
+ * therefore yield the identical compiled artifact.
60
+ */
61
+ export function compilePersistedStages(stages) {
62
+ return stages.map((stage) => stage.artifact).join("\n\n");
63
+ }
64
+ function personaStage(persona, backlog = false) {
65
+ return { kind: "persona", role: persona.role, persona, backlog };
66
+ }
67
+ /** Load the roster map, tolerating an absent deployed cast (returns undefined). */
68
+ function safeRosterMap(rosterMap) {
69
+ if (rosterMap) {
70
+ return rosterMap;
71
+ }
72
+ try {
73
+ return loadRosterMap();
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ }
79
+ /** Resolve the backlog-handoff persona (`product-owner` roster role). */
80
+ function resolveBacklogPersona(roots, rosterMap) {
81
+ const map = safeRosterMap(rosterMap);
82
+ if (!map) {
83
+ return undefined;
84
+ }
85
+ return resolvePersonaForRosterRole(BACKLOG_ROLE_KEY, map, roots);
86
+ }
87
+ /**
88
+ * Resolve a routed {@link RoutePlan} into the ordered advisory execution plan:
89
+ * [intake] -> research -> plan -> [council] -> [deliverable fan-out] -> review
90
+ * -> backlog-handoff.
91
+ *
92
+ * The intake gate is prepended only for a profile that seeds `intake-validator`
93
+ * (`product`, `full`); the council is interleaved between plan and review only
94
+ * when engaged; the fan-out replaces the single Implement stage for a profile
95
+ * carrying two or more deliverable-producing roles. A research-only route stays
96
+ * a single research stage. Stages whose persona cannot be resolved are dropped
97
+ * (never a silent wrong persona).
98
+ */
99
+ export function planAdvisoryStages(plan, roots, rosterMap) {
100
+ const ordered = [];
101
+ // The readiness gate runs BEFORE any downstream role is dispatched.
102
+ if (plan.intake) {
103
+ const intakePersona = resolvePersonaForRole(plan.intake.agentName, roots);
104
+ if (intakePersona) {
105
+ ordered.push({
106
+ ...personaStage(intakePersona),
107
+ intake: true,
108
+ roleKey: plan.intake.role,
109
+ });
110
+ }
111
+ }
112
+ // Research-only route: a single research stage, no council, no backlog.
113
+ if (plan.stages.length <= 1) {
114
+ const first = plan.stages[0];
115
+ const persona = first ? resolvePersonaForRole(first.agentName, roots) : undefined;
116
+ if (persona) {
117
+ ordered.push({ ...personaStage(persona), roleKey: first.role });
118
+ }
119
+ return ordered;
120
+ }
121
+ // Full advisory route: research -> plan -> [council] -> [fan-out] -> review -> backlog.
122
+ const [research, planStage, review] = plan.stages;
123
+ const researchPersona = resolvePersonaForRole(research.agentName, roots);
124
+ if (researchPersona) {
125
+ ordered.push({ ...personaStage(researchPersona), roleKey: research.role });
126
+ }
127
+ const planPersona = resolvePersonaForRole(planStage.agentName, roots);
128
+ if (planPersona) {
129
+ ordered.push({ ...personaStage(planPersona), roleKey: planStage.role });
130
+ }
131
+ if (plan.council.engaged) {
132
+ const members = resolveCouncilMembers(plan, roots);
133
+ if (members.length > 0) {
134
+ ordered.push({ kind: "council", role: "Council Verdict", members });
135
+ }
136
+ }
137
+ // Deliverable fan-out: the profile's specialists each own a distinct artifact.
138
+ const fannedOutRoles = new Set();
139
+ for (const stage of plan.fanOut) {
140
+ const persona = resolvePersonaForRole(stage.agentName, roots);
141
+ if (persona) {
142
+ ordered.push({ ...personaStage(persona), roleKey: stage.role });
143
+ fannedOutRoles.add(stage.role);
144
+ }
145
+ }
146
+ const reviewPersona = resolvePersonaForRole(review.agentName, roots);
147
+ if (reviewPersona) {
148
+ ordered.push({ ...personaStage(reviewPersona), roleKey: review.role });
149
+ }
150
+ // The fan-out already dispatched product-owner; a second pass would duplicate it.
151
+ if (!fannedOutRoles.has(BACKLOG_ROLE_KEY)) {
152
+ const backlogPersona = resolveBacklogPersona(roots, rosterMap);
153
+ if (backlogPersona) {
154
+ ordered.push({ ...personaStage(backlogPersona, true), roleKey: BACKLOG_ROLE_KEY });
155
+ }
156
+ }
157
+ return ordered;
158
+ }
159
+ /** Compile the accumulated stage sections into one artifact. */
160
+ function compileArtifact(stages) {
161
+ return stages.map((stage) => stage.section).join("\n\n");
162
+ }
163
+ /**
164
+ * Read the intake validator's verdict out of its completion.
165
+ *
166
+ * `squad-intake-gate.instructions.md` fixes the line as `Verdict: <value>`, so
167
+ * this looks for exactly that rather than pattern-matching prose. An unreadable
168
+ * verdict is treated as `Ready-With-Gaps`: a malformed line is a reporting fault,
169
+ * and halting a run on it would make the gate less reliable than no gate, while
170
+ * silently reading it as `Ready` would defeat the check.
171
+ */
172
+ export function intakeVerdictOf(text) {
173
+ const raw = text.match(/^\s*[*-]?\s*verdict\s*:\s*(ready-with-gaps|not-ready|ready)\b/im)?.[1];
174
+ switch (raw?.toLowerCase()) {
175
+ case "not-ready":
176
+ return "Not-Ready";
177
+ case "ready":
178
+ return "Ready";
179
+ default:
180
+ return "Ready-With-Gaps";
181
+ }
182
+ }
183
+ /** Collect the per-stage usage list from accumulated results. */
184
+ function collectUsage(stages) {
185
+ return stages.map((stage) => stage.usage).filter((u) => Boolean(u));
186
+ }
187
+ /**
188
+ * Run (or resume) the ordered advisory pipeline. When no `plan`/`resume` is
189
+ * injected the request is routed (`route`) and resolved (`planAdvisoryStages`)
190
+ * from the deployed cast. Returns the compiled artifact plus the terminal or
191
+ * resumable outcome.
192
+ */
193
+ export async function runAdvisoryPipeline(request, deps, opts = {}) {
194
+ const mode = normalizeAdvisoryMode(opts.mode ?? request.mode);
195
+ // Resolve (or resume) the ordered plan.
196
+ let orderedPlan;
197
+ const stages = [];
198
+ let priorArtifact;
199
+ let councilVerdict;
200
+ let startIndex = 0;
201
+ if (opts.resume) {
202
+ orderedPlan = opts.resume.plan;
203
+ stages.push(...opts.resume.stages);
204
+ priorArtifact = opts.resume.priorArtifact;
205
+ councilVerdict = opts.resume.councilVerdict;
206
+ startIndex = opts.resume.nextIndex;
207
+ }
208
+ else if (opts.plan) {
209
+ orderedPlan = opts.plan;
210
+ }
211
+ else {
212
+ const routePlan = route(request.request, {
213
+ profile: request.profile,
214
+ mode: request.mode,
215
+ tier: request.tier,
216
+ owner: request.owner,
217
+ });
218
+ orderedPlan = planAdvisoryStages(routePlan, opts.roots, opts.rosterMap);
219
+ }
220
+ const councilDeps = { backend: deps.backend };
221
+ for (let i = startIndex; i < orderedPlan.length; i += 1) {
222
+ // COST-2 (run scope) — check BEFORE the stage; halt with 0 further calls.
223
+ const check = deps.costLedger?.check();
224
+ if (check && !check.ok) {
225
+ return {
226
+ outcome: "halted",
227
+ artifact: compileArtifact(stages),
228
+ stages,
229
+ councilVerdict,
230
+ usage: collectUsage(stages),
231
+ costUsd: check.spentUsd,
232
+ reason: check.reason,
233
+ };
234
+ }
235
+ const stage = orderedPlan[i];
236
+ if (stage.kind === "council" && stage.members) {
237
+ const verdict = await runCouncil(stage.members, priorArtifact ?? "", request, councilDeps);
238
+ councilVerdict = verdict;
239
+ for (const usage of verdict.usage) {
240
+ deps.costLedger?.record(usage.estimatedCostUsd);
241
+ }
242
+ const result = {
243
+ kind: "council",
244
+ role: "Council Verdict",
245
+ section: verdict.markdown,
246
+ text: verdict.markdown,
247
+ usage: verdict.usage.at(-1),
248
+ };
249
+ stages.push(result);
250
+ priorArtifact = verdict.markdown;
251
+ // Phase 4 — persist the verdict section + structured verdict as the run
252
+ // advances (durable/async run only; a no-op in the in-process case).
253
+ await deps.persistence?.recordStage({ role: "Council Verdict", artifact: verdict.markdown });
254
+ await deps.persistence?.recordVerdict({
255
+ class: verdict.verdict,
256
+ conditions: verdict.conditions,
257
+ rendered: verdict.markdown,
258
+ });
259
+ await deps.ledger?.recordDecision(verdict.markdown);
260
+ // A Stop verdict halts the advisory pipeline (no implement stage to gate).
261
+ if (verdict.verdict === "Stop") {
262
+ return {
263
+ outcome: "halted",
264
+ artifact: compileArtifact(stages),
265
+ stages,
266
+ councilVerdict,
267
+ usage: collectUsage(stages),
268
+ costUsd: deps.costLedger?.spentUsd() ?? 0,
269
+ reason: "council_stop",
270
+ };
271
+ }
272
+ }
273
+ else if (stage.persona) {
274
+ // SEC-5 — persona charter is the ONLY authority; caller input + prior artifact are DATA.
275
+ const prompt = composeEmbeddedPrompt({
276
+ systemAuthority: stage.persona.charter,
277
+ request: request.request,
278
+ context: request.context,
279
+ priorArtifact,
280
+ });
281
+ const completion = await deps.backend.complete({
282
+ system: prompt.system,
283
+ messages: prompt.messages,
284
+ });
285
+ deps.costLedger?.record(completion.usage?.estimatedCostUsd);
286
+ const result = {
287
+ kind: "persona",
288
+ role: stage.role,
289
+ section: `## ${stage.role}\n\n${completion.text}`,
290
+ text: completion.text,
291
+ backendId: completion.backendId,
292
+ usage: completion.usage,
293
+ };
294
+ stages.push(result);
295
+ priorArtifact = completion.text;
296
+ // Phase 4 — persist the completed stage section (durable/async run only).
297
+ await deps.persistence?.recordStage({ role: stage.role, artifact: result.section });
298
+ // The ledger stores the WORK: this stage's deliverable under its roster
299
+ // root, plus the per-agent and per-run history entries.
300
+ await deps.ledger?.recordStage({
301
+ roleKey: stage.roleKey,
302
+ agentName: stage.role,
303
+ artifact: completion.text,
304
+ usage: completion.usage,
305
+ backendId: completion.backendId,
306
+ });
307
+ // The intake gate is a PRE-work readiness check: a Not-Ready verdict must
308
+ // stop the run rather than let downstream roles build on inputs the
309
+ // validator just judged unusable (`squad-intake-gate.instructions.md`).
310
+ if (stage.intake) {
311
+ const verdict = intakeVerdictOf(completion.text);
312
+ await deps.ledger?.recordDecision(`## Intake Readiness Verdict\n\n* Validator: ${stage.role}\n* Verdict: ${verdict}`);
313
+ if (verdict === "Not-Ready") {
314
+ return {
315
+ outcome: "halted",
316
+ artifact: compileArtifact(stages),
317
+ stages,
318
+ councilVerdict,
319
+ usage: collectUsage(stages),
320
+ costUsd: deps.costLedger?.spentUsd() ?? 0,
321
+ reason: "intake_not_ready",
322
+ };
323
+ }
324
+ }
325
+ }
326
+ // Interactive mode returns after each stage with a resume token.
327
+ if (mode === "interactive" && i < orderedPlan.length - 1) {
328
+ return {
329
+ outcome: "paused",
330
+ artifact: compileArtifact(stages),
331
+ stages,
332
+ councilVerdict,
333
+ usage: collectUsage(stages),
334
+ costUsd: deps.costLedger?.spentUsd() ?? 0,
335
+ resume: {
336
+ plan: orderedPlan,
337
+ stages: [...stages],
338
+ priorArtifact,
339
+ councilVerdict,
340
+ nextIndex: i + 1,
341
+ },
342
+ };
343
+ }
344
+ }
345
+ const artifact = compileArtifact(stages);
346
+ // The only advisory human gate: the existing final hold on the compiled artifact.
347
+ if (deps.finalHold && (await deps.finalHold.shouldHold(artifact))) {
348
+ return {
349
+ outcome: "held",
350
+ artifact,
351
+ stages,
352
+ councilVerdict,
353
+ usage: collectUsage(stages),
354
+ costUsd: deps.costLedger?.spentUsd() ?? 0,
355
+ reason: deps.finalHold.reason ?? "final_hold",
356
+ approvalRequest: deps.finalHold.approvalRequest,
357
+ };
358
+ }
359
+ return {
360
+ outcome: "completed",
361
+ artifact,
362
+ stages,
363
+ councilVerdict,
364
+ usage: collectUsage(stages),
365
+ costUsd: deps.costLedger?.spentUsd() ?? 0,
366
+ };
367
+ }
@@ -0,0 +1,31 @@
1
+ export class StoreAdvisoryPersistence {
2
+ store;
3
+ runId;
4
+ clock;
5
+ constructor(store, runId,
6
+ /** Clock injection for deterministic history timestamps in tests. */
7
+ clock = Date.now) {
8
+ this.store = store;
9
+ this.runId = runId;
10
+ this.clock = clock;
11
+ }
12
+ async recordStage(stage) {
13
+ const run = await this.store.get(this.runId);
14
+ if (!run) {
15
+ return;
16
+ }
17
+ const stages = [...(run.stages ?? []), stage];
18
+ const history = [
19
+ ...(run.history ?? []),
20
+ { stage: stage.role, at: new Date(this.clock()).toISOString() },
21
+ ];
22
+ await this.store.update(this.runId, { stages, history });
23
+ }
24
+ async recordVerdict(verdict) {
25
+ const run = await this.store.get(this.runId);
26
+ if (!run) {
27
+ return;
28
+ }
29
+ await this.store.update(this.runId, { councilVerdict: verdict });
30
+ }
31
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Squad ARTIFACT store — the `.copilot-tracking` tree, persisted.
3
+ *
4
+ * Auto-memory persists three flat keys per project (`state`, `decisions`, and
5
+ * `history/<toolId>-<runId>`). That is enough for continuity between two turns
6
+ * and nothing like what a squad run under GitHub Copilot leaves behind: a roster
7
+ * in `team.md`, a routing table, `state.json`, an append-only decision log, one
8
+ * history file per agent, a consumption ledger, and a deliverable under each
9
+ * role's own root (`research/<date>/`, `plans/`, `ppt/<date>/<slug>/`, `docs/`).
10
+ * A Copilot Studio user who pushes a backlog out through a connector has to be
11
+ * able to open the run that produced it afterwards, and flat keys cannot be
12
+ * browsed.
13
+ *
14
+ * This seam adds TREE semantics — a prefix listing — on top of the stores that
15
+ * already exist, rather than a sixth storage backend:
16
+ *
17
+ * * {@link MemoryBackedArtifactStore} adapts ANY {@link SquadMemoryStore}, so
18
+ * the filesystem, Azure Table, SharePoint/Graph, the caller-selectable
19
+ * target allow-list, and the >32 KiB blob-overflow decorator ALL become
20
+ * artifact backends for free, keeping the tenant isolation, the CAS write,
21
+ * the traversal guards, and the at-rest encryption those stores already
22
+ * carry rather than re-implementing (and re-auditing) each one.
23
+ *
24
+ * Paths are stored with their `.copilot-tracking/` prefix intact. It is one
25
+ * redundant segment against a real benefit: what the Graph and filesystem
26
+ * backends write is then byte-for-byte the tree a developer already browses
27
+ * locally, so "read the history" is the same operation in both places.
28
+ */
29
+ import { isSafeMemoryPath, } from "./squad-memory-state.js";
30
+ /** The tracking root every squad artifact path is written under. */
31
+ export const TRACKING_ROOT = ".copilot-tracking";
32
+ /** The squad-state directory within the tracking root. */
33
+ export const SQUAD_STATE_ROOT = `${TRACKING_ROOT}/squad`;
34
+ /**
35
+ * Reject a path that is unsafe or escapes the tracking root.
36
+ *
37
+ * The traversal guard is the memory seam's (`isSafeMemoryPath`), so both surfaces
38
+ * enforce one rule. The root check is the artifact-specific half: a run must not
39
+ * be able to write outside the tree the operator agreed to expose, and `docs/`
40
+ * and `outputs/` are the two deliverable roots the roster deliberately keeps at
41
+ * the repository root, so both are allowed alongside it.
42
+ */
43
+ const ALLOWED_ROOTS = [TRACKING_ROOT, "docs", "outputs"];
44
+ export function assertSafeArtifactPath(path) {
45
+ if (!isSafeMemoryPath(path)) {
46
+ throw new Error(`Unsafe artifact path: ${JSON.stringify(path)}.`);
47
+ }
48
+ const root = path.split("/")[0];
49
+ if (!ALLOWED_ROOTS.includes(root)) {
50
+ throw new Error(`Artifact path must sit under ${ALLOWED_ROOTS.join(", ")} — got ${JSON.stringify(path)}.`);
51
+ }
52
+ }
53
+ /** Maximum characters retained in a single artifact. */
54
+ export const ARTIFACT_MAX_CHARS = 256_000;
55
+ /** Maximum CAS attempts for an append before giving up. */
56
+ const APPEND_CAS_ATTEMPTS = 4;
57
+ function toArtifact(entry) {
58
+ return {
59
+ tenantId: entry.tenantId,
60
+ project: entry.project,
61
+ path: entry.path,
62
+ content: entry.content,
63
+ etag: entry.etag,
64
+ updatedAt: entry.updatedAt,
65
+ };
66
+ }
67
+ /**
68
+ * A {@link SquadArtifactStore} over any {@link SquadMemoryStore}.
69
+ *
70
+ * The memory seam is already a keyed `read`/`write`/`list` with CAS and tenant
71
+ * isolation; the only thing it lacks for a tree is a prefix filter, which is
72
+ * applied here. Every existing backend therefore becomes an artifact backend
73
+ * with no new credential path, no new traversal surface, and no second
74
+ * encryption implementation to audit.
75
+ */
76
+ export class MemoryBackedArtifactStore {
77
+ store;
78
+ /**
79
+ * One promise chain per `tenant/project/path`, so two appends to the same log
80
+ * inside this process are serialized rather than racing.
81
+ *
82
+ * This is needed because the memory seam has no create-if-absent: `write` with
83
+ * no `expectedEtag` is an unconditional upsert, so the FIRST two writers to a
84
+ * path cannot be arbitrated by compare-and-swap and one would silently
85
+ * overwrite the other. Every subsequent append does hold a real CAS token, and
86
+ * {@link SquadLedger.seed} pre-creates the shared logs so the unarbitrated
87
+ * window closes for them at seed time.
88
+ */
89
+ appendQueues = new Map();
90
+ constructor(store) {
91
+ this.store = store;
92
+ }
93
+ async put(tenantId, project, path, content, expectedEtag) {
94
+ assertSafeArtifactPath(path);
95
+ const bounded = content.length <= ARTIFACT_MAX_CHARS
96
+ ? content
97
+ : `${content.slice(0, ARTIFACT_MAX_CHARS)}\n…(truncated)…`;
98
+ const result = await this.store.write(tenantId, project, path, bounded, expectedEtag);
99
+ if (!result.ok) {
100
+ return {
101
+ ok: false,
102
+ conflict: true,
103
+ current: result.current ? toArtifact(result.current) : undefined,
104
+ };
105
+ }
106
+ return { ok: true, artifact: toArtifact(result.entry) };
107
+ }
108
+ async get(tenantId, project, path) {
109
+ assertSafeArtifactPath(path);
110
+ const entry = await this.store.read(tenantId, project, path);
111
+ return entry ? toArtifact(entry) : undefined;
112
+ }
113
+ async list(tenantId, project, prefix) {
114
+ const entries = await this.store.list(tenantId, project);
115
+ const normalized = prefix?.replace(/\/+$/, "");
116
+ return entries
117
+ .filter((entry) => normalized ? entry.path === normalized || entry.path.startsWith(`${normalized}/`) : true)
118
+ .map((entry) => ({
119
+ path: entry.path,
120
+ size: entry.content.length,
121
+ updatedAt: entry.updatedAt,
122
+ }))
123
+ .sort((a, b) => a.path.localeCompare(b.path));
124
+ }
125
+ /**
126
+ * Append under compare-and-swap.
127
+ *
128
+ * `decisions.md`, `notifications.md`, and `history/<agent>.md` are append-only
129
+ * in `squad-state.instructions.md` — "new entries are added to the end; prior
130
+ * entries are never edited or removed". Two roles finishing at once would
131
+ * otherwise last-write-wins one of them away, which is exactly the silent loss
132
+ * the append-only rule exists to prevent.
133
+ */
134
+ append(tenantId, project, path, block) {
135
+ assertSafeArtifactPath(path);
136
+ const key = `${tenantId}/${project}/${path}`;
137
+ const previous = this.appendQueues.get(key) ?? Promise.resolve();
138
+ const next = previous
139
+ .catch(() => undefined)
140
+ .then(() => this.appendOnce(tenantId, project, path, block));
141
+ this.appendQueues.set(key, next);
142
+ // Drop the chain once it drains so a long-lived server does not retain a
143
+ // queue entry for every path it has ever written.
144
+ void next.catch(() => undefined).finally(() => {
145
+ if (this.appendQueues.get(key) === next) {
146
+ this.appendQueues.delete(key);
147
+ }
148
+ });
149
+ return next;
150
+ }
151
+ async appendOnce(tenantId, project, path, block) {
152
+ let lastConflict;
153
+ for (let attempt = 0; attempt < APPEND_CAS_ATTEMPTS; attempt += 1) {
154
+ const current = await this.get(tenantId, project, path);
155
+ const next = current ? `${current.content.replace(/\s*$/, "")}\n\n${block}\n` : `${block}\n`;
156
+ const result = await this.put(tenantId, project, path, next, current?.etag);
157
+ if (result.ok) {
158
+ return result.artifact;
159
+ }
160
+ lastConflict = result.current;
161
+ }
162
+ throw new Error(`Could not append to ${path} after ${APPEND_CAS_ATTEMPTS} attempts (last revision ` +
163
+ `${lastConflict?.etag ?? "unknown"}).`);
164
+ }
165
+ }