sdtk-code-kit 0.3.0 → 0.3.1

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 (56) hide show
  1. package/README.md +204 -204
  2. package/assets/manifest/toolkit-bundle.manifest.json +147 -147
  3. package/assets/manifest/toolkit-bundle.sha256.txt +5 -5
  4. package/bin/sdtk-code.js +14 -14
  5. package/package.json +44 -44
  6. package/src/commands/agent-team.js +425 -174
  7. package/src/commands/build.js +53 -53
  8. package/src/commands/doctor.js +51 -51
  9. package/src/commands/generate.js +11 -11
  10. package/src/commands/guardrails.js +215 -215
  11. package/src/commands/help.js +264 -257
  12. package/src/commands/init.js +98 -98
  13. package/src/commands/plan.js +53 -53
  14. package/src/commands/readiness.js +77 -77
  15. package/src/commands/resume.js +61 -61
  16. package/src/commands/runtime.js +224 -224
  17. package/src/commands/ship.js +59 -59
  18. package/src/commands/sleep.js +132 -132
  19. package/src/commands/start.js +89 -89
  20. package/src/commands/status.js +77 -77
  21. package/src/commands/update.js +11 -11
  22. package/src/commands/verify.js +71 -71
  23. package/src/index.js +112 -112
  24. package/src/lib/agent-team-author.js +521 -0
  25. package/src/lib/agent-team-evidence.js +302 -0
  26. package/src/lib/agent-team-execute.js +892 -0
  27. package/src/lib/agent-team-export.js +411 -409
  28. package/src/lib/agent-team-plan.js +514 -514
  29. package/src/lib/agent-team-readiness.js +161 -0
  30. package/src/lib/agent-team-report.js +165 -0
  31. package/src/lib/args.js +107 -107
  32. package/src/lib/errors.js +41 -41
  33. package/src/lib/model-provider.js +219 -0
  34. package/src/lib/powershell.js +65 -65
  35. package/src/lib/project-target-guard.js +53 -53
  36. package/src/lib/scope.js +72 -72
  37. package/src/lib/ship-readiness.js +281 -281
  38. package/src/lib/sleep-plan.js +175 -175
  39. package/src/lib/sleep-report.js +229 -229
  40. package/src/lib/toolkit-payload.js +72 -72
  41. package/src/lib/trust-events.js +252 -185
  42. package/src/lib/trust-file-scope.js +154 -154
  43. package/src/lib/trust-policy.js +212 -212
  44. package/src/lib/trust-redact.js +58 -35
  45. package/src/lib/trust-trace.js +179 -179
  46. package/src/lib/update.js +344 -344
  47. package/src/lib/workflow-artifact.js +503 -503
  48. package/src/lib/workflow-build.js +127 -127
  49. package/src/lib/workflow-doctor.js +83 -83
  50. package/src/lib/workflow-handoff.js +1029 -1029
  51. package/src/lib/workflow-intake.js +101 -101
  52. package/src/lib/workflow-plan.js +193 -193
  53. package/src/lib/workflow-review-packet.js +650 -650
  54. package/src/lib/workflow-ship.js +213 -213
  55. package/src/lib/workflow-state.js +438 -438
  56. package/src/lib/workflow-verify.js +393 -393
