@loucompanion/forge-bridge 0.1.1-dev.9acab970e5d1 → 0.1.1-dev.a8025fe64c0a

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.
@@ -54,6 +54,8 @@ const qaBlockerReasons = new Set([
54
54
  "missing_worktree",
55
55
  "runner_failure"
56
56
  ]);
57
+ const resolvedFindingStatusValues = ["resolved", "disputed", "not_reproduced"];
58
+ const resolvedFindingStatuses = new Set(resolvedFindingStatusValues);
57
59
  const qaFindingSeverities = new Set(["critical", "major", "minor"]);
58
60
  const qaFindingScopes = new Set(["in_scope", "out_of_scope", "unclear"]);
59
61
  const qaCandidateBugActions = new Set(["create_bug", "create_follow_up", "accept_risk", "attach_to_current_item"]);
@@ -89,6 +91,10 @@ const phaseFiles = {
89
91
  debug_regression: {
90
92
  jsonFileName: "debug.regression.json",
91
93
  reportFileName: "debug.report.md"
94
+ },
95
+ architect: {
96
+ jsonFileName: "architect.verdict.json",
97
+ reportFileName: "architect.report.md"
92
98
  }
93
99
  };
94
100
  export function completionPhaseFromDispatch(dispatch) {
@@ -109,6 +115,9 @@ export function normalizeCompletionPhase(value) {
109
115
  if (normalized === "qa" || normalized === "quality_assurance" || normalized === "qualityassurance") {
110
116
  return "qa";
111
117
  }
118
+ if (normalized === "architect" || normalized === "architect_plan" || normalized === "planning" || normalized === "plan") {
119
+ return "architect";
120
+ }
112
121
  return "implementation";
113
122
  }
114
123
  export function usesDevelopCycleCompletion(dispatch) {
@@ -138,6 +147,12 @@ export function usesDebugCycleCompletion(dispatch) {
138
147
  && lane === "debug"
139
148
  && isDebugCompletionPhase(completionPhaseFromDispatch(dispatch));
140
149
  }
150
+ export function usesArchitectCycleCompletion(dispatch) {
151
+ const kind = dispatch.cycleRun.kind.trim().toLowerCase();
152
+ const role = dispatch.execution.role.trim().toLowerCase();
153
+ const lane = dispatch.execution.lane.trim().toLowerCase();
154
+ return kind === "architect" || role === "architect" || lane === "architect";
155
+ }
141
156
  export function completionToolNamesForPhase(phase) {
142
157
  if (isDebugCompletionPhase(phase)) {
143
158
  return completionToolNamesForDebugGate(phase);
@@ -148,7 +163,9 @@ export function completionToolNamesForPhase(phase) {
148
163
  ? "complete_self_review"
149
164
  : phase === "validation"
150
165
  ? "complete_validation"
151
- : "complete_qa";
166
+ : phase === "architect"
167
+ ? "complete_architect_plan"
168
+ : "complete_qa";
152
169
  return [`forge.${base}`, base];
153
170
  }
154
171
  export function completionToolNamesForQaGate(gate) {
@@ -171,14 +188,20 @@ export function expectedDebugCompletionToolName(gate) {
171
188
  export function artifactRootFor(worktreePath, workItemId) {
172
189
  return path.join(worktreePath, ".forge", "work-items", safePathSegment(workItemId, "work item id"), "artifacts");
173
190
  }
174
- function artifactRootForOwner(worktreePath, ownerType, ownerId) {
191
+ export function artifactRootForOwner(worktreePath, ownerType, ownerId) {
175
192
  return path.join(worktreePath, ".forge", artifactOwnerDirectory(ownerType), safePathSegment(ownerId, "owner id"), "artifacts");
176
193
  }
177
- export function completionArtifactJsonPath(worktreePath, workItemId, phase) {
178
- return path.join(artifactRootFor(worktreePath, workItemId), phaseFiles[phase].jsonFileName);
194
+ export function completionArtifactJsonPath(worktreePath, workItemId, phase, ownerType, ownerId) {
195
+ const artifactRoot = ownerType && ownerId
196
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
197
+ : artifactRootFor(worktreePath, workItemId);
198
+ return path.join(artifactRoot, phaseFiles[phase].jsonFileName);
179
199
  }
180
- export function completionArtifactReportPath(worktreePath, workItemId, phase) {
181
- return path.join(artifactRootFor(worktreePath, workItemId), phaseFiles[phase].reportFileName);
200
+ export function completionArtifactReportPath(worktreePath, workItemId, phase, ownerType, ownerId) {
201
+ const artifactRoot = ownerType && ownerId
202
+ ? artifactRootForOwner(worktreePath, ownerType, ownerId)
203
+ : artifactRootFor(worktreePath, workItemId);
204
+ return path.join(artifactRoot, phaseFiles[phase].reportFileName);
182
205
  }
183
206
  export async function prepareCompletionToolRuntime(options) {
184
207
  const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
@@ -195,7 +218,8 @@ export async function prepareCompletionToolRuntime(options) {
195
218
  producedBy: `${options.dispatch.execution.provider}-cli`,
196
219
  developCycle: usesDevelopCycleCompletion(options.dispatch),
197
220
  qaCycle: usesQaCycleCompletion(options.dispatch),
198
- debugCycle: usesDebugCycleCompletion(options.dispatch)
221
+ debugCycle: usesDebugCycleCompletion(options.dispatch),
222
+ architectCycle: usesArchitectCycleCompletion(options.dispatch)
199
223
  });
200
224
  const runtime = {
201
225
  serverName: toolServerName,
@@ -234,6 +258,9 @@ export function buildCompletionToolServerArgs(config) {
234
258
  if (config.debugCycle) {
235
259
  args.push("--debug-cycle");
236
260
  }
261
+ if (config.architectCycle) {
262
+ args.push("--architect-cycle");
263
+ }
237
264
  return args;
238
265
  }
239
266
  export function codexMcpConfigArgs(runtime) {
@@ -266,6 +293,17 @@ Do not write QA artifacts by hand. When QA is complete, call \`${toolName}(...)\
266
293
  That tool writes the durable QA bundle under \`.forge/work-items/{workItemId}/artifacts/\`: \`qa.plan.json\`, \`qa.evidence.json\`, \`qa.findings.json\`, \`${artifactName}\`, and \`qa.report.md\`.
267
294
  Use \`status: "pass"\` only when the validated changes satisfy acceptance criteria with concrete evidence. Use \`status: "needs_rework"\` with actionable in-scope findings, or \`status: "blocked"\` with a concrete blocker_reason.
268
295
  Forge will mirror only the tool-written QA artifacts; reporting QA completion in prose is not enough.`;
296
+ }
297
+ if (phase === "architect") {
298
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
299
+ Do not write Architect artifacts by hand. When the plan is complete, call \`${toolName}(...)\`${alias ? ` (or \`${alias}\` if your client shows unqualified MCP tool names)` : ""} with the full structured Architect planning payload.
300
+ That tool writes \`.forge/work-items/{workItemId}/artifacts/implementation.plan.json\`, \`qa.plan.json\`, \`${artifactName}\`, and \`architect.report.md\`.
301
+ The payload must put \`phases\`, \`tasks\`, \`dependencies\`, and \`phase_gates\` as top-level fields inside \`implementation_plan\`, for example:
302
+ \`{ "status": "pass", "summary": "...", "implementation_plan": { "schema_version": 1, "plan_id": "plan-...", "phases": [{ "id": "phase-1", "tasks": ["task-1"], "gate": "gate-1" }], "tasks": [{ "id": "task-1", "tests": [{ "command": "npm test" }] }], "dependencies": [], "phase_gates": [{ "id": "gate-1", "phase": "phase-1" }] }, "qa_plan": { "schema_version": 1, "final_qa": [{ "id": "qa-1", "coverage": "..." }] }, "report_markdown": "# Architect Report" }\`.
303
+ \`implementation_plan.tasks\` are Develop child tasks only: each task must require a focused repo/product implementation change. Put parent-story QA, sign-off, child-count/materialization inventory, parent plan artifact checks, and final integrated acceptance proof in \`qa_plan.final_qa\`, not as child Develop tasks.
304
+ Dependency entries use canonical \`before\` and \`after\` task ids, for example \`{ "before": "task-1", "after": "task-2" }\`. Forge accepts \`from\`/\`to\` only as aliases and normalizes them before writing artifacts.
305
+ Use \`status: "pass"\` for a valid pending-approval plan, \`needs_revision\` when story/design input must change, or \`blocked\` with a concrete blocker.
306
+ Forge will mirror only the tool-written Architect artifacts; reporting the plan in prose is not enough.`;
269
307
  }
270
308
  return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
271
309
  Do not write phase artifacts by hand. When the phase is complete, call \`${toolName}(...)\`${alias ? ` (or \`${alias}\` if your client shows unqualified MCP tool names)` : ""} with the required evidence payload.
@@ -315,7 +353,9 @@ export function completionToolNamesForServer(config) {
315
353
  ? qaCompletionGateOrder.flatMap((gate) => completionToolNamesForQaGate(gate))
316
354
  : config.developCycle
317
355
  ? completionPhaseOrder.flatMap((phase) => completionToolNamesForPhase(phase))
318
- : completionToolNamesForPhase(config.phase);
356
+ : config.architectCycle
357
+ ? completionToolNamesForPhase("architect")
358
+ : completionToolNamesForPhase(config.phase);
319
359
  }
320
360
  export class CompletionToolServerSession {
321
361
  config;
@@ -511,7 +551,10 @@ export async function writeCompletionArtifact(config, toolName, input) {
511
551
  }
512
552
  const payload = asRecord(input, "completion payload");
513
553
  const status = normalizeCompletionStatus(requiredString(payload, "status"), phase);
514
- const validationPayload = { ...payload, status };
554
+ let validationPayload = { ...payload, status };
555
+ if (config.qaCycle && qaGate === "qa_verdict") {
556
+ validationPayload = await synthesizeQaCycleVerdictPayload(config, validationPayload, status);
557
+ }
515
558
  validatePayloadShape(phase, validationPayload);
516
559
  validateOptionalWorkItemId(validationPayload, config.workItemId);
517
560
  const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
@@ -522,6 +565,9 @@ export async function writeCompletionArtifact(config, toolName, input) {
522
565
  if (phase === "qa") {
523
566
  return await writeQaCompletionArtifact(config, redactedPayload, status, producedBy);
524
567
  }
568
+ if (phase === "architect") {
569
+ return await writeArchitectCompletionArtifact(config, redactedPayload, status, producedBy);
570
+ }
525
571
  const artifactWithoutHash = normalizeArtifactPayload(redactedPayload, {
526
572
  phase,
527
573
  workItemId: config.workItemId,
@@ -554,6 +600,48 @@ export async function writeCompletionArtifact(config, toolName, input) {
554
600
  producedBy
555
601
  };
556
602
  }
603
+ async function writeArchitectCompletionArtifact(config, payload, status, producedBy) {
604
+ const ownerFields = artifactOwnerFields(config);
605
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
606
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
607
+ : artifactRootFor(config.worktreePath, config.workItemId);
608
+ const implementationPlanPath = path.join(artifactRoot, "implementation.plan.json");
609
+ const qaPlanPath = path.join(artifactRoot, "qa.plan.json");
610
+ const verdictPath = path.join(artifactRoot, "architect.verdict.json");
611
+ const reportPath = path.join(artifactRoot, "architect.report.md");
612
+ const implementationPlan = requiredRecord(payload, "implementation_plan");
613
+ const qaPlan = requiredRecord(payload, "qa_plan");
614
+ const report = optionalString(payload, "report") ?? optionalString(payload, "report_markdown") ?? reportMarkdown(payload, "architect", status, producedBy, "pending");
615
+ const artifactWithoutHash = normalizeArtifactPayload(payload, {
616
+ phase: "architect",
617
+ workItemId: config.workItemId,
618
+ ownerType: config.ownerType,
619
+ ownerId: config.ownerId,
620
+ producedBy,
621
+ status
622
+ });
623
+ const contentHash = sha256(stableStringify(artifactWithoutHash));
624
+ const verdict = {
625
+ ...artifactWithoutHash,
626
+ content_hash: contentHash
627
+ };
628
+ await fs.mkdir(artifactRoot, { recursive: true });
629
+ await writeFileAtomic(implementationPlanPath, jsonText(implementationPlan));
630
+ await writeFileAtomic(qaPlanPath, jsonText(qaPlan));
631
+ await writeFileAtomic(verdictPath, jsonText(verdict));
632
+ await writeFileAtomic(reportPath, `${report.trim()}\n`);
633
+ return {
634
+ phase: "architect",
635
+ workItemId: config.workItemId,
636
+ ...artifactReferenceOwnerFields(config),
637
+ repoPath: path.resolve(config.worktreePath),
638
+ path: verdictPath,
639
+ reportPath,
640
+ contentHash,
641
+ status,
642
+ producedBy
643
+ };
644
+ }
557
645
  async function writeQaGateCompletionArtifact(config, gate, input) {
558
646
  const payload = asRecord(input, "QA gate completion payload");
559
647
  const status = normalizeQaGateStatus(requiredString(payload, "status"));
@@ -709,6 +797,133 @@ async function writeQaCompletionArtifact(config, payload, status, producedBy) {
709
797
  producedBy
710
798
  };
711
799
  }
800
+ async function synthesizeQaCycleVerdictPayload(config, payload, status) {
801
+ const qaPlan = await readQaGateArtifact(config, "qa_plan");
802
+ const qaRegression = await readQaGateArtifact(config, "qa_regression");
803
+ const qaApi = await readQaGateArtifact(config, "qa_api");
804
+ const qaManualWeb = await readQaGateArtifact(config, "qa_manual_web");
805
+ const qaBugRepro = await readQaGateArtifact(config, "qa_bug_repro");
806
+ const qaFindings = await readQaGateArtifact(config, "qa_findings");
807
+ const evidenceGates = [qaRegression, qaApi, qaManualWeb, qaBugRepro];
808
+ const payloadEvidence = qaEvidenceSource(payload);
809
+ const merged = { ...payload };
810
+ const checklist = qaStringArray(payload, "checklist");
811
+ if (checklist.length === 0) {
812
+ const plannedChecklist = qaStringArray(qaPlan, "checklist");
813
+ merged.checklist = plannedChecklist.length > 0 ? plannedChecklist : defaultQaChecklist(status);
814
+ }
815
+ const testedAcceptanceCriteria = qaStringArray(payload, "tested_acceptance_criteria");
816
+ if (testedAcceptanceCriteria.length === 0) {
817
+ const plannedAcceptanceCriteria = qaStringArray(qaPlan, "acceptance_criteria");
818
+ const payloadAcceptanceCriteria = qaStringArray(payload, "acceptance_criteria");
819
+ const acceptanceCriteria = plannedAcceptanceCriteria.length > 0 ? plannedAcceptanceCriteria : payloadAcceptanceCriteria;
820
+ if (acceptanceCriteria.length > 0) {
821
+ merged.tested_acceptance_criteria = acceptanceCriteria;
822
+ }
823
+ }
824
+ const payloadCommands = qaArray(payload, "commands", payloadEvidence);
825
+ const inheritedCommands = evidenceGates.flatMap((gate) => qaArray(gate, "commands"));
826
+ const inheritedDiagnosticCommandNotes = status === "pass"
827
+ ? qaNonPassingCommandNotes(inheritedCommands)
828
+ : [];
829
+ merged.commands = dedupeUnknownArray([
830
+ ...payloadCommands,
831
+ ...(status === "pass" ? inheritedCommands.filter(isQaPassingCommandEvidence) : inheritedCommands)
832
+ ]);
833
+ merged.browser_checks = dedupeUnknownArray([
834
+ ...qaArray(payload, "browser_checks", payloadEvidence),
835
+ ...evidenceGates.flatMap((gate) => qaArray(gate, "browser_checks"))
836
+ ]);
837
+ merged.sidecars = dedupeUnknownArray([
838
+ ...qaArray(payload, "sidecars", payloadEvidence),
839
+ ...evidenceGates.flatMap((gate) => qaArray(gate, "sidecars"))
840
+ ]);
841
+ const notes = dedupeStrings([
842
+ optionalString(payload, "notes"),
843
+ optionalString(payloadEvidence, "notes"),
844
+ ...evidenceGates.map((gate) => optionalString(gate, "notes")),
845
+ ...inheritedDiagnosticCommandNotes
846
+ ]);
847
+ if (notes.length > 0) {
848
+ merged.notes = notes.join("\n");
849
+ }
850
+ merged.findings = mergeQaObjectArraysById(qaObjectArray(payload, "findings"), qaObjectArray(qaFindings, "findings"));
851
+ merged.candidate_bugs = mergeQaObjectArraysById(qaObjectArray(payload, "candidate_bugs"), qaObjectArray(qaFindings, "candidate_bugs"));
852
+ return merged;
853
+ }
854
+ async function readQaGateArtifact(config, gate) {
855
+ const ownerFields = artifactOwnerFields(config);
856
+ const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
857
+ ? artifactRootForOwner(config.worktreePath, ownerFields.owner_type, ownerFields.owner_id)
858
+ : artifactRootFor(config.worktreePath, config.workItemId);
859
+ const artifactPath = path.join(artifactRoot, qaGateFileNames[gate]);
860
+ const content = await readOptionalFile(artifactPath);
861
+ return content === null ? {} : parseOptionalJsonObject(content, qaGateFileNames[gate]);
862
+ }
863
+ function dedupeUnknownArray(values) {
864
+ const seen = new Set();
865
+ const deduped = [];
866
+ for (const value of values) {
867
+ const key = stableStringify(value);
868
+ if (seen.has(key)) {
869
+ continue;
870
+ }
871
+ seen.add(key);
872
+ deduped.push(value);
873
+ }
874
+ return deduped;
875
+ }
876
+ function isQaPassingCommandEvidence(value) {
877
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
878
+ return false;
879
+ }
880
+ const record = value;
881
+ return record.exit_code === 0 && normalizedString(record.status) === "pass";
882
+ }
883
+ function qaNonPassingCommandNotes(values) {
884
+ return values
885
+ .filter((value) => !isQaPassingCommandEvidence(value))
886
+ .map((value, index) => {
887
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
888
+ return `QA diagnostic command ${index + 1} was omitted from pass evidence because it was not a structured passing command.`;
889
+ }
890
+ const record = value;
891
+ const command = optionalString(record, "command") ?? "<missing command>";
892
+ const status = optionalString(record, "status") ?? "<missing status>";
893
+ const exitCode = typeof record.exit_code === "number" && Number.isFinite(record.exit_code)
894
+ ? String(record.exit_code)
895
+ : "<missing exit_code>";
896
+ const summary = optionalString(record, "summary");
897
+ return `QA diagnostic command omitted from pass evidence: ${command} (status ${status}, exit_code ${exitCode})${summary ? ` — ${summary}` : ""}.`;
898
+ });
899
+ }
900
+ function mergeQaObjectArraysById(primary, fallback) {
901
+ const seen = new Set();
902
+ const merged = [];
903
+ for (const value of [...primary, ...fallback]) {
904
+ const id = optionalString(value, "id");
905
+ const key = id ? `id:${id}` : stableStringify(value);
906
+ if (seen.has(key)) {
907
+ continue;
908
+ }
909
+ seen.add(key);
910
+ merged.push(value);
911
+ }
912
+ return merged;
913
+ }
914
+ function dedupeStrings(values) {
915
+ const seen = new Set();
916
+ const deduped = [];
917
+ for (const value of values) {
918
+ const trimmed = value?.trim();
919
+ if (!trimmed || seen.has(trimmed)) {
920
+ continue;
921
+ }
922
+ seen.add(trimmed);
923
+ deduped.push(trimmed);
924
+ }
925
+ return deduped;
926
+ }
712
927
  async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, ownerType, ownerId) {
713
928
  if (sidecars.length === 0) {
714
929
  return [];
@@ -762,19 +977,28 @@ async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, o
762
977
  }
763
978
  return validated;
764
979
  }
765
- export async function readCompletionArtifact(worktreePath, workItemId, phase) {
766
- const artifactPath = completionArtifactJsonPath(worktreePath, workItemId, phase);
767
- const reportPath = completionArtifactReportPath(worktreePath, workItemId, phase);
980
+ export async function readCompletionArtifact(worktreePath, workItemId, phase, ownerType, ownerId) {
981
+ const artifactPath = completionArtifactJsonPath(worktreePath, workItemId, phase, ownerType, ownerId);
982
+ const reportPath = completionArtifactReportPath(worktreePath, workItemId, phase, ownerType, ownerId);
768
983
  const verdictJson = await readOptionalFile(artifactPath);
769
984
  if (verdictJson === null) {
770
985
  return null;
771
986
  }
772
987
  const parsed = parseJsonObject(verdictJson, artifactPath);
773
988
  const report = await readOptionalFile(reportPath) ?? fallbackReport(parsed, phase, artifactPath);
989
+ const artifactRoot = path.dirname(artifactPath);
990
+ const implementationPlanJson = phase === "architect"
991
+ ? await readOptionalFile(path.join(artifactRoot, "implementation.plan.json"))
992
+ : null;
993
+ const qaPlanJson = phase === "architect"
994
+ ? await readOptionalFile(path.join(artifactRoot, "qa.plan.json"))
995
+ : null;
774
996
  return {
775
997
  repoPath: path.resolve(worktreePath),
776
998
  path: artifactPath,
777
999
  verdictJson,
1000
+ implementationPlanJson,
1001
+ qaPlanJson,
778
1002
  report,
779
1003
  producedBy: optionalString(parsed, "produced_by") ?? optionalString(parsed, "producedBy") ?? "forge-completion-tool",
780
1004
  status: optionalString(parsed, "status") ?? "unknown",
@@ -812,6 +1036,7 @@ export function parseCompletionMcpArgs(argv) {
812
1036
  let developCycle = false;
813
1037
  let qaCycle = false;
814
1038
  let debugCycle = false;
1039
+ let architectCycle = false;
815
1040
  for (let index = 1; index < argv.length; index += 1) {
816
1041
  const arg = argv[index];
817
1042
  if (arg === "--worktree") {
@@ -833,7 +1058,7 @@ export function parseCompletionMcpArgs(argv) {
833
1058
  const rawPhase = argv[++index];
834
1059
  const parsedPhase = parseStrictCompletionPhase(rawPhase);
835
1060
  if (!parsedPhase) {
836
- return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation, qa, debug-repro, debug-root-cause, debug-fix, debug-regression." };
1061
+ return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation, qa, architect, debug-repro, debug-root-cause, debug-fix, debug-regression." };
837
1062
  }
838
1063
  phase = parsedPhase;
839
1064
  }
@@ -849,6 +1074,9 @@ export function parseCompletionMcpArgs(argv) {
849
1074
  else if (arg === "--debug-cycle") {
850
1075
  debugCycle = true;
851
1076
  }
1077
+ else if (arg === "--architect-cycle") {
1078
+ architectCycle = true;
1079
+ }
852
1080
  else {
853
1081
  return { ok: false, error: `Unknown mcp argument: ${arg}` };
854
1082
  }
@@ -856,7 +1084,7 @@ export function parseCompletionMcpArgs(argv) {
856
1084
  if (!worktreePath?.trim() || !workItemId?.trim()) {
857
1085
  return { ok: false, error: "mcp requires --worktree and --work-item-id." };
858
1086
  }
859
- if ([developCycle, qaCycle, debugCycle].filter(Boolean).length > 1) {
1087
+ if ([developCycle, qaCycle, debugCycle, architectCycle].filter(Boolean).length > 1) {
860
1088
  return { ok: false, error: "mcp accepts only one cycle mode." };
861
1089
  }
862
1090
  if (developCycle && !isDevelopCompletionPhase(phase)) {
@@ -868,6 +1096,9 @@ export function parseCompletionMcpArgs(argv) {
868
1096
  if (debugCycle && !isDebugCompletionPhase(phase)) {
869
1097
  return { ok: false, error: "mcp --debug-cycle requires --phase debug-repro, debug-root-cause, debug-fix, or debug-regression." };
870
1098
  }
1099
+ if (architectCycle && phase !== "architect") {
1100
+ return { ok: false, error: "mcp --architect-cycle requires --phase architect." };
1101
+ }
871
1102
  return {
872
1103
  ok: true,
873
1104
  config: {
@@ -880,7 +1111,8 @@ export function parseCompletionMcpArgs(argv) {
880
1111
  redactionSecrets: parseCompletionRedactionSecrets(process.env[completionRedactionSecretsEnv]),
881
1112
  developCycle,
882
1113
  qaCycle,
883
- debugCycle
1114
+ debugCycle,
1115
+ architectCycle
884
1116
  }
885
1117
  };
886
1118
  }
@@ -1088,6 +1320,9 @@ function toolDescription(phase, qaGate = null) {
1088
1320
  if (phase === "qa") {
1089
1321
  return "Complete Forge QA by writing qa.plan.json, qa.evidence.json, qa.findings.json, qa.verdict.json, and qa.report.md with structured pass, needs-rework, or blocked evidence.";
1090
1322
  }
1323
+ if (phase === "architect") {
1324
+ return "Complete Forge Architect planning by writing implementation.plan.json, qa.plan.json, architect.verdict.json, and architect.report.md with a pending-approval plan or explicit revision/blocker reasons.";
1325
+ }
1091
1326
  return "Complete Forge validation by writing validation.verdict.json with command, build/test/lint/design, drift, acceptance-criteria, and ready-for-dev-test evidence.";
1092
1327
  }
1093
1328
  function toolInputSchema(phase, qaGate = null) {
@@ -1137,7 +1372,7 @@ function toolInputSchema(phase, qaGate = null) {
1137
1372
  },
1138
1373
  tests_added_or_updated: {
1139
1374
  type: "array",
1140
- description: "Required for pass. Use an object explaining why no tests were needed for docs/config-only work if empty would be ambiguous.",
1375
+ description: "Required for pass. Use an object explaining why no tests were needed for documentation/config-only work if empty would be ambiguous.",
1141
1376
  items: evidenceObjectSchema(["path", "summary"], {
1142
1377
  path: { type: "string" },
1143
1378
  summary: { type: "string" }
@@ -1168,6 +1403,11 @@ function toolInputSchema(phase, qaGate = null) {
1168
1403
  },
1169
1404
  next_phase_context: {
1170
1405
  description: "Required for pass. Context the self-review phase should carry forward."
1406
+ },
1407
+ resolved_findings: {
1408
+ type: "array",
1409
+ description: "Required for QA rework. Each entry must use status resolved, disputed, or not_reproduced.",
1410
+ items: resolvedFindingSchema()
1171
1411
  }
1172
1412
  }, ["status", "summary"], "For status pass, include plan, changed_files, tests_added_or_updated, docs_added_or_updated, acceptance_criteria, known_gaps, and next_phase_context. Acceptance criteria entries must use status: satisfied plus evidence.");
1173
1413
  }
@@ -1303,6 +1543,83 @@ function toolInputSchema(phase, qaGate = null) {
1303
1543
  }
1304
1544
  }, ["status", "summary"], "For pass, include tested_acceptance_criteria plus concrete command/browser/note evidence. For needs_rework, include at least one actionable in_scope finding. For blocked, include blocker_reason.");
1305
1545
  }
1546
+ if (phase === "architect") {
1547
+ return objectToolSchema({
1548
+ status: {
1549
+ type: "string",
1550
+ enum: ["pass", "needs_revision", "blocked"],
1551
+ description: "Use pass only for a complete pending-approval Architect plan. Use needs_revision for fixable story/design/repo gaps, or blocked for missing required context or decisions."
1552
+ },
1553
+ summary: { type: "string", description: "Concise Architect plan verdict summary." },
1554
+ implementation_plan: {
1555
+ type: "object",
1556
+ description: "Required for pass. Top-level fields inside this object must include schema_version, plan_id, phases, tasks, dependencies, and phase_gates.",
1557
+ additionalProperties: true,
1558
+ properties: {
1559
+ schema_version: { type: "number", enum: [1] },
1560
+ plan_id: { type: "string" },
1561
+ phases: {
1562
+ type: "array",
1563
+ description: "Required top-level implementation_plan.phases array.",
1564
+ items: { type: "object", additionalProperties: true }
1565
+ },
1566
+ tasks: {
1567
+ type: "array",
1568
+ description: "Required Develop child task list. Each task must include id and a non-empty tests array, and must require a focused repo/product implementation change. Do not put parent-story QA/sign-off, child-count/materialization inventory, parent plan artifact checks, or final acceptance proof here; those belong in qa_plan.final_qa.",
1569
+ items: { type: "object", additionalProperties: true }
1570
+ },
1571
+ dependencies: {
1572
+ type: "array",
1573
+ description: "Required dependency edge array. Use [] when no task dependencies exist. Each edge should use before and after task ids; from/to are accepted only as aliases and normalized before writing artifacts.",
1574
+ items: {
1575
+ type: "object",
1576
+ additionalProperties: true,
1577
+ properties: {
1578
+ id: { type: "string" },
1579
+ before: { type: "string", description: "Task id that must complete first." },
1580
+ after: { type: "string", description: "Task id that depends on before." },
1581
+ from: { type: "string", description: "Alias for before." },
1582
+ to: { type: "string", description: "Alias for after." },
1583
+ type: { type: "string" },
1584
+ rationale: { type: "string" }
1585
+ }
1586
+ }
1587
+ },
1588
+ phase_gates: {
1589
+ type: "array",
1590
+ description: "Required non-empty phase gate array.",
1591
+ items: { type: "object", additionalProperties: true }
1592
+ }
1593
+ }
1594
+ },
1595
+ qa_plan: {
1596
+ type: "object",
1597
+ description: "Required for pass. Must include schema_version: 1 and non-empty final_qa coverage.",
1598
+ additionalProperties: true,
1599
+ properties: {
1600
+ schema_version: { type: "number", enum: [1] },
1601
+ final_qa: {
1602
+ type: "array",
1603
+ description: "Required non-empty final QA coverage array.",
1604
+ items: { type: "object", additionalProperties: true }
1605
+ }
1606
+ }
1607
+ },
1608
+ report_markdown: { type: "string", description: "Human-readable Architect report. Use report as an alias only when the client cannot send report_markdown." },
1609
+ report: { type: "string", description: "Alias for report_markdown." },
1610
+ blockers: baseProperties.blockers,
1611
+ revision_questions: {
1612
+ type: "array",
1613
+ description: "Required for needs_revision when blockers are not used.",
1614
+ items: { type: "string" }
1615
+ },
1616
+ revision_reasons: {
1617
+ type: "array",
1618
+ description: "Concrete reasons that prevent pass status.",
1619
+ items: { type: "string" }
1620
+ }
1621
+ }, ["status", "summary"], "For status pass, include implementation_plan and qa_plan at the top level of the MCP tool arguments. implementation_plan.phases must be a top-level array inside implementation_plan, not nested under another object.");
1622
+ }
1306
1623
  return objectToolSchema({
1307
1624
  ...baseProperties,
1308
1625
  commands: {
@@ -1382,8 +1699,8 @@ function debugToolInputSchema(phase, baseProperties) {
1382
1699
  },
1383
1700
  resolved_findings: {
1384
1701
  type: "array",
1385
- description: "Required for QA rework. Entries should include qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.",
1386
- items: { type: "object", additionalProperties: true }
1702
+ description: "Required for QA rework. Each entry must use status resolved, disputed, or not_reproduced.",
1703
+ items: resolvedFindingSchema()
1387
1704
  }
1388
1705
  }, ["status", "summary"], "For status pass, include changed_files, tests_added_or_updated, and remaining_risks.");
1389
1706
  }
@@ -1490,6 +1807,29 @@ function commandEvidenceSchema() {
1490
1807
  summary: { type: "string" }
1491
1808
  });
1492
1809
  }
1810
+ function resolvedFindingSchema() {
1811
+ return evidenceObjectSchema([
1812
+ "qa_id",
1813
+ "status",
1814
+ "summary",
1815
+ "evidence",
1816
+ "changed_files",
1817
+ "tests_added_or_updated",
1818
+ "regression_evidence"
1819
+ ], {
1820
+ qa_id: { type: "string" },
1821
+ status: {
1822
+ type: "string",
1823
+ enum: [...resolvedFindingStatusValues],
1824
+ description: "Use resolved when fixed, disputed when the QA finding is incorrect/out-of-scope, or not_reproduced when retesting cannot reproduce it."
1825
+ },
1826
+ summary: { type: "string" },
1827
+ evidence: { description: "Concrete evidence for the resolution." },
1828
+ changed_files: { type: "array", description: "Required and non-empty when status is resolved." },
1829
+ tests_added_or_updated: { type: "array", description: "Required and non-empty when status is resolved." },
1830
+ regression_evidence: { description: "Concrete regression evidence for this QA finding." }
1831
+ });
1832
+ }
1493
1833
  function acceptanceCriteriaSchema() {
1494
1834
  return {
1495
1835
  type: "array",
@@ -1524,6 +1864,13 @@ function normalizeCompletionStatus(value, phase) {
1524
1864
  }
1525
1865
  return canonical;
1526
1866
  }
1867
+ if (phase === "architect") {
1868
+ const canonical = normalized === "needsrevision" ? "needs_revision" : normalized;
1869
+ if (canonical !== "pass" && canonical !== "needs_revision" && canonical !== "blocked") {
1870
+ throw new Error("Architect status must be pass, needs_revision, or blocked.");
1871
+ }
1872
+ return canonical;
1873
+ }
1527
1874
  const canonical = normalized === "blocked" || normalized === "needsrework"
1528
1875
  ? "needs_rework"
1529
1876
  : normalized === "failed"
@@ -1551,6 +1898,10 @@ function validatePayloadShape(phase, payload) {
1551
1898
  validateQaPayloadShape(payload, status);
1552
1899
  return;
1553
1900
  }
1901
+ if (phase === "architect") {
1902
+ validateArchitectPayloadShape(payload, status);
1903
+ return;
1904
+ }
1554
1905
  const pass = status === "pass";
1555
1906
  if (!pass) {
1556
1907
  requireNonPassEvidence(payload);
@@ -1570,6 +1921,7 @@ function validatePayloadShape(phase, payload) {
1570
1921
  requireField(payload, "next_phase_context");
1571
1922
  requireImplementationEvidence(payload);
1572
1923
  requireSatisfiedAcceptanceCriteria(payload);
1924
+ validateResolvedFindings(payload);
1573
1925
  return;
1574
1926
  }
1575
1927
  if (phase === "self_review") {
@@ -1623,6 +1975,7 @@ function validateDebugPayloadShape(phase, payload) {
1623
1975
  if (arrayLength(payload, "tests_added_or_updated") === 0 && arrayLength(payload, "remaining_risks") === 0) {
1624
1976
  throw new Error("tests_added_or_updated is empty; remaining_risks must explain why no regression coverage changed.");
1625
1977
  }
1978
+ validateResolvedFindings(payload);
1626
1979
  return;
1627
1980
  }
1628
1981
  requireArray(payload, "commands");
@@ -1668,6 +2021,7 @@ function validateQaGatePayloadShape(gate, payload, status) {
1668
2021
  if (commands.length === 0) {
1669
2022
  throw new Error(`${qaGateToolNames[gate]} pass requires commands with at least one entry.`);
1670
2023
  }
2024
+ validateQaGatePassingCommands(commands);
1671
2025
  }
1672
2026
  if (gate === "qa_manual_web" && status === "pass") {
1673
2027
  const browserChecks = qaArray(payload, "browser_checks");
@@ -1677,6 +2031,297 @@ function validateQaGatePayloadShape(gate, payload, status) {
1677
2031
  }
1678
2032
  }
1679
2033
  }
2034
+ function validateQaGatePassingCommands(commands) {
2035
+ for (const [index, command] of commands.entries()) {
2036
+ requireEvidenceRecord(command, `commands[${index}]`);
2037
+ const record = command;
2038
+ requireNonEmptyStringRecord(record, "command", `commands[${index}].`);
2039
+ requireNonEmptyStringRecord(record, "status", `commands[${index}].`);
2040
+ requireNonEmptyStringRecord(record, "summary", `commands[${index}].`);
2041
+ if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
2042
+ throw new Error(`commands[${index}].exit_code is required.`);
2043
+ }
2044
+ if (record.exit_code !== 0) {
2045
+ throw new Error(`commands[${index}].exit_code must be 0 when QA gate status is pass.`);
2046
+ }
2047
+ if (normalizedString(record.status) !== "pass") {
2048
+ throw new Error(`commands[${index}].status must be pass when QA gate status is pass.`);
2049
+ }
2050
+ }
2051
+ }
2052
+ function validateArchitectPayloadShape(payload, status) {
2053
+ if (status !== "pass") {
2054
+ requireArchitectNonPassEvidence(payload);
2055
+ return;
2056
+ }
2057
+ const implementationPlan = requiredRecord(payload, "implementation_plan");
2058
+ const qaPlan = requiredRecord(payload, "qa_plan");
2059
+ requireNumericOne(implementationPlan, "schema_version", "implementation_plan.schema_version");
2060
+ requireNonEmptyStringRecord(implementationPlan, "plan_id", "implementation_plan.");
2061
+ requireArchitectArray(implementationPlan, "phases", payload);
2062
+ requireArchitectArray(implementationPlan, "tasks", payload);
2063
+ requireArchitectArray(implementationPlan, "dependencies", payload, { allowEmpty: true });
2064
+ requireArchitectArray(implementationPlan, "phase_gates", payload);
2065
+ if (arrayLength(implementationPlan, "tasks") === 0) {
2066
+ throw new Error("implementation_plan.tasks: expected non-empty array; correction: include at least one task with id and tests.");
2067
+ }
2068
+ const taskIds = new Set();
2069
+ for (const task of implementationPlan.tasks) {
2070
+ if (!task || typeof task !== "object" || Array.isArray(task)) {
2071
+ throw new Error("implementation_plan.tasks[]: expected object entries; correction: each task must be an object with id and tests.");
2072
+ }
2073
+ const taskRecord = task;
2074
+ requireNonEmptyStringRecord(taskRecord, "id", "implementation_plan.tasks[].");
2075
+ const taskId = optionalString(taskRecord, "id") ?? "";
2076
+ if (taskIds.has(taskId)) {
2077
+ throw new Error(`implementation_plan.tasks: duplicate task id '${taskId}'.`);
2078
+ }
2079
+ taskIds.add(taskId);
2080
+ validateArchitectTaskDevelopScope(taskRecord, taskId);
2081
+ requireArchitectArray(taskRecord, "tests", payload, { path: `implementation_plan.tasks[${optionalString(taskRecord, "id") ?? "?"}].tests` });
2082
+ if (arrayLength(taskRecord, "tests") === 0) {
2083
+ throw new Error(`implementation_plan.tasks[${optionalString(taskRecord, "id") ?? "?"}].tests: expected non-empty array; correction: include task-specific verification.`);
2084
+ }
2085
+ }
2086
+ validateAndNormalizeArchitectDependencies(implementationPlan, taskIds);
2087
+ requireNumericOne(qaPlan, "schema_version", "qa_plan.schema_version");
2088
+ requireArchitectArray(qaPlan, "final_qa", payload, { path: "qa_plan.final_qa" });
2089
+ if (arrayLength(qaPlan, "final_qa") === 0) {
2090
+ throw new Error("qa_plan.final_qa: expected non-empty array; correction: include final QA coverage for the completed plan.");
2091
+ }
2092
+ }
2093
+ function validateArchitectTaskDevelopScope(task, taskId) {
2094
+ const explicitScope = firstOptionalString(task, ["execution_scope", "scope", "task_scope", "task_type", "lane", "kind", "type"]);
2095
+ if (isStoryQaScope(explicitScope)) {
2096
+ throw new Error(`implementation_plan.tasks[${taskId}]: story QA/sign-off work must not be materialized as a Develop child task; correction: move this coverage to qa_plan.final_qa and keep implementation_plan.tasks limited to repo/product changes.`);
2097
+ }
2098
+ if (looksLikeStoryLevelVerificationTask(architectTaskScopeText(task))) {
2099
+ throw new Error(`implementation_plan.tasks[${taskId}]: parent-story materialization or sign-off verification belongs in qa_plan.final_qa, not implementation_plan.tasks; correction: keep child tasks focused on implementation work and put child-count/parent-plan artifact checks in final QA coverage.`);
2100
+ }
2101
+ }
2102
+ function firstOptionalString(record, keys) {
2103
+ for (const key of keys) {
2104
+ const value = optionalString(record, key);
2105
+ if (value) {
2106
+ return value;
2107
+ }
2108
+ }
2109
+ return null;
2110
+ }
2111
+ function isStoryQaScope(value) {
2112
+ if (!value) {
2113
+ return false;
2114
+ }
2115
+ const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_");
2116
+ return [
2117
+ "qa",
2118
+ "story_qa",
2119
+ "final_qa",
2120
+ "sign_off",
2121
+ "signoff",
2122
+ "story_sign_off",
2123
+ "story_verification",
2124
+ "story_validation"
2125
+ ].includes(normalized);
2126
+ }
2127
+ function architectTaskScopeText(task) {
2128
+ const parts = [];
2129
+ for (const key of ["id", "title", "summary", "phase", "phase_id"]) {
2130
+ appendOptionalString(parts, task, key);
2131
+ }
2132
+ for (const key of ["acceptance_criteria", "expected_paths", "touched_surfaces", "implementation_notes"]) {
2133
+ appendOptionalStringArray(parts, task, key);
2134
+ }
2135
+ const tests = task.tests;
2136
+ if (Array.isArray(tests)) {
2137
+ for (const test of tests) {
2138
+ if (!test || typeof test !== "object" || Array.isArray(test)) {
2139
+ continue;
2140
+ }
2141
+ const record = test;
2142
+ for (const key of ["id", "command", "purpose", "target", "expected"]) {
2143
+ appendOptionalString(parts, record, key);
2144
+ }
2145
+ appendOptionalStringArray(parts, record, "steps");
2146
+ }
2147
+ }
2148
+ return parts.join(" ");
2149
+ }
2150
+ function appendOptionalString(parts, record, key) {
2151
+ const value = optionalString(record, key);
2152
+ if (value) {
2153
+ parts.push(value);
2154
+ }
2155
+ }
2156
+ function appendOptionalStringArray(parts, record, key) {
2157
+ const value = record[key];
2158
+ if (!Array.isArray(value)) {
2159
+ return;
2160
+ }
2161
+ for (const entry of value) {
2162
+ if (typeof entry === "string" && entry.trim().length > 0) {
2163
+ parts.push(entry.trim());
2164
+ }
2165
+ }
2166
+ }
2167
+ function looksLikeStoryLevelVerificationTask(text) {
2168
+ if (!text.trim()) {
2169
+ return false;
2170
+ }
2171
+ const normalized = text.toLowerCase();
2172
+ const verificationWords = [
2173
+ "verify",
2174
+ "verification",
2175
+ "validate",
2176
+ "validation",
2177
+ "inspect",
2178
+ "audit",
2179
+ "check",
2180
+ "confirm",
2181
+ "prove",
2182
+ "evidence",
2183
+ "sign-off",
2184
+ "sign off"
2185
+ ];
2186
+ if (!verificationWords.some((word) => normalized.includes(word))) {
2187
+ return false;
2188
+ }
2189
+ return [
2190
+ "materialization",
2191
+ "materialized child",
2192
+ "child inventory",
2193
+ "child work-item",
2194
+ "child work item",
2195
+ "created task count",
2196
+ "created_task_count",
2197
+ "parent plan",
2198
+ "parent story",
2199
+ "story sign-off",
2200
+ "story sign off",
2201
+ ".forge/work-items",
2202
+ ".forge\\work-items",
2203
+ ".forge/stories",
2204
+ ".forge\\stories",
2205
+ "implementation.plan.json",
2206
+ "qa.plan.json",
2207
+ "architect plan artifact",
2208
+ "child spec"
2209
+ ].some((needle) => normalized.includes(needle));
2210
+ }
2211
+ function validateAndNormalizeArchitectDependencies(implementationPlan, taskIds) {
2212
+ const dependencies = implementationPlan.dependencies;
2213
+ const edges = new Map();
2214
+ for (const taskId of taskIds) {
2215
+ edges.set(taskId, []);
2216
+ }
2217
+ const normalizedDependencies = [];
2218
+ for (const [index, dependency] of dependencies.entries()) {
2219
+ if (!dependency || typeof dependency !== "object" || Array.isArray(dependency)) {
2220
+ throw new Error("implementation_plan.dependencies[]: expected object entries; correction: each dependency must be an object with before and after task ids.");
2221
+ }
2222
+ const record = dependency;
2223
+ const before = architectDependencyEndpoint(record, index, "before", "from");
2224
+ const after = architectDependencyEndpoint(record, index, "after", "to");
2225
+ if (!taskIds.has(before) || !taskIds.has(after)) {
2226
+ throw new Error("implementation_plan.dependencies: dependency references an unknown task id.");
2227
+ }
2228
+ const normalized = stripUndefined({
2229
+ ...record,
2230
+ before,
2231
+ after,
2232
+ from: undefined,
2233
+ to: undefined
2234
+ });
2235
+ normalizedDependencies.push(normalized);
2236
+ edges.get(before)?.push(after);
2237
+ }
2238
+ implementationPlan.dependencies = normalizedDependencies;
2239
+ if (hasArchitectDependencyCycle(edges)) {
2240
+ throw new Error("implementation_plan.dependencies: expected acyclic graph; correction: remove or revise cyclic task dependencies.");
2241
+ }
2242
+ }
2243
+ function architectDependencyEndpoint(dependency, index, canonicalKey, aliasKey) {
2244
+ const canonical = optionalString(dependency, canonicalKey);
2245
+ const alias = optionalString(dependency, aliasKey);
2246
+ if (canonical && alias && canonical !== alias) {
2247
+ throw new Error(`implementation_plan.dependencies[${index}].${canonicalKey}: conflicts with ${aliasKey}; correction: use one task id for ${canonicalKey}.`);
2248
+ }
2249
+ const value = canonical ?? alias;
2250
+ if (!value) {
2251
+ throw new Error(`implementation_plan.dependencies[${index}].${canonicalKey}: expected string; correction: use before and after task ids for each dependency.`);
2252
+ }
2253
+ return value;
2254
+ }
2255
+ function hasArchitectDependencyCycle(edges) {
2256
+ const visiting = new Set();
2257
+ const visited = new Set();
2258
+ const visit = (node) => {
2259
+ if (visited.has(node)) {
2260
+ return false;
2261
+ }
2262
+ if (visiting.has(node)) {
2263
+ return true;
2264
+ }
2265
+ visiting.add(node);
2266
+ for (const next of edges.get(node) ?? []) {
2267
+ if (visit(next)) {
2268
+ return true;
2269
+ }
2270
+ }
2271
+ visiting.delete(node);
2272
+ visited.add(node);
2273
+ return false;
2274
+ };
2275
+ for (const node of edges.keys()) {
2276
+ if (visit(node)) {
2277
+ return true;
2278
+ }
2279
+ }
2280
+ return false;
2281
+ }
2282
+ function requireArchitectNonPassEvidence(payload) {
2283
+ const evidenceKeys = ["blockers", "revision_questions", "revision_reasons", "known_gaps", "findings", "remaining_risks", "failures"];
2284
+ const hasEvidence = evidenceKeys.some((key) => {
2285
+ const value = payload[key];
2286
+ if (typeof value === "string") {
2287
+ return value.trim().length > 0;
2288
+ }
2289
+ if (Array.isArray(value)) {
2290
+ return value.length > 0;
2291
+ }
2292
+ return Boolean(value && typeof value === "object");
2293
+ });
2294
+ if (!hasEvidence) {
2295
+ throw new Error("status: non-pass Architect completion requires blockers, revision_questions, revision_reasons, findings, failures, or known_gaps; correction: explain why the plan cannot pass.");
2296
+ }
2297
+ }
2298
+ function requireArchitectArray(source, key, rootPayload, options = {}) {
2299
+ const pathLabel = options.path ?? `implementation_plan.${key}`;
2300
+ if (!Array.isArray(source[key])) {
2301
+ const nestedHint = architectNestedArrayHint(rootPayload, key);
2302
+ throw new Error(`${pathLabel}: expected array${key === "phases" ? " as a top-level field inside implementation_plan" : ""}; correction: ${nestedHint ?? `set ${pathLabel} to an array${options.allowEmpty ? " (use [] when none exist)" : " with at least one entry"}.`}`);
2303
+ }
2304
+ if (!options.allowEmpty && arrayLength(source, key) === 0) {
2305
+ throw new Error(`${pathLabel}: expected non-empty array; correction: include at least one entry.`);
2306
+ }
2307
+ }
2308
+ function architectNestedArrayHint(rootPayload, key) {
2309
+ if (Array.isArray(rootPayload[key])) {
2310
+ return `move top-level ${key} into implementation_plan.${key}.`;
2311
+ }
2312
+ const implementationPlan = rootPayload.implementation_plan;
2313
+ if (!implementationPlan || typeof implementationPlan !== "object" || Array.isArray(implementationPlan)) {
2314
+ return null;
2315
+ }
2316
+ const plan = implementationPlan;
2317
+ for (const container of ["plan", "dag", "implementation_dag", "implementationPlan", "implementation_plan"]) {
2318
+ const nested = plan[container];
2319
+ if (nested && typeof nested === "object" && !Array.isArray(nested) && Array.isArray(nested[key])) {
2320
+ return `move implementation_plan.${container}.${key} to implementation_plan.${key}.`;
2321
+ }
2322
+ }
2323
+ return null;
2324
+ }
1680
2325
  function validateQaPayloadShape(payload, status) {
1681
2326
  const evidenceSource = qaEvidenceSource(payload);
1682
2327
  const commands = qaArray(payload, "commands", evidenceSource);
@@ -1881,6 +2526,9 @@ function parseStrictCompletionPhase(value) {
1881
2526
  if (normalized === "qa" || normalized === "quality_assurance" || normalized === "qualityassurance") {
1882
2527
  return "qa";
1883
2528
  }
2529
+ if (normalized === "architect" || normalized === "architect_plan" || normalized === "planning" || normalized === "plan") {
2530
+ return "architect";
2531
+ }
1884
2532
  return null;
1885
2533
  }
1886
2534
  function normalizeDebugCompletionPhase(value) {
@@ -1949,6 +2597,9 @@ function phaseFromToolName(toolName) {
1949
2597
  if (normalized === "forge.complete_qa" || normalized === "complete_qa") {
1950
2598
  return "qa";
1951
2599
  }
2600
+ if (normalized === "forge.complete_architect_plan" || normalized === "complete_architect_plan") {
2601
+ return "architect";
2602
+ }
1952
2603
  const debugGate = debugGateFromToolName(toolName);
1953
2604
  if (debugGate) {
1954
2605
  return debugGate;
@@ -2067,11 +2718,20 @@ function requireObject(payload, key) {
2067
2718
  throw new Error(`${key} must be an object.`);
2068
2719
  }
2069
2720
  }
2721
+ function requiredRecord(payload, key) {
2722
+ requireObject(payload, key);
2723
+ return payload[key];
2724
+ }
2070
2725
  function requireBoolean(payload, key) {
2071
2726
  if (typeof payload[key] !== "boolean") {
2072
2727
  throw new Error(`${key} must be a boolean.`);
2073
2728
  }
2074
2729
  }
2730
+ function requireNumericOne(payload, key, pathLabel) {
2731
+ if (payload[key] !== 1) {
2732
+ throw new Error(`${pathLabel}: expected numeric 1; correction: set ${pathLabel} to 1.`);
2733
+ }
2734
+ }
2075
2735
  function requireSatisfiedAcceptanceCriteria(payload) {
2076
2736
  const criteria = payload.acceptance_criteria;
2077
2737
  if (!Array.isArray(criteria)) {
@@ -2089,6 +2749,37 @@ function requireSatisfiedAcceptanceCriteria(payload) {
2089
2749
  }
2090
2750
  }
2091
2751
  }
2752
+ function validateResolvedFindings(payload) {
2753
+ const resolvedFindings = payload.resolved_findings;
2754
+ if (resolvedFindings === undefined || resolvedFindings === null) {
2755
+ return;
2756
+ }
2757
+ if (!Array.isArray(resolvedFindings)) {
2758
+ throw new Error("resolved_findings must be an array.");
2759
+ }
2760
+ for (const [index, finding] of resolvedFindings.entries()) {
2761
+ const prefix = `resolved_findings[${index}].`;
2762
+ if (!finding || typeof finding !== "object" || Array.isArray(finding)) {
2763
+ throw new Error(`resolved_findings[${index}] must be an object.`);
2764
+ }
2765
+ const record = finding;
2766
+ requireNonEmptyStringRecord(record, "qa_id", prefix);
2767
+ requireKnownStringRecord(record, "status", resolvedFindingStatuses, prefix);
2768
+ requireNonEmptyStringRecord(record, "summary", prefix);
2769
+ requireSubstantiveValueRecord(record, "evidence", prefix);
2770
+ requireArrayRecord(record, "changed_files", prefix);
2771
+ requireArrayRecord(record, "tests_added_or_updated", prefix);
2772
+ requireSubstantiveValueRecord(record, "regression_evidence", prefix);
2773
+ if (normalizedString(record.status) === "resolved") {
2774
+ if (record.changed_files.length === 0) {
2775
+ throw new Error(`${prefix}changed_files must include at least one changed file for resolved QA findings.`);
2776
+ }
2777
+ if (record.tests_added_or_updated.length === 0) {
2778
+ throw new Error(`${prefix}tests_added_or_updated must include at least one regression test for resolved QA findings.`);
2779
+ }
2780
+ }
2781
+ }
2782
+ }
2092
2783
  function qaEvidenceSource(payload) {
2093
2784
  const evidence = payload.evidence;
2094
2785
  return evidence && typeof evidence === "object" && !Array.isArray(evidence)
@@ -2138,6 +2829,11 @@ function requireNonEmptyStringRecord(source, key, prefix = "") {
2138
2829
  throw new Error(`${prefix}${key} is required.`);
2139
2830
  }
2140
2831
  }
2832
+ function requireArrayRecord(source, key, prefix = "") {
2833
+ if (!Array.isArray(source[key])) {
2834
+ throw new Error(`${prefix}${key} must be an array.`);
2835
+ }
2836
+ }
2141
2837
  function requireKnownStringRecord(source, key, allowed, prefix = "") {
2142
2838
  const value = normalizedString(optionalString(source, key));
2143
2839
  if (!allowed.has(value)) {
@@ -2155,6 +2851,11 @@ function requireNonEmptyStringArrayRecord(source, key, prefix = "") {
2155
2851
  }
2156
2852
  }
2157
2853
  }
2854
+ function requireSubstantiveValueRecord(source, key, prefix = "") {
2855
+ if (!hasSubstantiveJsonValue(source[key])) {
2856
+ throw new Error(`${prefix}${key} must include at least one concrete evidence reference or summary.`);
2857
+ }
2858
+ }
2158
2859
  function requireSubstantiveEvidenceRecord(source, prefix = "") {
2159
2860
  const evidence = source.evidence;
2160
2861
  if (!evidence || typeof evidence !== "object" || Array.isArray(evidence)) {
@@ -2237,7 +2938,7 @@ function parseJsonObject(content, label) {
2237
2938
  return asRecord(JSON.parse(content), label);
2238
2939
  }
2239
2940
  catch (error) {
2240
- throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`);
2941
+ throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`, { cause: error });
2241
2942
  }
2242
2943
  }
2243
2944
  function parseOptionalJsonObject(content, label) {