agy-squad 0.0.0-stage → 0.1.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 (65) hide show
  1. package/.agents/skills/full-review/SKILL.md +89 -0
  2. package/.agents/skills/full-review/references/evidence-intake.md +146 -0
  3. package/.agents/skills/full-review/references/report-template.md +216 -0
  4. package/.agents/skills/full-review/references/review-roles.md +91 -0
  5. package/.agents/skills/pr-review/SKILL.md +60 -0
  6. package/.agents/skills/pr-review/references/pr-review-standard.md +163 -0
  7. package/.agents/skills/self-diagnosis/SKILL.md +63 -0
  8. package/.agents/skills/self-diagnosis/references/execution-and-teardown.md +71 -0
  9. package/.agents/skills/self-diagnosis/references/optimization-and-review-rubric.md +61 -0
  10. package/.agents/skills/self-diagnosis/resources/comparative-research-manifest.json +42 -0
  11. package/.agents/skills/self-diagnosis/resources/self-diagnosis-manifest.json +144 -0
  12. package/.agents/skills/self-diagnosis/scripts/diagnose.mjs +1971 -0
  13. package/.agents/skills/swarm-governance/SKILL.md +59 -0
  14. package/.agents/skills/swarm-governance/references/bundling-and-wire-format.md +88 -0
  15. package/.agents/skills/swarm-governance/references/intake-and-planning.md +120 -0
  16. package/.agents/skills/swarm-governance/references/large-swarms.md +39 -0
  17. package/CHANGELOG.md +16 -0
  18. package/LICENSE +21 -0
  19. package/README.md +156 -2
  20. package/bin/agy-squad.mjs +293 -0
  21. package/docs/assets/architecture-overview.svg +39 -0
  22. package/docs/assets/manifest-and-modes.svg +39 -0
  23. package/docs/assets/role-and-verdict-gate.svg +39 -0
  24. package/docs/assets/skill-role-workflows.svg +39 -0
  25. package/docs/assets/swarm-lifecycle.svg +39 -0
  26. package/docs/benchmarks.md +102 -0
  27. package/docs/concepts.md +81 -0
  28. package/docs/core-workflows.md +128 -0
  29. package/docs/getting-started.md +116 -0
  30. package/docs/index.md +47 -0
  31. package/docs/plans/LEDGER.md +24 -0
  32. package/docs/plans/comparative-harness-architecture-retest.md +1174 -0
  33. package/docs/plans/comparative-harness-architecture-teamwork.md +1170 -0
  34. package/docs/plans/comparative-harness-architecture.md +256 -0
  35. package/docs/plans/native-enforcement-ledger.md +126 -0
  36. package/docs/plans/pr3-option-b-fixes.md +803 -0
  37. package/docs/plans/wsl-cli-verification.md +55 -0
  38. package/docs/reviews/post-pr5-governance-review.md +221 -0
  39. package/docs/reviews/pr1-code-review-ledger.md +581 -0
  40. package/docs/reviews/pr1-production-readiness-review.md +764 -0
  41. package/docs/reviews/pr2-documentation-review-ledger.md +380 -0
  42. package/docs/reviews/pr3-squad-alignment-full-review.md +1021 -0
  43. package/docs/reviews/pr4-swarm-governance-pivot-review.md +593 -0
  44. package/docs/reviews/pr5-full-review-direction.md +330 -0
  45. package/docs/reviews/pr5-independent-review.md +266 -0
  46. package/docs/reviews/pr5-layered-swarm-review.md +513 -0
  47. package/docs/reviews/pr5-phase2-swarm-planner-review.md +470 -0
  48. package/docs/reviews/pr5-reconciled-review.md +573 -0
  49. package/docs/reviews/rebuild-wsl-dispatch-review-r2.md +427 -0
  50. package/docs/reviews/rebuild-wsl-dispatch-review.md +552 -0
  51. package/docs/roles-and-workflows.md +115 -0
  52. package/docs/stopping-agents.md +39 -0
  53. package/docs/tools.md +122 -0
  54. package/install.ps1 +5 -0
  55. package/install.sh +4 -0
  56. package/mcp/briefs.mjs +202 -0
  57. package/mcp/dispatch.mjs +280 -0
  58. package/mcp/handoffs.mjs +814 -0
  59. package/mcp/index.js +322 -0
  60. package/mcp/planner.mjs +755 -0
  61. package/mcp/verdicts.mjs +224 -0
  62. package/package.json +57 -4
  63. package/plugin.json +20 -0
  64. package/scripts/install-register.mjs +510 -0
  65. package/scripts/release-preflight.mjs +142 -0
