@jstn-sdk/ma 0.1.11 → 0.1.13

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 (159) hide show
  1. package/.codex/agents/Architect.toml +0 -2
  2. package/.codex/agents/Auditor.toml +0 -2
  3. package/.codex/agents/Builder.toml +0 -2
  4. package/.codex/agents/Flow.toml +0 -2
  5. package/.codex/agents/Sage.toml +0 -2
  6. package/.codex/agents/Vibe.toml +0 -2
  7. package/.codex/hooks.json +14 -13
  8. package/.codex/prompts/enforcement.md +4 -0
  9. package/.codex/prompts/skill-contract.md +4 -0
  10. package/COVERAGE.md +211 -0
  11. package/DEMO.md +265 -0
  12. package/README.md +287 -37
  13. package/bin/ma.js +232 -71
  14. package/data/clone-data.ledger.json +41 -0
  15. package/data/clone-data.proof.json +50 -0
  16. package/data/clone-data.rvf +37 -0
  17. package/docs/README.md +7 -1
  18. package/docs/getting-started.md +108 -37
  19. package/docs/installed-sdk.md +23 -0
  20. package/docs/mcp-setup.md +65 -1
  21. package/docs/onboarding.md +18 -2
  22. package/docs/prompt-guidance-contract.md +17 -0
  23. package/docs/prompt-guidance-fragments/active-autonomy-core.md +7 -0
  24. package/docs/qa/release-issue-gates-0.1.13.json +644 -0
  25. package/docs/qa/release-readiness-0.1.13.md +116 -0
  26. package/docs/qa/release-readiness-0.1.5.md +1 -1
  27. package/docs/reference/native-engineering-patterns.md +35 -0
  28. package/docs/reference/native-security-playbooks.md +27 -0
  29. package/docs/reference/native-source-selection.md +27 -0
  30. package/docs/reference/native-style-and-deslop.md +20 -0
  31. package/docs/release-spec.md +37 -10
  32. package/docs/skills-publishing.md +25 -1
  33. package/docs/skills.md +37 -12
  34. package/index.js +222 -2
  35. package/mcp/collections.json +23 -6
  36. package/mcp/local/code-intel.js +113 -0
  37. package/mcp/local/memory.js +46 -0
  38. package/mcp/local/playbooks.js +168 -0
  39. package/mcp/local/state.js +71 -0
  40. package/mcp/local/team-run.js +113 -0
  41. package/mcp/local/trace.js +60 -0
  42. package/mcp/local-capabilities.json +56 -0
  43. package/mcp/native-playbooks.json +117 -0
  44. package/mcp/servers.json +34 -0
  45. package/package.json +8 -2
  46. package/plugins/meta-architect/.app.json +1 -1
  47. package/plugins/meta-architect/.codex-plugin/plugin.json +4 -4
  48. package/plugins/meta-architect/.mcp.json +1 -1
  49. package/plugins/meta-architect/README.md +34 -1
  50. package/plugins/meta-architect/obsidian/main.js +401 -0
  51. package/plugins/meta-architect/obsidian/manifest.json +9 -0
  52. package/plugins/meta-architect/obsidian/styles.css +7 -0
  53. package/plugins/meta-architect/skills/align/SKILL.md +24 -0
  54. package/plugins/meta-architect/skills/align/agents/openai.yaml +4 -0
  55. package/plugins/meta-architect/skills/align/references/shared-language.md +24 -0
  56. package/plugins/meta-architect/skills/arch/SKILL.md +2 -0
  57. package/plugins/meta-architect/skills/build/SKILL.md +3 -0
  58. package/plugins/meta-architect/skills/cleanup/SKILL.md +23 -0
  59. package/plugins/meta-architect/skills/cleanup/agents/openai.yaml +4 -0
  60. package/plugins/meta-architect/skills/cleanup/references/style-and-deslop.md +18 -0
  61. package/plugins/meta-architect/skills/diagnose/SKILL.md +24 -0
  62. package/plugins/meta-architect/skills/diagnose/agents/openai.yaml +4 -0
  63. package/plugins/meta-architect/skills/flow/SKILL.md +2 -0
  64. package/plugins/meta-architect/skills/maestro/SKILL.md +36 -3
  65. package/plugins/meta-architect/skills/maestro/agents/openai.yaml +2 -2
  66. package/plugins/meta-architect/skills/maestro/references/native-ingest-map.md +44 -0
  67. package/plugins/meta-architect/skills/sage/SKILL.md +5 -1
  68. package/plugins/meta-architect/skills/sage/references/source-selection.md +36 -0
  69. package/plugins/meta-architect/skills/tdd/SKILL.md +24 -0
  70. package/plugins/meta-architect/skills/tdd/agents/openai.yaml +4 -0
  71. package/plugins/meta-architect/skills/vet/SKILL.md +5 -1
  72. package/plugins/meta-architect/skills/vet/references/security-playbooks.md +30 -0
  73. package/plugins/meta-architect/skills/vibe/SKILL.md +2 -0
  74. package/scripts/active-autonomy-hook.mjs +96 -0
  75. package/scripts/build-linux-packages.mjs +328 -0
  76. package/scripts/doctor.js +36 -4
  77. package/scripts/install.sh +28 -0
  78. package/scripts/linux-package-lib.mjs +40 -0
  79. package/scripts/linux-package-smoke.mjs +103 -0
  80. package/scripts/ralph/prompt.md +35 -0
  81. package/scripts/release-sync.js +13 -6
  82. package/scripts/release-verify.js +166 -1
  83. package/skills/align/SKILL.md +24 -0
  84. package/skills/align/agents/openai.yaml +4 -0
  85. package/skills/align/references/shared-language.md +24 -0
  86. package/skills/arch/SKILL.md +2 -0
  87. package/skills/build/SKILL.md +3 -0
  88. package/skills/cleanup/SKILL.md +23 -0
  89. package/skills/cleanup/agents/openai.yaml +4 -0
  90. package/skills/cleanup/references/style-and-deslop.md +18 -0
  91. package/skills/diagnose/SKILL.md +24 -0
  92. package/skills/diagnose/agents/openai.yaml +4 -0
  93. package/skills/flow/SKILL.md +2 -0
  94. package/skills/index.json +21 -6
  95. package/skills/maestro/SKILL.md +36 -3
  96. package/skills/maestro/agents/openai.yaml +2 -2
  97. package/skills/maestro/references/native-ingest-map.md +44 -0
  98. package/skills/sage/SKILL.md +5 -1
  99. package/skills/sage/references/source-selection.md +36 -0
  100. package/skills/tdd/SKILL.md +24 -0
  101. package/skills/tdd/agents/openai.yaml +4 -0
  102. package/skills/vet/SKILL.md +5 -1
  103. package/skills/vet/references/security-playbooks.md +30 -0
  104. package/skills/vibe/SKILL.md +2 -0
  105. package/src/bootstrap.js +141 -24
  106. package/src/build-gate.js +2 -2
  107. package/src/decision-log.js +12 -9
  108. package/src/launcher.js +4 -0
  109. package/src/mcp-config.js +130 -8
  110. package/src/mcp-live-client.js +289 -3
  111. package/src/paths.js +37 -1
  112. package/src/policy.js +1 -1
  113. package/src/release-issue-gates.js +190 -0
  114. package/src/release-state.js +30 -1
  115. package/src/runtime/active-autonomy-core.js +208 -0
  116. package/src/runtime/alignment-sentinel.js +165 -0
  117. package/src/runtime/architect-review.js +88 -0
  118. package/src/runtime/build-readiness.js +62 -0
  119. package/src/runtime/code-graph-rehearse.js +113 -0
  120. package/src/runtime/context-economy-core.js +276 -0
  121. package/src/runtime/continuity-notes.js +79 -0
  122. package/src/runtime/core-source-ingest.js +379 -0
  123. package/src/runtime/detached-provider.js +74 -0
  124. package/src/runtime/environment-awareness-core.js +460 -0
  125. package/src/runtime/exposure-catalog.js +276 -0
  126. package/src/runtime/guidance-stack.js +42 -0
  127. package/src/runtime/helper-orchestration-core.js +307 -0
  128. package/src/runtime/learning-loop-core.js +238 -0
  129. package/src/runtime/maestro-events.js +18 -0
  130. package/src/runtime/maestro-manager.js +605 -0
  131. package/src/runtime/maestro-state.js +125 -0
  132. package/src/runtime/mcp-policy.js +192 -0
  133. package/src/runtime/obsidian-integration-core.js +851 -0
  134. package/src/runtime/obsidian-plugin-bridge.js +739 -0
  135. package/src/runtime/orchestrator.js +158 -0
  136. package/src/runtime/prompt-strategy-core.js +230 -0
  137. package/src/runtime/quorum-review.js +90 -0
  138. package/src/runtime/ralph-execution-core.js +217 -0
  139. package/src/runtime/redaction-gateway.js +174 -0
  140. package/src/runtime/runtime-state.js +1223 -0
  141. package/src/runtime/semantic-recording-core.js +147 -0
  142. package/src/runtime/signal-hooks.js +67 -0
  143. package/src/runtime/skills-registry-export.js +670 -0
  144. package/src/runtime/startup-path.js +14 -0
  145. package/src/runtime/universal-plugin-broker-core.js +575 -0
  146. package/src/runtime/workspace-intelligence-runtime.js +674 -0
  147. package/src/runtime/workspace-virtualizer.js +102 -0
  148. package/src/runtime/workspaces.js +25 -0
  149. package/src/runtime-artifacts.js +407 -84
  150. package/src/skill-installer.js +53 -5
  151. package/src/skills.js +1454 -78
  152. package/src/state-sync.js +51 -8
  153. package/docs/qa/release-readiness-0.1.11.md +0 -79
  154. package/plugins/meta-architect/skills/meta-architect/SKILL.md +0 -32
  155. package/plugins/meta-architect/skills/meta-architect/agents/openai.yaml +0 -4
  156. package/skills/meta-architect/SKILL.md +0 -32
  157. package/skills/meta-architect/agents/openai.yaml +0 -4
  158. /package/plugins/meta-architect/skills/{meta-architect → maestro}/references/core-release-rules.md +0 -0
  159. /package/skills/{meta-architect → maestro}/references/core-release-rules.md +0 -0
package/src/skills.js CHANGED
@@ -3,11 +3,55 @@ import path from "node:path";
3
3
  import { appendDecision } from "./decision-log.js";
4
4
  import { readJson, writeFileIfMissing, writeJson } from "./fs-utils.js";
5
5
  import { validateMcpServers } from "./mcp-config.js";
6
- import { McpSseClient } from "./mcp-live-client.js";
6
+ import { createMcpLiveClient, hasConfiguredMcpRemoteBridge } from "./mcp-live-client.js";
7
7
  import { getRepoRoot, getRuntimeReadPath, getRuntimeWritePath, packageRoot } from "./paths.js";