@@ -1,1029 +1,1029 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const { extractManagedBlock, getWorkflowArtifactPath } = require("./workflow-artifact");
6
-
7
- const LATEST_HANDOFF_SCHEMA_VERSION = "0.2";
8
- const ACCEPTED_HANDOFF_SCHEMA_VERSIONS = new Set(["0.1", "0.2"]);
9
- const HANDOFF_STATUSES = new Set(["READY_FOR_SDTK_CODE", "BLOCKED_FOR_SDTK_CODE"]);
10
- const HANDOFF_LANES = new Set(["feature", "bugfix"]);
11
- const OPS_HANDOFF_SCHEMA_VERSION = "0.1";
12
- const OPS_HANDOFF_READY_STATUS = "READY_FOR_SDTK_OPS";
13
-
14
- function normalizePathForDoc(projectPath, targetPath) {
15
- return path.relative(projectPath, targetPath).split(path.sep).join("/");
16
- }
17
-
18
- function getCodeHandoffPath(projectPath, featureKey) {
19
- return path.join(projectPath, "docs", "dev", `CODE_HANDOFF_${featureKey}.json`);
20
- }
21
-
22
- function getOpsHandoffPath(projectPath, featureKey) {
23
- return path.join(projectPath, "docs", "dev", `OPS_HANDOFF_${featureKey}.json`);
24
- }
25
-
26
- function buildPathEntry(key, projectPath, relativePath) {
27
- const normalized = relativePath.split("/").join(path.sep);
28
- const fullPath = path.join(projectPath, normalized);
29
- return {
30
- key,
31
- path: fullPath,
32
- exists: fs.existsSync(fullPath),
33
- };
34
- }
35
-
36
- function uniquePathEntries(entries) {
37
- const seen = new Set();
38
- const result = [];
39
-
40
- for (const entry of entries) {
41
- const key = `${entry.key}::${entry.path}`;
42
- if (seen.has(key)) {
43
- continue;
44
- }
45
- seen.add(key);
46
- result.push(entry);
47
- }
48
-
49
- return result;
50
- }
51
-
52
- function getSuggestedEngineSkills(lane, blocked) {
53
- if (blocked) {
54
- return ["code-discover"];
55
- }
56
- if (lane === "feature") {
57
- return ["code-plan", "code-brainstorm (if ambiguity remains)"];
58
- }
59
- return ["code-debug (when reproducing failure)", "code-tdd", "code-execute"];
60
- }
61
-
62
- function createIntakeResult({
63
- projectPath,
64
- featureKey,
65
- lane,
66
- requiredInputs,
67
- optionalInputs,
68
- missingInputs,
69
- blocked,
70
- intakeOutcome,
71
- nextPhase,
72
- phaseStatus,
73
- blockingState,
74
- intakeSource,
75
- handoffStatus,
76
- compatibilityWarnings = [],
77
- blockingMessage,
78
- blockingDetails = [],
79
- candidateSlices = [],
80
- candidatePlanningNotes = [],
81
- }) {
82
- return {
83
- requiredInputs: uniquePathEntries(requiredInputs || []),
84
- optionalInputs: uniquePathEntries(optionalInputs || []),
85
- missingInputs: uniquePathEntries(missingInputs || []),
86
- blocked,
87
- intakeOutcome,
88
- nextPhase,
89
- phaseStatus,
90
- blockingState,
91
- suggestedEngineSkills: getSuggestedEngineSkills(lane, blocked),
92
- normalizePath: (targetPath) => normalizePathForDoc(projectPath, targetPath),
93
- intakeSource,
94
- handoffStatus,
95
- compatibilityWarnings,
96
- blockingMessage,
97
- blockingDetails,
98
- featureKey,
99
- lane,
100
- candidateSlices,
101
- candidatePlanningNotes,
102
- };
103
- }
104
-
105
- function createBlockedFormalIntake({
106
- projectPath,
107
- featureKey,
108
- lane,
109
- handoffStatus,
110
- requiredInputs,
111
- optionalInputs,
112
- blockingState,
113
- blockingMessage,
114
- blockingDetails = [],
115
- compatibilityWarnings = [],
116
- }) {
117
- const missingInputs = (requiredInputs || []).filter((entry) => !entry.exists);
118
-
119
- return createIntakeResult({
120
- projectPath,
121
- featureKey,
122
- lane,
123
- requiredInputs,
124
- optionalInputs,
125
- missingInputs,
126
- blocked: true,
127
- intakeOutcome: "BLOCKED_UPSTREAM_HANDOFF",
128
- nextPhase: "blocked",
129
- phaseStatus: "blocked",
130
- blockingState,
131
- intakeSource: "formal_handoff",
132
- handoffStatus,
133
- compatibilityWarnings,
134
- blockingMessage,
135
- blockingDetails,
136
- });
137
- }
138
-
139
- function isNonEmptyString(value) {
140
- return typeof value === "string" && value.trim().length > 0;
141
- }
142
-
143
- function normalizeRelativePath(value, label) {
144
- if (!isNonEmptyString(value)) {
145
- throw new Error(`${label} must be a non-empty repo-relative forward-slash path.`);
146
- }
147
-
148
- const trimmed = value.trim();
149
- if (trimmed.includes("\\")) {
150
- throw new Error(`${label} must use repo-relative forward-slash paths: ${trimmed}`);
151
- }
152
- if (trimmed.startsWith("/")) {
153
- throw new Error(`${label} must be repo-relative, not absolute: ${trimmed}`);
154
- }
155
- if (/^[A-Za-z]:/.test(trimmed)) {
156
- throw new Error(`${label} must be repo-relative, not drive-qualified: ${trimmed}`);
157
- }
158
-
159
- return trimmed;
160
- }
161
-
162
- function requireArray(payload, key) {
163
- if (!Array.isArray(payload[key])) {
164
- throw new Error(`${key} must be an array.`);
165
- }
166
- return payload[key];
167
- }
168
-
169
- function collectSoftWarnings(payload) {
170
- const warnings = [];
171
-
172
- if (payload.schema_version === "0.1") {
173
- warnings.push(
174
- 'Formal handoff compatibility warning: schema_version "0.1" is still accepted, but richer BK-057 planning context is unavailable.'
175
- );
176
- }
177
-
178
- if (payload.generated_by !== "sdtk-dev") {
179
- warnings.push(
180
- `Formal handoff compatibility warning: generated_by is ${JSON.stringify(
181
- payload.generated_by
182
- )}; expected "sdtk-dev".`
183
- );
184
- }
185
-
186
- if (!isNonEmptyString(payload.generated_at)) {
187
- warnings.push("Formal handoff compatibility warning: generated_at is missing or empty.");
188
- }
189
-
190
- return warnings;
191
- }
192
-
193
- function normalizeStringArray(entries, label) {
194
- if (!Array.isArray(entries)) {
195
- throw new Error(`${label} must be an array.`);
196
- }
197
-
198
- return entries.map((entry) => String(entry).trim()).filter(Boolean);
199
- }
200
-
201
- function normalizeOptionalStringArray(entries, label) {
202
- if (entries == null) {
203
- return [];
204
- }
205
-
206
- return normalizeStringArray(entries, label);
207
- }
208
-
209
- function normalizeImpactMap(impactMap) {
210
- if (impactMap == null) {
211
- return null;
212
- }
213
- if (!impactMap || typeof impactMap !== "object" || Array.isArray(impactMap)) {
214
- throw new Error("impact_map must be an object.");
215
- }
216
-
217
- return {
218
- api_refs: normalizeStringArray(requireArray(impactMap, "api_refs"), "impact_map.api_refs").map((entry, index) =>
219
- normalizeRelativePath(entry, `impact_map.api_refs[${index}]`)
220
- ),
221
- database_refs: normalizeStringArray(requireArray(impactMap, "database_refs"), "impact_map.database_refs").map(
222
- (entry, index) => normalizeRelativePath(entry, `impact_map.database_refs[${index}]`)
223
- ),
224
- ui_refs: normalizeStringArray(requireArray(impactMap, "ui_refs"), "impact_map.ui_refs").map((entry, index) =>
225
- normalizeRelativePath(entry, `impact_map.ui_refs[${index}]`)
226
- ),
227
- flow_refs: normalizeStringArray(requireArray(impactMap, "flow_refs"), "impact_map.flow_refs").map((entry, index) =>
228
- normalizeRelativePath(entry, `impact_map.flow_refs[${index}]`)
229
- ),
230
- };
231
- }
232
-
233
- function buildImpactPlanningNotes(impactMap) {
234
- if (!impactMap) {
235
- return [];
236
- }
237
-
238
- const categoryLabels = {
239
- api_refs: "API refs",
240
- database_refs: "Database refs",
241
- ui_refs: "UI refs",
242
- flow_refs: "Flow refs",
243
- };
244
-
245
- return Object.entries(categoryLabels)
246
- .filter(([key]) => Array.isArray(impactMap[key]) && impactMap[key].length > 0)
247
- .map(([key, label]) => `Seeded impact ${label}: ${impactMap[key].join(", ")}`);
248
- }
249
-
250
- function buildCandidatePlanningSeed(
251
- lane,
252
- implementationSlices,
253
- testObligations,
254
- { schemaVersion, impactMap = null, recoveryNotes = [] } = {}
255
- ) {
256
- if (lane !== "feature") {
257
- return {
258
- candidateSlices: [],
259
- candidatePlanningNotes: [],
260
- };
261
- }
262
-
263
- const candidatePlanningNotes = [
264
- "Seeded from the formal SDTK-SPEC handoff. Confirm or refine these candidate slices during `sdtk-code plan`.",
265
- ];
266
-
267
- if (schemaVersion === "0.2") {
268
- candidatePlanningNotes.push(
269
- "Seeded build order: implementation_slices order from the formal SDTK-SPEC handoff is the recommended downstream sequence."
270
- );
271
- candidatePlanningNotes.push(...buildImpactPlanningNotes(impactMap));
272
- }
273
-
274
- if (testObligations.length > 0) {
275
- candidatePlanningNotes.push(
276
- ...testObligations.map((entry) => `Seeded test obligation: ${entry}`)
277
- );
278
- }
279
-
280
- if (schemaVersion === "0.2" && recoveryNotes.length > 0) {
281
- candidatePlanningNotes.push(
282
- ...recoveryNotes.map((entry) => `Seeded recovery note: ${entry}`)
283
- );
284
- }
285
-
286
- return {
287
- candidateSlices: implementationSlices,
288
- candidatePlanningNotes,
289
- };
290
- }
291
-
292
- function humanizeFeatureKey(featureKey) {
293
- return String(featureKey)
294
- .split("_")
295
- .filter(Boolean)
296
- .map((token) => token.charAt(0) + token.slice(1).toLowerCase())
297
- .join(" ");
298
- }
299
-
300
- function uniqueStrings(entries) {
301
- return [...new Set((entries || []).map((entry) => String(entry).trim()).filter(Boolean))];
302
- }
303
-
304
- function uniqueObjects(entries, keyBuilder) {
305
- const seen = new Set();
306
- const results = [];
307
- for (const entry of entries || []) {
308
- const key = keyBuilder(entry);
309
- if (!key || seen.has(key)) {
310
- continue;
311
- }
312
- seen.add(key);
313
- results.push(entry);
314
- }
315
- return results;
316
- }
317
-
318
- function parseBulletEntries(sectionText) {
319
- if (!sectionText) {
320
- return [];
321
- }
322
-
323
- return sectionText
324
- .split(/\r?\n/)
325
- .map((line) => line.trim())
326
- .filter((line) => line.startsWith("- "))
327
- .map((line) => line.slice(2).trim())
328
- .filter(Boolean);
329
- }
330
-
331
- function parseBlockSection(blockText, heading) {
332
- if (!blockText) {
333
- return [];
334
- }
335
-
336
- const escapedHeading = heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
337
- const match = blockText.match(new RegExp(`### ${escapedHeading}\\r?\\n([\\s\\S]*?)(?=\\r?\\n### |$)`));
338
- return match ? parseBulletEntries(match[1]) : [];
339
- }
340
-
341
- function parseInlineSliceSection(planBlock) {
342
- if (!planBlock) {
343
- return [];
344
- }
345
-
346
- const match = planBlock.match(/## 4\. Plan \/ Slices\r?\n([\s\S]*?)(?=\r?\n### Planning Notes)/);
347
- return match ? parseBulletEntries(match[1]) : [];
348
- }
349
-
350
- function isPlaceholderSlice(value) {
351
- return [
352
- "Pending confirmation during workflow planning.",
353
- "Pending lane-specific planning or build guidance.",
354
- "Lightweight bugfix planning not recorded yet.",
355
- "No active build slices recorded yet.",
356
- "Pending build-phase execution.",
357
- ].includes(value);
358
- }
359
-
360
- function cleanSliceEntries(entries) {
361
- return uniqueStrings(entries).filter((entry) => !isPlaceholderSlice(entry));
362
- }
363
-
364
- function deriveScopeSliceId(title, index) {
365
- const prefixed = title.match(/^([A-Z]\d+(?:-[A-Za-z0-9]+)?)\s*:/);
366
- if (prefixed) {
367
- return prefixed[1];
368
- }
369
-
370
- const tokenized = title.match(/^([A-Z]\d+(?:-[A-Za-z0-9]+)?)\b/);
371
- if (tokenized) {
372
- return tokenized[1];
373
- }
374
-
375
- return `S${index + 1}`;
376
- }
377
-
378
- function deriveOpsImpactSummary(title) {
379
- const lower = title.toLowerCase();
380
-
381
- if (/\b(database|migration|schema|sql|table|db)\b/.test(lower)) {
382
- return "Requires rollout sequencing plus migration and recovery safety checks.";
383
- }
384
- if (/\b(api|service|endpoint|backend|auth)\b/.test(lower)) {
385
- return "Requires runtime service deployment plus API smoke validation.";
386
- }
387
- if (/\b(ui|screen|frontend|page|form|layout)\b/.test(lower)) {
388
- return "Requires user-facing rollout validation for the updated UI surface.";
389
- }
390
- if (/\b(flow|interaction|integration|dispatch)\b/.test(lower)) {
391
- return "Requires end-to-end runtime validation across the affected interaction path.";
392
- }
393
-
394
- return "Requires bounded runtime rollout and post-deploy validation for the scoped slice.";
395
- }
396
-
397
- function parseWorkflowScopeSlices(workflowText, handoffPayload) {
398
- const planBlock = extractManagedBlock(workflowText, "PLAN");
399
- const buildBlock = extractManagedBlock(workflowText, "BUILD");
400
-
401
- let sliceTitles = cleanSliceEntries(parseBlockSection(planBlock, "Finalized Slices After `plan`"));
402
- if (sliceTitles.length === 0) {
403
- sliceTitles = cleanSliceEntries(parseInlineSliceSection(planBlock));
404
- }
405
- if (sliceTitles.length === 0) {
406
- sliceTitles = cleanSliceEntries(parseBlockSection(buildBlock, "Active Slices"));
407
- }
408
- if (sliceTitles.length === 0) {
409
- sliceTitles = uniqueStrings(handoffPayload.implementation_slices || []);
410
- }
411
-
412
- return sliceTitles.map((title, index) => ({
413
- slice_id: deriveScopeSliceId(title, index),
414
- title,
415
- ops_impact_summary: deriveOpsImpactSummary(title),
416
- }));
417
- }
418
-
419
- function inferEvidenceKind(checkName, refPath) {
420
- const combined = `${checkName} ${refPath}`.toLowerCase();
421
- if (/\b(review|checklist|approval|captain)\b/.test(combined)) {
422
- return "review";
423
- }
424
- if (/\b(pack|build|bundle|artifact)\b/.test(combined)) {
425
- return "build";
426
- }
427
- if (/\b(pytest|npm test|test|regression|smoke|verify)\b/.test(combined)) {
428
- return "test";
429
- }
430
- return "artifact";
431
- }
432
-
433
- function parseEvidenceEntriesFromWorkflow(workflowText) {
434
- const entries = [];
435
- const regex = /^- `([^`]+)` \| `([^`]+)` \| ([^\r\n]+?) \| Raw output: `([^`]+)`$/gm;
436
- let match;
437
- while ((match = regex.exec(workflowText)) !== null) {
438
- entries.push({
439
- checkName: match[1],
440
- result: match[2],
441
- summary: match[3].trim(),
442
- rawOutputRef: match[4],
443
- });
444
- }
445
- return entries;
446
- }
447
-
448
- function buildCodeEvidenceRefs(projectPath, featureKey, workflowText) {
449
- const workflowPath = getWorkflowArtifactPath(projectPath, featureKey);
450
- const refs = [
451
- {
452
- label: `${humanizeFeatureKey(featureKey)} code workflow artifact`,
453
- path: normalizePathForDoc(projectPath, workflowPath),
454
- kind: "workflow",
455
- },
456
- ];
457
-
458
- for (const entry of parseEvidenceEntriesFromWorkflow(workflowText)) {
459
- refs.push({
460
- label: `${entry.checkName} evidence`,
461
- path: entry.rawOutputRef,
462
- kind: inferEvidenceKind(entry.checkName, entry.rawOutputRef),
463
- notes: entry.summary,
464
- });
465
- }
466
-
467
- return uniqueObjects(refs, (entry) => `${entry.kind}::${entry.path}`);
468
- }
469
-
470
- function hasRequiredRef(payload, prefix) {
471
- return Array.isArray(payload.required_refs)
472
- ? payload.required_refs.some((entry) => String(entry).startsWith(prefix))
473
- : false;
474
- }
475
-
476
- function buildDeploymentPrerequisites(preflightEntries) {
477
- return uniqueStrings(
478
- preflightEntries.map((entry) => `${entry.checkName}: ${entry.summary}`)
479
- );
480
- }
481
-
482
- function buildEnvironmentAssumptions(handoffPayload, decision) {
483
- const assumptions = [
484
- "OPS intake remains anchored to the current formal CODE_HANDOFF and repo config contract.",
485
- `DEV-Run should use ${handoffPayload.repo_config_ref} as the current repo command/config reference.`,
486
- ];
487
-
488
- if (decision === "finish") {
489
- assumptions.push(
490
- 'The CODE closeout used "finish", so remaining hardening or deployment work stays explicit during DEV-Run intake.'
491
- );
492
- }
493
-
494
- if (hasRequiredRef(handoffPayload, "docs/api/")) {
495
- assumptions.push("Runtime execution can reach the service or API surfaces referenced by the scoped slices.");
496
- }
497
- if (hasRequiredRef(handoffPayload, "docs/database/")) {
498
- assumptions.push("Runtime rollout preserves compatible database state for the scoped slices.");
499
- }
500
-
501
- return uniqueStrings(assumptions);
502
- }
503
-
504
- function buildInfraRuntimeDependencies(handoffPayload) {
505
- const dependencies = [
506
- {
507
- dependency: "sdtk-spec.config.json",
508
- requirement: "Use the repo command and environment contract from sdtk-spec.config.json during DEV-Run execution.",
509
- },
510
- ];
511
-
512
- if (hasRequiredRef(handoffPayload, "docs/api/")) {
513
- dependencies.push({
514
- dependency: "Application service runtime",
515
- requirement: "Deploy and validate the API or service surfaces referenced by the scoped slices.",
516
- });
517
- }
518
- if (hasRequiredRef(handoffPayload, "docs/database/")) {
519
- dependencies.push({
520
- dependency: "Database / schema state",
521
- requirement: "Provision compatible database state, migration handling, and recovery safety for the scoped slices.",
522
- });
523
- }
524
- if (hasRequiredRef(handoffPayload, "docs/design/")) {
525
- dependencies.push({
526
- dependency: "Frontend or admin delivery surface",
527
- requirement: "Expose the updated UI surface and verify that the scoped routes remain reachable after rollout.",
528
- });
529
- }
530
-
531
- return uniqueObjects(dependencies, (entry) => entry.dependency);
532
- }
533
-
534
- function buildObservabilityRequirements(handoffPayload) {
535
- const requirements = [
536
- "DEV-Run must capture deployment and post-deploy validation evidence for the scoped slices.",
537
- ];
538
-
539
- if (hasRequiredRef(handoffPayload, "docs/api/")) {
540
- requirements.push("API or service health plus bounded smoke results must be observable during OPS rollout.");
541
- }
542
- if (hasRequiredRef(handoffPayload, "docs/database/")) {
543
- requirements.push("Migration and persistence outcomes must be observable through logs, health checks, or equivalent evidence.");
544
- }
545
-
546
- return uniqueStrings(requirements);
547
- }
548
-
549
- function buildRollbackRecoveryExpectations(handoffPayload, decision) {
550
- const expectations = [
551
- "Rollback or recovery steps must be explicit before runtime rollout begins.",
552
- ];
553
-
554
- if (hasRequiredRef(handoffPayload, "docs/database/")) {
555
- expectations.push("Database-affecting slices require rollback-safe migrations or documented restore steps.");
556
- }
557
- if (decision === "finish") {
558
- expectations.push("Remaining hardening items carried from CODE closeout must stay explicit if rollback readiness is incomplete.");
559
- }
560
-
561
- return uniqueStrings(expectations);
562
- }
563
-
564
- function buildSuggestedNextOpsPath(lane, decision) {
565
- const suggestedChain =
566
- lane === "bugfix"
567
- ? ["ops-plan", "ops-deploy"]
568
- : ["ops-plan", "ops-deploy", "ops-monitor"];
569
-
570
- return {
571
- start_with: suggestedChain[0],
572
- suggested_chain: suggestedChain,
573
- close_with: "ops-verify",
574
- why:
575
- decision === "finish"
576
- ? "CODE closed a bounded implementation pass and DEV-Run should carry the explicit hardening or deployment follow-up into the OPS path."
577
- : "CODE closed the scoped implementation with the stronger closeout bundle and DEV-Run can continue with the normal OPS path.",
578
- };
579
- }
580
-
581
- function buildOptionalReferenceEntries(handoffPayload) {
582
- const refs = [];
583
-
584
- if (isNonEmptyString(handoffPayload.feature_impl_plan_path)) {
585
- refs.push({
586
- label: "Upstream feature implementation plan",
587
- path: handoffPayload.feature_impl_plan_path.trim(),
588
- kind: "artifact",
589
- });
590
- }
591
-
592
- if (Array.isArray(handoffPayload.optional_refs)) {
593
- handoffPayload.optional_refs.forEach((entry, index) => {
594
- if (isNonEmptyString(entry)) {
595
- refs.push({
596
- label: `Optional upstream ref ${index + 1}`,
597
- path: entry.trim(),
598
- kind: "artifact",
599
- });
600
- }
601
- });
602
- }
603
-
604
- return uniqueObjects(refs, (entry) => entry.path);
605
- }
606
-
607
- function buildOptionalOpsNotes(decision, followUps, shipNotes) {
608
- const notes = [];
609
-
610
- if (decision === "finish") {
611
- notes.push('CODE closeout used "finish", so remaining hardening or deployment work stays explicit for DEV-Run.');
612
- }
613
-
614
- notes.push(...normalizeOptionalNotes(shipNotes));
615
- notes.push(...normalizeOptionalNotes((followUps || []).map((entry) => `Follow-up: ${entry}`)));
616
-
617
- return uniqueStrings(notes);
618
- }
619
-
620
- function normalizeOptionalNotes(entries) {
621
- return (entries || []).map((entry) => String(entry).trim()).filter(Boolean);
622
- }
623
-
624
- function readJsonObject(jsonPath, label) {
625
- let payload;
626
- try {
627
- payload = JSON.parse(fs.readFileSync(jsonPath, "utf-8"));
628
- } catch (error) {
629
- throw new Error(`${label} is invalid JSON: ${error.message}`);
630
- }
631
-
632
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
633
- throw new Error(`${label} must be a JSON object.`);
634
- }
635
-
636
- return payload;
637
- }
638
-
639
- function loadFormalCodeHandoffForOps(projectPath, featureKey, lane) {
640
- const handoffPath = getCodeHandoffPath(projectPath, featureKey);
641
- if (!fs.existsSync(handoffPath)) {
642
- return null;
643
- }
644
-
645
- const payload = readJsonObject(handoffPath, "CODE_HANDOFF");
646
-
647
- if (!ACCEPTED_HANDOFF_SCHEMA_VERSIONS.has(payload.schema_version)) {
648
- throw new Error(`CODE_HANDOFF schema_version must be one of: ${[...ACCEPTED_HANDOFF_SCHEMA_VERSIONS].join(", ")}.`);
649
- }
650
- if (payload.feature_key !== featureKey) {
651
- throw new Error(`CODE_HANDOFF feature_key must match ${featureKey}.`);
652
- }
653
- if (!HANDOFF_LANES.has(payload.recommended_lane) || payload.recommended_lane !== lane) {
654
- throw new Error(`CODE_HANDOFF recommended_lane must match the current lane "${lane}".`);
655
- }
656
- if (!HANDOFF_STATUSES.has(payload.handoff_status) || payload.handoff_status !== "READY_FOR_SDTK_CODE") {
657
- throw new Error('CODE_HANDOFF must remain "READY_FOR_SDTK_CODE" for canonical OPS emission.');
658
- }
659
- if (payload.repo_config_ref !== "sdtk-spec.config.json") {
660
- throw new Error('CODE_HANDOFF repo_config_ref must remain "sdtk-spec.config.json".');
661
- }
662
- if (!Array.isArray(payload.implementation_slices) || payload.implementation_slices.length === 0) {
663
- throw new Error("CODE_HANDOFF must keep at least one implementation_slices entry.");
664
- }
665
-
666
- return {
667
- handoffPath,
668
- payload,
669
- };
670
- }
671
-
672
- function emitOpsHandoffForCompletedCloseout({
673
- projectPath,
674
- featureKey,
675
- lane,
676
- decision,
677
- preflightEntries,
678
- shipFollowUps,
679
- shipNotes,
680
- }) {
681
- let formalCodeHandoff;
682
- try {
683
- formalCodeHandoff = loadFormalCodeHandoffForOps(projectPath, featureKey, lane);
684
- } catch (error) {
685
- return {
686
- emitted: false,
687
- reason: `skipped because the current formal CODE_HANDOFF is invalid (${error.message})`,
688
- };
689
- }
690
-
691
- if (!formalCodeHandoff) {
692
- return {
693
- emitted: false,
694
- reason:
695
- "skipped because compatibility fallback workflows do not emit the canonical CODE -> OPS bridge without docs/dev/CODE_HANDOFF_[FEATURE_KEY].json",
696
- };
697
- }
698
-
699
- const workflowPath = getWorkflowArtifactPath(projectPath, featureKey);
700
- const workflowText = fs.readFileSync(workflowPath, "utf-8");
701
- const scopeSlices = parseWorkflowScopeSlices(workflowText, formalCodeHandoff.payload);
702
- const codeEvidenceRefs = buildCodeEvidenceRefs(projectPath, featureKey, workflowText);
703
- const opsHandoffPath = getOpsHandoffPath(projectPath, featureKey);
704
- const relativeWorkflowPath = normalizePathForDoc(projectPath, workflowPath);
705
- const relativeCodeHandoffPath = normalizePathForDoc(projectPath, formalCodeHandoff.handoffPath);
706
- const optionalRefs = buildOptionalReferenceEntries(formalCodeHandoff.payload);
707
- const notes = buildOptionalOpsNotes(decision, shipFollowUps, shipNotes);
708
-
709
- const payload = {
710
- schema_version: OPS_HANDOFF_SCHEMA_VERSION,
711
- feature_key: featureKey,
712
- feature_name: humanizeFeatureKey(featureKey),
713
- delivery_lane: lane,
714
- generated_by: "sdtk-code",
715
- generated_at: new Date().toISOString(),
716
- handoff_status: OPS_HANDOFF_READY_STATUS,
717
- producer_owner: "DEV-Code",
718
- consumer_owner: "DEV-Run",
719
- code_workflow_path: relativeWorkflowPath,
720
- code_handoff_path: relativeCodeHandoffPath,
721
- repo_config_ref: formalCodeHandoff.payload.repo_config_ref,
722
- scope_slices: scopeSlices,
723
- code_evidence_refs: codeEvidenceRefs,
724
- deployment_prerequisites: buildDeploymentPrerequisites(preflightEntries),
725
- environment_assumptions: buildEnvironmentAssumptions(formalCodeHandoff.payload, decision),
726
- infra_runtime_dependencies: buildInfraRuntimeDependencies(formalCodeHandoff.payload),
727
- observability_requirements: buildObservabilityRequirements(formalCodeHandoff.payload),
728
- rollback_recovery_expectations: buildRollbackRecoveryExpectations(
729
- formalCodeHandoff.payload,
730
- decision
731
- ),
732
- open_blockers: [],
733
- suggested_next_ops_path: buildSuggestedNextOpsPath(lane, decision),
734
- };
735
-
736
- if (optionalRefs.length > 0) {
737
- payload.optional_refs = optionalRefs;
738
- }
739
- if (notes.length > 0) {
740
- payload.notes = notes;
741
- }
742
-
743
- fs.writeFileSync(opsHandoffPath, JSON.stringify(payload, null, 2) + "\n", "utf-8");
744
-
745
- return {
746
- emitted: true,
747
- opsHandoffPath,
748
- handoffStatus: OPS_HANDOFF_READY_STATUS,
749
- scopeSliceCount: scopeSlices.length,
750
- evidenceRefCount: codeEvidenceRefs.length,
751
- };
752
- }
753
-
754
- function validateRequiredRefCoverage(requiredRefs, implementationSlices, featureKey) {
755
- const archPath = `docs/architecture/ARCH_DESIGN_${featureKey}.md`;
756
- const backlogPath = `docs/product/BACKLOG_${featureKey}.md`;
757
-
758
- for (const mustHave of [archPath, backlogPath]) {
759
- if (!requiredRefs.includes(mustHave)) {
760
- throw new Error(`required_refs must include: ${mustHave}`);
761
- }
762
- }
763
-
764
- const sliceText = implementationSlices.map((entry) => String(entry).toLowerCase()).join(" || ");
765
- if (!sliceText) {
766
- return;
767
- }
768
-
769
- if (/\b(api|endpoint|contract|service|backend)\b/.test(sliceText)) {
770
- if (!requiredRefs.some((entry) => entry.startsWith("docs/api/"))) {
771
- throw new Error(
772
- "implementation_slices reference API or backend scope, so required_refs must include at least one docs/api/* source."
773
- );
774
- }
775
- }
776
-
777
- if (/\b(database|migration|schema|table|sql|db)\b/.test(sliceText)) {
778
- if (!requiredRefs.some((entry) => entry.startsWith("docs/database/"))) {
779
- throw new Error(
780
- "implementation_slices reference database scope, so required_refs must include at least one docs/database/* source."
781
- );
782
- }
783
- }
784
-
785
- if (/\b(ui|screen|frontend|page|form|layout)\b/.test(sliceText)) {
786
- if (!requiredRefs.some((entry) => entry.startsWith("docs/design/"))) {
787
- throw new Error(
788
- "implementation_slices reference UI scope, so required_refs must include at least one docs/design/* source."
789
- );
790
- }
791
- }
792
-
793
- if (/\b(flow|interaction)\b/.test(sliceText)) {
794
- if (!requiredRefs.some((entry) => entry.startsWith("docs/specs/") && entry.endsWith("_FLOW_ACTION_SPEC.md"))) {
795
- throw new Error(
796
- "implementation_slices reference flow scope, so required_refs must include docs/specs/[FEATURE_KEY]_FLOW_ACTION_SPEC.md."
797
- );
798
- }
799
- }
800
- }
801
-
802
- function buildInputEntries(projectPath, payload, featureKey, handoffPath) {
803
- const requiredInputs = [
804
- {
805
- key: "CODE_HANDOFF",
806
- path: handoffPath,
807
- exists: true,
808
- },
809
- ];
810
- const optionalInputs = [];
811
-
812
- if (isNonEmptyString(payload.feature_impl_plan_path)) {
813
- requiredInputs.push(buildPathEntry("FEATURE_IMPL_PLAN", projectPath, payload.feature_impl_plan_path.trim()));
814
- }
815
-
816
- if (isNonEmptyString(payload.repo_config_ref)) {
817
- requiredInputs.push(buildPathEntry("SDTK_CONFIG", projectPath, payload.repo_config_ref.trim()));
818
- }
819
-
820
- if (Array.isArray(payload.required_refs)) {
821
- payload.required_refs.forEach((entry, index) => {
822
- if (isNonEmptyString(entry)) {
823
- requiredInputs.push(buildPathEntry(`REQUIRED_REF_${index + 1}`, projectPath, entry.trim()));
824
- }
825
- });
826
- }
827
-
828
- if (Array.isArray(payload.optional_refs)) {
829
- payload.optional_refs.forEach((entry, index) => {
830
- if (isNonEmptyString(entry)) {
831
- optionalInputs.push(buildPathEntry(`OPTIONAL_REF_${index + 1}`, projectPath, entry.trim()));
832
- }
833
- });
834
- }
835
-
836
- return {
837
- requiredInputs: uniquePathEntries(requiredInputs),
838
- optionalInputs: uniquePathEntries(optionalInputs),
839
- };
840
- }
841
-
842
- function resolveFormalHandoffIntake(projectPath, featureKey, lane) {
843
- const handoffPath = path.join(projectPath, "docs", "dev", `CODE_HANDOFF_${featureKey}.json`);
844
- if (!fs.existsSync(handoffPath)) {
845
- return null;
846
- }
847
-
848
- let payload;
849
- try {
850
- payload = JSON.parse(fs.readFileSync(handoffPath, "utf-8"));
851
- } catch (error) {
852
- return createBlockedFormalIntake({
853
- projectPath,
854
- featureKey,
855
- lane,
856
- handoffStatus: "INVALID_JSON",
857
- requiredInputs: [
858
- {
859
- key: "CODE_HANDOFF",
860
- path: handoffPath,
861
- exists: true,
862
- },
863
- ],
864
- optionalInputs: [],
865
- blockingState: "invalid_handoff_contract",
866
- blockingMessage: `SDTK-CODE handoff contract is invalid: failed to parse JSON (${error.message}).`,
867
- });
868
- }
869
-
870
- let compatibilityWarnings = collectSoftWarnings(payload);
871
- const { requiredInputs, optionalInputs } = buildInputEntries(projectPath, payload, featureKey, handoffPath);
872
-
873
- try {
874
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
875
- throw new Error("Formal handoff root value must be a JSON object.");
876
- }
877
-
878
- if (!ACCEPTED_HANDOFF_SCHEMA_VERSIONS.has(payload.schema_version)) {
879
- throw new Error(`schema_version must be one of: ${[...ACCEPTED_HANDOFF_SCHEMA_VERSIONS].join(", ")}.`);
880
- }
881
-
882
- const schemaVersion = payload.schema_version;
883
-
884
- if (!isNonEmptyString(payload.feature_key)) {
885
- throw new Error("feature_key must be a non-empty string.");
886
- }
887
- if (!/^[A-Z][A-Z0-9_]*$/.test(payload.feature_key.trim())) {
888
- throw new Error("feature_key must use UPPER_SNAKE_CASE.");
889
- }
890
- if (payload.feature_key.trim() !== featureKey) {
891
- throw new Error(`feature_key must match CLI --feature-key: ${featureKey}`);
892
- }
893
-
894
- if (!HANDOFF_STATUSES.has(payload.handoff_status)) {
895
- throw new Error('handoff_status must be "READY_FOR_SDTK_CODE" or "BLOCKED_FOR_SDTK_CODE".');
896
- }
897
-
898
- if (!HANDOFF_LANES.has(payload.recommended_lane)) {
899
- throw new Error('recommended_lane must be "feature" or "bugfix".');
900
- }
901
- if (payload.recommended_lane !== lane) {
902
- throw new Error(`recommended_lane must match CLI --lane: ${lane}`);
903
- }
904
-
905
- const featureImplPlanPath = normalizeRelativePath(
906
- payload.feature_impl_plan_path,
907
- "feature_impl_plan_path"
908
- );
909
- const expectedPlanPath = `docs/dev/FEATURE_IMPL_PLAN_${featureKey}.md`;
910
- if (featureImplPlanPath !== expectedPlanPath) {
911
- throw new Error(`feature_impl_plan_path must match the current feature key: ${expectedPlanPath}`);
912
- }
913
-
914
- const repoConfigRef = normalizeRelativePath(payload.repo_config_ref, "repo_config_ref");
915
- if (repoConfigRef !== "sdtk-spec.config.json") {
916
- throw new Error('repo_config_ref must be exactly "sdtk-spec.config.json".');
917
- }
918
-
919
- const requiredRefs = requireArray(payload, "required_refs").map((entry, index) =>
920
- normalizeRelativePath(entry, `required_refs[${index}]`)
921
- );
922
- const optionalRefs = requireArray(payload, "optional_refs").map((entry, index) =>
923
- normalizeRelativePath(entry, `optional_refs[${index}]`)
924
- );
925
- const openBlockers = normalizeStringArray(requireArray(payload, "open_blockers"), "open_blockers");
926
- const implementationSlices = normalizeStringArray(
927
- requireArray(payload, "implementation_slices"),
928
- "implementation_slices"
929
- );
930
- const testObligations = normalizeStringArray(requireArray(payload, "test_obligations"), "test_obligations");
931
- const impactMap = schemaVersion === "0.2" ? normalizeImpactMap(payload.impact_map) : null;
932
- const recoveryNotes = schemaVersion === "0.2" ? normalizeOptionalStringArray(payload.recovery_notes, "recovery_notes") : [];
933
-
934
- if (schemaVersion === "0.2" && !impactMap) {
935
- compatibilityWarnings = [
936
- ...compatibilityWarnings,
937
- 'Formal handoff compatibility warning: schema_version "0.2" is present without impact_map; richer impact seeding is unavailable.',
938
- ];
939
- }
940
-
941
- validateRequiredRefCoverage(requiredRefs, implementationSlices, featureKey);
942
-
943
- const missingInputs = requiredInputs.filter((entry) => !entry.exists);
944
- const missingOptional = optionalInputs.filter((entry) => !entry.exists);
945
- if (missingInputs.length > 0) {
946
- const missingList = missingInputs
947
- .map((entry) => normalizePathForDoc(projectPath, entry.path))
948
- .join(", ");
949
- throw new Error(`formal handoff references missing required paths: ${missingList}`);
950
- }
951
- if (missingOptional.length > 0) {
952
- const missingList = missingOptional
953
- .map((entry) => normalizePathForDoc(projectPath, entry.path))
954
- .join(", ");
955
- throw new Error(`formal handoff references missing optional paths: ${missingList}`);
956
- }
957
-
958
- if (payload.handoff_status === "READY_FOR_SDTK_CODE") {
959
- if (openBlockers.length > 0) {
960
- throw new Error("READY_FOR_SDTK_CODE requires empty open_blockers.");
961
- }
962
- if (implementationSlices.length === 0) {
963
- throw new Error("READY_FOR_SDTK_CODE requires at least one implementation_slices entry.");
964
- }
965
- if (testObligations.length === 0) {
966
- throw new Error("READY_FOR_SDTK_CODE requires at least one test_obligations entry.");
967
- }
968
- } else if (openBlockers.length === 0) {
969
- throw new Error("BLOCKED_FOR_SDTK_CODE requires at least one open_blockers entry.");
970
- }
971
-
972
- if (payload.handoff_status === "BLOCKED_FOR_SDTK_CODE") {
973
- return createBlockedFormalIntake({
974
- projectPath,
975
- featureKey,
976
- lane,
977
- handoffStatus: payload.handoff_status,
978
- requiredInputs,
979
- optionalInputs,
980
- blockingState: "blocked_upstream_handoff",
981
- blockingMessage: "SDTK-CODE handoff is blocked by upstream /dev blockers:",
982
- blockingDetails: openBlockers,
983
- compatibilityWarnings,
984
- });
985
- }
986
-
987
- const candidatePlanningSeed = buildCandidatePlanningSeed(lane, implementationSlices, testObligations, {
988
- schemaVersion,
989
- impactMap,
990
- recoveryNotes,
991
- });
992
-
993
- return createIntakeResult({
994
- projectPath,
995
- featureKey,
996
- lane,
997
- requiredInputs,
998
- optionalInputs,
999
- missingInputs: [],
1000
- blocked: false,
1001
- intakeOutcome: lane === "feature" ? "READY_FOR_PLAN" : "READY_FOR_BUILD_BUGFIX",
1002
- nextPhase: lane === "feature" ? "plan" : "build",
1003
- phaseStatus: "completed",
1004
- blockingState: "clear",
1005
- intakeSource: "formal_handoff",
1006
- handoffStatus: payload.handoff_status,
1007
- compatibilityWarnings,
1008
- ...candidatePlanningSeed,
1009
- });
1010
- } catch (error) {
1011
- return createBlockedFormalIntake({
1012
- projectPath,
1013
- featureKey,
1014
- lane,
1015
- handoffStatus: payload && payload.handoff_status ? String(payload.handoff_status) : "INVALID_CONTRACT",
1016
- requiredInputs,
1017
- optionalInputs,
1018
- blockingState: "invalid_handoff_contract",
1019
- blockingMessage: `SDTK-CODE handoff contract is invalid: ${error.message}`,
1020
- compatibilityWarnings,
1021
- });
1022
- }
1023
- }
1024
-
1025
- module.exports = {
1026
- emitOpsHandoffForCompletedCloseout,
1027
- getOpsHandoffPath,
1028
- resolveFormalHandoffIntake,
1029
- };
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { extractManagedBlock, getWorkflowArtifactPath } = require("./workflow-artifact");
6
+
7
+ const LATEST_HANDOFF_SCHEMA_VERSION = "0.2";
8
+ const ACCEPTED_HANDOFF_SCHEMA_VERSIONS = new Set(["0.1", "0.2"]);
9
+ const HANDOFF_STATUSES = new Set(["READY_FOR_SDTK_CODE", "BLOCKED_FOR_SDTK_CODE"]);
10
+ const HANDOFF_LANES = new Set(["feature", "bugfix"]);
11
+ const OPS_HANDOFF_SCHEMA_VERSION = "0.1";
12
+ const OPS_HANDOFF_READY_STATUS = "READY_FOR_SDTK_OPS";
13
+
14
+ function normalizePathForDoc(projectPath, targetPath) {
15
+ return path.relative(projectPath, targetPath).split(path.sep).join("/");
16
+ }
17
+
18
+ function getCodeHandoffPath(projectPath, featureKey) {
19
+ return path.join(projectPath, "docs", "dev", `CODE_HANDOFF_${featureKey}.json`);
20
+ }
21
+
22
+ function getOpsHandoffPath(projectPath, featureKey) {
23
+ return path.join(projectPath, "docs", "dev", `OPS_HANDOFF_${featureKey}.json`);
24
+ }
25
+
26
+ function buildPathEntry(key, projectPath, relativePath) {
27
+ const normalized = relativePath.split("/").join(path.sep);
28
+ const fullPath = path.join(projectPath, normalized);
29
+ return {
30
+ key,
31
+ path: fullPath,
32
+ exists: fs.existsSync(fullPath),
33
+ };
34
+ }
35
+
36
+ function uniquePathEntries(entries) {
37
+ const seen = new Set();
38
+ const result = [];
39
+
40
+ for (const entry of entries) {
41
+ const key = `${entry.key}::${entry.path}`;
42
+ if (seen.has(key)) {
43
+ continue;
44
+ }
45
+ seen.add(key);
46
+ result.push(entry);
47
+ }
48
+
49
+ return result;
50
+ }
51
+
52
+ function getSuggestedEngineSkills(lane, blocked) {
53
+ if (blocked) {
54
+ return ["code-discover"];
55
+ }
56
+ if (lane === "feature") {
57
+ return ["code-plan", "code-brainstorm (if ambiguity remains)"];
58
+ }
59
+ return ["code-debug (when reproducing failure)", "code-tdd", "code-execute"];
60
+ }
61
+
62
+ function createIntakeResult({
63
+ projectPath,
64
+ featureKey,
65
+ lane,
66
+ requiredInputs,
67
+ optionalInputs,
68
+ missingInputs,
69
+ blocked,
70
+ intakeOutcome,
71
+ nextPhase,
72
+ phaseStatus,
73
+ blockingState,
74
+ intakeSource,
75
+ handoffStatus,
76
+ compatibilityWarnings = [],
77
+ blockingMessage,
78
+ blockingDetails = [],
79
+ candidateSlices = [],
80
+ candidatePlanningNotes = [],
81
+ }) {
82
+ return {
83
+ requiredInputs: uniquePathEntries(requiredInputs || []),
84
+ optionalInputs: uniquePathEntries(optionalInputs || []),
85
+ missingInputs: uniquePathEntries(missingInputs || []),
86
+ blocked,
87
+ intakeOutcome,
88
+ nextPhase,
89
+ phaseStatus,
90
+ blockingState,
91
+ suggestedEngineSkills: getSuggestedEngineSkills(lane, blocked),
92
+ normalizePath: (targetPath) => normalizePathForDoc(projectPath, targetPath),
93
+ intakeSource,
94
+ handoffStatus,
95
+ compatibilityWarnings,
96
+ blockingMessage,
97
+ blockingDetails,
98
+ featureKey,
99
+ lane,
100
+ candidateSlices,
101
+ candidatePlanningNotes,
102
+ };
103
+ }
104
+
105
+ function createBlockedFormalIntake({
106
+ projectPath,
107
+ featureKey,
108
+ lane,
109
+ handoffStatus,
110
+ requiredInputs,
111
+ optionalInputs,
112
+ blockingState,
113
+ blockingMessage,
114
+ blockingDetails = [],
115
+ compatibilityWarnings = [],
116
+ }) {
117
+ const missingInputs = (requiredInputs || []).filter((entry) => !entry.exists);
118
+
119
+ return createIntakeResult({
120
+ projectPath,
121
+ featureKey,
122
+ lane,
123
+ requiredInputs,
124
+ optionalInputs,
125
+ missingInputs,
126
+ blocked: true,
127
+ intakeOutcome: "BLOCKED_UPSTREAM_HANDOFF",
128
+ nextPhase: "blocked",
129
+ phaseStatus: "blocked",
130
+ blockingState,
131
+ intakeSource: "formal_handoff",
132
+ handoffStatus,
133
+ compatibilityWarnings,
134
+ blockingMessage,
135
+ blockingDetails,
136
+ });
137
+ }
138
+
139
+ function isNonEmptyString(value) {
140
+ return typeof value === "string" && value.trim().length > 0;
141
+ }
142
+
143
+ function normalizeRelativePath(value, label) {
144
+ if (!isNonEmptyString(value)) {
145
+ throw new Error(`${label} must be a non-empty repo-relative forward-slash path.`);
146
+ }
147
+
148
+ const trimmed = value.trim();
149
+ if (trimmed.includes("\\")) {
150
+ throw new Error(`${label} must use repo-relative forward-slash paths: ${trimmed}`);
151
+ }
152
+ if (trimmed.startsWith("/")) {
153
+ throw new Error(`${label} must be repo-relative, not absolute: ${trimmed}`);
154
+ }
155
+ if (/^[A-Za-z]:/.test(trimmed)) {
156
+ throw new Error(`${label} must be repo-relative, not drive-qualified: ${trimmed}`);
157
+ }
158
+
159
+ return trimmed;
160
+ }
161
+
162
+ function requireArray(payload, key) {
163
+ if (!Array.isArray(payload[key])) {
164
+ throw new Error(`${key} must be an array.`);
165
+ }
166
+ return payload[key];
167
+ }
168
+
169
+ function collectSoftWarnings(payload) {
170
+ const warnings = [];
171
+
172
+ if (payload.schema_version === "0.1") {
173
+ warnings.push(
174
+ 'Formal handoff compatibility warning: schema_version "0.1" is still accepted, but richer BK-057 planning context is unavailable.'
175
+ );
176
+ }
177
+
178
+ if (payload.generated_by !== "sdtk-dev") {
179
+ warnings.push(
180
+ `Formal handoff compatibility warning: generated_by is ${JSON.stringify(
181
+ payload.generated_by
182
+ )}; expected "sdtk-dev".`
183
+ );
184
+ }
185
+
186
+ if (!isNonEmptyString(payload.generated_at)) {
187
+ warnings.push("Formal handoff compatibility warning: generated_at is missing or empty.");
188
+ }
189
+
190
+ return warnings;
191
+ }
192
+
193
+ function normalizeStringArray(entries, label) {
194
+ if (!Array.isArray(entries)) {
195
+ throw new Error(`${label} must be an array.`);
196
+ }
197
+
198
+ return entries.map((entry) => String(entry).trim()).filter(Boolean);
199
+ }
200
+
201
+ function normalizeOptionalStringArray(entries, label) {
202
+ if (entries == null) {
203
+ return [];
204
+ }
205
+
206
+ return normalizeStringArray(entries, label);
207
+ }
208
+
209
+ function normalizeImpactMap(impactMap) {
210
+ if (impactMap == null) {
211
+ return null;
212
+ }
213
+ if (!impactMap || typeof impactMap !== "object" || Array.isArray(impactMap)) {
214
+ throw new Error("impact_map must be an object.");
215
+ }
216
+
217
+ return {
218
+ api_refs: normalizeStringArray(requireArray(impactMap, "api_refs"), "impact_map.api_refs").map((entry, index) =>
219
+ normalizeRelativePath(entry, `impact_map.api_refs[${index}]`)
220
+ ),
221
+ database_refs: normalizeStringArray(requireArray(impactMap, "database_refs"), "impact_map.database_refs").map(
222
+ (entry, index) => normalizeRelativePath(entry, `impact_map.database_refs[${index}]`)
223
+ ),
224
+ ui_refs: normalizeStringArray(requireArray(impactMap, "ui_refs"), "impact_map.ui_refs").map((entry, index) =>
225
+ normalizeRelativePath(entry, `impact_map.ui_refs[${index}]`)
226
+ ),
227
+ flow_refs: normalizeStringArray(requireArray(impactMap, "flow_refs"), "impact_map.flow_refs").map((entry, index) =>
228
+ normalizeRelativePath(entry, `impact_map.flow_refs[${index}]`)
229
+ ),
230
+ };
231
+ }
232
+
233
+ function buildImpactPlanningNotes(impactMap) {
234
+ if (!impactMap) {
235
+ return [];
236
+ }
237
+
238
+ const categoryLabels = {
239
+ api_refs: "API refs",
240
+ database_refs: "Database refs",
241
+ ui_refs: "UI refs",
242
+ flow_refs: "Flow refs",
243
+ };
244
+
245
+ return Object.entries(categoryLabels)
246
+ .filter(([key]) => Array.isArray(impactMap[key]) && impactMap[key].length > 0)
247
+ .map(([key, label]) => `Seeded impact ${label}: ${impactMap[key].join(", ")}`);
248
+ }
249
+
250
+ function buildCandidatePlanningSeed(
251
+ lane,
252
+ implementationSlices,
253
+ testObligations,
254
+ { schemaVersion, impactMap = null, recoveryNotes = [] } = {}
255
+ ) {
256
+ if (lane !== "feature") {
257
+ return {
258
+ candidateSlices: [],
259
+ candidatePlanningNotes: [],
260
+ };
261
+ }
262
+
263
+ const candidatePlanningNotes = [
264
+ "Seeded from the formal SDTK-SPEC handoff. Confirm or refine these candidate slices during `sdtk-code plan`.",
265
+ ];
266
+
267
+ if (schemaVersion === "0.2") {
268
+ candidatePlanningNotes.push(
269
+ "Seeded build order: implementation_slices order from the formal SDTK-SPEC handoff is the recommended downstream sequence."
270
+ );
271
+ candidatePlanningNotes.push(...buildImpactPlanningNotes(impactMap));
272
+ }
273
+
274
+ if (testObligations.length > 0) {
275
+ candidatePlanningNotes.push(
276
+ ...testObligations.map((entry) => `Seeded test obligation: ${entry}`)
277
+ );
278
+ }
279
+
280
+ if (schemaVersion === "0.2" && recoveryNotes.length > 0) {
281
+ candidatePlanningNotes.push(
282
+ ...recoveryNotes.map((entry) => `Seeded recovery note: ${entry}`)
283
+ );
284
+ }
285
+
286
+ return {
287
+ candidateSlices: implementationSlices,
288
+ candidatePlanningNotes,
289
+ };
290
+ }
291
+
292
+ function humanizeFeatureKey(featureKey) {
293
+ return String(featureKey)
294
+ .split("_")
295
+ .filter(Boolean)
296
+ .map((token) => token.charAt(0) + token.slice(1).toLowerCase())
297
+ .join(" ");
298
+ }
299
+
300
+ function uniqueStrings(entries) {
301
+ return [...new Set((entries || []).map((entry) => String(entry).trim()).filter(Boolean))];
302
+ }
303
+
304
+ function uniqueObjects(entries, keyBuilder) {
305
+ const seen = new Set();
306
+ const results = [];
307
+ for (const entry of entries || []) {
308
+ const key = keyBuilder(entry);
309
+ if (!key || seen.has(key)) {
310
+ continue;
311
+ }
312
+ seen.add(key);
313
+ results.push(entry);
314
+ }
315
+ return results;
316
+ }
317
+
318
+ function parseBulletEntries(sectionText) {
319
+ if (!sectionText) {
320
+ return [];
321
+ }
322
+
323
+ return sectionText
324
+ .split(/\r?\n/)
325
+ .map((line) => line.trim())
326
+ .filter((line) => line.startsWith("- "))
327
+ .map((line) => line.slice(2).trim())
328
+ .filter(Boolean);
329
+ }
330
+
331
+ function parseBlockSection(blockText, heading) {
332
+ if (!blockText) {
333
+ return [];
334
+ }
335
+
336
+ const escapedHeading = heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
337
+ const match = blockText.match(new RegExp(`### ${escapedHeading}\\r?\\n([\\s\\S]*?)(?=\\r?\\n### |$)`));
338
+ return match ? parseBulletEntries(match[1]) : [];
339
+ }
340
+
341
+ function parseInlineSliceSection(planBlock) {
342
+ if (!planBlock) {
343
+ return [];
344
+ }
345
+
346
+ const match = planBlock.match(/## 4\. Plan \/ Slices\r?\n([\s\S]*?)(?=\r?\n### Planning Notes)/);
347
+ return match ? parseBulletEntries(match[1]) : [];
348
+ }
349
+
350
+ function isPlaceholderSlice(value) {
351
+ return [
352
+ "Pending confirmation during workflow planning.",
353
+ "Pending lane-specific planning or build guidance.",
354
+ "Lightweight bugfix planning not recorded yet.",
355
+ "No active build slices recorded yet.",
356
+ "Pending build-phase execution.",
357
+ ].includes(value);
358
+ }
359
+
360
+ function cleanSliceEntries(entries) {
361
+ return uniqueStrings(entries).filter((entry) => !isPlaceholderSlice(entry));
362
+ }
363
+
364
+ function deriveScopeSliceId(title, index) {
365
+ const prefixed = title.match(/^([A-Z]\d+(?:-[A-Za-z0-9]+)?)\s*:/);
366
+ if (prefixed) {
367
+ return prefixed[1];
368
+ }
369
+
370
+ const tokenized = title.match(/^([A-Z]\d+(?:-[A-Za-z0-9]+)?)\b/);
371
+ if (tokenized) {
372
+ return tokenized[1];
373
+ }
374
+
375
+ return `S${index + 1}`;
376
+ }
377
+
378
+ function deriveOpsImpactSummary(title) {
379
+ const lower = title.toLowerCase();
380
+
381
+ if (/\b(database|migration|schema|sql|table|db)\b/.test(lower)) {
382
+ return "Requires rollout sequencing plus migration and recovery safety checks.";
383
+ }
384
+ if (/\b(api|service|endpoint|backend|auth)\b/.test(lower)) {
385
+ return "Requires runtime service deployment plus API smoke validation.";
386
+ }
387
+ if (/\b(ui|screen|frontend|page|form|layout)\b/.test(lower)) {
388
+ return "Requires user-facing rollout validation for the updated UI surface.";
389
+ }
390
+ if (/\b(flow|interaction|integration|dispatch)\b/.test(lower)) {
391
+ return "Requires end-to-end runtime validation across the affected interaction path.";
392
+ }
393
+
394
+ return "Requires bounded runtime rollout and post-deploy validation for the scoped slice.";
395
+ }
396
+
397
+ function parseWorkflowScopeSlices(workflowText, handoffPayload) {
398
+ const planBlock = extractManagedBlock(workflowText, "PLAN");
399
+ const buildBlock = extractManagedBlock(workflowText, "BUILD");
400
+
401
+ let sliceTitles = cleanSliceEntries(parseBlockSection(planBlock, "Finalized Slices After `plan`"));
402
+ if (sliceTitles.length === 0) {
403
+ sliceTitles = cleanSliceEntries(parseInlineSliceSection(planBlock));
404
+ }
405
+ if (sliceTitles.length === 0) {
406
+ sliceTitles = cleanSliceEntries(parseBlockSection(buildBlock, "Active Slices"));
407
+ }
408
+ if (sliceTitles.length === 0) {
409
+ sliceTitles = uniqueStrings(handoffPayload.implementation_slices || []);
410
+ }
411
+
412
+ return sliceTitles.map((title, index) => ({
413
+ slice_id: deriveScopeSliceId(title, index),
414
+ title,
415
+ ops_impact_summary: deriveOpsImpactSummary(title),
416
+ }));
417
+ }
418
+
419
+ function inferEvidenceKind(checkName, refPath) {
420
+ const combined = `${checkName} ${refPath}`.toLowerCase();
421
+ if (/\b(review|checklist|approval|captain)\b/.test(combined)) {
422
+ return "review";
423
+ }
424
+ if (/\b(pack|build|bundle|artifact)\b/.test(combined)) {
425
+ return "build";
426
+ }
427
+ if (/\b(pytest|npm test|test|regression|smoke|verify)\b/.test(combined)) {
428
+ return "test";
429
+ }
430
+ return "artifact";
431
+ }
432
+
433
+ function parseEvidenceEntriesFromWorkflow(workflowText) {
434
+ const entries = [];
435
+ const regex = /^- `([^`]+)` \| `([^`]+)` \| ([^\r\n]+?) \| Raw output: `([^`]+)`$/gm;
436
+ let match;
437
+ while ((match = regex.exec(workflowText)) !== null) {
438
+ entries.push({
439
+ checkName: match[1],
440
+ result: match[2],
441
+ summary: match[3].trim(),
442
+ rawOutputRef: match[4],
443
+ });
444
+ }
445
+ return entries;
446
+ }
447
+
448
+ function buildCodeEvidenceRefs(projectPath, featureKey, workflowText) {
449
+ const workflowPath = getWorkflowArtifactPath(projectPath, featureKey);
450
+ const refs = [
451
+ {
452
+ label: `${humanizeFeatureKey(featureKey)} code workflow artifact`,
453
+ path: normalizePathForDoc(projectPath, workflowPath),
454
+ kind: "workflow",
455
+ },
456
+ ];
457
+
458
+ for (const entry of parseEvidenceEntriesFromWorkflow(workflowText)) {
459
+ refs.push({
460
+ label: `${entry.checkName} evidence`,
461
+ path: entry.rawOutputRef,
462
+ kind: inferEvidenceKind(entry.checkName, entry.rawOutputRef),
463
+ notes: entry.summary,
464
+ });
465
+ }
466
+
467
+ return uniqueObjects(refs, (entry) => `${entry.kind}::${entry.path}`);
468
+ }
469
+
470
+ function hasRequiredRef(payload, prefix) {
471
+ return Array.isArray(payload.required_refs)
472
+ ? payload.required_refs.some((entry) => String(entry).startsWith(prefix))
473
+ : false;
474
+ }
475
+
476
+ function buildDeploymentPrerequisites(preflightEntries) {
477
+ return uniqueStrings(
478
+ preflightEntries.map((entry) => `${entry.checkName}: ${entry.summary}`)
479
+ );
480
+ }
481
+
482
+ function buildEnvironmentAssumptions(handoffPayload, decision) {
483
+ const assumptions = [
484
+ "OPS intake remains anchored to the current formal CODE_HANDOFF and repo config contract.",
485
+ `DEV-Run should use ${handoffPayload.repo_config_ref} as the current repo command/config reference.`,
486
+ ];
487
+
488
+ if (decision === "finish") {
489
+ assumptions.push(
490
+ 'The CODE closeout used "finish", so remaining hardening or deployment work stays explicit during DEV-Run intake.'
491
+ );
492
+ }
493
+
494
+ if (hasRequiredRef(handoffPayload, "docs/api/")) {
495
+ assumptions.push("Runtime execution can reach the service or API surfaces referenced by the scoped slices.");
496
+ }
497
+ if (hasRequiredRef(handoffPayload, "docs/database/")) {
498
+ assumptions.push("Runtime rollout preserves compatible database state for the scoped slices.");
499
+ }
500
+
501
+ return uniqueStrings(assumptions);
502
+ }
503
+
504
+ function buildInfraRuntimeDependencies(handoffPayload) {
505
+ const dependencies = [
506
+ {
507
+ dependency: "sdtk-spec.config.json",
508
+ requirement: "Use the repo command and environment contract from sdtk-spec.config.json during DEV-Run execution.",
509
+ },
510
+ ];
511
+
512
+ if (hasRequiredRef(handoffPayload, "docs/api/")) {
513
+ dependencies.push({
514
+ dependency: "Application service runtime",
515
+ requirement: "Deploy and validate the API or service surfaces referenced by the scoped slices.",
516
+ });
517
+ }
518
+ if (hasRequiredRef(handoffPayload, "docs/database/")) {
519
+ dependencies.push({
520
+ dependency: "Database / schema state",
521
+ requirement: "Provision compatible database state, migration handling, and recovery safety for the scoped slices.",
522
+ });
523
+ }
524
+ if (hasRequiredRef(handoffPayload, "docs/design/")) {
525
+ dependencies.push({
526
+ dependency: "Frontend or admin delivery surface",
527
+ requirement: "Expose the updated UI surface and verify that the scoped routes remain reachable after rollout.",
528
+ });
529
+ }
530
+
531
+ return uniqueObjects(dependencies, (entry) => entry.dependency);
532
+ }
533
+
534
+ function buildObservabilityRequirements(handoffPayload) {
535
+ const requirements = [
536
+ "DEV-Run must capture deployment and post-deploy validation evidence for the scoped slices.",
537
+ ];
538
+
539
+ if (hasRequiredRef(handoffPayload, "docs/api/")) {
540
+ requirements.push("API or service health plus bounded smoke results must be observable during OPS rollout.");
541
+ }
542
+ if (hasRequiredRef(handoffPayload, "docs/database/")) {
543
+ requirements.push("Migration and persistence outcomes must be observable through logs, health checks, or equivalent evidence.");
544
+ }
545
+
546
+ return uniqueStrings(requirements);
547
+ }
548
+
549
+ function buildRollbackRecoveryExpectations(handoffPayload, decision) {
550
+ const expectations = [
551
+ "Rollback or recovery steps must be explicit before runtime rollout begins.",
552
+ ];
553
+
554
+ if (hasRequiredRef(handoffPayload, "docs/database/")) {
555
+ expectations.push("Database-affecting slices require rollback-safe migrations or documented restore steps.");
556
+ }
557
+ if (decision === "finish") {
558
+ expectations.push("Remaining hardening items carried from CODE closeout must stay explicit if rollback readiness is incomplete.");
559
+ }
560
+
561
+ return uniqueStrings(expectations);
562
+ }
563
+
564
+ function buildSuggestedNextOpsPath(lane, decision) {
565
+ const suggestedChain =
566
+ lane === "bugfix"
567
+ ? ["ops-plan", "ops-deploy"]
568
+ : ["ops-plan", "ops-deploy", "ops-monitor"];
569
+
570
+ return {
571
+ start_with: suggestedChain[0],
572
+ suggested_chain: suggestedChain,
573
+ close_with: "ops-verify",
574
+ why:
575
+ decision === "finish"
576
+ ? "CODE closed a bounded implementation pass and DEV-Run should carry the explicit hardening or deployment follow-up into the OPS path."
577
+ : "CODE closed the scoped implementation with the stronger closeout bundle and DEV-Run can continue with the normal OPS path.",
578
+ };
579
+ }
580
+
581
+ function buildOptionalReferenceEntries(handoffPayload) {
582
+ const refs = [];
583
+
584
+ if (isNonEmptyString(handoffPayload.feature_impl_plan_path)) {
585
+ refs.push({
586
+ label: "Upstream feature implementation plan",
587
+ path: handoffPayload.feature_impl_plan_path.trim(),
588
+ kind: "artifact",
589
+ });
590
+ }
591
+
592
+ if (Array.isArray(handoffPayload.optional_refs)) {
593
+ handoffPayload.optional_refs.forEach((entry, index) => {
594
+ if (isNonEmptyString(entry)) {
595
+ refs.push({
596
+ label: `Optional upstream ref ${index + 1}`,
597
+ path: entry.trim(),
598
+ kind: "artifact",
599
+ });
600
+ }
601
+ });
602
+ }
603
+
604
+ return uniqueObjects(refs, (entry) => entry.path);
605
+ }
606
+
607
+ function buildOptionalOpsNotes(decision, followUps, shipNotes) {
608
+ const notes = [];
609
+
610
+ if (decision === "finish") {
611
+ notes.push('CODE closeout used "finish", so remaining hardening or deployment work stays explicit for DEV-Run.');
612
+ }
613
+
614
+ notes.push(...normalizeOptionalNotes(shipNotes));
615
+ notes.push(...normalizeOptionalNotes((followUps || []).map((entry) => `Follow-up: ${entry}`)));
616
+
617
+ return uniqueStrings(notes);
618
+ }
619
+
620
+ function normalizeOptionalNotes(entries) {
621
+ return (entries || []).map((entry) => String(entry).trim()).filter(Boolean);
622
+ }
623
+
624
+ function readJsonObject(jsonPath, label) {
625
+ let payload;
626
+ try {
627
+ payload = JSON.parse(fs.readFileSync(jsonPath, "utf-8"));
628
+ } catch (error) {
629
+ throw new Error(`${label} is invalid JSON: ${error.message}`);
630
+ }
631
+
632
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
633
+ throw new Error(`${label} must be a JSON object.`);
634
+ }
635
+
636
+ return payload;
637
+ }
638
+
639
+ function loadFormalCodeHandoffForOps(projectPath, featureKey, lane) {
640
+ const handoffPath = getCodeHandoffPath(projectPath, featureKey);
641
+ if (!fs.existsSync(handoffPath)) {
642
+ return null;
643
+ }
644
+
645
+ const payload = readJsonObject(handoffPath, "CODE_HANDOFF");
646
+
647
+ if (!ACCEPTED_HANDOFF_SCHEMA_VERSIONS.has(payload.schema_version)) {
648
+ throw new Error(`CODE_HANDOFF schema_version must be one of: ${[...ACCEPTED_HANDOFF_SCHEMA_VERSIONS].join(", ")}.`);
649
+ }
650
+ if (payload.feature_key !== featureKey) {
651
+ throw new Error(`CODE_HANDOFF feature_key must match ${featureKey}.`);
652
+ }
653
+ if (!HANDOFF_LANES.has(payload.recommended_lane) || payload.recommended_lane !== lane) {
654
+ throw new Error(`CODE_HANDOFF recommended_lane must match the current lane "${lane}".`);
655
+ }
656
+ if (!HANDOFF_STATUSES.has(payload.handoff_status) || payload.handoff_status !== "READY_FOR_SDTK_CODE") {
657
+ throw new Error('CODE_HANDOFF must remain "READY_FOR_SDTK_CODE" for canonical OPS emission.');
658
+ }
659
+ if (payload.repo_config_ref !== "sdtk-spec.config.json") {
660
+ throw new Error('CODE_HANDOFF repo_config_ref must remain "sdtk-spec.config.json".');
661
+ }
662
+ if (!Array.isArray(payload.implementation_slices) || payload.implementation_slices.length === 0) {
663
+ throw new Error("CODE_HANDOFF must keep at least one implementation_slices entry.");
664
+ }
665
+
666
+ return {
667
+ handoffPath,
668
+ payload,
669
+ };
670
+ }
671
+
672
+ function emitOpsHandoffForCompletedCloseout({
673
+ projectPath,
674
+ featureKey,
675
+ lane,
676
+ decision,
677
+ preflightEntries,
678
+ shipFollowUps,
679
+ shipNotes,
680
+ }) {
681
+ let formalCodeHandoff;
682
+ try {
683
+ formalCodeHandoff = loadFormalCodeHandoffForOps(projectPath, featureKey, lane);
684
+ } catch (error) {
685
+ return {
686
+ emitted: false,
687
+ reason: `skipped because the current formal CODE_HANDOFF is invalid (${error.message})`,
688
+ };
689
+ }
690
+
691
+ if (!formalCodeHandoff) {
692
+ return {
693
+ emitted: false,
694
+ reason:
695
+ "skipped because compatibility fallback workflows do not emit the canonical CODE -> OPS bridge without docs/dev/CODE_HANDOFF_[FEATURE_KEY].json",
696
+ };
697
+ }
698
+
699
+ const workflowPath = getWorkflowArtifactPath(projectPath, featureKey);
700
+ const workflowText = fs.readFileSync(workflowPath, "utf-8");
701
+ const scopeSlices = parseWorkflowScopeSlices(workflowText, formalCodeHandoff.payload);
702
+ const codeEvidenceRefs = buildCodeEvidenceRefs(projectPath, featureKey, workflowText);
703
+ const opsHandoffPath = getOpsHandoffPath(projectPath, featureKey);
704
+ const relativeWorkflowPath = normalizePathForDoc(projectPath, workflowPath);
705
+ const relativeCodeHandoffPath = normalizePathForDoc(projectPath, formalCodeHandoff.handoffPath);
706
+ const optionalRefs = buildOptionalReferenceEntries(formalCodeHandoff.payload);
707
+ const notes = buildOptionalOpsNotes(decision, shipFollowUps, shipNotes);
708
+
709
+ const payload = {
710
+ schema_version: OPS_HANDOFF_SCHEMA_VERSION,
711
+ feature_key: featureKey,
712
+ feature_name: humanizeFeatureKey(featureKey),
713
+ delivery_lane: lane,
714
+ generated_by: "sdtk-code",
715
+ generated_at: new Date().toISOString(),
716
+ handoff_status: OPS_HANDOFF_READY_STATUS,
717
+ producer_owner: "DEV-Code",
718
+ consumer_owner: "DEV-Run",
719
+ code_workflow_path: relativeWorkflowPath,
720
+ code_handoff_path: relativeCodeHandoffPath,
721
+ repo_config_ref: formalCodeHandoff.payload.repo_config_ref,
722
+ scope_slices: scopeSlices,
723
+ code_evidence_refs: codeEvidenceRefs,
724
+ deployment_prerequisites: buildDeploymentPrerequisites(preflightEntries),
725
+ environment_assumptions: buildEnvironmentAssumptions(formalCodeHandoff.payload, decision),
726
+ infra_runtime_dependencies: buildInfraRuntimeDependencies(formalCodeHandoff.payload),
727
+ observability_requirements: buildObservabilityRequirements(formalCodeHandoff.payload),
728
+ rollback_recovery_expectations: buildRollbackRecoveryExpectations(
729
+ formalCodeHandoff.payload,
730
+ decision
731
+ ),
732
+ open_blockers: [],
733
+ suggested_next_ops_path: buildSuggestedNextOpsPath(lane, decision),
734
+ };
735
+
736
+ if (optionalRefs.length > 0) {
737
+ payload.optional_refs = optionalRefs;
738
+ }
739
+ if (notes.length > 0) {
740
+ payload.notes = notes;
741
+ }
742
+
743
+ fs.writeFileSync(opsHandoffPath, JSON.stringify(payload, null, 2) + "\n", "utf-8");
744
+
745
+ return {
746
+ emitted: true,
747
+ opsHandoffPath,
748
+ handoffStatus: OPS_HANDOFF_READY_STATUS,
749
+ scopeSliceCount: scopeSlices.length,
750
+ evidenceRefCount: codeEvidenceRefs.length,
751
+ };
752
+ }
753
+
754
+ function validateRequiredRefCoverage(requiredRefs, implementationSlices, featureKey) {
755
+ const archPath = `docs/architecture/ARCH_DESIGN_${featureKey}.md`;
756
+ const backlogPath = `docs/product/BACKLOG_${featureKey}.md`;
757
+
758
+ for (const mustHave of [archPath, backlogPath]) {
759
+ if (!requiredRefs.includes(mustHave)) {
760
+ throw new Error(`required_refs must include: ${mustHave}`);
761
+ }
762
+ }
763
+
764
+ const sliceText = implementationSlices.map((entry) => String(entry).toLowerCase()).join(" || ");
765
+ if (!sliceText) {
766
+ return;
767
+ }
768
+
769
+ if (/\b(api|endpoint|contract|service|backend)\b/.test(sliceText)) {
770
+ if (!requiredRefs.some((entry) => entry.startsWith("docs/api/"))) {
771
+ throw new Error(
772
+ "implementation_slices reference API or backend scope, so required_refs must include at least one docs/api/* source."
773
+ );
774
+ }
775
+ }
776
+
777
+ if (/\b(database|migration|schema|table|sql|db)\b/.test(sliceText)) {
778
+ if (!requiredRefs.some((entry) => entry.startsWith("docs/database/"))) {
779
+ throw new Error(
780
+ "implementation_slices reference database scope, so required_refs must include at least one docs/database/* source."
781
+ );
782
+ }
783
+ }
784
+
785
+ if (/\b(ui|screen|frontend|page|form|layout)\b/.test(sliceText)) {
786
+ if (!requiredRefs.some((entry) => entry.startsWith("docs/design/"))) {
787
+ throw new Error(
788
+ "implementation_slices reference UI scope, so required_refs must include at least one docs/design/* source."
789
+ );
790
+ }
791
+ }
792
+
793
+ if (/\b(flow|interaction)\b/.test(sliceText)) {
794
+ if (!requiredRefs.some((entry) => entry.startsWith("docs/specs/") && entry.endsWith("_FLOW_ACTION_SPEC.md"))) {
795
+ throw new Error(
796
+ "implementation_slices reference flow scope, so required_refs must include docs/specs/[FEATURE_KEY]_FLOW_ACTION_SPEC.md."
797
+ );
798
+ }
799
+ }
800
+ }
801
+
802
+ function buildInputEntries(projectPath, payload, featureKey, handoffPath) {
803
+ const requiredInputs = [
804
+ {
805
+ key: "CODE_HANDOFF",
806
+ path: handoffPath,
807
+ exists: true,
808
+ },
809
+ ];
810
+ const optionalInputs = [];
811
+
812
+ if (isNonEmptyString(payload.feature_impl_plan_path)) {
813
+ requiredInputs.push(buildPathEntry("FEATURE_IMPL_PLAN", projectPath, payload.feature_impl_plan_path.trim()));
814
+ }
815
+
816
+ if (isNonEmptyString(payload.repo_config_ref)) {
817
+ requiredInputs.push(buildPathEntry("SDTK_CONFIG", projectPath, payload.repo_config_ref.trim()));
818
+ }
819
+
820
+ if (Array.isArray(payload.required_refs)) {
821
+ payload.required_refs.forEach((entry, index) => {
822
+ if (isNonEmptyString(entry)) {
823
+ requiredInputs.push(buildPathEntry(`REQUIRED_REF_${index + 1}`, projectPath, entry.trim()));
824
+ }
825
+ });
826
+ }
827
+
828
+ if (Array.isArray(payload.optional_refs)) {
829
+ payload.optional_refs.forEach((entry, index) => {
830
+ if (isNonEmptyString(entry)) {
831
+ optionalInputs.push(buildPathEntry(`OPTIONAL_REF_${index + 1}`, projectPath, entry.trim()));
832
+ }
833
+ });
834
+ }
835
+
836
+ return {
837
+ requiredInputs: uniquePathEntries(requiredInputs),
838
+ optionalInputs: uniquePathEntries(optionalInputs),
839
+ };
840
+ }
841
+
842
+ function resolveFormalHandoffIntake(projectPath, featureKey, lane) {
843
+ const handoffPath = path.join(projectPath, "docs", "dev", `CODE_HANDOFF_${featureKey}.json`);
844
+ if (!fs.existsSync(handoffPath)) {
845
+ return null;
846
+ }
847
+
848
+ let payload;
849
+ try {
850
+ payload = JSON.parse(fs.readFileSync(handoffPath, "utf-8"));
851
+ } catch (error) {
852
+ return createBlockedFormalIntake({
853
+ projectPath,
854
+ featureKey,
855
+ lane,
856
+ handoffStatus: "INVALID_JSON",
857
+ requiredInputs: [
858
+ {
859
+ key: "CODE_HANDOFF",
860
+ path: handoffPath,
861
+ exists: true,
862
+ },
863
+ ],
864
+ optionalInputs: [],
865
+ blockingState: "invalid_handoff_contract",
866
+ blockingMessage: `SDTK-CODE handoff contract is invalid: failed to parse JSON (${error.message}).`,
867
+ });
868
+ }
869
+
870
+ let compatibilityWarnings = collectSoftWarnings(payload);
871
+ const { requiredInputs, optionalInputs } = buildInputEntries(projectPath, payload, featureKey, handoffPath);
872
+
873
+ try {
874
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
875
+ throw new Error("Formal handoff root value must be a JSON object.");
876
+ }
877
+
878
+ if (!ACCEPTED_HANDOFF_SCHEMA_VERSIONS.has(payload.schema_version)) {
879
+ throw new Error(`schema_version must be one of: ${[...ACCEPTED_HANDOFF_SCHEMA_VERSIONS].join(", ")}.`);
880
+ }
881
+
882
+ const schemaVersion = payload.schema_version;
883
+
884
+ if (!isNonEmptyString(payload.feature_key)) {
885
+ throw new Error("feature_key must be a non-empty string.");
886
+ }
887
+ if (!/^[A-Z][A-Z0-9_]*$/.test(payload.feature_key.trim())) {
888
+ throw new Error("feature_key must use UPPER_SNAKE_CASE.");
889
+ }
890
+ if (payload.feature_key.trim() !== featureKey) {
891
+ throw new Error(`feature_key must match CLI --feature-key: ${featureKey}`);
892
+ }
893
+
894
+ if (!HANDOFF_STATUSES.has(payload.handoff_status)) {
895
+ throw new Error('handoff_status must be "READY_FOR_SDTK_CODE" or "BLOCKED_FOR_SDTK_CODE".');
896
+ }
897
+
898
+ if (!HANDOFF_LANES.has(payload.recommended_lane)) {
899
+ throw new Error('recommended_lane must be "feature" or "bugfix".');
900
+ }
901
+ if (payload.recommended_lane !== lane) {
902
+ throw new Error(`recommended_lane must match CLI --lane: ${lane}`);
903
+ }
904
+
905
+ const featureImplPlanPath = normalizeRelativePath(
906
+ payload.feature_impl_plan_path,
907
+ "feature_impl_plan_path"
908
+ );
909
+ const expectedPlanPath = `docs/dev/FEATURE_IMPL_PLAN_${featureKey}.md`;
910
+ if (featureImplPlanPath !== expectedPlanPath) {
911
+ throw new Error(`feature_impl_plan_path must match the current feature key: ${expectedPlanPath}`);
912
+ }
913
+
914
+ const repoConfigRef = normalizeRelativePath(payload.repo_config_ref, "repo_config_ref");
915
+ if (repoConfigRef !== "sdtk-spec.config.json") {
916
+ throw new Error('repo_config_ref must be exactly "sdtk-spec.config.json".');
917
+ }
918
+
919
+ const requiredRefs = requireArray(payload, "required_refs").map((entry, index) =>
920
+ normalizeRelativePath(entry, `required_refs[${index}]`)
921
+ );
922
+ const optionalRefs = requireArray(payload, "optional_refs").map((entry, index) =>
923
+ normalizeRelativePath(entry, `optional_refs[${index}]`)
924
+ );
925
+ const openBlockers = normalizeStringArray(requireArray(payload, "open_blockers"), "open_blockers");
926
+ const implementationSlices = normalizeStringArray(
927
+ requireArray(payload, "implementation_slices"),
928
+ "implementation_slices"
929
+ );
930
+ const testObligations = normalizeStringArray(requireArray(payload, "test_obligations"), "test_obligations");
931
+ const impactMap = schemaVersion === "0.2" ? normalizeImpactMap(payload.impact_map) : null;
932
+ const recoveryNotes = schemaVersion === "0.2" ? normalizeOptionalStringArray(payload.recovery_notes, "recovery_notes") : [];
933
+
934
+ if (schemaVersion === "0.2" && !impactMap) {
935
+ compatibilityWarnings = [
936
+ ...compatibilityWarnings,
937
+ 'Formal handoff compatibility warning: schema_version "0.2" is present without impact_map; richer impact seeding is unavailable.',
938
+ ];
939
+ }
940
+
941
+ validateRequiredRefCoverage(requiredRefs, implementationSlices, featureKey);
942
+
943
+ const missingInputs = requiredInputs.filter((entry) => !entry.exists);
944
+ const missingOptional = optionalInputs.filter((entry) => !entry.exists);
945
+ if (missingInputs.length > 0) {
946
+ const missingList = missingInputs
947
+ .map((entry) => normalizePathForDoc(projectPath, entry.path))
948
+ .join(", ");
949
+ throw new Error(`formal handoff references missing required paths: ${missingList}`);
950
+ }
951
+ if (missingOptional.length > 0) {
952
+ const missingList = missingOptional
953
+ .map((entry) => normalizePathForDoc(projectPath, entry.path))
954
+ .join(", ");
955
+ throw new Error(`formal handoff references missing optional paths: ${missingList}`);
956
+ }
957
+
958
+ if (payload.handoff_status === "READY_FOR_SDTK_CODE") {
959
+ if (openBlockers.length > 0) {
960
+ throw new Error("READY_FOR_SDTK_CODE requires empty open_blockers.");
961
+ }
962
+ if (implementationSlices.length === 0) {
963
+ throw new Error("READY_FOR_SDTK_CODE requires at least one implementation_slices entry.");
964
+ }
965
+ if (testObligations.length === 0) {
966
+ throw new Error("READY_FOR_SDTK_CODE requires at least one test_obligations entry.");
967
+ }
968
+ } else if (openBlockers.length === 0) {
969
+ throw new Error("BLOCKED_FOR_SDTK_CODE requires at least one open_blockers entry.");
970
+ }
971
+
972
+ if (payload.handoff_status === "BLOCKED_FOR_SDTK_CODE") {
973
+ return createBlockedFormalIntake({
974
+ projectPath,
975
+ featureKey,
976
+ lane,
977
+ handoffStatus: payload.handoff_status,
978
+ requiredInputs,
979
+ optionalInputs,
980
+ blockingState: "blocked_upstream_handoff",
981
+ blockingMessage: "SDTK-CODE handoff is blocked by upstream /dev blockers:",
982
+ blockingDetails: openBlockers,
983
+ compatibilityWarnings,
984
+ });
985
+ }
986
+
987
+ const candidatePlanningSeed = buildCandidatePlanningSeed(lane, implementationSlices, testObligations, {
988
+ schemaVersion,
989
+ impactMap,
990
+ recoveryNotes,
991
+ });
992
+
993
+ return createIntakeResult({
994
+ projectPath,
995
+ featureKey,
996
+ lane,
997
+ requiredInputs,
998
+ optionalInputs,
999
+ missingInputs: [],
1000
+ blocked: false,
1001
+ intakeOutcome: lane === "feature" ? "READY_FOR_PLAN" : "READY_FOR_BUILD_BUGFIX",
1002
+ nextPhase: lane === "feature" ? "plan" : "build",
1003
+ phaseStatus: "completed",
1004
+ blockingState: "clear",
1005
+ intakeSource: "formal_handoff",
1006
+ handoffStatus: payload.handoff_status,
1007
+ compatibilityWarnings,
1008
+ ...candidatePlanningSeed,
1009
+ });
1010
+ } catch (error) {
1011
+ return createBlockedFormalIntake({
1012
+ projectPath,
1013
+ featureKey,
1014
+ lane,
1015
+ handoffStatus: payload && payload.handoff_status ? String(payload.handoff_status) : "INVALID_CONTRACT",
1016
+ requiredInputs,
1017
+ optionalInputs,
1018
+ blockingState: "invalid_handoff_contract",
1019
+ blockingMessage: `SDTK-CODE handoff contract is invalid: ${error.message}`,
1020
+ compatibilityWarnings,
1021
+ });
1022
+ }
1023
+ }
1024
+
1025
+ module.exports = {
1026
+ emitOpsHandoffForCompletedCloseout,
1027
+ getOpsHandoffPath,
1028
+ resolveFormalHandoffIntake,
1029
+ };