@@ -0,0 +1,755 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { SUBAGENT_MODEL_ALIASES, buildSubagentSpec, validateScopeFiles } from "./briefs.mjs";
4
+ import {
5
+ loadSquads,
6
+ manifestSquads,
7
+ resolveIntegrityAuditor,
8
+ resolveSquadLead,
9
+ specialistAssignments
10
+ } from "./dispatch.mjs";
11
+ import { normalizeReportRoot, reportPath } from "./handoffs.mjs";
12
+
13
+ const ALLOWED_PLANNER_KEYS = new Set([
14
+ "manifestPath",
15
+ "manifest",
16
+ "task",
17
+ "squadId",
18
+ "executionMode",
19
+ "model",
20
+ "workspaceIsolation",
21
+ "scopeFiles",
22
+ "roles",
23
+ "includeIntegrityAuditor",
24
+ "reportRoot",
25
+ "knownModels",
26
+ "occupiedWorkerNames",
27
+ "topology"
28
+ ]);
29
+
30
+ const WORKSPACE_ISOLATIONS = new Set(["inherit", "share", "branch"]);
31
+ const MAX_SWARM_NAME_LENGTH = 24;
32
+ const AGENT_ALIAS_PAIRS = [
33
+ ["role", "Role"],
34
+ ["objective", "Objective"],
35
+ ["scopeFiles", "ScopeFiles"],
36
+ ["instructions", "Instructions"],
37
+ ["expectedDeliverable", "ExpectedDeliverable"],
38
+ ["typeName", "TypeName"],
39
+ ["model", "Model"],
40
+ ["workspace", "Workspace"]
41
+ ];
42
+
43
+ function slugifyName(value, fallback) {
44
+ const slug = String(value ?? "")
45
+ .toLowerCase()
46
+ .replace(/[^a-z0-9]+/g, "-")
47
+ .replace(/^-+|-+$/g, "")
48
+ .slice(0, MAX_SWARM_NAME_LENGTH)
49
+ .replace(/-+$/, "");
50
+ if (slug) return slug;
51
+ const fallbackSlug = String(fallback ?? "")
52
+ .toLowerCase()
53
+ .replace(/[^a-z0-9]+/g, "-")
54
+ .replace(/^-+|-+$/g, "")
55
+ .slice(0, MAX_SWARM_NAME_LENGTH)
56
+ .replace(/-+$/, "");
57
+ return fallbackSlug || "worker";
58
+ }
59
+
60
+ function allocateWorkerName(usedWorkerNames, rawValue, fallback) {
61
+ const base = slugifyName(rawValue, fallback);
62
+ if (!usedWorkerNames.has(base)) {
63
+ usedWorkerNames.add(base);
64
+ return base;
65
+ }
66
+ const safeFallback = slugifyName(fallback, "worker");
67
+ for (let counter = 2; ; counter++) {
68
+ const suffix = `-${counter}`;
69
+ const maxPrefixLen = Math.max(1, MAX_SWARM_NAME_LENGTH - suffix.length);
70
+ const prefix =
71
+ base.slice(0, maxPrefixLen).replace(/-+$/, "") ||
72
+ safeFallback.slice(0, maxPrefixLen).replace(/-+$/, "") ||
73
+ "w";
74
+ const candidate = `${prefix}${suffix}`;
75
+ if (!usedWorkerNames.has(candidate)) {
76
+ usedWorkerNames.add(candidate);
77
+ return candidate;
78
+ }
79
+ }
80
+ }
81
+
82
+ function normalizeExplicitModel(rawModel) {
83
+ if (typeof rawModel !== "string") return undefined;
84
+ const trimmed = rawModel.trim();
85
+ return trimmed && trimmed !== "inherit" ? trimmed : undefined;
86
+ }
87
+
88
+ function resolveWorkerModels(executionMode, requestedModel, specModelRaw, overriddenSubagentModels) {
89
+ if (specModelRaw !== undefined && typeof specModelRaw !== "string") {
90
+ return {
91
+ requested: requestedModel ?? "inherit",
92
+ effective: "inherit",
93
+ swarmPin: requestedModel,
94
+ compiledModel: specModelRaw
95
+ };
96
+ }
97
+ const explicitSpecModel = normalizeExplicitModel(specModelRaw);
98
+ const targetModel = requestedModel ?? explicitSpecModel;
99
+ if (executionMode === "subagent") {
100
+ const effectiveModel = targetModel && SUBAGENT_MODEL_ALIASES.has(targetModel) ? targetModel : "inherit";
101
+ if (!requestedModel && explicitSpecModel && !SUBAGENT_MODEL_ALIASES.has(explicitSpecModel)) {
102
+ overriddenSubagentModels.push(explicitSpecModel);
103
+ }
104
+ return {
105
+ requested: targetModel ?? "inherit",
106
+ effective: effectiveModel,
107
+ swarmPin: undefined,
108
+ compiledModel: effectiveModel
109
+ };
110
+ }
111
+ return {
112
+ requested: targetModel ?? "inherit",
113
+ effective: targetModel ?? "inherit",
114
+ swarmPin: targetModel,
115
+ compiledModel: targetModel ?? (specModelRaw ?? "inherit")
116
+ };
117
+ }
118
+
119
+ function normalizeScopePath(scopeEntry, root) {
120
+ const trimmed = scopeEntry.trim().replace(/\/+$/, "");
121
+ if (trimmed === ".") return "";
122
+ if (root) {
123
+ try {
124
+ const candidate = path.resolve(root, trimmed);
125
+ const real = fs.realpathSync(candidate);
126
+ const rel = path.relative(root, real).split(path.sep).join("/");
127
+ if (rel === "") return "";
128
+ if (rel !== ".." && !rel.startsWith("../") && !path.isAbsolute(rel)) {
129
+ return rel;
130
+ }
131
+ } catch {
132
+ // Planned path may not exist on disk yet; keep normalized lexical form.
133
+ }
134
+ }
135
+ return trimmed;
136
+ }
137
+
138
+ function scopesOverlap(a, b, root) {
139
+ const normA = normalizeScopePath(a, root);
140
+ const normB = normalizeScopePath(b, root);
141
+ if (normA === "" || normB === "") return true;
142
+ return normA === normB || normA.startsWith(`${normB}/`) || normB.startsWith(`${normA}/`);
143
+ }
144
+
145
+ function findScopeOverlaps(entries, root) {
146
+ const normalizedEntries = entries.map(entry => ({
147
+ label: entry.label,
148
+ scopes: entry.scopeFiles.map(raw => ({ raw, norm: normalizeScopePath(raw, root) }))
149
+ }));
150
+ const overlaps = [];
151
+ for (let i = 0; i < normalizedEntries.length; i++) {
152
+ for (let j = i + 1; j < normalizedEntries.length; j++) {
153
+ const left = normalizedEntries[i];
154
+ const right = normalizedEntries[j];
155
+ const matchingPair = [];
156
+ for (const a of left.scopes) {
157
+ for (const b of right.scopes) {
158
+ if (a.norm === "" || b.norm === "" || a.norm === b.norm || a.norm.startsWith(`${b.norm}/`) || b.norm.startsWith(`${a.norm}/`)) {
159
+ matchingPair.push([a.raw, b.raw]);
160
+ }
161
+ }
162
+ }
163
+ if (matchingPair.length > 0) {
164
+ overlaps.push({
165
+ workerA: left.label,
166
+ workerB: right.label,
167
+ pairs: matchingPair.map(([a, b]) => `${a} <-> ${b}`)
168
+ });
169
+ }
170
+ }
171
+ }
172
+ return overlaps;
173
+ }
174
+
175
+ function canonicalizeAgentSpec(spec, fallbackLabel) {
176
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) {
177
+ throw new Error(`Agent '${fallbackLabel}' must be an object.`);
178
+ }
179
+ const agentLabel = spec.role ?? spec.Role ?? fallbackLabel;
180
+ if (spec.readOnly !== undefined && spec.ReadOnly !== undefined && spec.readOnly !== spec.ReadOnly) {
181
+ throw new Error(`Agent '${agentLabel}' cannot define both 'readOnly' and 'ReadOnly'.`);
182
+ }
183
+ const readOnly = spec.readOnly !== undefined ? spec.readOnly : spec.ReadOnly;
184
+ if (readOnly !== undefined && typeof readOnly !== "boolean") {
185
+ throw new Error(`Agent '${agentLabel}' readOnly must be a boolean.`);
186
+ }
187
+ const canonical = { ...spec };
188
+ delete canonical.readOnly;
189
+ delete canonical.ReadOnly;
190
+ for (const [lower, upper] of AGENT_ALIAS_PAIRS) {
191
+ const hasLower = canonical[lower] !== undefined;
192
+ const hasUpper = canonical[upper] !== undefined;
193
+ if (hasLower && hasUpper && canonical[lower] !== canonical[upper]) {
194
+ throw new Error(`Agent '${agentLabel}' has conflicting ${lower} and ${upper} fields.`);
195
+ }
196
+ if (!hasLower && hasUpper) {
197
+ canonical[lower] = canonical[upper];
198
+ }
199
+ delete canonical[upper];
200
+ }
201
+ return { canonical, readOnly };
202
+ }
203
+
204
+ function deriveTaskSquads(task, roles, scopeFiles) {
205
+ const validatedScopes = validateScopeFiles(scopeFiles === undefined ? ["."] : scopeFiles, "task");
206
+ if (roles !== undefined && (!Array.isArray(roles) || roles.length === 0)) {
207
+ throw new Error("roles must be a non-empty array of non-empty strings.");
208
+ }
209
+ const roleList = roles ?? ["Task Worker"];
210
+ const specialists = roleList.map((role, index) => {
211
+ if (typeof role !== "string" || !role.trim()) {
212
+ throw new Error(`Role at index ${index} must be a non-empty string.`);
213
+ }
214
+ return {
215
+ role: role.trim(),
216
+ objective: roleList.length === 1 ? task.trim() : `${task.trim()} — Focus: ${role.trim()}.`,
217
+ scopeFiles: validatedScopes,
218
+ expectedDeliverable: "Markdown evidence report with verified file paths, commands, exit codes, and test outputs."
219
+ };
220
+ });
221
+ return { task_squad: { specialists } };
222
+ }
223
+
224
+ function buildSwarmWorkerBrief(compiledBrief, targetModel, workspaceIsolation) {
225
+ const modelNote = targetModel
226
+ ? `Pinned model expectation: ${targetModel} (verify via swarm status).`
227
+ : "Model: coordinator default.";
228
+ return workspaceIsolation === "inherit"
229
+ ? `${compiledBrief.Prompt}\n${modelNote}`
230
+ : `${compiledBrief.Prompt}\n${modelNote}\nIsolated '${workspaceIsolation}' workspace: coordinator collects outputs before bundling.`;
231
+ }
232
+
233
+ /**
234
+ * Compile an execution plan pairing Agy-Squad governance with Antigravity native /swarm
235
+ * or invoke_subagent dispatch, explicit model provenance, scope-overlap checks, and L6-safe
236
+ * integrity audit scaffolding.
237
+ */
238
+ function planSquadCohort(args = {}, workspace = process.env.AGY_SQUAD_WORKSPACE || process.cwd()) {
239
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
240
+ throw new Error("Provide a planner options object.");
241
+ }
242
+ for (const key of Object.keys(args)) {
243
+ if (!ALLOWED_PLANNER_KEYS.has(key)) {
244
+ throw new Error(`Unsupported squad_planner option '${key}'.`);
245
+ }
246
+ }
247
+
248
+ const {
249
+ manifestPath,
250
+ manifest,
251
+ task,
252
+ squadId,
253
+ executionMode = "swarm",
254
+ model,
255
+ workspaceIsolation = "inherit",
256
+ scopeFiles,
257
+ roles,
258
+ includeIntegrityAuditor = true,
259
+ reportRoot,
260
+ knownModels,
261
+ occupiedWorkerNames,
262
+ topology
263
+ } = args;
264
+
265
+ if (topology !== undefined && topology !== "flat" && topology !== "layered") {
266
+ throw new Error("topology must be 'flat' or 'layered'.");
267
+ }
268
+
269
+ if (knownModels !== undefined) {
270
+ if (!Array.isArray(knownModels) || knownModels.length === 0 || knownModels.some(m => typeof m !== "string" || !m.trim())) {
271
+ throw new Error("knownModels must be a non-empty array of non-empty model ID strings (for example the model IDs returned by swarm{action:\"models\"}).");
272
+ }
273
+ }
274
+
275
+ if (occupiedWorkerNames !== undefined) {
276
+ if (!Array.isArray(occupiedWorkerNames) || occupiedWorkerNames.some(n => typeof n !== "string" || !n.trim())) {
277
+ throw new Error("occupiedWorkerNames must be an array of non-empty worker name strings.");
278
+ }
279
+ }
280
+
281
+ const sources = [
282
+ manifestPath !== undefined ? "manifestPath" : null,
283
+ manifest !== undefined ? "manifest" : null,
284
+ task !== undefined ? "task" : null
285
+ ].filter(Boolean);
286
+ if (sources.length !== 1) {
287
+ throw new Error("Provide exactly one of manifestPath, manifest, or task.");
288
+ }
289
+ if (executionMode !== "swarm" && executionMode !== "subagent") {
290
+ throw new Error("executionMode must be 'swarm' or 'subagent'.");
291
+ }
292
+ if (!WORKSPACE_ISOLATIONS.has(workspaceIsolation)) {
293
+ throw new Error("workspaceIsolation must be 'inherit', 'share', or 'branch'.");
294
+ }
295
+ if (executionMode === "subagent" && workspaceIsolation !== "inherit") {
296
+ throw new Error("workspaceIsolation 'share' or 'branch' requires executionMode 'swarm'; subagent mode requires 'inherit'.");
297
+ }
298
+ if (model !== undefined && (typeof model !== "string" || !model.trim())) {
299
+ throw new Error("model must be a non-empty string when provided.");
300
+ }
301
+ if (includeIntegrityAuditor !== undefined && typeof includeIntegrityAuditor !== "boolean") {
302
+ throw new Error("includeIntegrityAuditor must be a boolean.");
303
+ }
304
+ const normalizedReportRoot = reportRoot !== undefined ? normalizeReportRoot(reportRoot) : undefined;
305
+
306
+ const root = fs.realpathSync(workspace);
307
+ let loadedSquads;
308
+ let selectedManifest;
309
+ if (task !== undefined) {
310
+ if (typeof task !== "string" || !task.trim()) {
311
+ throw new Error("task must be a non-empty string.");
312
+ }
313
+ if (topology === "layered") {
314
+ throw new Error("topology 'layered' requires a manifest with per-squad leads; use topology 'flat' (or omit topology) with task.");
315
+ }
316
+ loadedSquads = deriveTaskSquads(task, roles, scopeFiles);
317
+ selectedManifest = "inline-task";
318
+ } else if (manifest !== undefined) {
319
+ if (scopeFiles !== undefined || roles !== undefined) {
320
+ throw new Error("scopeFiles and roles can only be passed with task.");
321
+ }
322
+ loadedSquads = manifestSquads(manifest);
323
+ selectedManifest = "inline-manifest";
324
+ } else {
325
+ if (typeof manifestPath !== "string" || !manifestPath.trim()) {
326
+ throw new Error("manifestPath must be a non-empty string.");
327
+ }
328
+ if (scopeFiles !== undefined || roles !== undefined) {
329
+ throw new Error("scopeFiles and roles can only be passed with task.");
330
+ }
331
+ const loaded = loadSquads(root, manifestPath);
332
+ loadedSquads = loaded.squads;
333
+ selectedManifest = loaded.selectedManifest;
334
+ }
335
+
336
+ const isAuditKey = id => id === "integrity_auditor" || id.startsWith("integrity_auditor-");
337
+ const allWorkingIds = Object.keys(loadedSquads).filter(id => !isAuditKey(id));
338
+ const targetWorkingIds = squadId !== undefined
339
+ ? (() => {
340
+ if (typeof squadId !== "string" || !squadId.trim()) {
341
+ throw new Error("squadId must be a non-empty string.");
342
+ }
343
+ if (!Object.hasOwn(loadedSquads, squadId) || isAuditKey(squadId)) {
344
+ throw new Error(`Unknown working squadId '${squadId}'.`);
345
+ }
346
+ return [squadId];
347
+ })()
348
+ : allWorkingIds;
349
+
350
+ if (!targetWorkingIds.length) {
351
+ throw new Error("Manifest must define at least one non-audit working squad.");
352
+ }
353
+
354
+ const requestedModel = normalizeExplicitModel(model);
355
+ const effectiveSubagentModel = requestedModel && SUBAGENT_MODEL_ALIASES.has(requestedModel)
356
+ ? requestedModel
357
+ : "inherit";
358
+ const modelProvenance = executionMode === "swarm"
359
+ ? {
360
+ executionMode: "swarm",
361
+ requestedModel: requestedModel ?? "inherit (coordinator default)",
362
+ pinningSupported: true,
363
+ perWorkerModelExposed: true,
364
+ verificationMethod: "Call swarm{action: \"status\"} after spawning workers to verify actual running model IDs.",
365
+ caveat: requestedModel
366
+ ? "Each swarm add pins the requested model; monitor/coordinator model remains whatever session hosts the coordinator."
367
+ : "No explicit model passed; workers default to the coordinator's active model."
368
+ }
369
+ : {
370
+ executionMode: "subagent",
371
+ requestedModel: requestedModel ?? "inherit",
372
+ effectiveModel: effectiveSubagentModel,
373
+ pinningSupported: false,
374
+ perChildModelExposed: false,
375
+ verificationMethod: "invoke_subagent inherits or aliases ('inherit'|'flash'|'flash_lite'|'pro'); neither 'agy-context transcript read' (read_transcript) nor manage_subagents exposes per-child resolved model IDs.",
376
+ ...(requestedModel && !SUBAGENT_MODEL_ALIASES.has(requestedModel)
377
+ ? {
378
+ warning: `Requested explicit model '${requestedModel}' cannot be pinned under executionMode 'subagent'; compiled Model defaults to 'inherit'. Switch to executionMode 'swarm' to pin exact model IDs.`
379
+ }
380
+ : {})
381
+ };
382
+
383
+ const manifestPathForBrief =
384
+ selectedManifest === "inline-manifest" || selectedManifest === "inline-task"
385
+ ? undefined
386
+ : selectedManifest;
387
+ const writableScopeEntries = [];
388
+ const workers = [];
389
+ const provenanceEntries = [];
390
+ const bundleRecordTemplates = Object.create(null);
391
+ const usedWorkerNames = new Set();
392
+ for (const occupied of occupiedWorkerNames ?? []) {
393
+ const trimmed = occupied.trim();
394
+ usedWorkerNames.add(trimmed);
395
+ usedWorkerNames.add(slugifyName(trimmed, trimmed));
396
+ }
397
+ const overriddenSubagentModels = [];
398
+ let totalSpecialists = 0;
399
+
400
+ for (const id of targetWorkingIds) {
401
+ const squad = loadedSquads[id];
402
+ const leadSpec =
403
+ topology === "flat"
404
+ ? undefined
405
+ : resolveSquadLead(squad, id, topology === "layered");
406
+ const specs = specialistAssignments(loadedSquads, id);
407
+ totalSpecialists += specs.length;
408
+
409
+ const leadSlot = reportPath(id, undefined, normalizedReportRoot);
410
+ let compiledLead;
411
+ let leadModel;
412
+ let leadWorkerName;
413
+ if (leadSpec) {
414
+ const { canonical: rawLead, readOnly: leadReadOnly } = canonicalizeAgentSpec(leadSpec, `${id}-lead`);
415
+ const leadScope = validateScopeFiles(rawLead.scopeFiles, rawLead.role);
416
+ if (leadReadOnly !== true) {
417
+ writableScopeEntries.push({
418
+ label: `${id}-lead (${rawLead.role ?? "Lead"})`,
419
+ scopeFiles: leadScope
420
+ });
421
+ }
422
+ leadModel = resolveWorkerModels(
423
+ executionMode,
424
+ requestedModel,
425
+ rawLead.model,
426
+ overriddenSubagentModels
427
+ );
428
+ const cleanedLead = {
429
+ ...rawLead,
430
+ model: leadModel.compiledModel
431
+ };
432
+ compiledLead = buildSubagentSpec(
433
+ cleanedLead,
434
+ id,
435
+ manifestPathForBrief,
436
+ undefined,
437
+ normalizedReportRoot,
438
+ { executionMode, workspaceIsolation: "inherit", isIntegrityAuditor: false, precompiledSpecialists: true }
439
+ );
440
+ leadWorkerName = allocateWorkerName(usedWorkerNames, `${id}-lead`, `${id}-lead`);
441
+ }
442
+
443
+ const compiledSpecialists = [];
444
+ const assignmentsTemplate = [];
445
+ for (const { spec, number } of specs) {
446
+ const { canonical: rawSpec, readOnly: specReadOnly } = canonicalizeAgentSpec(spec, `${id}#${number}`);
447
+ const specScope = validateScopeFiles(rawSpec.scopeFiles, rawSpec.role);
448
+ if (specReadOnly !== true) {
449
+ writableScopeEntries.push({
450
+ label: `${id}#${number} (${rawSpec.role ?? `Specialist ${number}`})`,
451
+ scopeFiles: specScope
452
+ });
453
+ }
454
+ const specModel = resolveWorkerModels(
455
+ executionMode,
456
+ requestedModel,
457
+ rawSpec.model,
458
+ overriddenSubagentModels
459
+ );
460
+ const subSpec = {
461
+ ...rawSpec,
462
+ model: specModel.compiledModel
463
+ };
464
+ const compiled = buildSubagentSpec(
465
+ subSpec,
466
+ id,
467
+ manifestPathForBrief,
468
+ number,
469
+ normalizedReportRoot,
470
+ { executionMode, workspaceIsolation, isIntegrityAuditor: false }
471
+ );
472
+ const slot = reportPath(id, number, normalizedReportRoot);
473
+ const workerName = allocateWorkerName(
474
+ usedWorkerNames,
475
+ `${id}-${rawSpec.role ?? number}`,
476
+ `${id}-worker-${number}`
477
+ );
478
+ compiledSpecialists.push({ slot, workerName, specModel, compiled });
479
+ assignmentsTemplate.push({
480
+ // Swarm identifies members on the board by roster name, so the name is the sender identity.
481
+ conversationId: executionMode === "swarm" ? workerName : `<invoke_subagent:${workerName}:conversationId>`,
482
+ report: slot
483
+ });
484
+ provenanceEntries.push({
485
+ squadId: id,
486
+ slotType: "specialist",
487
+ workerName,
488
+ role: compiled.Role,
489
+ reportSlot: slot,
490
+ requestedModel: specModel.requested,
491
+ effectiveModel: specModel.effective,
492
+ conversationId: "<record-after-launch>",
493
+ resolvedModel: executionMode === "swarm" ? "<verify-via-swarm-status>" : "<inherited-from-parent-unverified>"
494
+ });
495
+ }
496
+
497
+ if (compiledLead) {
498
+ provenanceEntries.push({
499
+ squadId: id,
500
+ slotType: "lead",
501
+ workerName: leadWorkerName,
502
+ role: compiledLead.Role,
503
+ reportSlot: leadSlot,
504
+ requestedModel: leadModel.requested,
505
+ effectiveModel: leadModel.effective,
506
+ conversationId: "<record-after-launch>",
507
+ resolvedModel: executionMode === "swarm" ? "<verify-via-swarm-status>" : "<inherited-from-parent-unverified>"
508
+ });
509
+ }
510
+
511
+ workers.push({
512
+ squadId: id,
513
+ lead: compiledLead
514
+ ? {
515
+ workerName: leadWorkerName,
516
+ reportSlot: leadSlot,
517
+ ...(executionMode === "swarm"
518
+ ? {
519
+ swarmAdd: {
520
+ action: "add",
521
+ name: leadWorkerName,
522
+ ...(leadModel.swarmPin ? { model: leadModel.swarmPin } : {}),
523
+ workspace: "inherit",
524
+ brief: buildSwarmWorkerBrief(compiledLead, leadModel.swarmPin, "inherit")
525
+ }
526
+ }
527
+ : { Subagent: compiledLead })
528
+ }
529
+ : null,
530
+ specialists: compiledSpecialists.map(({ slot, workerName, specModel, compiled }) => ({
531
+ workerName,
532
+ reportSlot: slot,
533
+ ...(executionMode === "swarm"
534
+ ? {
535
+ swarmAdd: {
536
+ action: "add",
537
+ name: workerName,
538
+ ...(specModel.swarmPin ? { model: specModel.swarmPin } : {}),
539
+ workspace: workspaceIsolation,
540
+ brief: buildSwarmWorkerBrief(compiled, specModel.swarmPin, workspaceIsolation)
541
+ }
542
+ }
543
+ : { Subagent: compiled })
544
+ }))
545
+ });
546
+
547
+ bundleRecordTemplates[id] = {
548
+ squadId: id,
549
+ workspace: root,
550
+ ...(normalizedReportRoot ? { reportRoot: normalizedReportRoot } : {}),
551
+ verdict: "PASS",
552
+ verifiedFiles: {},
553
+ assignments: assignmentsTemplate,
554
+ handoffs: [],
555
+ requireIntegrityAudit: includeIntegrityAuditor
556
+ };
557
+ }
558
+
559
+ const integrityAuditPlan = includeIntegrityAuditor
560
+ ? targetWorkingIds.flatMap(id => {
561
+ const auditSpecs = resolveIntegrityAuditor(
562
+ loadedSquads,
563
+ allWorkingIds.length > 1 || targetWorkingIds.length > 1 ? id : undefined
564
+ );
565
+ const compiledAudits = auditSpecs.map(auditItem => {
566
+ const auditSquadId = auditItem.id;
567
+ const auditSlot = reportPath(auditSquadId, auditItem.number, normalizedReportRoot);
568
+ const { canonical: rawAudit } = canonicalizeAgentSpec(auditItem.spec, `${auditSquadId}#${auditItem.number}`);
569
+ const auditModel = resolveWorkerModels(
570
+ executionMode,
571
+ requestedModel,
572
+ rawAudit.model,
573
+ overriddenSubagentModels
574
+ );
575
+ const targetScopeNote = executionMode === "swarm"
576
+ ? `Audit provenanceScaffold entries for squad '${id}'. Verify reports, verifiedFiles hashes, and Evidence Digest ('agy-squad digest <record.json>'). read_board/swarm status confirm handoffs/roster/model only; verify worker execution traces via 'agy-context transcript query --id <id> --summary' (when granted access) or via a coordinator-extracted sanitized transcript index in scratch/ before CLEAN (re-execution alone cannot satisfy CLEAN; report 'Integrity Verdict: INTEGRITY VIOLATION' if traces are unavailable). NEVER copy raw .system_generated/ transcripts into scratch/.`
577
+ : `Audit provenanceScaffold entries for squad '${id}'. Verify reports, verifiedFiles hashes, Evidence Digest ('agy-squad digest <record.json>'), and spot-check traces ONLY via single-pass 'agy-context transcript query --id <id> --summary' (or query_transcript(summaryOnly=true)) on coordinator-recorded conversationIds. NEVER copy .system_generated/ transcripts into scratch/.`;
578
+ const compiledAudit = buildSubagentSpec(
579
+ {
580
+ ...rawAudit,
581
+ model: auditModel.compiledModel,
582
+ instructions: [rawAudit.instructions, targetScopeNote].filter(Boolean).join("\n")
583
+ },
584
+ auditSquadId,
585
+ manifestPathForBrief,
586
+ auditItem.number,
587
+ normalizedReportRoot,
588
+ { executionMode, workspaceIsolation: "inherit", isIntegrityAuditor: true, precompiledSpecialists: true }
589
+ );
590
+ const rawAuditName =
591
+ auditSpecs.length > 1
592
+ ? `audit-${id}-${rawAudit.role ?? auditItem.number}`
593
+ : `audit-${id}`;
594
+ const auditWorkerName = allocateWorkerName(usedWorkerNames, rawAuditName, "audit");
595
+ return {
596
+ targetSquad: id,
597
+ dispatchSquadId: allWorkingIds.length > 1 ? `integrity_auditor:${id}` : "integrity_auditor",
598
+ reportSlot: auditSlot,
599
+ workerName: auditWorkerName,
600
+ ...(executionMode === "swarm"
601
+ ? {
602
+ swarmAdd: {
603
+ action: "add",
604
+ name: auditWorkerName,
605
+ ...(auditModel.swarmPin ? { model: auditModel.swarmPin } : {}),
606
+ workspace: "inherit",
607
+ brief: buildSwarmWorkerBrief(compiledAudit, auditModel.swarmPin, "inherit")
608
+ }
609
+ }
610
+ : { Subagent: compiledAudit })
611
+ };
612
+ });
613
+ if (bundleRecordTemplates[id]) {
614
+ bundleRecordTemplates[id].integrityAuditSlots = compiledAudits.map(entry => entry.reportSlot);
615
+ }
616
+ return compiledAudits;
617
+ })
618
+ : [];
619
+
620
+ if (executionMode === "subagent" && !modelProvenance.warning && overriddenSubagentModels.length > 0) {
621
+ const uniqueOverridden = [...new Set(overriddenSubagentModels)];
622
+ modelProvenance.warning = `Manifest model(s) (${uniqueOverridden.join(", ")}) cannot be pinned under executionMode 'subagent'; compiled Model defaults to 'inherit'. Switch to executionMode 'swarm' to pin exact model IDs.`;
623
+ }
624
+
625
+ const scopeOverlaps = findScopeOverlaps(writableScopeEntries, root);
626
+ const warnings = [];
627
+ if (scopeOverlaps.length > 0 && workspaceIsolation === "inherit") {
628
+ warnings.push(
629
+ `Detected ${scopeOverlaps.length} writable sibling scopeFiles overlap(s) with workspaceIsolation='inherit'; split scopeFiles across workers or use executionMode='swarm' with workspaceIsolation='share'.`
630
+ );
631
+ }
632
+ if (
633
+ executionMode === "swarm" &&
634
+ occupiedWorkerNames === undefined &&
635
+ targetWorkingIds.some(id => id.length > 18)
636
+ ) {
637
+ warnings.push(
638
+ "Swarm worker names truncate at 24 characters; if reusing an active /swarm board across separate plan calls, pass occupiedWorkerNames to prevent cross-plan name collisions."
639
+ );
640
+ }
641
+ if (executionMode === "swarm" && workspaceIsolation !== "inherit") {
642
+ warnings.push(
643
+ `Swarm workers run in '${workspaceIsolation}' copies; merge or collect report slots from worker copies into the coordinator workspace before running agy-squad bundle.`
644
+ );
645
+ }
646
+ if (modelProvenance.warning) {
647
+ warnings.push(modelProvenance.warning);
648
+ }
649
+
650
+ const pinnedModels = new Set();
651
+ if (executionMode === "swarm") {
652
+ for (const w of workers) {
653
+ if (w.lead?.swarmAdd?.model) pinnedModels.add(w.lead.swarmAdd.model);
654
+ for (const s of w.specialists) if (s.swarmAdd?.model) pinnedModels.add(s.swarmAdd.model);
655
+ }
656
+ for (const a of integrityAuditPlan) if (a.swarmAdd?.model) pinnedModels.add(a.swarmAdd.model);
657
+ }
658
+ let modelValidation;
659
+ if (executionMode === "swarm" && pinnedModels.size > 0) {
660
+ const pinned = [...pinnedModels];
661
+ if (!requestedModel) {
662
+ modelProvenance.requestedModel = `per-worker (${pinned.join(", ")})`;
663
+ modelProvenance.caveat =
664
+ "Top-level model omitted, but worker/lead specs pin explicit models; verify actual running IDs via swarm{action:\"status\"}.";
665
+ }
666
+ if (knownModels !== undefined) {
667
+ const known = new Set(knownModels.map(m => m.trim()));
668
+ const unknown = pinned.filter(m => !known.has(m));
669
+ if (unknown.length > 0) {
670
+ throw new Error(`Pinned model(s) not in knownModels: ${unknown.join(", ")}. Run swarm{action:"models"} and pass its model IDs, or fix the model name.`);
671
+ }
672
+ modelValidation = { status: "checked-against-supplied-list", pinned, source: "knownModels argument" };
673
+ } else {
674
+ modelValidation = {
675
+ status: "unverified",
676
+ pinned,
677
+ reason: "The planner has no access to the host's swarm{action:\"models\"} list, so pinned model names are not checked here."
678
+ };
679
+ warnings.push(
680
+ `Pinned model(s) ${pinned.join(", ")} are unverified. Run swarm{action:"models"} before the first swarm add, or pass its IDs as knownModels so the planner can reject typos.`
681
+ );
682
+ }
683
+ }
684
+
685
+ const notes = [];
686
+ if (executionMode === "swarm" && workers.some(w => w.lead)) {
687
+ notes.push(
688
+ "Layered plan: working squad(s) define a squad lead on top of the swarm coordinator. Compared with flat plans (specialists reporting directly to the coordinator), layered plans isolate multi-domain syntheses at higher coordination token cost. Neither topology is forced as default; ask the user which topology they want if unspecified."
689
+ );
690
+ } else if (executionMode === "swarm") {
691
+ notes.push(
692
+ "Flat plan: specialists report directly to the swarm coordinator without per-squad leads. Compared with layered plans, flat plans use fewer coordination hops when a single synthesis suffices. Neither topology is forced as default; ask the user which topology they want if unspecified."
693
+ );
694
+ }
695
+ if (executionMode === "swarm") {
696
+ notes.push(
697
+ "Pointer-Over-Wire on the swarm board is a convention, not enforced: workers can post anything. 'agy-squad inspect' detects violations after the fact; it does not prevent them."
698
+ );
699
+ }
700
+
701
+ return {
702
+ plannerVersion: "2.0.0",
703
+ source: selectedManifest,
704
+ executionMode,
705
+ workspaceIsolation,
706
+ topology: {
707
+ compiledPattern: workers.some(w => w.lead) ? "layered" : "flat",
708
+ defaultBias: "none (ask user if unspecified)",
709
+ workingSquads: targetWorkingIds.length,
710
+ totalSpecialists,
711
+ scopeOverlaps,
712
+ scopeOverlapComparison: "canonical-when-present-else-lexical"
713
+ },
714
+ modelProvenance,
715
+ ...(modelValidation ? { modelValidation } : {}),
716
+ warnings,
717
+ notes,
718
+ ...(executionMode === "swarm"
719
+ ? { preflight: ["swarm{action:\"models\"} // confirm pinned model IDs and quota before the first add", "swarm{action:\"status\"} // after spawning, confirm each worker runs the pinned model"] }
720
+ : {}),
721
+ workers,
722
+ provenanceScaffold: {
723
+ transcriptIsolation: "L6 convention: keep raw transcripts in .system_generated/; never copy transcripts into scratch/ or lead/leaf directories.",
724
+ identity: executionMode === "swarm"
725
+ ? "Swarm identifies members by roster name: bundle assignments[].conversationId and handoffs[].sender use the swarm member name shown above and on the board."
726
+ : "invoke_subagent returns a conversationId per child; record it in assignments[].conversationId and use it as handoffs[].sender.",
727
+ coordinatorSessionModel: "<record-coordinator-model-from-swarm-status>",
728
+ entries: provenanceEntries
729
+ },
730
+ integrityAuditPlan,
731
+ bundleRecordTemplates,
732
+ verificationPipeline: [
733
+ "agy-squad fingerprint <changed-or-verified-files...>",
734
+ "agy-squad inspect <bundle-record.json>",
735
+ "agy-squad digest <bundle-record.json>",
736
+ "agy-squad bundle <bundle-record.json>",
737
+ "agy-squad verify <report.sources.json>",
738
+ "agy-squad prune <report.sources.json> <accepted-sha256>"
739
+ ]
740
+ };
741
+ }
742
+
743
+ function handleSquadPlanner(args = {}, workspace = process.env.AGY_SQUAD_WORKSPACE || process.cwd()) {
744
+ try {
745
+ const plan = planSquadCohort(args, workspace);
746
+ return {
747
+ content: [{ type: "text", text: JSON.stringify(plan, null, 2) }]
748
+ };
749
+ } catch (error) {
750
+ const message = error.code === "ENOENT" ? "Manifest or workspace not found." : error.message;
751
+ return { isError: true, content: [{ type: "text", text: `squad_planner: ${message}` }] };
752
+ }
753
+ }
754
+
755
+ export { handleSquadPlanner, planSquadCohort, scopesOverlap };