8
+ import {
9
+ evaluateAlignmentDrift,
10
+ saveAlignmentSentinelReport,
11
+ } from "./runtime/alignment-sentinel.js";
12
+ import { evaluateRuntimeBuildReadiness } from "./runtime/build-readiness.js";
13
+ import {
14
+ findIngestedCoreSourceForRepo,
15
+ loadCoreSourceIngest,
16
+ } from "./runtime/core-source-ingest.js";
17
+ import { launchDetachedTrack } from "./runtime/detached-provider.js";
18
+ import {
19
+ scanLockfilePackageExposure,
20
+ validateMcpPolicyExposure,
21
+ } from "./runtime/exposure-catalog.js";
22
+ import { createHelperReceipt } from "./runtime/helper-orchestration-core.js";
23
+ import { appendMaestroEvent } from "./runtime/maestro-events.js";
24
+ import {
25
+ buildHelperFailureMatrix,
26
+ chooseMaestroManagerAction,
27
+ createManagerRun,
28
+ getActiveManagerRun,
29
+ loadManagerRunRegistry,
30
+ saveManagerRunRegistry,
31
+ } from "./runtime/maestro-manager.js";
32
+ import {
33
+ beginMaestroOrchestration,
34
+ loadMaestroStateOrDefault,
35
+ saveMaestroState,
36
+ } from "./runtime/maestro-state.js";
37
+ import { submitTask } from "./runtime/orchestrator.js";
38
+ import {
39
+ createQuorumReviewReceipt,
40
+ evaluateQuorumVotes,
41
+ quorumDecisions,
42
+ } from "./runtime/quorum-review.js";
43
+ import { writeRalphExecutionContract } from "./runtime/ralph-execution-core.js";
44
+ import { redactProviderBoundText, seedRedactionVault } from "./runtime/redaction-gateway.js";
45
+ import {
46
+ assertLeaderAuthority,
47
+ createRuntimeSummary,
48
+ loadRuntimeSnapshot,
49
+ repairRuntimeScratchpadArtifacts,
50
+ } from "./runtime/runtime-state.js";
8
51
  import {
9
52
  seedRuntimeArtifacts,
10
53
  writeArchitectureArtifacts,
54
+ writeBuildPlanArtifact,
11
55
  writeEvidenceSpec,
12
56
  writeExperienceSpec,
13
57
  writeLogicSpec,
@@ -17,10 +61,23 @@ import {
17
61
  } from "./runtime-artifacts.js";
18
62
  import { syncStatusUpdates } from "./state-sync.js";
19
63
 
20
- const skillNames = ["$maestro", "$arch", "$sage", "$flow", "$vet", "$vibe", "$build"];
64
+ const skillNames = [
65
+ "$maestro",
66
+ "$arch",
67
+ "$sage",
68
+ "$flow",
69
+ "$vet",
70
+ "$vibe",
71
+ "$build",
72
+ "$align",
73
+ "$diagnose",
74
+ "$tdd",
75
+ "$cleanup",
76
+ ];
77
+ const maestroWorkflowSequence = ["$arch", "$sage", "$flow", "$vet", "$vibe", "$build"];
21
78
  const workflowTemplates = {
22
79
  "maestro.skill.md":
23
- "# `$maestro`\n\nChooses the best next workflow step and recommends the right lane or assignment.\n",
80
+ "# `$maestro`\n\nThe singular Meta-Architect umbrella workflow. Inspect runtime state, execute bounded helper or gated work when it is safe, persist the manager-run control plane, and return the exact next trigger.\n",
24
81
  "arch.skill.md":
25
82
  "# `$arch`\n\nProduces blueprint architecture, stack rationale, subsystem design, and tradeoffs.\n",
26
83
  "sage.skill.md":
@@ -30,6 +87,14 @@ const workflowTemplates = {
30
87
  "vibe.skill.md":
31
88
  "# `$vibe`\n\nReviews developer and user experience risks before build execution.\n",
32
89
  "build.skill.md": "# `$build`\n\nChecks gates and plans bounded build execution.\n",
90
+ "align.skill.md":
91
+ "# `$align`\n\nHelper skill for scope alignment, shared language, and docs clarity. Non-gating.\n",
92
+ "diagnose.skill.md":
93
+ "# `$diagnose`\n\nHelper skill for blocked-lane diagnosis and root-cause slicing. Non-gating.\n",
94
+ "tdd.skill.md":
95
+ "# `$tdd`\n\nHelper skill for regression-first or test-first preparation. Non-gating.\n",
96
+ "cleanup.skill.md":
97
+ "# `$cleanup`\n\nHelper skill for simplification, anti-slop cleanup, and final-pass polish. Non-gating.\n",
33
98
  "sync.skill.md":
34
99
  "# `$sync`\n\nReserved for refreshing mapped MCP sources and availability records.\n",
35
100
  };
@@ -38,7 +103,7 @@ export function listSkills() {
38
103
  return skillNames;
39
104
  }
40
105
 
41
- function chooseMaestroRecommendation(releaseState, idea) {
106
+ function chooseMaestroRecommendation(releaseState, idea, buildReadiness = null) {
42
107
  if (releaseState.idea_status !== "CLEAR") {
43
108
  return {
44
109
  nextStep: "Capture or refine the project brief before any design or validation lane starts.",
@@ -127,6 +192,21 @@ function chooseMaestroRecommendation(releaseState, idea) {
127
192
  }
128
193
 
129
194
  if (releaseState.build_status === "LOCKED") {
195
+ if (buildReadiness && buildReadiness.releaseBlockers.length === 0 && !buildReadiness.allowed) {
196
+ return {
197
+ nextStep: "Repair runtime artifacts before bounded build planning can unlock.",
198
+ why: "The release gates are green, but runtime artifacts or pending mailbox proposals are still blocking build readiness.",
199
+ primaryLane: "runtime repair",
200
+ supportLane: "$build",
201
+ assignments: [
202
+ "Repair the listed runtime blockers first.",
203
+ "Re-run $build only after runtime blockers are cleared.",
204
+ ],
205
+ avoid: ["Do not unlock bounded implementation planning while runtime blockers remain."],
206
+ nextTrigger: "`repair runtime artifacts`",
207
+ };
208
+ }
209
+
130
210
  return {
131
211
  nextStep: "Unlock bounded implementation planning.",
132
212
  why: "All upstream quality gates are green, so the workflow can now evaluate build readiness.",
@@ -141,6 +221,35 @@ function chooseMaestroRecommendation(releaseState, idea) {
141
221
  };
142
222
  }
143
223
 
224
+ if (releaseState.build_status === "READY") {
225
+ return {
226
+ nextStep: "Start the bounded build execution substep.",
227
+ why: "The build lane has prepared a narrow slice and verification plan, and the next safe move is to begin that bounded substep.",
228
+ primaryLane: "$build",
229
+ supportLane: "implementation",
230
+ assignments: [
231
+ "Run $build again to move the bounded build slice into active execution.",
232
+ "Keep the slice reversible and lane-owned.",
233
+ ],
234
+ avoid: ["Do not merge or release before the bounded build slice is complete."],
235
+ nextTrigger: "`$build`",
236
+ };
237
+ }
238
+
239
+ if (releaseState.build_status === "RUNNING") {
240
+ return {
241
+ nextStep: "Finalize the bounded build execution substep.",
242
+ why: "The build lane is already running its bounded slice and now needs completion evidence before downstream promotion.",
243
+ primaryLane: "$build",
244
+ supportLane: "verification",
245
+ assignments: [
246
+ "Run $build again to finalize the bounded build substep and persist completion evidence.",
247
+ ],
248
+ avoid: ["Do not merge or release before the build lane records DONE."],
249
+ nextTrigger: "`$build`",
250
+ };
251
+ }
252
+
144
253
  if (releaseState.merge_status !== "MERGED_TO_DEVELOPMENT") {
145
254
  return {
146
255
  nextStep: "Finish the implementation slice and merge it into development.",
@@ -188,7 +297,681 @@ async function readIdeaText() {
188
297
  return ideaDecision?.idea ?? null;
189
298
  }
190
299
 
300
+ async function readRuntimeSummary() {
301
+ const runtimeSnapshot = await loadRuntimeSnapshot();
302
+ return createRuntimeSummary(runtimeSnapshot);
303
+ }
304
+
305
+ function assertControlPlaneReady(runtimeSummary) {
306
+ const blockingInvalidArtifacts = runtimeSummary.invalidArtifacts.filter((artifact) =>
307
+ ["runtime.release", "runtime.decisions"].includes(artifact),
308
+ );
309
+ const blockingMissingArtifacts = runtimeSummary.missingArtifacts.filter(
310
+ (artifact) => artifact === "runtime.decisions" || artifact === "runtime.release",
311
+ );
312
+
313
+ const blockingArtifacts = [...blockingInvalidArtifacts, ...blockingMissingArtifacts];
314
+ if (blockingArtifacts.length > 0) {
315
+ throw new Error(`Invalid runtime artifacts: ${blockingArtifacts.join(", ")}`);
316
+ }
317
+ }
318
+
319
+ function getManagerDecisionStatus(managerRun) {
320
+ return managerRun.state.toUpperCase().replaceAll("-", "_");
321
+ }
322
+
323
+ function stripBackticks(value) {
324
+ return value.replaceAll("`", "");
325
+ }
326
+
327
+ function isGitMcpDocumentationTool(tool, action) {
328
+ if (!tool || typeof tool.name !== "string") {
329
+ return false;
330
+ }
331
+ if (!tool.name.startsWith(`${action}_`)) {
332
+ return false;
333
+ }
334
+ if (tool.name === "fetch_generic_url_content") {
335
+ return false;
336
+ }
337
+
338
+ const lowerName = tool.name.toLowerCase();
339
+ return (
340
+ lowerName.includes("_documentation") ||
341
+ lowerName.includes("_docs") ||
342
+ `${tool.description ?? ""}`.toLowerCase().includes("documentation")
343
+ );
344
+ }
345
+
346
+ function createBoundedBuildSlice() {
347
+ return [
348
+ "Create or confirm the bounded implementation and verification slice for the current release-ready state.",
349
+ "Keep the slice reversible and owned by the $build lane.",
350
+ ];
351
+ }
352
+
353
+ function createBuildVerificationPlan(nextTrigger = "$build") {
354
+ return [
355
+ "Confirm release gates and runtime control-plane artifacts are still green.",
356
+ `Use ${nextTrigger} as the bounded verification loop trigger for the current build slice.`,
357
+ ];
358
+ }
359
+
360
+ function createBuildRepairPath() {
361
+ return [
362
+ "If the bounded build slice becomes invalid without upstream gate regression, return to READY and rerun `$build`.",
363
+ "If runtime or upstream gates regress, fail closed and repair those blockers before resuming.",
364
+ ];
365
+ }
366
+
367
+ async function updateMaestroLedgerForBuild({
368
+ buildStatus,
369
+ runtimeSummary,
370
+ blockers,
371
+ nextTriggers,
372
+ gateState,
373
+ trackStatus,
374
+ completionEvidence = [],
375
+ }) {
376
+ let maestroState = await loadMaestroStateOrDefault();
377
+ maestroState = beginMaestroOrchestration(maestroState, {
378
+ globalStatus: gateState,
379
+ });
380
+ maestroState.runtime_tracks.track_0_sync = {
381
+ active_gate: "$build",
382
+ status: trackStatus,
383
+ pid: null,
384
+ execution_pane: null,
385
+ exit_code: trackStatus === "COMPLETED" ? 0 : null,
386
+ blockers,
387
+ next_triggers: nextTriggers,
388
+ completion_evidence: completionEvidence,
389
+ build_status: buildStatus,
390
+ updated_at: new Date().toISOString(),
391
+ runtime_summary: {
392
+ pendingMailboxCount: runtimeSummary.pendingMailboxCount,
393
+ invalidArtifacts: runtimeSummary.invalidArtifacts,
394
+ missingArtifacts: runtimeSummary.missingArtifacts,
395
+ },
396
+ };
397
+ maestroState.downstream_lock_table.$build = {
398
+ is_locked: buildStatus !== "DONE",
399
+ locked_by: buildStatus === "DONE" ? [] : ["$build"],
400
+ unlock_criteria: "build_status == 'DONE'",
401
+ };
402
+ maestroState.timestamp = new Date().toISOString();
403
+ maestroState.global_status = gateState;
404
+ await saveMaestroState(maestroState);
405
+ await appendMaestroEvent({
406
+ record_type: "runtime:track_status",
407
+ gate: "$build",
408
+ global_status: gateState,
409
+ track_status: trackStatus,
410
+ build_status: buildStatus,
411
+ next_triggers: nextTriggers,
412
+ blockers,
413
+ });
414
+ await appendMaestroEvent({
415
+ record_type: "lock:downstream_circuit_breaker",
416
+ target_gate: "$build",
417
+ is_locked: buildStatus !== "DONE",
418
+ locked_by: buildStatus === "DONE" ? [] : ["$build"],
419
+ unlock_criteria: "build_status == 'DONE'",
420
+ });
421
+ }
422
+
423
+ async function updateScratchpadTrackForLane({
424
+ gate,
425
+ trackStatus,
426
+ globalStatus,
427
+ blockers = [],
428
+ nextTriggers = [],
429
+ detached = null,
430
+ details = {},
431
+ }) {
432
+ let maestroState = await loadMaestroStateOrDefault();
433
+ maestroState = beginMaestroOrchestration(maestroState, {
434
+ globalStatus,
435
+ });
436
+ const trackKey = `track_${gate.replaceAll("$", "")}_sync`;
437
+ maestroState.runtime_tracks[trackKey] = {
438
+ active_gate: gate,
439
+ status: trackStatus,
440
+ pid: null,
441
+ execution_pane: detached?.executionPane ?? null,
442
+ provider: detached?.provider ?? "none",
443
+ log_path: detached?.logPath ?? null,
444
+ exit_code: trackStatus === "COMPLETED" ? 0 : null,
445
+ blockers,
446
+ next_triggers: nextTriggers,
447
+ updated_at: new Date().toISOString(),
448
+ ...details,
449
+ };
450
+ maestroState.timestamp = new Date().toISOString();
451
+ maestroState.global_status = globalStatus;
452
+ await saveMaestroState(maestroState);
453
+ await appendMaestroEvent({
454
+ record_type: "runtime:track_status",
455
+ gate,
456
+ global_status: globalStatus,
457
+ track_status: trackStatus,
458
+ next_triggers: nextTriggers,
459
+ blockers,
460
+ provider: detached?.provider ?? "none",
461
+ });
462
+ }
463
+
464
+ export async function runBuildLane({ actor = null, reviewMode = null, quorumVotes = [] } = {}) {
465
+ const authority = await assertLeaderAuthority(actor);
466
+ const runtimeSnapshot = await loadRuntimeSnapshot();
467
+ const runtimeSummary = createRuntimeSummary(runtimeSnapshot);
468
+ const evaluation = evaluateRuntimeBuildReadiness(runtimeSnapshot.release, runtimeSummary);
469
+
470
+ if (evaluation.controlPlaneBlockers.length > 0) {
471
+ throw new Error(`Invalid runtime artifacts: ${evaluation.controlPlaneBlockers.join(", ")}`);
472
+ }
473
+
474
+ if (!evaluation.allowed) {
475
+ await writeBuildPlanArtifact({
476
+ allowed: false,
477
+ gateState: "LOCKED",
478
+ blockers: evaluation.blockers,
479
+ nextTriggers: evaluation.nextTriggers,
480
+ buildSlice: createBoundedBuildSlice(),
481
+ verificationPlan: createBuildVerificationPlan("`$build`"),
482
+ repairPath: createBuildRepairPath(),
483
+ runtimeSummary,
484
+ });
485
+ await updateMaestroLedgerForBuild({
486
+ buildStatus: runtimeSnapshot.release.build_status,
487
+ runtimeSummary,
488
+ blockers: evaluation.blockers,
489
+ nextTriggers: evaluation.nextTriggers,
490
+ gateState: "LOCKED",
491
+ trackStatus: "BLOCKED",
492
+ });
493
+ await appendDecision({
494
+ actor: authority.leaderActor,
495
+ kind: "skill",
496
+ skill: "$build",
497
+ decision: "Build execution remains locked under the current runtime and release state.",
498
+ status: "BLOCKED",
499
+ evidence: [{ kind: "runtime-summary", value: runtimeSummary }],
500
+ blockers: evaluation.blockers,
501
+ next_allowed_triggers: evaluation.nextTriggers,
502
+ });
503
+ return {
504
+ status: "BLOCKED",
505
+ nextTrigger: evaluation.nextTriggers[0] ?? "$build",
506
+ blockers: evaluation.blockers,
507
+ };
508
+ }
509
+
510
+ const suggestedBranches = ["feature/implementation", "feature/verification"];
511
+ const buildSlice = createBoundedBuildSlice();
512
+ const verificationPlan = createBuildVerificationPlan("`$build`");
513
+ const repairPath = createBuildRepairPath();
514
+ const ralphContract = await writeRalphExecutionContract({
515
+ buildSlice,
516
+ verificationPlan,
517
+ runtimeSummary,
518
+ });
519
+
520
+ if (runtimeSnapshot.release.build_status === "LOCKED") {
521
+ await writeBuildPlanArtifact({
522
+ allowed: true,
523
+ gateState: "READY",
524
+ blockers: [],
525
+ nextTriggers: ["$build"],
526
+ suggestedBranches,
527
+ buildSlice,
528
+ verificationPlan,
529
+ repairPath,
530
+ runtimeSummary,
531
+ });
532
+ await appendDecision({
533
+ actor: authority.leaderActor,
534
+ kind: "skill",
535
+ skill: "$build",
536
+ decision: "Build gate ready",
537
+ status: "READY",
538
+ evidence: [
539
+ { kind: "runtime-summary", value: runtimeSummary },
540
+ { kind: "branches", value: suggestedBranches },
541
+ { kind: "build-slice", value: buildSlice },
542
+ { kind: "ralph-prd", value: ralphContract.prdPath },
543
+ ],
544
+ blockers: [],
545
+ next_allowed_triggers: ["$build"],
546
+ });
547
+ await syncStatusUpdates({ build_status: "READY" }, { actor: authority.leaderActor });
548
+ await updateMaestroLedgerForBuild({
549
+ buildStatus: "READY",
550
+ runtimeSummary,
551
+ blockers: [],
552
+ nextTriggers: ["$build"],
553
+ gateState: "READY",
554
+ trackStatus: "READY",
555
+ });
556
+ return {
557
+ status: "READY",
558
+ nextTrigger: "$build",
559
+ blockers: [],
560
+ suggestedBranches,
561
+ };
562
+ }
563
+
564
+ if (runtimeSnapshot.release.build_status === "READY") {
565
+ await writeBuildPlanArtifact({
566
+ allowed: true,
567
+ gateState: "RUNNING",
568
+ blockers: [],
569
+ nextTriggers: ["$build"],
570
+ suggestedBranches,
571
+ buildSlice,
572
+ verificationPlan,
573
+ repairPath,
574
+ runtimeSummary,
575
+ });
576
+ await appendDecision({
577
+ actor: authority.leaderActor,
578
+ kind: "skill",
579
+ skill: "$build",
580
+ decision: "Started the bounded build execution substep",
581
+ status: "RUNNING",
582
+ evidence: [
583
+ { kind: "runtime-summary", value: runtimeSummary },
584
+ { kind: "build-slice", value: buildSlice },
585
+ { kind: "verification-plan", value: verificationPlan },
586
+ { kind: "ralph-prd", value: ralphContract.prdPath },
587
+ ],
588
+ blockers: [],
589
+ next_allowed_triggers: ["$build"],
590
+ });
591
+ await syncStatusUpdates({ build_status: "RUNNING" }, { actor: authority.leaderActor });
592
+ await updateMaestroLedgerForBuild({
593
+ buildStatus: "RUNNING",
594
+ runtimeSummary,
595
+ blockers: [],
596
+ nextTriggers: ["$build"],
597
+ gateState: "RUNNING",
598
+ trackStatus: "RUNNING",
599
+ });
600
+ return {
601
+ status: "RUNNING",
602
+ nextTrigger: "$build",
603
+ blockers: [],
604
+ suggestedBranches,
605
+ };
606
+ }
607
+
608
+ const completionEvidence = [
609
+ "Build slice remained release-ready through the bounded verification substep.",
610
+ "Runtime control-plane artifacts remained valid at completion.",
611
+ ];
612
+ if (reviewMode === "quorum") {
613
+ const quorum = evaluateQuorumVotes(quorumVotes);
614
+ const quorumReceipt = createQuorumReviewReceipt({ votes: quorumVotes, evaluation: quorum });
615
+ if (quorum.decision !== quorumDecisions.APPROVED) {
616
+ await writeBuildPlanArtifact({
617
+ allowed: true,
618
+ gateState: "READY",
619
+ blockers: quorum.blockers,
620
+ nextTriggers: ["$build"],
621
+ suggestedBranches,
622
+ buildSlice,
623
+ verificationPlan: [
624
+ ...verificationPlan,
625
+ "Resolve quorum disagreement or provide a compatible majority fingerprint before promotion.",
626
+ ],
627
+ repairPath,
628
+ runtimeSummary,
629
+ });
630
+ await appendDecision({
631
+ actor: authority.leaderActor,
632
+ kind: "skill",
633
+ skill: "$build",
634
+ decision: "Quorum review did not approve the current bounded build slice",
635
+ status: "READY",
636
+ evidence: [
637
+ { kind: "runtime-summary", value: runtimeSummary },
638
+ { kind: "quorum-votes", value: quorumVotes },
639
+ { kind: "quorum-decision", value: quorum },
640
+ { kind: "quorum-receipt", value: quorumReceipt },
641
+ { kind: "ralph-prd", value: ralphContract.prdPath },
642
+ ],
643
+ blockers: quorum.blockers,
644
+ next_allowed_triggers: ["$build"],
645
+ });
646
+ await syncStatusUpdates({ build_status: "READY" }, { actor: authority.leaderActor });
647
+ await updateMaestroLedgerForBuild({
648
+ buildStatus: "READY",
649
+ runtimeSummary,
650
+ blockers: quorum.blockers,
651
+ nextTriggers: ["$build"],
652
+ gateState: "READY",
653
+ trackStatus: "BLOCKED",
654
+ completionEvidence: ["Quorum review returned INDETERMINATE or non-approval."],
655
+ });
656
+ return {
657
+ status: "READY",
658
+ nextTrigger: "$build",
659
+ blockers: quorum.blockers,
660
+ suggestedBranches,
661
+ };
662
+ }
663
+ completionEvidence.push(
664
+ "Quorum review approved the bounded build slice with a majority-compatible fingerprint.",
665
+ );
666
+ completionEvidence.push(
667
+ `Quorum confidence receipt recorded with ${quorumReceipt.reviewer_count} reviewers.`,
668
+ );
669
+ }
670
+ await writeBuildPlanArtifact({
671
+ allowed: true,
672
+ gateState: "DONE",
673
+ blockers: [],
674
+ nextTriggers: ["ma merge <feature/*> development"],
675
+ suggestedBranches,
676
+ buildSlice,
677
+ verificationPlan,
678
+ repairPath,
679
+ completionEvidence,
680
+ runtimeSummary,
681
+ });
682
+ await appendDecision({
683
+ actor: authority.leaderActor,
684
+ kind: "skill",
685
+ skill: "$build",
686
+ decision: "Completed the bounded build execution substep",
687
+ status: "DONE",
688
+ evidence: [
689
+ { kind: "runtime-summary", value: runtimeSummary },
690
+ { kind: "branches", value: suggestedBranches },
691
+ { kind: "completion-evidence", value: completionEvidence },
692
+ { kind: "ralph-prd", value: ralphContract.prdPath },
693
+ ],
694
+ blockers: [],
695
+ next_allowed_triggers: ["ma merge <feature/*> development"],
696
+ });
697
+ await syncStatusUpdates({ build_status: "DONE" }, { actor: authority.leaderActor });
698
+ await updateMaestroLedgerForBuild({
699
+ buildStatus: "DONE",
700
+ runtimeSummary,
701
+ blockers: [],
702
+ nextTriggers: ["ma merge <feature/*> development"],
703
+ gateState: "COMPLETED",
704
+ trackStatus: "COMPLETED",
705
+ completionEvidence,
706
+ });
707
+ return {
708
+ status: "DONE",
709
+ nextTrigger: "ma merge <feature/*> development",
710
+ blockers: [],
711
+ suggestedBranches,
712
+ };
713
+ }
714
+
715
+ function getAutonomousGateRunners() {
716
+ return {
717
+ $arch: runArch,
718
+ $sage: runSage,
719
+ $flow: runFlow,
720
+ $vet: runVet,
721
+ $vibe: runVibe,
722
+ $build: runBuildLane,
723
+ };
724
+ }
725
+
726
+ function updateManagerRunTimestamps(managerRun, overrides = {}) {
727
+ const now = new Date().toISOString();
728
+ Object.assign(managerRun, overrides, { updatedAt: now });
729
+ if (["completed", "blocked", "failed", "cancelled"].includes(managerRun.state)) {
730
+ managerRun.completedAt ??= now;
731
+ }
732
+ }
733
+
734
+ function buildManagerDecisionEvidence(managerRun, recommendation) {
735
+ return [
736
+ {
737
+ runId: managerRun.id,
738
+ mode: managerRun.mode,
739
+ state: managerRun.state,
740
+ nextAction: managerRun.nextAction,
741
+ helperRuns: managerRun.helperRuns.map((helper) => ({
742
+ id: helper.id,
743
+ skill: helper.skill,
744
+ status: helper.status,
745
+ objective: helper.objective,
746
+ })),
747
+ dispatchPlan: {
748
+ helpers: managerRun.dispatchPlan.helpers.map((helper) => ({
749
+ skill: helper.skill,
750
+ objective: helper.objective,
751
+ })),
752
+ gated: managerRun.dispatchPlan.gated.map((gate) => ({
753
+ skill: gate.skill,
754
+ objective: gate.objective,
755
+ status: gate.status,
756
+ })),
757
+ team: managerRun.dispatchPlan.team
758
+ ? {
759
+ title: managerRun.dispatchPlan.team.title,
760
+ createdTaskIds: managerRun.dispatchPlan.team.createdTaskIds,
761
+ }
762
+ : null,
763
+ },
764
+ },
765
+ recommendation,
766
+ ];
767
+ }
768
+
769
+ function buildManagerDecisionBlockers(managerRun, runtimeSummary, buildReadiness) {
770
+ const blockers = [];
771
+ if (managerRun.state === "waiting-review" && managerRun.pendingReview.proposalPath) {
772
+ blockers.push(`Manager run is waiting for review at ${managerRun.pendingReview.proposalPath}.`);
773
+ }
774
+ if (managerRun.state === "blocked" && managerRun.retry.lastReason) {
775
+ blockers.push(managerRun.retry.lastReason);
776
+ }
777
+ if (
778
+ buildReadiness &&
779
+ !buildReadiness.allowed &&
780
+ buildReadiness.nextTriggers.includes("repair runtime artifacts")
781
+ ) {
782
+ blockers.push(...buildReadiness.runtimeBlockers);
783
+ }
784
+ if (runtimeSummary.pendingMailboxCount > 0) {
785
+ blockers.push("Pending mailbox proposals require leader review.");
786
+ }
787
+
788
+ return [...new Set(blockers)];
789
+ }
790
+
791
+ function executeManagerHelper(helper, { releaseState, runtimeSummary, recommendation }) {
792
+ const baseReceipt = ({ observedContext, result, nextTrigger }) => ({
793
+ helperId: helper.id,
794
+ ...createHelperReceipt({
795
+ skill: helper.skill,
796
+ objective: helper.objective,
797
+ observedContext,
798
+ result,
799
+ nextTrigger: nextTrigger ?? recommendation.nextTrigger ?? "$maestro",
800
+ }),
801
+ });
802
+
803
+ if (helper.skill === "$align") {
804
+ return {
805
+ ...baseReceipt({
806
+ observedContext: `build_status=${releaseState.build_status}; next=${recommendation.nextTrigger}`,
807
+ result: "Normalized the manager handoff around the current lane sequence and next trigger.",
808
+ }),
809
+ workflowSequence: maestroWorkflowSequence,
810
+ currentBuildStatus: releaseState.build_status,
811
+ recommendedNextTrigger: recommendation.nextTrigger,
812
+ };
813
+ }
814
+
815
+ if (helper.skill === "$diagnose") {
816
+ return {
817
+ ...baseReceipt({
818
+ observedContext: `pending_mailbox=${runtimeSummary.pendingMailboxCount}; invalid_artifacts=${runtimeSummary.invalidArtifacts.length}; missing_artifacts=${runtimeSummary.missingArtifacts.length}`,
819
+ result: "Captured the smallest blocker slices before the manager resumes gated work.",
820
+ }),
821
+ pendingMailboxCount: runtimeSummary.pendingMailboxCount,
822
+ invalidArtifacts: runtimeSummary.invalidArtifacts,
823
+ missingArtifacts: runtimeSummary.missingArtifacts,
824
+ };
825
+ }
826
+
827
+ if (helper.skill === "$tdd") {
828
+ return {
829
+ ...baseReceipt({
830
+ observedContext: `build_status=${releaseState.build_status}; next=${recommendation.nextTrigger}`,
831
+ result: "Defined the regression-first boundary for the owning implementation lane.",
832
+ }),
833
+ buildStatus: releaseState.build_status,
834
+ nextTrigger: recommendation.nextTrigger,
835
+ };
836
+ }
837
+
838
+ if (helper.skill === "$cleanup") {
839
+ return {
840
+ ...baseReceipt({
841
+ observedContext: `merge_status=${releaseState.merge_status}; release_status=${releaseState.release_status}`,
842
+ result: "Prepared contract-preserving simplification without changing release authority.",
843
+ }),
844
+ mergeStatus: releaseState.merge_status,
845
+ releaseStatus: releaseState.release_status,
846
+ };
847
+ }
848
+
849
+ return {
850
+ helperId: helper.id,
851
+ kind: "manager-helper",
852
+ objective: helper.objective,
853
+ };
854
+ }
855
+
856
+ async function executeManagerHelpers({
857
+ registry,
858
+ managerRun,
859
+ releaseState,
860
+ runtimeSummary,
861
+ recommendation,
862
+ helperFailureMatrix,
863
+ }) {
864
+ const startedAt = new Date().toISOString();
865
+ updateManagerRunTimestamps(managerRun, { state: "running" });
866
+ for (const helperRun of managerRun.helperRuns) {
867
+ helperRun.status = "running";
868
+ helperRun.startedAt = startedAt;
869
+ }
870
+ await saveManagerRunRegistry(registry);
871
+
872
+ const results = await Promise.allSettled(
873
+ managerRun.helperRuns.map(async (helperRun) => {
874
+ const evidence = executeManagerHelper(helperRun, {
875
+ releaseState,
876
+ runtimeSummary,
877
+ recommendation,
878
+ });
879
+ return { helperRun, evidence };
880
+ }),
881
+ );
882
+
883
+ const continuedHelpers = [];
884
+ let hadFailure = false;
885
+ for (const result of results) {
886
+ const helperRun =
887
+ result.status === "fulfilled"
888
+ ? result.value.helperRun
889
+ : managerRun.helperRuns[results.indexOf(result)];
890
+
891
+ if (result.status === "fulfilled") {
892
+ helperRun.status = "completed";
893
+ helperRun.evidence.push(result.value.evidence);
894
+ helperRun.completedAt = new Date().toISOString();
895
+ continuedHelpers.push(helperRun.skill);
896
+ continue;
897
+ }
898
+
899
+ hadFailure = true;
900
+ const policy = helperFailureMatrix.helper_failed_but_manager_can_fall_back_to_safe_summary;
901
+ helperRun.status = "failed";
902
+ helperRun.errorClass = "helper_failed_but_manager_can_fall_back_to_safe_summary";
903
+ helperRun.errorMessage = result.reason?.message ?? String(result.reason);
904
+ helperRun.completedAt = new Date().toISOString();
905
+ helperRun.evidence.push({
906
+ runId: managerRun.id,
907
+ helperId: helperRun.id,
908
+ skill: helperRun.skill,
909
+ objective: helperRun.objective,
910
+ degradedReason: helperRun.errorMessage,
911
+ safeNextTrigger: recommendation.nextTrigger,
912
+ siblingHelperPolicy: policy.siblingHelperPolicy,
913
+ continuedHelpers,
914
+ });
915
+ }
916
+
917
+ if (hadFailure) {
918
+ updateManagerRunTimestamps(managerRun, {
919
+ state: "completed",
920
+ retry: {
921
+ count: managerRun.retry.count + 1,
922
+ lastReason: "One or more helper runs degraded to recommendation-only behavior.",
923
+ },
924
+ });
925
+ await saveManagerRunRegistry(registry);
926
+ return false;
927
+ }
928
+
929
+ await saveManagerRunRegistry(registry);
930
+ return true;
931
+ }
932
+
933
+ async function executeManagerTeamDispatch(registry, managerRun) {
934
+ const teamPlan = managerRun.dispatchPlan.team;
935
+ if (!teamPlan) {
936
+ return;
937
+ }
938
+
939
+ const taskResult = await submitTask({
940
+ title: teamPlan.title,
941
+ owner: "leader",
942
+ metadata: {
943
+ classification: "durable-team-task",
944
+ managerOwner: "$maestro",
945
+ managerRunId: managerRun.id,
946
+ objective: teamPlan.objective,
947
+ verificationOwner: teamPlan.verificationOwner,
948
+ launchHints: teamPlan.launchHints,
949
+ staffing: teamPlan.staffing,
950
+ },
951
+ });
952
+
953
+ if (taskResult.proposed) {
954
+ updateManagerRunTimestamps(managerRun, {
955
+ state: "waiting-review",
956
+ pendingReview: {
957
+ proposalPath: taskResult.proposalPath,
958
+ mailboxOwner: "leader",
959
+ resumeTrigger: "Review the queued team task proposal, then rerun `$maestro`.",
960
+ },
961
+ });
962
+ await saveManagerRunRegistry(registry);
963
+ return;
964
+ }
965
+
966
+ teamPlan.createdTaskIds.push(taskResult.task.id);
967
+ updateManagerRunTimestamps(managerRun, { state: "running" });
968
+ await saveManagerRunRegistry(registry);
969
+ }
970
+
191
971
  export async function runIdea(idea) {
972
+ const runtimeSummary = await readRuntimeSummary();
973
+ assertControlPlaneReady(runtimeSummary);
974
+ await assertLeaderAuthority();
192
975
  const trimmed = idea.trim();
193
976
  if (!trimmed) {
194
977
  throw new Error("Idea text is required");
@@ -203,25 +986,45 @@ export async function runIdea(idea) {
203
986
  status: "CLEAR",
204
987
  evidence: [{ kind: "user-input", value: trimmed }],
205
988
  blockers: [],
206
- next_allowed_triggers: ["$arch"],
989
+ next_allowed_triggers: ["$maestro"],
207
990
  });
208
991
 
209
992
  await syncStatusUpdates({ idea_status: "CLEAR" });
210
993
  }
211
994
 
212
995
  export async function runArch() {
996
+ await assertLeaderAuthority();
997
+ const runtimeSummary = await readRuntimeSummary();
998
+ assertControlPlaneReady(runtimeSummary);
213
999
  const idea = await readIdeaText();
214
1000
  if (!idea) {
215
1001
  throw new Error("Cannot run $arch before ma idea captures a project brief");
216
1002
  }
217
1003
 
218
1004
  const blueprint = {
219
- summary: `Blueprint derived from idea: ${idea}`,
220
- suggestedStack: ["Node.js", "MCP", "GitMCP", "Git worktree"],
221
- outcome: "Produce a gated architecture and implementation plan",
1005
+ decision: "Approve the first bounded architecture direction.",
1006
+ status: "APPROVED",
1007
+ summary: `Blueprint derived from idea: ${idea}. Runtime shell currently exposes ${runtimeSummary.workerCount} workers, ${runtimeSummary.workspaceCount} workspaces, and ${runtimeSummary.guidanceSourceCount} guidance sources.`,
1008
+ suggestedStack: ["Node.js", "MCP", "GitMCP", "Git worktree", "File-backed runtime state"],
1009
+ workloadAssumptions: [
1010
+ "single-repo operator workflow",
1011
+ "gate-driven release discipline",
1012
+ "file-backed runtime state",
1013
+ ],
1014
+ rejectedAlternatives: [
1015
+ "Standalone second umbrella runtime surface because it would weaken Meta-Architect ownership.",
1016
+ ],
1017
+ evidence: [
1018
+ `Workers detected: ${runtimeSummary.workerCount}`,
1019
+ `Workspaces detected: ${runtimeSummary.workspaceCount}`,
1020
+ `Guidance sources detected: ${runtimeSummary.guidanceSourceCount}`,
1021
+ ],
1022
+ blockers: [],
1023
+ nextAllowedTriggers: ["`$sage`"],
1024
+ outcome: "Produce a gated architecture and implementation plan backed by runtime state.",
222
1025
  };
223
1026
 
224
- await writeArchitectureArtifacts({ idea, blueprint });
1027
+ await writeArchitectureArtifacts({ idea, blueprint, runtimeSummary });
225
1028
 
226
1029
  await appendDecision({
227
1030
  kind: "skill",
@@ -234,75 +1037,143 @@ export async function runArch() {
234
1037
  });
235
1038
 
236
1039
  await syncStatusUpdates({ architecture_status: "APPROVED" });
1040
+ await updateScratchpadTrackForLane({
1041
+ gate: "$arch",
1042
+ trackStatus: "COMPLETED",
1043
+ globalStatus: "COMPLETED",
1044
+ nextTriggers: ["$sage"],
1045
+ details: {
1046
+ decision: blueprint.decision,
1047
+ rejected_alternatives: blueprint.rejectedAlternatives,
1048
+ },
1049
+ });
237
1050
  }
238
1051
 
239
1052
  export async function runSage() {
1053
+ await assertLeaderAuthority();
240
1054
  const config = await validateMcpServers();
1055
+ const runtimeSummary = await readRuntimeSummary();
1056
+ assertControlPlaneReady(runtimeSummary);
1057
+ await seedRedactionVault();
1058
+ const disableLiveProbe = process.env.MA_DISABLE_LIVE_MCP === "1";
241
1059
  const sourceEntries = config.servers.map((server) => ({
242
1060
  repo: server.repo,
243
1061
  endpoint: server.endpoint,
244
1062
  category: server.category,
1063
+ exactUpstreamMapping: server.repo,
1064
+ evidenceGrade: disableLiveProbe ? "PARTIAL" : "MISSING",
245
1065
  }));
246
1066
  const blockers = [];
247
1067
  const idea = (await readIdeaText()) ?? "software architecture";
248
- const disableLiveProbe = process.env.MA_DISABLE_LIVE_MCP === "1";
249
- const probeCandidates = sourceEntries.slice(0, 1);
250
- let liveSuccessCount = 0;
1068
+ let verificationSuccessCount = 0;
1069
+ let coreSourceIngest = null;
1070
+ try {
1071
+ coreSourceIngest = await loadCoreSourceIngest();
1072
+ } catch {
1073
+ coreSourceIngest = null;
1074
+ }
251
1075
 
252
1076
  for (const source of sourceEntries) {
253
- if (disableLiveProbe) {
1077
+ const ingestedSource = findIngestedCoreSourceForRepo(coreSourceIngest, source.repo);
1078
+ if (ingestedSource) {
1079
+ source.localSourceSnapshot = {
1080
+ status: ingestedSource.status,
1081
+ localPath: ingestedSource.local_path,
1082
+ capability: ingestedSource.capability,
1083
+ semanticRole: ingestedSource.semantic_role,
1084
+ fileCount: ingestedSource.file_count,
1085
+ contentSha256: ingestedSource.content_sha256,
1086
+ gitCommit: ingestedSource.git_commit,
1087
+ sampledFiles: ingestedSource.sampled_files,
1088
+ };
254
1089
  source.liveProbe = {
255
- skipped: true,
256
- reason: "MA_DISABLE_LIVE_MCP=1",
1090
+ transport: "local-core-source-ingest",
1091
+ queryMode: "local-snapshot",
1092
+ sampleText: ingestedSource.sample_text?.slice(0, 400) ?? null,
257
1093
  };
1094
+ source.evidenceGrade = "VERIFIED";
1095
+ verificationSuccessCount += 1;
258
1096
  continue;
259
1097
  }
260
1098
 
261
- if (!probeCandidates.includes(source)) {
1099
+ if (disableLiveProbe) {
262
1100
  source.liveProbe = {
263
1101
  skipped: true,
264
- reason: "Not selected for the live probe set in this run",
1102
+ reason: "MA_DISABLE_LIVE_MCP=1",
265
1103
  };
266
1104
  continue;
267
1105
  }
268
1106
 
269
- const client = new McpSseClient(source.endpoint);
1107
+ const client = createMcpLiveClient(source.endpoint);
270
1108
  try {
271
1109
  const init = await client.connect();
272
1110
  const tools = await client.request("tools/list", {});
273
- const searchTool = tools.tools?.find(
274
- (tool) => tool.name.includes("search_") && tool.name.endsWith("_documentation"),
275
- );
276
- const fetchTool = tools.tools?.find(
277
- (tool) => tool.name.includes("fetch_") && tool.name.endsWith("_documentation"),
278
- );
1111
+ const searchTool = tools.tools?.find((tool) => isGitMcpDocumentationTool(tool, "search"));
1112
+ const fetchTool = tools.tools?.find((tool) => isGitMcpDocumentationTool(tool, "fetch"));
279
1113
 
280
1114
  let evidence = null;
281
- if (searchTool) {
282
- evidence = await client.request("tools/call", {
283
- name: searchTool.name,
284
- arguments: { query: idea },
285
- });
286
- } else if (fetchTool) {
287
- evidence = await client.request("tools/call", {
288
- name: fetchTool.name,
289
- arguments: {},
1115
+ let queryMode = "list-only";
1116
+ const callFailures = [];
1117
+ if (fetchTool) {
1118
+ try {
1119
+ evidence = await client.request("tools/call", {
1120
+ name: fetchTool.name,
1121
+ arguments: {},
1122
+ });
1123
+ queryMode = "fetch";
1124
+ } catch (error) {
1125
+ callFailures.push({
1126
+ tool: fetchTool.name,
1127
+ error: error.message,
1128
+ });
1129
+ }
1130
+ }
1131
+ if (!evidence && searchTool) {
1132
+ const redactedQuery = await redactProviderBoundText(idea, {
1133
+ kind: "sage-live-query",
1134
+ repo: source.repo,
290
1135
  });
1136
+ try {
1137
+ evidence = await client.request("tools/call", {
1138
+ name: searchTool.name,
1139
+ arguments: { query: redactedQuery.sanitizedText },
1140
+ });
1141
+ queryMode = "search";
1142
+ } catch (error) {
1143
+ callFailures.push({
1144
+ tool: searchTool.name,
1145
+ error: error.message,
1146
+ });
1147
+ }
1148
+ }
1149
+ if ((fetchTool || searchTool) && !evidence) {
1150
+ throw new Error(
1151
+ `No GitMCP documentation call succeeded: ${callFailures
1152
+ .map((failure) => `${failure.tool}: ${failure.error}`)
1153
+ .join("; ")}`,
1154
+ );
291
1155
  }
292
1156
 
293
1157
  source.liveProbe = {
1158
+ transport: hasConfiguredMcpRemoteBridge() ? "stdio-bridge" : "direct-sse",
294
1159
  serverName: init.serverInfo?.name ?? "unknown",
295
1160
  serverVersion: init.serverInfo?.version ?? "unknown",
296
1161
  toolsCount: tools.tools?.length ?? 0,
297
- queryMode: searchTool ? "search" : fetchTool ? "fetch" : "list-only",
1162
+ queryMode,
1163
+ callFailures,
298
1164
  sampleText:
299
1165
  evidence?.content?.find((item) => item.type === "text")?.text?.slice(0, 400) ?? null,
300
1166
  };
301
- liveSuccessCount += 1;
1167
+ source.evidenceGrade = "VERIFIED";
1168
+ source.exactUpstreamMapping = source.repo;
1169
+ verificationSuccessCount += 1;
302
1170
  } catch (error) {
303
1171
  source.liveProbe = {
1172
+ transport: hasConfiguredMcpRemoteBridge() ? "stdio-bridge" : "direct-sse",
304
1173
  error: error.message,
305
1174
  };
1175
+ source.evidenceGrade = "PARTIAL";
1176
+ source.exactUpstreamMapping = source.repo;
306
1177
  blockers.push(`Live MCP query failed for ${source.repo}: ${error.message}`);
307
1178
  } finally {
308
1179
  await client.close().catch(() => {});
@@ -313,13 +1184,21 @@ export async function runSage() {
313
1184
  existing.items = sourceEntries;
314
1185
  await writeJson(getRuntimeWritePath("evidence", "sources.json"), existing);
315
1186
 
316
- const verified = sourceEntries.length > 0 && (disableLiveProbe || liveSuccessCount > 0);
317
- await writeEvidenceSpec({ idea, sourceEntries, verified, blockers });
1187
+ const verified = sourceEntries.length > 0 && verificationSuccessCount === sourceEntries.length;
1188
+ if (sourceEntries.length > 0 && !verified && blockers.length === 0) {
1189
+ blockers.push(
1190
+ disableLiveProbe
1191
+ ? "Live MCP verification was skipped, so evidence remains unverified."
1192
+ : "No live MCP verification succeeded, so evidence remains unverified.",
1193
+ );
1194
+ }
1195
+ await writeEvidenceSpec({ idea, sourceEntries, verified, blockers, runtimeSummary });
318
1196
  await appendDecision({
319
1197
  kind: "skill",
320
1198
  skill: "$sage",
321
- decision: "Bound architectural choices to approved GitMCP sources using live MCP queries",
322
- status: verified ? "VERIFIED" : "UNVERIFIED",
1199
+ decision:
1200
+ "Bound architectural choices to approved sources using local core-source snapshots first, with GitMCP only as refresh/provenance fallback",
1201
+ status: verified ? "VERIFIED" : sourceEntries.length > 0 ? "PARTIAL" : "MISSING",
323
1202
  evidence: sourceEntries,
324
1203
  blockers: sourceEntries.length > 0 ? blockers : ["No approved GitMCP sources configured"],
325
1204
  next_allowed_triggers: verified ? ["$flow"] : ["mcp/servers.json", "$sage"],
@@ -328,13 +1207,71 @@ export async function runSage() {
328
1207
  await syncStatusUpdates({
329
1208
  evidence_status: verified ? "VERIFIED" : sourceEntries.length > 0 ? "PARTIAL" : "MISSING",
330
1209
  });
1210
+ await updateScratchpadTrackForLane({
1211
+ gate: "$sage",
1212
+ trackStatus: verified ? "COMPLETED" : "BLOCKED",
1213
+ globalStatus: verified ? "COMPLETED" : "LOCKED",
1214
+ blockers: sourceEntries.length > 0 ? blockers : ["No approved GitMCP sources configured"],
1215
+ nextTriggers: verified ? ["$flow"] : ["$sage"],
1216
+ details: {
1217
+ evidence_grade: verified ? "VERIFIED" : sourceEntries.length > 0 ? "PARTIAL" : "MISSING",
1218
+ exact_upstream_mapping: sourceEntries.map((source) => source.repo),
1219
+ },
1220
+ });
331
1221
  }
332
1222
 
333
1223
  export async function runFlow() {
1224
+ await assertLeaderAuthority();
1225
+ const runtimeSnapshot = await loadRuntimeSnapshot();
1226
+ const runtimeSummary = createRuntimeSummary(runtimeSnapshot);
1227
+ assertControlPlaneReady(runtimeSummary);
1228
+ if (runtimeSnapshot.release.evidence_status !== "VERIFIED") {
1229
+ throw new Error("Cannot run $flow before $sage reaches VERIFIED evidence_status");
1230
+ }
1231
+ const blockers = [];
1232
+ if (runtimeSummary.missingArtifacts.length > 0) {
1233
+ blockers.push(`Missing runtime artifacts: ${runtimeSummary.missingArtifacts.join(", ")}`);
1234
+ }
1235
+ if (runtimeSummary.invalidArtifacts.length > 0) {
1236
+ blockers.push(`Invalid runtime artifacts: ${runtimeSummary.invalidArtifacts.join(", ")}`);
1237
+ }
1238
+ if (runtimeSummary.pendingMailboxCount > 0) {
1239
+ blockers.push(
1240
+ "Pending mailbox proposals require leader review before logic can be marked green.",
1241
+ );
1242
+ }
1243
+ if (runtimeSummary.workerCount > 0 && runtimeSummary.workspaceCount === 0) {
1244
+ blockers.push("Workers exist without registered workspaces.");
1245
+ }
1246
+ const actors = ["leader", "worker", "guidance_stack", "hook_dispatcher", "workspace_manager"];
334
1247
  const logicMap = {
1248
+ actors,
1249
+ decision:
1250
+ blockers.length === 0
1251
+ ? "Approve the current behavioral model for downstream review."
1252
+ : "Behavioral model remains blocked until the identified logic/runtime issues are resolved.",
1253
+ status: blockers.length === 0 ? "GREEN" : "RED",
335
1254
  states: ["idea", "architecture", "evidence", "logic", "security", "experience", "build"],
336
- blockers: [],
1255
+ stateMap: [
1256
+ "idea -> architecture -> evidence -> logic -> security -> experience -> build",
1257
+ "logic review must stop if runtime artifacts are invalid or worker/workspace integrity breaks",
1258
+ ],
1259
+ failureFlows:
1260
+ blockers.length > 0
1261
+ ? blockers
1262
+ : ["No blocking failure flow detected in the current runtime snapshot."],
1263
+ evidence: [
1264
+ `actors observed: ${actors.length}`,
1265
+ `pending mailbox proposals: ${runtimeSummary.pendingMailboxCount}`,
1266
+ `registered workspaces: ${runtimeSummary.workspaceCount}`,
1267
+ ],
1268
+ runtimeSummary,
1269
+ blockers,
1270
+ nextTrigger: blockers.length === 0 ? "`$vet`" : "`$flow`",
1271
+ nextAllowedTriggers: blockers.length === 0 ? ["`$vet`"] : ["`$flow`"],
337
1272
  };
1273
+ const status = blockers.length === 0 ? "GREEN" : "RED";
1274
+ const nextAllowedTriggers = blockers.length === 0 ? ["$vet"] : ["$flow"];
338
1275
 
339
1276
  await writeLogicSpec(logicMap);
340
1277
 
@@ -342,87 +1279,507 @@ export async function runFlow() {
342
1279
  kind: "skill",
343
1280
  skill: "$flow",
344
1281
  decision: "Validated logic and state transitions",
345
- status: "GREEN",
1282
+ status,
346
1283
  evidence: [logicMap],
347
- blockers: [],
348
- next_allowed_triggers: ["$vet"],
1284
+ blockers,
1285
+ next_allowed_triggers: nextAllowedTriggers,
349
1286
  });
350
1287
 
351
- await syncStatusUpdates({ logic_status: "GREEN" });
1288
+ await syncStatusUpdates({ logic_status: status });
1289
+ await updateScratchpadTrackForLane({
1290
+ gate: "$flow",
1291
+ trackStatus: status === "GREEN" ? "COMPLETED" : "BLOCKED",
1292
+ globalStatus: status === "GREEN" ? "COMPLETED" : "LOCKED",
1293
+ blockers,
1294
+ nextTriggers: nextAllowedTriggers,
1295
+ details: {
1296
+ failure_flows: logicMap.failureFlows,
1297
+ state_map: logicMap.stateMap,
1298
+ hardening_mode: runtimeSummary.pendingMailboxCount > 0 ? "STRICT" : "STANDARD",
1299
+ },
1300
+ });
352
1301
  }
353
1302
 
354
1303
  export async function runVet() {
1304
+ await assertLeaderAuthority();
1305
+ const runtimeSummary = await readRuntimeSummary();
1306
+ assertControlPlaneReady(runtimeSummary);
355
1307
  const auditLog = await readJson(getRuntimeWritePath("evidence", "audits.json"));
356
1308
  const cveLog = await readJson(getRuntimeWritePath("evidence", "cves.json"));
357
- const finding = {
358
- severity: "INFO",
359
- summary: "Baseline review completed for the approved kernel",
360
- unresolved: false,
361
- };
362
- auditLog.items.push(finding);
1309
+ const packageExposureFindings = await scanLockfilePackageExposure();
1310
+ const policyFindings = await validateMcpPolicyExposure();
1311
+ const criticalPackageExposure = packageExposureFindings.filter(
1312
+ (finding) => finding.severity === "critical",
1313
+ );
1314
+ const blockingPolicyFindings = policyFindings.filter((finding) =>
1315
+ ["critical", "high"].includes(`${finding.severity}`.toLowerCase()),
1316
+ );
1317
+ const reviewApproved =
1318
+ auditLog.items.some((item) => item.source === "review" || item.approved === true) ||
1319
+ cveLog.items.some((item) => item.source === "review" || item.approved === true);
1320
+ const scanApproved = criticalPackageExposure.length === 0 && blockingPolicyFindings.length === 0;
1321
+ const finding =
1322
+ criticalPackageExposure.length > 0
1323
+ ? {
1324
+ severity: criticalPackageExposure[0].severity.toUpperCase(),
1325
+ source: "package-exposure-scan",
1326
+ summary: criticalPackageExposure
1327
+ .map(
1328
+ (item) =>
1329
+ `${item.package_name}@${item.package_version}: ${item.diagnostic} (${item.advisory_reference})`,
1330
+ )
1331
+ .join(" "),
1332
+ unresolved: true,
1333
+ trustBoundaries: [
1334
+ "lockfile metadata vs provider-bound or build-unlocking execution",
1335
+ "repo-owned MCP config vs runtime-local scratchpad state",
1336
+ "published docs vs private `.ma` execution state",
1337
+ ],
1338
+ acceptedRisks: ["No accepted risk: blocking package exposure must be remediated."],
1339
+ }
1340
+ : {
1341
+ severity: policyFindings.length > 0 ? "WARNING" : "INFO",
1342
+ source: policyFindings.length > 0 ? "mcp-policy-validation" : "runtime-review",
1343
+ summary:
1344
+ policyFindings.length > 0
1345
+ ? policyFindings.map((item) => item.diagnostic).join(" ")
1346
+ : `No blocking package exposure was detected in the current bounded scan. Review still remains required after checking ${runtimeSummary.compatibilityHookCount} compatibility hooks and ${runtimeSummary.runtimeHookCount} runtime events.`,
1347
+ unresolved: !reviewApproved && !scanApproved,
1348
+ trustBoundaries: [
1349
+ "leader vs worker mutation authority",
1350
+ "repo-owned MCP config vs runtime-local scratchpad state",
1351
+ "published docs vs private `.ma` execution state",
1352
+ ],
1353
+ acceptedRisks: scanApproved
1354
+ ? ["No material unresolved risk remains for the current bounded step."]
1355
+ : [
1356
+ "Security evidence still requires explicit approval or remediation before promotion.",
1357
+ ],
1358
+ };
1359
+ auditLog.items.push(finding, ...packageExposureFindings, ...policyFindings);
363
1360
  await writeJson(getRuntimeWritePath("evidence", "audits.json"), auditLog);
364
- cveLog.items.push({
365
- id: "baseline-review",
366
- severity: "INFO",
367
- unresolved: false,
368
- });
1361
+ cveLog.items.push(
1362
+ ...packageExposureFindings.map((item) => ({
1363
+ id: item.advisory_reference ?? `${item.package_name}-${item.package_version}`,
1364
+ source: "package-exposure-scan",
1365
+ severity: item.severity.toUpperCase(),
1366
+ unresolved: true,
1367
+ package_name: item.package_name,
1368
+ package_version: item.package_version,
1369
+ })),
1370
+ {
1371
+ id: "baseline-review",
1372
+ source: packageExposureFindings.length > 0 ? "package-exposure-scan" : "runtime-review",
1373
+ severity: packageExposureFindings.length > 0 ? "CRITICAL" : "INFO",
1374
+ unresolved: !reviewApproved && !scanApproved,
1375
+ },
1376
+ );
369
1377
  await writeJson(getRuntimeWritePath("evidence", "cves.json"), cveLog);
1378
+ for (const exposureFinding of packageExposureFindings) {
1379
+ await appendMaestroEvent(exposureFinding);
1380
+ }
1381
+ for (const policyFinding of policyFindings) {
1382
+ await appendMaestroEvent(policyFinding);
1383
+ }
370
1384
  await writeSecuritySpec({
371
1385
  finding,
372
1386
  auditCount: auditLog.items.length,
373
1387
  cveCount: cveLog.items.length,
1388
+ runtimeSummary,
1389
+ nextTrigger: scanApproved ? "`$vibe`" : "`$vet`",
374
1390
  });
1391
+ const status = scanApproved ? "GREEN" : criticalPackageExposure.length > 0 ? "RED" : "PENDING";
1392
+ const blockers =
1393
+ criticalPackageExposure.length > 0
1394
+ ? criticalPackageExposure.map(
1395
+ (item) =>
1396
+ `${item.package_name}@${item.package_version}: ${item.diagnostic} (${item.advisory_reference})`,
1397
+ )
1398
+ : reviewApproved
1399
+ ? []
1400
+ : blockingPolicyFindings.map((finding) => finding.diagnostic);
1401
+ const nextAllowedTriggers = scanApproved
1402
+ ? ["$vibe"]
1403
+ : criticalPackageExposure.length > 0
1404
+ ? ["$vet"]
1405
+ : ["$vet"];
375
1406
 
376
1407
  await appendDecision({
377
1408
  kind: "skill",
378
1409
  skill: "$vet",
379
1410
  decision: "Reviewed security posture for the current implementation",
380
- status: "GREEN",
1411
+ status,
381
1412
  evidence: [finding],
382
- blockers: [],
383
- next_allowed_triggers: ["$vibe"],
1413
+ blockers,
1414
+ next_allowed_triggers: nextAllowedTriggers,
384
1415
  });
385
1416
 
386
- await syncStatusUpdates({ security_status: "GREEN" });
1417
+ await syncStatusUpdates({ security_status: status });
1418
+ await updateScratchpadTrackForLane({
1419
+ gate: "$vet",
1420
+ trackStatus: status === "GREEN" ? "COMPLETED" : "BLOCKED",
1421
+ globalStatus:
1422
+ status === "GREEN" ? "COMPLETED" : status === "RED" ? "LOCKED" : "DEGRADED_HEALING",
1423
+ blockers,
1424
+ nextTriggers: nextAllowedTriggers,
1425
+ details: {
1426
+ trust_boundaries: finding.trustBoundaries,
1427
+ accepted_risks: finding.acceptedRisks,
1428
+ healing_ledger: reviewApproved
1429
+ ? null
1430
+ : {
1431
+ current_attempt: 0,
1432
+ strategy_assigned: "BOUNDED_DIAGNOSTIC_REVIEW",
1433
+ status: "PENDING_OPERATOR_APPROVAL",
1434
+ },
1435
+ },
1436
+ });
387
1437
  }
388
1438
 
389
1439
  export async function runVibe() {
1440
+ await assertLeaderAuthority();
1441
+ const runtimeSummary = await readRuntimeSummary();
1442
+ assertControlPlaneReady(runtimeSummary);
390
1443
  const outcomes = await readJson(getRuntimeWritePath("evidence", "outcomes.json"));
1444
+ const reviewApproved = outcomes.items.some(
1445
+ (item) => item.source === "review" || item.approved === true,
1446
+ );
1447
+ const runtimeApproved = runtimeSummary.pendingMailboxCount === 0;
391
1448
  const note = {
392
1449
  area: "developer-experience",
393
- summary: "The in-session skill flow remains the primary Meta-Architect surface",
1450
+ source: "runtime-vibe-review",
1451
+ summary: `Runtime DX/UX review recorded from current coordination state: ${runtimeSummary.taskCount} tasks, ${runtimeSummary.workspaceCount} workspaces, and ${runtimeSummary.pendingMailboxCount} pending mailbox proposals.`,
1452
+ operatorFriction: [
1453
+ runtimeSummary.pendingMailboxCount > 0
1454
+ ? "Pending mailbox proposals increase operator coordination overhead."
1455
+ : "Operator flow is bounded and clear in the current runtime state.",
1456
+ ],
1457
+ userFriction: [
1458
+ "The gated sequence is explicit, but users still need clearer build-loop feedback once execution starts.",
1459
+ ],
1460
+ approved: reviewApproved || runtimeApproved,
394
1461
  };
395
1462
  outcomes.items.push(note);
396
1463
  await writeJson(getRuntimeWritePath("evidence", "outcomes.json"), outcomes);
397
- await writeExperienceSpec({ note, outcomeCount: outcomes.items.length });
1464
+ const status = reviewApproved || runtimeApproved ? "GREEN" : "PENDING";
1465
+ const blockers =
1466
+ status === "GREEN"
1467
+ ? []
1468
+ : ["Pending mailbox proposals must be resolved before DX/UX can be marked GREEN."];
1469
+ const nextAllowedTriggers = status === "GREEN" ? ["$build"] : ["$vibe"];
1470
+ await writeExperienceSpec({
1471
+ note,
1472
+ outcomeCount: outcomes.items.length,
1473
+ runtimeSummary,
1474
+ nextTrigger: status === "GREEN" ? "`$build`" : "`$vibe`",
1475
+ });
398
1476
 
399
1477
  await appendDecision({
400
1478
  kind: "skill",
401
1479
  skill: "$vibe",
402
1480
  decision: "Recorded DX/UX review notes",
403
- status: "GREEN",
1481
+ status,
404
1482
  evidence: [note],
405
- blockers: [],
406
- next_allowed_triggers: ["$build"],
1483
+ blockers,
1484
+ next_allowed_triggers: nextAllowedTriggers,
407
1485
  });
408
1486
 
409
- await syncStatusUpdates({ experience_status: "GREEN" });
1487
+ await syncStatusUpdates({ experience_status: status });
1488
+ await updateScratchpadTrackForLane({
1489
+ gate: "$vibe",
1490
+ trackStatus: status === "GREEN" ? "COMPLETED" : "BLOCKED",
1491
+ globalStatus: status === "GREEN" ? "COMPLETED" : "LOCKED",
1492
+ blockers,
1493
+ nextTriggers: nextAllowedTriggers,
1494
+ details: {
1495
+ operator_friction: note.operatorFriction,
1496
+ user_friction: note.userFriction,
1497
+ },
1498
+ });
410
1499
  }
411
1500
 
412
- export async function runMaestro() {
413
- const releaseState = await readJson(getRuntimeReadPath("release.json"));
414
- const idea = await readIdeaText();
415
- const recommendation = chooseMaestroRecommendation(releaseState, idea);
1501
+ export async function runMaestro({ autoHeal = false, parallel = false } = {}) {
1502
+ await assertLeaderAuthority();
1503
+ let runtimeSnapshot = await loadRuntimeSnapshot();
1504
+ let releaseState = runtimeSnapshot.release;
1505
+ let runtimeSummary = createRuntimeSummary(runtimeSnapshot);
1506
+ assertControlPlaneReady(runtimeSummary);
1507
+ let idea = await readIdeaText();
1508
+ let buildReadiness = evaluateRuntimeBuildReadiness(releaseState, runtimeSummary);
1509
+ let recommendation = chooseMaestroRecommendation(releaseState, idea, buildReadiness);
1510
+ const helperFailureMatrix = buildHelperFailureMatrix();
1511
+ const alignmentReport = {
1512
+ ...evaluateAlignmentDrift({
1513
+ releaseState,
1514
+ decisionLog: runtimeSnapshot.decisions,
1515
+ }),
1516
+ lastRunAt: new Date().toISOString(),
1517
+ baselineArtifacts: [
1518
+ ".ma/release.json",
1519
+ ".ma/decisions.json",
1520
+ ".ma/state/manager-runs.json",
1521
+ ".ma/state/maestro-state.json",
1522
+ ],
1523
+ };
1524
+ await saveAlignmentSentinelReport(alignmentReport);
1525
+ if (alignmentReport.driftStatus === "DRIFTED") {
1526
+ await updateScratchpadTrackForLane({
1527
+ gate: "$maestro",
1528
+ trackStatus: "BLOCKED",
1529
+ globalStatus: "LOCKED",
1530
+ blockers: alignmentReport.findings.map(
1531
+ (finding) =>
1532
+ `${finding.skill} expects ${finding.releaseField} to remain in ${finding.expectedReleaseValues.join(" or ")}, but the current value is ${finding.actualReleaseValue}.`,
1533
+ ),
1534
+ nextTriggers: ["$maestro"],
1535
+ details: {
1536
+ drift_status: alignmentReport.driftStatus,
1537
+ reboot_planned: alignmentReport.rebootPlanned,
1538
+ resume_trigger: alignmentReport.resumeTrigger,
1539
+ },
1540
+ });
1541
+ await appendMaestroEvent({
1542
+ record_type: "alignment:drift_detected",
1543
+ gate: "$maestro",
1544
+ findings: alignmentReport.findings,
1545
+ reboot_planned: alignmentReport.rebootPlanned,
1546
+ resume_trigger: alignmentReport.resumeTrigger,
1547
+ });
1548
+ const driftRecommendation = {
1549
+ nextStep: "Resolve alignment drift before manager dispatch continues.",
1550
+ why: alignmentReport.rebootReason,
1551
+ primaryLane: "$maestro",
1552
+ supportLane: "none",
1553
+ assignments: [
1554
+ "Review the persisted alignment report and conflicting lane-owned decisions.",
1555
+ "Rehydrate the next manager run from baseline `.ma/` artifacts after the conflicting state is repaired.",
1556
+ ],
1557
+ avoid: [
1558
+ "Do not continue autonomous dispatch while release state contradicts approved lane decisions.",
1559
+ ],
1560
+ nextTrigger: "`$maestro`",
1561
+ };
1562
+ await writeMaestroPlan({
1563
+ releaseState,
1564
+ recommendation: driftRecommendation,
1565
+ runtimeSummary,
1566
+ workflowSequence: maestroWorkflowSequence,
1567
+ managerRun: null,
1568
+ });
1569
+ await appendDecision({
1570
+ kind: "skill",
1571
+ skill: "$maestro",
1572
+ decision:
1573
+ "Alignment Sentinel blocked manager execution and requested a fresh worker rehydration path.",
1574
+ status: "BLOCKED",
1575
+ evidence: [alignmentReport],
1576
+ blockers: alignmentReport.findings.map(
1577
+ (finding) =>
1578
+ `${finding.skill} approved ${finding.expectedDecisionStatus}, but ${finding.releaseField} regressed to ${finding.actualReleaseValue}.`,
1579
+ ),
1580
+ next_allowed_triggers: ["$maestro"],
1581
+ });
1582
+ return;
1583
+ }
1584
+ if (
1585
+ autoHeal &&
1586
+ buildReadiness.releaseBlockers.length === 0 &&
1587
+ buildReadiness.nextTriggers.includes("repair runtime artifacts")
1588
+ ) {
1589
+ const repairedArtifacts = await repairRuntimeScratchpadArtifacts([
1590
+ ...runtimeSummary.invalidArtifacts,
1591
+ ...runtimeSummary.missingArtifacts,
1592
+ ]);
1593
+ if (repairedArtifacts.length > 0) {
1594
+ const detached = await launchDetachedTrack({
1595
+ trackId: "heal-sync",
1596
+ title: "Meta-Architect bounded diagnostic sidecar",
1597
+ command: "/bin/sh",
1598
+ args: [
1599
+ "-lc",
1600
+ `printf '%s\n' "Repaired scratchpad artifacts: ${repairedArtifacts.join(", ")}"`,
1601
+ ],
1602
+ });
1603
+ let maestroState = await loadMaestroStateOrDefault();
1604
+ maestroState = beginMaestroOrchestration(maestroState, {
1605
+ globalStatus: "DEGRADED_HEALING",
1606
+ configuration: {
1607
+ auto_heal: true,
1608
+ concurrency_limit: parallel ? 4 : 1,
1609
+ },
1610
+ });
1611
+ maestroState.runtime_tracks.track_heal_sync = {
1612
+ active_gate: "$maestro",
1613
+ status: "COMPLETED",
1614
+ pid: null,
1615
+ execution_pane: detached.executionPane,
1616
+ provider: detached.provider,
1617
+ log_path: detached.logPath,
1618
+ exit_code: 0,
1619
+ repaired_artifacts: repairedArtifacts,
1620
+ updated_at: new Date().toISOString(),
1621
+ };
1622
+ await saveMaestroState(maestroState);
1623
+ await appendMaestroEvent({
1624
+ record_type: "healing:attempt",
1625
+ gate: "$maestro",
1626
+ global_status: "DEGRADED_HEALING",
1627
+ track_status: "COMPLETED",
1628
+ repaired_artifacts: repairedArtifacts,
1629
+ repaired_count: repairedArtifacts.length,
1630
+ });
1631
+ runtimeSnapshot = await loadRuntimeSnapshot();
1632
+ releaseState = runtimeSnapshot.release;
1633
+ runtimeSummary = createRuntimeSummary(runtimeSnapshot);
1634
+ buildReadiness = evaluateRuntimeBuildReadiness(releaseState, runtimeSummary);
1635
+ recommendation = chooseMaestroRecommendation(releaseState, idea, buildReadiness);
1636
+ }
1637
+ }
1638
+ const registry = await loadManagerRunRegistry();
1639
+ const activeRun = getActiveManagerRun(registry);
1640
+ const managerAction = chooseMaestroManagerAction({
1641
+ releaseState,
1642
+ runtimeSummary,
1643
+ buildReadiness,
1644
+ recommendation,
1645
+ activeRun,
1646
+ });
1647
+
1648
+ if (activeRun?.state === "waiting-review" && managerAction.nextAction === "recommend") {
1649
+ await writeMaestroPlan({
1650
+ releaseState,
1651
+ recommendation,
1652
+ runtimeSummary,
1653
+ workflowSequence: maestroWorkflowSequence,
1654
+ managerRun: activeRun,
1655
+ });
1656
+ await appendDecision({
1657
+ kind: "skill",
1658
+ skill: "$maestro",
1659
+ decision: "Held the manager in waiting-review until the pending proposal is resolved",
1660
+ status: "WAITING_REVIEW",
1661
+ evidence: buildManagerDecisionEvidence(activeRun, recommendation),
1662
+ blockers: buildManagerDecisionBlockers(activeRun, runtimeSummary, buildReadiness),
1663
+ next_allowed_triggers: [stripBackticks(recommendation.nextTrigger)],
1664
+ });
1665
+ return;
1666
+ }
1667
+
1668
+ const managerRun = createManagerRun({
1669
+ parentRunId: activeRun?.id ?? null,
1670
+ triggeredBy: "$maestro",
1671
+ mode: managerAction.mode,
1672
+ nextAction: managerAction.nextAction,
1673
+ dispatchPlan: managerAction.dispatchPlan,
1674
+ pendingReview: managerAction.pendingReview ?? null,
1675
+ });
1676
+ registry.runs.push(managerRun);
1677
+ updateManagerRunTimestamps(managerRun);
1678
+ await saveManagerRunRegistry(registry);
1679
+
1680
+ try {
1681
+ updateManagerRunTimestamps(managerRun, { state: "dispatching" });
1682
+ await saveManagerRunRegistry(registry);
1683
+
1684
+ if (managerRun.helperRuns.length > 0) {
1685
+ const helpersCompleted = await executeManagerHelpers({
1686
+ registry,
1687
+ managerRun,
1688
+ releaseState,
1689
+ runtimeSummary,
1690
+ recommendation,
1691
+ helperFailureMatrix,
1692
+ });
1693
+ if (!helpersCompleted) {
1694
+ runtimeSnapshot = await loadRuntimeSnapshot();
1695
+ releaseState = runtimeSnapshot.release;
1696
+ runtimeSummary = createRuntimeSummary(runtimeSnapshot);
1697
+ buildReadiness = evaluateRuntimeBuildReadiness(releaseState, runtimeSummary);
1698
+ recommendation = chooseMaestroRecommendation(releaseState, idea, buildReadiness);
1699
+ }
1700
+ }
1701
+
1702
+ if (managerRun.state !== "completed" && managerRun.nextAction === "dispatch-gated") {
1703
+ const gateRunners = getAutonomousGateRunners();
1704
+ for (const gate of managerRun.dispatchPlan.gated) {
1705
+ const runner = gateRunners[gate.skill];
1706
+ if (!runner) {
1707
+ gate.status = "recommended";
1708
+ continue;
1709
+ }
1710
+
1711
+ const detached =
1712
+ parallel && ["$flow", "$vet", "$vibe", "$build"].includes(gate.skill)
1713
+ ? await launchDetachedTrack({
1714
+ trackId: `${managerRun.id}-${gate.skill.replaceAll("$", "")}`,
1715
+ title: `Meta-Architect detached track ${gate.skill}`,
1716
+ command: "/bin/sh",
1717
+ args: ["-lc", `printf '%s\n' "Detached scratchpad track for ${gate.skill}"`],
1718
+ })
1719
+ : null;
1720
+ gate.status = "running";
1721
+ updateManagerRunTimestamps(managerRun, { state: "running" });
1722
+ await saveManagerRunRegistry(registry);
1723
+ await updateScratchpadTrackForLane({
1724
+ gate: gate.skill,
1725
+ trackStatus: "RUNNING",
1726
+ globalStatus: "RUNNING",
1727
+ nextTriggers: [gate.skill],
1728
+ detached,
1729
+ details: {
1730
+ objective: gate.objective,
1731
+ },
1732
+ });
1733
+ await runner();
1734
+ gate.status = "completed";
1735
+ await saveManagerRunRegistry(registry);
1736
+ }
1737
+ }
1738
+
1739
+ if (managerRun.state !== "completed" && managerRun.nextAction === "dispatch-team") {
1740
+ await executeManagerTeamDispatch(registry, managerRun);
1741
+ }
1742
+ } catch (error) {
1743
+ updateManagerRunTimestamps(managerRun, {
1744
+ state: "failed",
1745
+ retry: {
1746
+ count: managerRun.retry.count + 1,
1747
+ lastReason: error.message,
1748
+ },
1749
+ });
1750
+ await saveManagerRunRegistry(registry);
1751
+ throw error;
1752
+ }
1753
+
1754
+ runtimeSnapshot = await loadRuntimeSnapshot();
1755
+ releaseState = runtimeSnapshot.release;
1756
+ runtimeSummary = createRuntimeSummary(runtimeSnapshot);
1757
+ assertControlPlaneReady(runtimeSummary);
1758
+ idea = await readIdeaText();
1759
+ buildReadiness = evaluateRuntimeBuildReadiness(releaseState, runtimeSummary);
1760
+ recommendation = chooseMaestroRecommendation(releaseState, idea, buildReadiness);
416
1761
 
417
- await writeMaestroPlan({ releaseState, recommendation });
1762
+ if (managerRun.state === "dispatching" || managerRun.state === "running") {
1763
+ updateManagerRunTimestamps(managerRun, { state: "completed" });
1764
+ await saveManagerRunRegistry(registry);
1765
+ }
1766
+
1767
+ await writeMaestroPlan({
1768
+ releaseState,
1769
+ recommendation,
1770
+ runtimeSummary,
1771
+ workflowSequence: maestroWorkflowSequence,
1772
+ managerRun,
1773
+ });
418
1774
  await appendDecision({
419
1775
  kind: "skill",
420
1776
  skill: "$maestro",
421
- decision: "Recommended the next workflow step and assignment lane",
422
- status: "ADVISORY",
423
- evidence: [recommendation],
424
- blockers: [],
425
- next_allowed_triggers: [recommendation.nextTrigger.replaceAll("`", "")],
1777
+ decision:
1778
+ "Executed the autonomous Meta-Architect manager run and persisted the control-plane record",
1779
+ status: getManagerDecisionStatus(managerRun),
1780
+ evidence: buildManagerDecisionEvidence(managerRun, recommendation),
1781
+ blockers: buildManagerDecisionBlockers(managerRun, runtimeSummary, buildReadiness),
1782
+ next_allowed_triggers: [stripBackticks(recommendation.nextTrigger)],
426
1783
  });
427
1784
  }
428
1785
 
@@ -433,6 +1790,12 @@ export async function runInit() {
433
1790
  ".codex/prompts",
434
1791
  ".ma/skills",
435
1792
  ".ma/evidence",
1793
+ ".ma/guidance",
1794
+ ".ma/memory",
1795
+ ".ma/hooks",
1796
+ ".ma/tasks",
1797
+ ".ma/workspaces",
1798
+ ".ma/state",
436
1799
  ".ma/context",
437
1800
  ".ma/specs",
438
1801
  ".ma/plans",
@@ -508,8 +1871,12 @@ export async function runInit() {
508
1871
  path.join(getRepoRoot(), "docs", "release-spec.md"),
509
1872
  ],
510
1873
  [
511
- path.join(packageRoot, "docs", "qa", "release-readiness-0.1.11.md"),
512
- path.join(getRepoRoot(), "docs", "qa", "release-readiness-0.1.11.md"),
1874
+ path.join(packageRoot, "docs", "qa", "release-readiness-0.1.13.md"),
1875
+ path.join(getRepoRoot(), "docs", "qa", "release-readiness-0.1.13.md"),
1876
+ ],
1877
+ [
1878
+ path.join(packageRoot, "docs", "qa", "release-issue-gates-0.1.13.json"),
1879
+ path.join(getRepoRoot(), "docs", "qa", "release-issue-gates-0.1.13.json"),
513
1880
  ],
514
1881
  ];
515
1882
 
@@ -531,7 +1898,12 @@ export async function runInit() {
531
1898
  ]);
532
1899
  }
533
1900
 
534
- for (const file of ["servers.json", "collections.json", "fallback.json"]) {
1901
+ for (const file of [
1902
+ "servers.json",
1903
+ "collections.json",
1904
+ "fallback.json",
1905
+ "local-capabilities.json",
1906
+ ]) {
535
1907
  templateCopies.push([
536
1908
  path.join(packageRoot, "mcp", file),
537
1909
  path.join(getRepoRoot(), "mcp", file),
@@ -599,6 +1971,10 @@ export async function runInit() {
599
1971
  path.join(getRepoRoot(), "mcp", "servers.json"),
600
1972
  `${JSON.stringify({ schemaVersion: "0.1.0", servers: [] }, null, 2)}\n`,
601
1973
  );
1974
+ await writeFileIfMissing(
1975
+ path.join(getRepoRoot(), "mcp", "local-capabilities.json"),
1976
+ `${JSON.stringify({ schemaVersion: "0.1.0", capabilities: [] }, null, 2)}\n`,
1977
+ );
602
1978
  await writeFileIfMissing(
603
1979
  path.join(getRepoRoot(), "mcp", "collections.json"),
604
1980
  `${JSON.stringify({ schemaVersion: "0.1.0", collections: {} }, null, 2)}\n`,