@gtrabanco/agentic-workflow-schema 2.1.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,15 @@
1
1
  /**
2
2
  * @gtrabanco/agentic-workflow-schema
3
3
  *
4
- * Types, extraction, and validation for the agentic-workflow **machine
5
- * envelope** — the fixed JSON block a driven agent turn ends with (emitted by
6
- * workflow-status always, and by any other skill when the driver injects the
7
- * canonical system-prompt snippet).
4
+ * Types, extraction, and validation for the agentic-workflow machine contracts:
5
+ * Envelope v2, SkillOutcome v1, and WorkflowSnapshot v1.
8
6
  *
9
- * Parse contract (mirrors skills/orchestration-envelope/SKILL.md):
7
+ * Envelope parse contract:
10
8
  * take the LAST fenced ```json block of the assistant's final message;
11
9
  * exactly one envelope per turn; all top-level keys always present.
12
10
  */
13
11
  // ---------------------------------------------------------------------------
14
- // Types (source of truth: skills/orchestration-envelope/SKILL.md)
12
+ // Types (source of truth: this package; the internal skill carries policy only)
15
13
  // ---------------------------------------------------------------------------
16
14
  export const ENVELOPE_STATES = [
17
15
  "OK",
@@ -253,11 +251,11 @@ export function validateEnvelope(value) {
253
251
  !findings.issues_filed.every((n) => typeof n === "number" && Number.isInteger(n))) {
254
252
  errors.push("findings.issues_filed must be an array of integers");
255
253
  }
256
- if (typeof findings.untriaged !== "number" || !Number.isInteger(findings.untriaged)) {
257
- errors.push("findings.untriaged must be an integer");
254
+ if (typeof findings.untriaged !== "number" || !Number.isInteger(findings.untriaged) || findings.untriaged < 0) {
255
+ errors.push("findings.untriaged must be a non-negative integer");
258
256
  }
259
- if (typeof findings.decisions_recorded !== "number" || !Number.isInteger(findings.decisions_recorded)) {
260
- errors.push("findings.decisions_recorded must be an integer");
257
+ if (typeof findings.decisions_recorded !== "number" || !Number.isInteger(findings.decisions_recorded) || findings.decisions_recorded < 0) {
258
+ errors.push("findings.decisions_recorded must be a non-negative integer");
261
259
  }
262
260
  }
263
261
  if (!isObj(value.next)) {
@@ -338,3 +336,897 @@ export function isRunHalt(envelope) {
338
336
  return (envelope.state === "HALT" ||
339
337
  envelope.blockers.some((b) => b.scope === "run"));
340
338
  }
339
+ // ---------------------------------------------------------------------------
340
+ // Machine contracts — strict v2 compatibility, compact outcomes, snapshots
341
+ // ---------------------------------------------------------------------------
342
+ /** The strict, driver-facing interpretation of the legacy envelope. */
343
+ const STRICT_V2_KEYS = [...REQUIRED_KEYS, "detail"];
344
+ function rejectUnexpectedKeys(value, path, keys, errors) {
345
+ if (!isObj(value))
346
+ return;
347
+ const allowed = new Set(keys);
348
+ for (const key of Object.keys(value)) {
349
+ if (!allowed.has(key))
350
+ errors.push(`unexpected key: ${path}.${key}`);
351
+ }
352
+ }
353
+ function rejectUnexpectedEnvelopeKeys(value, errors) {
354
+ rejectUnexpectedKeys(value.unit, "unit", ["type", "id", "issue", "branch"], errors);
355
+ rejectUnexpectedKeys(value.phase, "phase", ["current", "total", "completed"], errors);
356
+ rejectUnexpectedKeys(value.pr, "pr", ["number", "url", "state", "head_sha", "merge_ready", "ci"], errors);
357
+ rejectUnexpectedKeys(value.gates, "gates", ["verification", "review_pending", "audit_pending"], errors);
358
+ rejectUnexpectedKeys(value.findings, "findings", ["fix_now", "issues_filed", "untriaged", "decisions_recorded"], errors);
359
+ if (isObj(value.findings) && Array.isArray(value.findings.fix_now)) {
360
+ value.findings.fix_now.forEach((finding, index) => {
361
+ rejectUnexpectedKeys(finding, `findings.fix_now[${index}]`, ["id", "file", "axis", "severity", "class", "route", "suggested_tier"], errors);
362
+ });
363
+ }
364
+ if (Array.isArray(value.blockers)) {
365
+ value.blockers.forEach((blocker, index) => {
366
+ rejectUnexpectedKeys(blocker, `blockers[${index}]`, ["kind", "id", "scope", "detail"], errors);
367
+ });
368
+ }
369
+ rejectUnexpectedKeys(value.dependencies, "dependencies", ["unmet", "build_order"], errors);
370
+ rejectUnexpectedKeys(value.recommendations, "recommendations", ["product_audit", "reason"], errors);
371
+ if (value.needs_input !== null) {
372
+ rejectUnexpectedKeys(value.needs_input, "needs_input", ["question", "options"], errors);
373
+ }
374
+ rejectUnexpectedKeys(value.next, "next", ["recommended", "alternatives", "tier", "suggested"], errors);
375
+ if (isObj(value.next) && Array.isArray(value.next.suggested)) {
376
+ value.next.suggested.forEach((suggestion, index) => {
377
+ rejectUnexpectedKeys(suggestion, `next.suggested[${index}]`, ["command", "trigger", "source_skill"], errors);
378
+ });
379
+ }
380
+ }
381
+ /**
382
+ * Validates the documented v2 shape at a driver boundary.
383
+ *
384
+ * `validateEnvelope()` remains intentionally source-compatible for existing
385
+ * package consumers. New drivers use this stricter entry point: `detail` is
386
+ * present and top-level schema extensions are rejected instead of silently
387
+ * becoming a second, undocumented contract.
388
+ */
389
+ export function validateEnvelopeV2Strict(value) {
390
+ const base = validateEnvelope(value);
391
+ if (!base.ok)
392
+ return base;
393
+ if (!isObj(value))
394
+ return { ok: false, errors: ["envelope is not a JSON object"] };
395
+ const errors = [];
396
+ for (const key of STRICT_V2_KEYS) {
397
+ if (!(key in value))
398
+ errors.push(`missing required key: ${key}`);
399
+ }
400
+ const allowed = new Set(STRICT_V2_KEYS);
401
+ for (const key of Object.keys(value)) {
402
+ if (!allowed.has(key))
403
+ errors.push(`unexpected top-level key: ${key}`);
404
+ }
405
+ rejectUnexpectedEnvelopeKeys(value, errors);
406
+ return errors.length === 0 ? { ok: true, envelope: base.envelope } : { ok: false, errors };
407
+ }
408
+ /** Extract, parse, and validate the strict driver-facing v2 envelope. */
409
+ export function parseEnvelopeV2Strict(text) {
410
+ const raw = extractLastJsonBlock(text);
411
+ if (raw === null)
412
+ return { ok: false, errors: ["no fenced ```json block found"], raw: null };
413
+ let parsed;
414
+ try {
415
+ parsed = JSON.parse(raw);
416
+ }
417
+ catch (error) {
418
+ return {
419
+ ok: false,
420
+ errors: [`invalid JSON in last fenced block: ${error.message}`],
421
+ raw,
422
+ };
423
+ }
424
+ const result = validateEnvelopeV2Strict(parsed);
425
+ return result.ok
426
+ ? { ok: true, envelope: result.envelope, raw }
427
+ : { ok: false, errors: result.errors, raw };
428
+ }
429
+ export const WORKFLOW_INTENTS = [
430
+ "init-workspace",
431
+ "status",
432
+ "discover-repository-state",
433
+ "resolve-repository-state",
434
+ "design-feature",
435
+ "plan-feature",
436
+ "plan-fix",
437
+ "triage-issue",
438
+ "execute-phase",
439
+ "review-change",
440
+ "loop-review-fold",
441
+ "audit-pr",
442
+ "merge",
443
+ "ask-human",
444
+ "stop",
445
+ "none",
446
+ ];
447
+ /**
448
+ * The portable skill inventory consumed by headless drivers. Profiles are
449
+ * programmatic metadata, not duplicated prompt sections in user-facing skills.
450
+ */
451
+ export const WORKFLOW_SKILL_PROFILES = [
452
+ { skill: "init-workspace", output: "skill-outcome-v1", nativeFallback: "none" },
453
+ { skill: "workflow-status", output: "envelope-v2", nativeFallback: "none" },
454
+ { skill: "discover-repository-state", output: "skill-outcome-v1", nativeFallback: "none" },
455
+ { skill: "resolve-repository-state", output: "skill-outcome-v1", nativeFallback: "none" },
456
+ { skill: "design-feature", output: "skill-outcome-v1", nativeFallback: "none" },
457
+ { skill: "plan-feature", output: "skill-outcome-v1", nativeFallback: "none" },
458
+ { skill: "plan-fix", output: "skill-outcome-v1", nativeFallback: "none" },
459
+ { skill: "triage-issue", output: "skill-outcome-v1", nativeFallback: "none" },
460
+ { skill: "execute-phase", output: "skill-outcome-v1", nativeFallback: "none" },
461
+ { skill: "review-change", output: "skill-outcome-v1", nativeFallback: "none" },
462
+ { skill: "loop-review-fold", output: "skill-outcome-v1", nativeFallback: "fixed-verdict" },
463
+ { skill: "audit-pr", output: "skill-outcome-v1", nativeFallback: "fixed-verdict" },
464
+ ];
465
+ function workflowSkillProfile(skill) {
466
+ return WORKFLOW_SKILL_PROFILES.find((profile) => profile.skill === skill);
467
+ }
468
+ function isWorkflowIntent(value) {
469
+ return typeof value === "string" && WORKFLOW_INTENTS.includes(value);
470
+ }
471
+ function isBlockerKind(value) {
472
+ return typeof value === "string" && BLOCKER_KINDS.includes(value);
473
+ }
474
+ function isBlockerScope(value) {
475
+ return typeof value === "string" && BLOCKER_SCOPES.includes(value);
476
+ }
477
+ /** Validates the strict, model-owned SkillOutcome v1 JSON contract. */
478
+ export function validateSkillOutcomeV1(value) {
479
+ if (!isObj(value))
480
+ return { ok: false, errors: ["skill outcome is not a JSON object"] };
481
+ const required = [
482
+ "contract",
483
+ "version",
484
+ "skill",
485
+ "status",
486
+ "summary",
487
+ "next",
488
+ "blockers",
489
+ "questions",
490
+ "discoveries",
491
+ "evidence_refs",
492
+ ];
493
+ const errors = [];
494
+ for (const key of required)
495
+ if (!(key in value))
496
+ errors.push(`missing required key: ${key}`);
497
+ const allowed = new Set(required);
498
+ for (const key of Object.keys(value))
499
+ if (!allowed.has(key))
500
+ errors.push(`unexpected top-level key: ${key}`);
501
+ if (value.contract !== "agentic-workflow/skill-outcome")
502
+ errors.push("contract must be agentic-workflow/skill-outcome");
503
+ if (value.version !== 1)
504
+ errors.push("version must be 1");
505
+ if (typeof value.skill !== "string" || value.skill.length === 0)
506
+ errors.push("skill must be a non-empty string");
507
+ if (!["completed", "continue", "blocked", "needs-input", "failed"].includes(value.status)) {
508
+ errors.push("status must be completed|continue|blocked|needs-input|failed");
509
+ }
510
+ if (typeof value.summary !== "string")
511
+ errors.push("summary must be a string");
512
+ if (!isObj(value.next)) {
513
+ errors.push("next must be an object");
514
+ }
515
+ else {
516
+ rejectUnexpectedKeys(value.next, "next", ["intent", "targets"], errors);
517
+ if (!isWorkflowIntent(value.next.intent))
518
+ errors.push("next.intent must be a known workflow intent");
519
+ if (!isStringArray(value.next.targets))
520
+ errors.push("next.targets must be an array of strings");
521
+ }
522
+ if (!Array.isArray(value.blockers)) {
523
+ errors.push("blockers must be an array");
524
+ }
525
+ else {
526
+ value.blockers.forEach((blocker, index) => {
527
+ if (!isObj(blocker)) {
528
+ errors.push(`blockers[${index}] must be an object`);
529
+ return;
530
+ }
531
+ rejectUnexpectedKeys(blocker, `blockers[${index}]`, ["kind", "id", "scope", "detail"], errors);
532
+ if (!isBlockerKind(blocker.kind))
533
+ errors.push(`blockers[${index}].kind is invalid`);
534
+ if (typeof blocker.id !== "string")
535
+ errors.push(`blockers[${index}].id must be a string`);
536
+ if (!isBlockerScope(blocker.scope))
537
+ errors.push(`blockers[${index}].scope is invalid`);
538
+ if (typeof blocker.detail !== "string")
539
+ errors.push(`blockers[${index}].detail must be a string`);
540
+ });
541
+ }
542
+ if (!Array.isArray(value.questions)) {
543
+ errors.push("questions must be an array");
544
+ }
545
+ else {
546
+ value.questions.forEach((question, index) => {
547
+ if (!isObj(question)) {
548
+ errors.push(`questions[${index}] must be an object`);
549
+ return;
550
+ }
551
+ rejectUnexpectedKeys(question, `questions[${index}]`, ["id", "question", "options"], errors);
552
+ if (typeof question.id !== "string")
553
+ errors.push(`questions[${index}].id must be a string`);
554
+ if (typeof question.question !== "string")
555
+ errors.push(`questions[${index}].question must be a string`);
556
+ if (!isStringArray(question.options))
557
+ errors.push(`questions[${index}].options must be an array of strings`);
558
+ });
559
+ }
560
+ if (!Array.isArray(value.discoveries)) {
561
+ errors.push("discoveries must be an array");
562
+ }
563
+ else {
564
+ const discoveryKinds = ["defect", "risk", "opportunity", "environment", "scope-gap", "unknown"];
565
+ const discoveryScopes = ["current-unit", "outside-unit", "run"];
566
+ value.discoveries.forEach((discovery, index) => {
567
+ if (!isObj(discovery)) {
568
+ errors.push(`discoveries[${index}] must be an object`);
569
+ return;
570
+ }
571
+ rejectUnexpectedKeys(discovery, `discoveries[${index}]`, ["kind", "scope", "summary", "evidence_refs", "proposed_intent"], errors);
572
+ if (!discoveryKinds.includes(discovery.kind))
573
+ errors.push(`discoveries[${index}].kind is invalid`);
574
+ if (!discoveryScopes.includes(discovery.scope))
575
+ errors.push(`discoveries[${index}].scope is invalid`);
576
+ if (typeof discovery.summary !== "string")
577
+ errors.push(`discoveries[${index}].summary must be a string`);
578
+ if (!isStringArray(discovery.evidence_refs))
579
+ errors.push(`discoveries[${index}].evidence_refs must be an array of strings`);
580
+ if (!isWorkflowIntent(discovery.proposed_intent))
581
+ errors.push(`discoveries[${index}].proposed_intent is invalid`);
582
+ });
583
+ }
584
+ if (!isStringArray(value.evidence_refs))
585
+ errors.push("evidence_refs must be an array of strings");
586
+ return errors.length === 0
587
+ ? { ok: true, outcome: value }
588
+ : { ok: false, errors };
589
+ }
590
+ function nextIntent(command) {
591
+ const match = /\/([a-z-]+)/.exec(command);
592
+ switch (match?.[1]) {
593
+ case "workflow-status":
594
+ return "status";
595
+ case "init-workspace":
596
+ case "discover-repository-state":
597
+ case "resolve-repository-state":
598
+ case "design-feature":
599
+ case "plan-feature":
600
+ case "plan-fix":
601
+ case "triage-issue":
602
+ case "review-change":
603
+ case "loop-review-fold":
604
+ case "audit-pr":
605
+ return match[1];
606
+ case "merge":
607
+ return "merge";
608
+ case "execute-phase":
609
+ return "execute-phase";
610
+ default:
611
+ return "none";
612
+ }
613
+ }
614
+ function outcomeStatus(state) {
615
+ if (state === "BLOCKED")
616
+ return "blocked";
617
+ if (state === "NEEDS_INPUT")
618
+ return "needs-input";
619
+ if (state === "FAILED" || state === "HALT")
620
+ return "failed";
621
+ if (state === "CONTINUE" || state === "NEEDS_FIXES")
622
+ return "continue";
623
+ return "completed";
624
+ }
625
+ function outcomeFromEnvelope(envelope) {
626
+ const intent = nextIntent(envelope.next.recommended);
627
+ const targets = envelope.unit.id === null ? [] : [envelope.unit.id];
628
+ return {
629
+ contract: "agentic-workflow/skill-outcome",
630
+ version: 1,
631
+ skill: envelope.skill,
632
+ status: outcomeStatus(envelope.state),
633
+ summary: envelope.summary,
634
+ next: { intent, targets },
635
+ blockers: envelope.blockers,
636
+ questions: envelope.needs_input === null
637
+ ? []
638
+ : [{ id: "needs-input", question: envelope.needs_input.question, options: envelope.needs_input.options }],
639
+ discoveries: [],
640
+ evidence_refs: [],
641
+ };
642
+ }
643
+ function parseLastJson(text) {
644
+ const raw = extractLastJsonBlock(text);
645
+ if (raw === null)
646
+ return { ok: false, error: "no fenced ```json block found" };
647
+ try {
648
+ return { ok: true, value: JSON.parse(raw) };
649
+ }
650
+ catch (error) {
651
+ return { ok: false, error: `invalid JSON in last fenced block: ${error.message}` };
652
+ }
653
+ }
654
+ function normalizeCompatibilityEnvelope(value, skill, context) {
655
+ if (!isObj(value))
656
+ return { ok: false, errors: ["envelope is not a JSON object"], diagnostics: [] };
657
+ const diagnostics = [];
658
+ const normalized = { ...value };
659
+ if (!("detail" in normalized)) {
660
+ normalized.detail = null;
661
+ diagnostics.push({ code: "detail-defaulted", detail: "Missing legacy detail was normalized to null." });
662
+ }
663
+ if ("design_candidates" in normalized) {
664
+ if (normalized.detail !== null && normalized.detail !== undefined && !isObj(normalized.detail)) {
665
+ return {
666
+ ok: false,
667
+ errors: ["legacy design_candidates cannot be moved into a non-object detail"],
668
+ diagnostics,
669
+ };
670
+ }
671
+ const detail = isObj(normalized.detail) ? { ...normalized.detail } : {};
672
+ detail.design_candidates = normalized.design_candidates;
673
+ normalized.detail = detail;
674
+ delete normalized.design_candidates;
675
+ diagnostics.push({ code: "design-candidates-moved", detail: "Legacy root design_candidates moved under detail." });
676
+ }
677
+ if (skill === "audit-pr") {
678
+ if (isObj(normalized.unit) && typeof normalized.unit.id === "number") {
679
+ const unitId = context?.unitId;
680
+ if (unitId !== undefined && unitId.startsWith(`${normalized.unit.id}-`)) {
681
+ normalized.unit = { ...normalized.unit, id: unitId };
682
+ diagnostics.push({ code: "unit-id-from-context", detail: "Numeric legacy unit id matched trusted driver context." });
683
+ }
684
+ }
685
+ if (isObj(normalized.findings) && typeof normalized.findings.issues_filed === "number") {
686
+ if (normalized.findings.issues_filed === 0) {
687
+ normalized.findings = { ...normalized.findings, issues_filed: [] };
688
+ diagnostics.push({ code: "zero-issue-count", detail: "A zero legacy issue count was normalized to an empty identity list." });
689
+ }
690
+ else {
691
+ return {
692
+ ok: false,
693
+ errors: [`issues_filed count ${normalized.findings.issues_filed} cannot be normalized without issue identities`],
694
+ diagnostics,
695
+ };
696
+ }
697
+ }
698
+ if (Array.isArray(normalized.blockers)) {
699
+ const mapped = [];
700
+ for (const blocker of normalized.blockers) {
701
+ if (isObj(blocker) &&
702
+ typeof blocker.gate === "string" &&
703
+ typeof blocker.evidence === "string" &&
704
+ typeof blocker.route === "string") {
705
+ mapped.push({ kind: "gate", id: blocker.gate, scope: "unit", detail: blocker.evidence });
706
+ diagnostics.push({ code: "audit-pr-blocker-mapped", detail: `Native gate ${blocker.gate} mapped to a canonical blocker.` });
707
+ }
708
+ else {
709
+ mapped.push(blocker);
710
+ }
711
+ }
712
+ normalized.blockers = mapped;
713
+ }
714
+ }
715
+ return { ok: true, envelope: normalized, diagnostics };
716
+ }
717
+ function parseNativeTurn(skill, text) {
718
+ const lines = text.trim().split(/\r?\n/).filter((line) => line.trim().length > 0);
719
+ if (lines.length === 0)
720
+ return null;
721
+ const nextIndex = lines.findIndex((line) => /^→\s*Next:/i.test(line.trim()));
722
+ if (nextIndex < 0)
723
+ return null;
724
+ const command = /^→\s*Next:\s*(\/[-a-z]+(?:\s+[^\n—]+)?)\s+—/i.exec(lines[nextIndex].trim())?.[1]?.trim();
725
+ if (skill === "loop-review-fold") {
726
+ const nextIsFinal = lines.slice(nextIndex + 1).every((line) => /^·/.test(line.trim()));
727
+ if (!nextIsFinal || command === undefined || nextIntent(command) === "none")
728
+ return null;
729
+ const verdict = /^REVIEW-FOLD LOOP\s+[—-]\s+(PASS|TRIAGE-REQUIRED|BLOCKED)\s*$/i.exec(lines[0])?.[1]?.toUpperCase();
730
+ if (verdict === undefined)
731
+ return null;
732
+ if (!lines.some((line) => /^Unit:\s*.+\s+·\s+PR:\s*\S+\s+·\s+HEAD:\s*\S+\s*$/i.test(line.trim())))
733
+ return null;
734
+ if (!lines.some((line) => /^First action:\s*(PASS|review-change|fold-findings)\s*$/i.test(line.trim())))
735
+ return null;
736
+ if (!lines.some((line) => /^Review:\s*(PASS|FAIL|not-run)\s+·\s+Fold:\s*(changed|unchanged|not-run)\s*$/i.test(line.trim())))
737
+ return null;
738
+ if (!lines.some((line) => /^Unresolved:\s*(none|F\d+(?:\s*\+\s*F\d+)*)\s*$/i.test(line.trim())))
739
+ return null;
740
+ if (!lines.some((line) => /^Evidence:\s*\S+/i.test(line.trim())))
741
+ return null;
742
+ const status = verdict === "PASS" ? "completed" : verdict === "BLOCKED" ? "blocked" : "continue";
743
+ return nativeOutcome(skill, status, `loop-review-fold returned ${verdict}.`, command, []);
744
+ }
745
+ if (skill === "audit-pr") {
746
+ const auditBody = lines.slice(0, nextIndex).join("\n");
747
+ const nextLines = lines.slice(nextIndex + 1);
748
+ const nextIsFinal = nextLines.length > 0 && nextLines.every((line) => /^·/.test(line.trim()));
749
+ const nextBulletCommand = nextLines
750
+ .flatMap((line) => [...line.matchAll(/\/[-a-z]+(?:\s+--[-a-z]+(?:\s+\S+)?)?/g)].map((match) => match[0]))
751
+ .find((value) => value !== undefined && nextIntent(value) !== "none");
752
+ if (!nextIsFinal || (command !== undefined && nextIntent(command) === "none") || (command === undefined && nextBulletCommand === undefined)) {
753
+ return null;
754
+ }
755
+ if (!lines.some((line) => /^PR #\d+\s+[—-]\s+\S+/i.test(line.trim())))
756
+ return null;
757
+ if (!lines.some((line) => /^URL:\s*https?:\/\/\S+$/i.test(line.trim())))
758
+ return null;
759
+ if (!lines.some((line) => /^Base:\s*\S+\s+←\s+Head:\s*\S+\s+@\s+\S+\s+CI:\s*(green|failing|pending)\s*$/i.test(line.trim())))
760
+ return null;
761
+ const verdicts = lines
762
+ .slice(0, nextIndex)
763
+ .map((line) => /^VERDICT:\s*(MERGE-READY|BLOCKED\s*\((\d+)\s+blockers?\))\s*$/i.exec(line.trim()))
764
+ .filter((value) => value !== null);
765
+ if (verdicts.length !== 1)
766
+ return null;
767
+ const verdict = verdicts[0]?.[1]?.toUpperCase();
768
+ if (verdict === undefined)
769
+ return null;
770
+ const blockers = [];
771
+ for (const match of auditBody.matchAll(/^\s*\d+\.\s*\[([^\]\n]+)\]\s+([^—\n]+?)\s+[—-]\s+(.+?)(?:\s+→|\s*$)/gim)) {
772
+ const label = match[1]?.trim();
773
+ const reportedKind = label?.toLowerCase();
774
+ const kind = isBlockerKind(reportedKind) ? reportedKind : "gate";
775
+ const id = isBlockerKind(reportedKind) ? match[2]?.trim() : label;
776
+ const detail = isBlockerKind(reportedKind)
777
+ ? match[3]?.trim()
778
+ : `${match[2]?.trim()} — ${match[3]?.trim()}`;
779
+ if (id !== undefined && detail !== undefined) {
780
+ blockers.push({ kind, id, scope: "unit", detail });
781
+ }
782
+ }
783
+ const status = verdict.startsWith("MERGE-READY") ? "completed" : "blocked";
784
+ const expectedBlockers = Number(verdicts[0]?.[2]);
785
+ if (status === "blocked" && (!/^Blockers \(ranked\):$/im.test(auditBody) || blockers.length !== expectedBlockers)) {
786
+ return {
787
+ ok: false,
788
+ errors: ["audit-pr BLOCKED verdict has no complete deterministic blocker rows"],
789
+ diagnostics: [],
790
+ };
791
+ }
792
+ if (status === "completed" && !lines.some((line) => /^Nothing blocks merge\.$/i.test(line.trim())))
793
+ return null;
794
+ const rawBlockerRoute = /→\s*fix:?\s*[^\n(]*\((\/[-a-z]+(?:\s+[^\n)]*)?)\)/i.exec(auditBody)?.[1]?.trim();
795
+ const blockerRoute = rawBlockerRoute !== undefined && nextIntent(rawBlockerRoute) !== "none" ? rawBlockerRoute : undefined;
796
+ const nextCommand = status === "blocked" ? blockerRoute ?? command ?? nextBulletCommand : "/merge";
797
+ if (nextCommand === undefined)
798
+ return null;
799
+ return nativeOutcome(skill, status, `audit-pr returned ${verdict}.`, nextCommand, blockers);
800
+ }
801
+ return null;
802
+ }
803
+ function nativeOutcome(skill, status, summary, command, blockers) {
804
+ return {
805
+ ok: true,
806
+ source: "native",
807
+ envelope: null,
808
+ diagnostics: [],
809
+ outcome: {
810
+ contract: "agentic-workflow/skill-outcome",
811
+ version: 1,
812
+ skill,
813
+ status,
814
+ summary,
815
+ next: { intent: nextIntent(command), targets: [] },
816
+ blockers,
817
+ questions: [],
818
+ discoveries: [],
819
+ evidence_refs: [],
820
+ },
821
+ };
822
+ }
823
+ /**
824
+ * Parses a machine result in strict precedence order. Compatibility mappings
825
+ * are intentionally small and named; arbitrary prose is never promoted into
826
+ * a workflow fact.
827
+ */
828
+ export function parseTurn(input) {
829
+ const profile = workflowSkillProfile(input.skill);
830
+ if (profile === undefined) {
831
+ return {
832
+ ok: false,
833
+ errors: [`unknown workflow skill: ${input.skill}`],
834
+ diagnostics: [],
835
+ };
836
+ }
837
+ const parsed = parseLastJson(input.text);
838
+ if (parsed.ok) {
839
+ const outcome = validateSkillOutcomeV1(parsed.value);
840
+ if (outcome.ok) {
841
+ if (profile.output !== "skill-outcome-v1") {
842
+ return {
843
+ ok: false,
844
+ errors: [`${input.skill} requires an envelope-v2 result`],
845
+ diagnostics: [],
846
+ };
847
+ }
848
+ if (outcome.outcome.skill !== input.skill) {
849
+ return { ok: false, errors: [`expected skill ${input.skill}, received ${outcome.outcome.skill}`], diagnostics: [] };
850
+ }
851
+ return { ok: true, source: "skill-outcome-v1", outcome: outcome.outcome, envelope: null, diagnostics: [] };
852
+ }
853
+ const strict = validateEnvelopeV2Strict(parsed.value);
854
+ if (strict.ok) {
855
+ if (strict.envelope.skill !== input.skill) {
856
+ return { ok: false, errors: [`expected skill ${input.skill}, received ${strict.envelope.skill}`], diagnostics: [] };
857
+ }
858
+ return {
859
+ ok: true,
860
+ source: "envelope-v2-strict",
861
+ outcome: outcomeFromEnvelope(strict.envelope),
862
+ envelope: strict.envelope,
863
+ diagnostics: [],
864
+ };
865
+ }
866
+ const compatibility = normalizeCompatibilityEnvelope(parsed.value, input.skill, input.context);
867
+ if (compatibility.ok) {
868
+ const compatible = validateEnvelopeV2Strict(compatibility.envelope);
869
+ if (compatible.ok) {
870
+ if (compatible.envelope.skill !== input.skill) {
871
+ return { ok: false, errors: [`expected skill ${input.skill}, received ${compatible.envelope.skill}`], diagnostics: compatibility.diagnostics };
872
+ }
873
+ return {
874
+ ok: true,
875
+ source: "envelope-v2-compat",
876
+ outcome: outcomeFromEnvelope(compatible.envelope),
877
+ envelope: compatible.envelope,
878
+ diagnostics: compatibility.diagnostics,
879
+ };
880
+ }
881
+ return { ok: false, errors: compatible.errors, diagnostics: compatibility.diagnostics };
882
+ }
883
+ return compatibility;
884
+ }
885
+ const native = parseNativeTurn(input.skill, input.text);
886
+ if (native !== null)
887
+ return native;
888
+ return { ok: false, errors: ["no deterministic workflow result found"], diagnostics: [] };
889
+ }
890
+ /** Returns the smallest driver instruction appropriate for the selected skill. */
891
+ export function renderOutputInstruction(skill) {
892
+ const profile = workflowSkillProfile(skill);
893
+ if (profile === undefined)
894
+ throw new Error(`unknown workflow skill: ${skill}`);
895
+ if (profile.output === "envelope-v2") {
896
+ return [
897
+ "Return exactly one final fenced JSON machine envelope matching agentic-workflow/envelope@2.",
898
+ "detail is required; unit.id is a string or null; findings.issues_filed is an array of integers;",
899
+ "blockers[] items are {kind, id, scope, detail}. Emit nothing after it.",
900
+ ].join(" ");
901
+ }
902
+ return [
903
+ "Return exactly one final fenced JSON object matching agentic-workflow/skill-outcome version 1.",
904
+ `Set skill to ${JSON.stringify(skill)}.`,
905
+ "Required keys: contract, version, skill, status, summary, next, blockers, questions, discoveries, evidence_refs.",
906
+ "next is {intent, targets}; blockers[] items are {kind, id, scope, detail};",
907
+ "questions[] items are {id, question, options}; discoveries[] items are {kind, scope, summary, evidence_refs, proposed_intent}.",
908
+ "Use only a known workflow intent. Emit nothing after the JSON object.",
909
+ ].join(" ");
910
+ }
911
+ function lineNumber(content, needle) {
912
+ const index = content.indexOf(needle);
913
+ return index < 0 ? 1 : content.slice(0, index).split("\n").length;
914
+ }
915
+ function documentFor(documents, suffix) {
916
+ return documents.find((document) => document.path.endsWith(suffix));
917
+ }
918
+ function repositoryStateFrom(document) {
919
+ if (document === undefined)
920
+ return "missing";
921
+ const value = /(?:^|\n)Status:\s*([^\n\r]+)/i.exec(document.content)?.[1]?.trim().toLowerCase();
922
+ if (value === "draft" || value === "frozen" || value === "contradicted" || value === "needs-input")
923
+ return value;
924
+ return "unknown";
925
+ }
926
+ function roadmapFeature(document) {
927
+ if (document === undefined)
928
+ return null;
929
+ const candidates = [];
930
+ for (const row of document.content.split("\n")) {
931
+ const cells = row.split("|").map((cell) => cell.trim()).filter(Boolean);
932
+ if (cells.length < 3 || !/^\d{2}$/.test(cells[0] ?? ""))
933
+ continue;
934
+ const slug = cells[1]?.replace(/^`|`$/g, "");
935
+ if (slug === undefined || slug.length === 0)
936
+ continue;
937
+ const id = `${cells[0]}-${slug}`;
938
+ candidates.push({ id, status: cells[2] ?? "unknown", row });
939
+ }
940
+ return candidates.find((candidate) => indexStatus(candidate.status) === "in-progress")
941
+ ?? candidates.find((candidate) => indexStatus(candidate.status) !== "done")
942
+ ?? null;
943
+ }
944
+ function indexStatus(value) {
945
+ return value.split("·", 1)[0]?.trim().toLowerCase() ?? "unknown";
946
+ }
947
+ function fixUnit(document) {
948
+ if (document === undefined)
949
+ return null;
950
+ const candidates = [];
951
+ for (const row of document.content.split("\n")) {
952
+ const cells = row.split("|").map((cell) => cell.trim()).filter(Boolean);
953
+ if (cells.length < 3)
954
+ continue;
955
+ const id = cells[0]?.replace(/^`|`$/g, "") ?? "";
956
+ if (!/^\d+-[A-Za-z0-9._-]+$/.test(id))
957
+ continue;
958
+ candidates.push({ id, status: cells[2] ?? "unknown", row });
959
+ }
960
+ return candidates.find((candidate) => indexStatus(candidate.status) === "in-progress")
961
+ ?? candidates.find((candidate) => indexStatus(candidate.status) !== "done")
962
+ ?? null;
963
+ }
964
+ function phasesFrom(spec) {
965
+ if (spec === undefined)
966
+ return [];
967
+ const phases = [];
968
+ for (const line of spec.content.split("\n")) {
969
+ const match = /^#{2,4}\s+(P\d+)\s+[—-]\s+(.+?)\s*$/.exec(line);
970
+ if (match?.[1] && match[2])
971
+ phases.push({ id: match[1], name: `${match[1]} — ${match[2]}`, line });
972
+ }
973
+ return phases;
974
+ }
975
+ /** Validates the strict, deterministic WorkflowSnapshot v1 JSON contract. */
976
+ export function validateWorkflowSnapshotV1(value) {
977
+ if (!isObj(value))
978
+ return { ok: false, errors: ["workflow snapshot is not a JSON object"] };
979
+ const errors = [];
980
+ const required = [
981
+ "contract",
982
+ "version",
983
+ "sourceRevision",
984
+ "repository",
985
+ "repositoryState",
986
+ "unit",
987
+ "phase",
988
+ "provenance",
989
+ "contradictions",
990
+ "unknowns",
991
+ ];
992
+ for (const key of required)
993
+ if (!(key in value))
994
+ errors.push(`missing required key: ${key}`);
995
+ const allowed = new Set(required);
996
+ for (const key of Object.keys(value))
997
+ if (!allowed.has(key))
998
+ errors.push(`unexpected top-level key: ${key}`);
999
+ if (value.contract !== "agentic-workflow/workflow-snapshot") {
1000
+ errors.push("contract must be agentic-workflow/workflow-snapshot");
1001
+ }
1002
+ if (value.version !== 1)
1003
+ errors.push("version must be 1");
1004
+ if (typeof value.sourceRevision !== "string" || value.sourceRevision.length === 0) {
1005
+ errors.push("sourceRevision must be a non-empty string");
1006
+ }
1007
+ if (!isObj(value.repository)) {
1008
+ errors.push("repository must be an object");
1009
+ }
1010
+ else {
1011
+ rejectUnexpectedKeys(value.repository, "repository", ["branch", "headSha", "dirty"], errors);
1012
+ if (typeof value.repository.branch !== "string")
1013
+ errors.push("repository.branch must be a string");
1014
+ if (typeof value.repository.headSha !== "string")
1015
+ errors.push("repository.headSha must be a string");
1016
+ if (typeof value.repository.dirty !== "boolean")
1017
+ errors.push("repository.dirty must be a boolean");
1018
+ }
1019
+ const repositoryStates = ["missing", "draft", "frozen", "contradicted", "needs-input", "unknown"];
1020
+ if (!repositoryStates.includes(value.repositoryState))
1021
+ errors.push("repositoryState is invalid");
1022
+ if (value.unit !== null) {
1023
+ if (!isObj(value.unit)) {
1024
+ errors.push("unit must be an object or null");
1025
+ }
1026
+ else {
1027
+ rejectUnexpectedKeys(value.unit, "unit", ["kind", "id", "status"], errors);
1028
+ if (value.unit.kind !== "feature" && value.unit.kind !== "fix")
1029
+ errors.push("unit.kind must be feature|fix");
1030
+ if (typeof value.unit.id !== "string")
1031
+ errors.push("unit.id must be a string");
1032
+ if (typeof value.unit.status !== "string")
1033
+ errors.push("unit.status must be a string");
1034
+ }
1035
+ }
1036
+ if (!isObj(value.phase)) {
1037
+ errors.push("phase must be an object");
1038
+ }
1039
+ else {
1040
+ rejectUnexpectedKeys(value.phase, "phase", ["current", "total", "completed", "names"], errors);
1041
+ if (!isStringOrNull(value.phase.current))
1042
+ errors.push("phase.current must be a string or null");
1043
+ if (!isIntOrNull(value.phase.total))
1044
+ errors.push("phase.total must be an integer or null");
1045
+ if (!isIntOrNull(value.phase.completed))
1046
+ errors.push("phase.completed must be an integer or null");
1047
+ if (!isStringArray(value.phase.names))
1048
+ errors.push("phase.names must be an array of strings");
1049
+ }
1050
+ const validateEntries = (raw, field, keys, check) => {
1051
+ if (!Array.isArray(raw)) {
1052
+ errors.push(`${field} must be an array`);
1053
+ return;
1054
+ }
1055
+ raw.forEach((entry, index) => {
1056
+ if (!isObj(entry)) {
1057
+ errors.push(`${field}[${index}] must be an object`);
1058
+ return;
1059
+ }
1060
+ rejectUnexpectedKeys(entry, `${field}[${index}]`, keys, errors);
1061
+ check(entry, index);
1062
+ });
1063
+ };
1064
+ validateEntries(value.provenance, "provenance", ["field", "source", "line"], (entry, index) => {
1065
+ if (typeof entry.field !== "string")
1066
+ errors.push(`provenance[${index}].field must be a string`);
1067
+ if (typeof entry.source !== "string")
1068
+ errors.push(`provenance[${index}].source must be a string`);
1069
+ if (typeof entry.line !== "number" || !Number.isInteger(entry.line) || entry.line < 1) {
1070
+ errors.push(`provenance[${index}].line must be a positive integer`);
1071
+ }
1072
+ });
1073
+ validateEntries(value.contradictions, "contradictions", ["field", "source", "line", "detail"], (entry, index) => {
1074
+ if (typeof entry.field !== "string")
1075
+ errors.push(`contradictions[${index}].field must be a string`);
1076
+ if (typeof entry.source !== "string")
1077
+ errors.push(`contradictions[${index}].source must be a string`);
1078
+ if (typeof entry.line !== "number" || !Number.isInteger(entry.line) || entry.line < 1) {
1079
+ errors.push(`contradictions[${index}].line must be a positive integer`);
1080
+ }
1081
+ if (typeof entry.detail !== "string")
1082
+ errors.push(`contradictions[${index}].detail must be a string`);
1083
+ });
1084
+ validateEntries(value.unknowns, "unknowns", ["field", "reason"], (entry, index) => {
1085
+ if (typeof entry.field !== "string")
1086
+ errors.push(`unknowns[${index}].field must be a string`);
1087
+ if (typeof entry.reason !== "string")
1088
+ errors.push(`unknowns[${index}].reason must be a string`);
1089
+ });
1090
+ return errors.length === 0
1091
+ ? { ok: true, snapshot: value }
1092
+ : { ok: false, errors };
1093
+ }
1094
+ /**
1095
+ * Compiles only facts represented by the versioned workflow documents passed
1096
+ * in by the caller. It performs no filesystem or Git I/O and records source
1097
+ * locations for every value it derives.
1098
+ */
1099
+ export function compileWorkflowSnapshot(input) {
1100
+ const repositoryStateDocument = documentFor(input.documents, "docs/workflow/REPOSITORY_STATE.md");
1101
+ const roadmapDocument = documentFor(input.documents, "docs/features/ROADMAP.md");
1102
+ const feature = roadmapFeature(roadmapDocument);
1103
+ const fixIndexDocument = documentFor(input.documents, "docs/fix/README.md");
1104
+ const fix = feature === null ? fixUnit(fixIndexDocument) : null;
1105
+ const selected = feature ?? fix;
1106
+ const selectedKind = feature === null && fix !== null ? "fix" : "feature";
1107
+ const provenance = [];
1108
+ const contradictions = [];
1109
+ const unknowns = [];
1110
+ const repositoryState = repositoryStateFrom(repositoryStateDocument);
1111
+ if (repositoryStateDocument !== undefined) {
1112
+ provenance.push({
1113
+ field: "repositoryState",
1114
+ source: repositoryStateDocument.path,
1115
+ line: lineNumber(repositoryStateDocument.content, "Status:"),
1116
+ });
1117
+ if (repositoryState === "unknown") {
1118
+ unknowns.push({ field: "repositoryState", reason: "REPOSITORY_STATE.md does not declare a recognized status." });
1119
+ }
1120
+ }
1121
+ else {
1122
+ unknowns.push({ field: "repositoryState", reason: "REPOSITORY_STATE.md is absent." });
1123
+ }
1124
+ if (repositoryState === "contradicted" && repositoryStateDocument !== undefined) {
1125
+ contradictions.push({
1126
+ field: "repositoryState",
1127
+ source: repositoryStateDocument.path,
1128
+ line: lineNumber(repositoryStateDocument.content, "Status:"),
1129
+ detail: "REPOSITORY_STATE.md declares the repository state contradicted.",
1130
+ });
1131
+ }
1132
+ if (selected === null) {
1133
+ unknowns.push({ field: "unit", reason: "No feature row could be read from ROADMAP.md." });
1134
+ }
1135
+ else if (selectedKind === "feature" && roadmapDocument !== undefined) {
1136
+ provenance.push({ field: "unit", source: roadmapDocument.path, line: lineNumber(roadmapDocument.content, selected.row) });
1137
+ }
1138
+ else if (selectedKind === "fix" && fixIndexDocument !== undefined) {
1139
+ provenance.push({ field: "unit", source: fixIndexDocument.path, line: lineNumber(fixIndexDocument.content, selected.row) });
1140
+ }
1141
+ const spec = selected === null
1142
+ ? undefined
1143
+ : documentFor(input.documents, selectedKind === "feature"
1144
+ ? `docs/features/${selected.id}/SPEC.md`
1145
+ : `docs/fix/${selected.id}/SPEC.md`);
1146
+ const phases = phasesFrom(spec);
1147
+ const hasPhaseDefinitions = spec !== undefined && phases.length > 0;
1148
+ const phaseDefinitionReason = spec === undefined
1149
+ ? "The active unit SPEC.md is absent."
1150
+ : "The active unit SPEC.md has no recognized phase headings.";
1151
+ if (selected !== null && !hasPhaseDefinitions) {
1152
+ unknowns.push({ field: "phase.names", reason: phaseDefinitionReason });
1153
+ unknowns.push({ field: "phase.total", reason: phaseDefinitionReason });
1154
+ }
1155
+ const progress = selected === null
1156
+ ? undefined
1157
+ : documentFor(input.documents, selectedKind === "feature"
1158
+ ? `docs/features/${selected.id}/progress.md`
1159
+ : `docs/fix/${selected.id}/progress.md`);
1160
+ const phaseIds = new Set(phases.map((phase) => phase.id));
1161
+ const completedIds = new Set();
1162
+ const unknownCompletedIds = new Set();
1163
+ const doneReceiptLines = [];
1164
+ if (progress !== undefined) {
1165
+ for (const match of progress.content.matchAll(/(?:^|\n)-\s*Done:\s*(P\d+)\b/g)) {
1166
+ if (match[1] && phaseIds.has(match[1]))
1167
+ completedIds.add(match[1]);
1168
+ if (match[1] && !phaseIds.has(match[1]))
1169
+ unknownCompletedIds.add(match[1]);
1170
+ if (match[1])
1171
+ doneReceiptLines.push(match[1]);
1172
+ }
1173
+ }
1174
+ const remains = progress === undefined ? undefined : /(?:^|\n)-\s*Remains:\s*(P\d+)\b/.exec(progress.content)?.[1];
1175
+ const current = remains !== undefined && phaseIds.has(remains) ? remains : null;
1176
+ if (selected !== null && !hasPhaseDefinitions) {
1177
+ unknowns.push({ field: "phase.current", reason: phaseDefinitionReason });
1178
+ }
1179
+ else if (remains !== undefined && !phaseIds.has(remains)) {
1180
+ unknowns.push({ field: "phase.current", reason: `Progress names unknown phase ${remains}.` });
1181
+ }
1182
+ else if (current !== null && progress !== undefined) {
1183
+ provenance.push({ field: "phase.current", source: progress.path, line: lineNumber(progress.content, `Remains: ${current}`) });
1184
+ }
1185
+ else if (phases.length > 0) {
1186
+ unknowns.push({ field: "phase.current", reason: "No explicit remaining phase receipt was found." });
1187
+ }
1188
+ if (hasPhaseDefinitions && spec !== undefined) {
1189
+ const specLine = lineNumber(spec.content, phases[0]?.line ?? "");
1190
+ provenance.push({ field: "phase.names", source: spec.path, line: specLine });
1191
+ provenance.push({ field: "phase.total", source: spec.path, line: specLine });
1192
+ }
1193
+ let completed = null;
1194
+ if (selected !== null && !hasPhaseDefinitions) {
1195
+ unknowns.push({ field: "phase.completed", reason: phaseDefinitionReason });
1196
+ }
1197
+ else if (progress !== undefined && doneReceiptLines.length > 0 && unknownCompletedIds.size === 0) {
1198
+ completed = completedIds.size;
1199
+ provenance.push({
1200
+ field: "phase.completed",
1201
+ source: progress.path,
1202
+ line: lineNumber(progress.content, `Done: ${doneReceiptLines[0]}`),
1203
+ });
1204
+ }
1205
+ else if (phases.length > 0) {
1206
+ const reason = unknownCompletedIds.size > 0
1207
+ ? `Progress names unknown completed phase(s): ${[...unknownCompletedIds].join(", ")}.`
1208
+ : "No explicit completed phase receipt was found.";
1209
+ unknowns.push({ field: "phase.completed", reason });
1210
+ }
1211
+ const snapshot = {
1212
+ contract: "agentic-workflow/workflow-snapshot",
1213
+ version: 1,
1214
+ sourceRevision: input.sourceRevision,
1215
+ repository: input.repository,
1216
+ repositoryState,
1217
+ unit: selected === null ? null : { kind: selectedKind, id: selected.id, status: selected.status },
1218
+ phase: {
1219
+ current,
1220
+ total: phases.length === 0 ? null : phases.length,
1221
+ completed,
1222
+ names: phases.map((phase) => phase.name),
1223
+ },
1224
+ provenance,
1225
+ contradictions,
1226
+ unknowns,
1227
+ };
1228
+ const validation = validateWorkflowSnapshotV1(snapshot);
1229
+ return validation.ok
1230
+ ? { ok: true, snapshot: validation.snapshot }
1231
+ : { ok: false, errors: validation.errors };
1232
+ }