@gtrabanco/agentic-workflow-schema 3.1.0 → 3.3.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/README.es.md +72 -0
- package/README.md +68 -0
- package/candidate-snapshot.schema.json +129 -0
- package/dist/index.d.ts +247 -0
- package/dist/index.js +976 -0
- package/package.json +7 -2
- package/review-receipt.schema.json +130 -0
package/dist/index.js
CHANGED
|
@@ -445,6 +445,408 @@ export const WORKFLOW_INTENTS = [
|
|
|
445
445
|
"none",
|
|
446
446
|
];
|
|
447
447
|
// ---------------------------------------------------------------------------
|
|
448
|
+
// Workflow transition decider — reason codes, decision types, transition table
|
|
449
|
+
// ---------------------------------------------------------------------------
|
|
450
|
+
/** Sense reason codes: transition cannot proceed without more sensor input. */
|
|
451
|
+
export const WORKFLOW_DECISION_SENSE_CODES = Object.freeze([
|
|
452
|
+
"sense-initial",
|
|
453
|
+
"sense-stale-revision",
|
|
454
|
+
"sense-missing-evidence",
|
|
455
|
+
"sense-unknown-state",
|
|
456
|
+
"sense-unlisted-transition",
|
|
457
|
+
]);
|
|
458
|
+
/** Stop reason codes: the transition is explicitly blocked or must terminate. */
|
|
459
|
+
export const WORKFLOW_DECISION_STOP_CODES = Object.freeze([
|
|
460
|
+
"stop-blocked",
|
|
461
|
+
"stop-needs-input",
|
|
462
|
+
"stop-failed",
|
|
463
|
+
"stop-contradiction",
|
|
464
|
+
"stop-policy-denied",
|
|
465
|
+
"stop-forbidden-transition",
|
|
466
|
+
]);
|
|
467
|
+
/** Invoke reason codes: transition is proven and allowed. */
|
|
468
|
+
export const WORKFLOW_DECISION_INVOKE_CODES = Object.freeze([
|
|
469
|
+
"invoke-proven-transition",
|
|
470
|
+
]);
|
|
471
|
+
/**
|
|
472
|
+
* Frozen, versioned direct-invocation transition table.
|
|
473
|
+
*
|
|
474
|
+
* Maps each last-validated skill to its allowed next intents. Rows whose
|
|
475
|
+
* `allowed` array contains a literal "frozen" permit transitions only when
|
|
476
|
+
* the snapshot repository state is "frozen"; rows with an empty array
|
|
477
|
+
* explicitly forbid any transition (return sense/stop rather than invoke).
|
|
478
|
+
*
|
|
479
|
+
* Derived condition semantics (from the Design):
|
|
480
|
+
* none → sense-initial
|
|
481
|
+
* init-workspace → exactly discover-repository-state
|
|
482
|
+
* workflow-status → broad set of planning/execution skills
|
|
483
|
+
* discover-repository-state → row allowed iff snapshot.state === "frozen"
|
|
484
|
+
* resolve-repository-state → row allowed iff snapshot.contradictions.length > 0
|
|
485
|
+
* design-feature, plan-feature → 0..n allowed, each must be a plan/execute skill
|
|
486
|
+
* plan-fix → exactly 1, must be triage-issue
|
|
487
|
+
* triage-issue → 1..n allowed, each must be an issue identity string
|
|
488
|
+
* init-workspace, discover-repository-state → 0 allowed → stop-forbidden-transition
|
|
489
|
+
* resolve-repository-state → each allowed must match a contradiction field
|
|
490
|
+
* merge → exactly 1, must be the PR identity from audit-pr
|
|
491
|
+
*/
|
|
492
|
+
export const WORKFLOW_TRANSITION_TABLE = Object.freeze([
|
|
493
|
+
// Last skill = none → no transition possible
|
|
494
|
+
{
|
|
495
|
+
key: "none",
|
|
496
|
+
allowed: [],
|
|
497
|
+
condition: "no last validated skill; return sense-initial",
|
|
498
|
+
},
|
|
499
|
+
// init-workspace → discover-repository-state only
|
|
500
|
+
{
|
|
501
|
+
key: "init-workspace",
|
|
502
|
+
allowed: ["discover-repository-state"],
|
|
503
|
+
condition: "exactly 1 target; any other target → stop-forbidden-transition",
|
|
504
|
+
},
|
|
505
|
+
// status → broad planning and execution set
|
|
506
|
+
{
|
|
507
|
+
key: "status",
|
|
508
|
+
allowed: [
|
|
509
|
+
"init-workspace",
|
|
510
|
+
"discover-repository-state",
|
|
511
|
+
"resolve-repository-state",
|
|
512
|
+
"design-feature",
|
|
513
|
+
"plan-feature",
|
|
514
|
+
"plan-fix",
|
|
515
|
+
"triage-issue",
|
|
516
|
+
"execute-phase",
|
|
517
|
+
"review-change",
|
|
518
|
+
"loop-review-fold",
|
|
519
|
+
"audit-pr",
|
|
520
|
+
"ask-human",
|
|
521
|
+
"stop",
|
|
522
|
+
],
|
|
523
|
+
condition: "all allowed intents after status",
|
|
524
|
+
},
|
|
525
|
+
// discover-repository-state → planning allowed only when repo is frozen
|
|
526
|
+
{
|
|
527
|
+
key: "discover-repository-state",
|
|
528
|
+
allowed: [
|
|
529
|
+
"resolve-repository-state",
|
|
530
|
+
"design-feature",
|
|
531
|
+
"plan-feature",
|
|
532
|
+
"plan-fix",
|
|
533
|
+
"triage-issue",
|
|
534
|
+
"execute-phase",
|
|
535
|
+
"review-change",
|
|
536
|
+
"loop-review-fold",
|
|
537
|
+
"audit-pr",
|
|
538
|
+
"ask-human",
|
|
539
|
+
"stop",
|
|
540
|
+
],
|
|
541
|
+
condition: "row allowed only when snapshot.repositoryState === 'frozen';"
|
|
542
|
+
+ " any target when state is not frozen → sense-missing-evidence",
|
|
543
|
+
},
|
|
544
|
+
// resolve-repository-state → contradiction targets only
|
|
545
|
+
{
|
|
546
|
+
key: "resolve-repository-state",
|
|
547
|
+
allowed: ["resolve-repository-state"],
|
|
548
|
+
condition: "0..n allowed, each === a snapshot contradiction field identity;"
|
|
549
|
+
+ " non-contradiction target → stop-forbidden-transition",
|
|
550
|
+
},
|
|
551
|
+
// design-feature → next roadmap unit or the active unit / named dependency
|
|
552
|
+
{
|
|
553
|
+
key: "design-feature",
|
|
554
|
+
allowed: [
|
|
555
|
+
"plan-feature",
|
|
556
|
+
"plan-fix",
|
|
557
|
+
"triage-issue",
|
|
558
|
+
"execute-phase",
|
|
559
|
+
"review-change",
|
|
560
|
+
"loop-review-fold",
|
|
561
|
+
"audit-pr",
|
|
562
|
+
"ask-human",
|
|
563
|
+
"stop",
|
|
564
|
+
],
|
|
565
|
+
condition: "0..n allowed, each must be the next roadmap unit, the active unit id,"
|
|
566
|
+
+ " or the named dependency unit recorded by the last outcome;"
|
|
567
|
+
+ " non-allowed target → stop-forbidden-transition",
|
|
568
|
+
},
|
|
569
|
+
// plan-feature → active or dependency unit, max 1
|
|
570
|
+
{
|
|
571
|
+
key: "plan-feature",
|
|
572
|
+
allowed: [
|
|
573
|
+
"triage-issue",
|
|
574
|
+
"execute-phase",
|
|
575
|
+
"review-change",
|
|
576
|
+
"loop-review-fold",
|
|
577
|
+
"audit-pr",
|
|
578
|
+
"ask-human",
|
|
579
|
+
"stop",
|
|
580
|
+
],
|
|
581
|
+
condition: "0..1 allowed; 0 → next roadmap unit; 1 → active unit id or named dependency;"
|
|
582
|
+
+ ">1 → stop-forbidden-transition",
|
|
583
|
+
},
|
|
584
|
+
// plan-fix → triage-issue only, exactly 1
|
|
585
|
+
{
|
|
586
|
+
key: "plan-fix",
|
|
587
|
+
allowed: ["triage-issue"],
|
|
588
|
+
condition: "exactly 1 target (the issue identity); 0 → sense-missing-evidence;"
|
|
589
|
+
+ ">1 → stop-forbidden-transition",
|
|
590
|
+
},
|
|
591
|
+
// triage-issue → issue identities, 1..n
|
|
592
|
+
{
|
|
593
|
+
key: "triage-issue",
|
|
594
|
+
allowed: [
|
|
595
|
+
"execute-phase",
|
|
596
|
+
"review-change",
|
|
597
|
+
"loop-review-fold",
|
|
598
|
+
"audit-pr",
|
|
599
|
+
"ask-human",
|
|
600
|
+
"stop",
|
|
601
|
+
],
|
|
602
|
+
condition: "1..n allowed, each must be an issue identity recorded by the last outcome;"
|
|
603
|
+
+ " 0 → sense-missing-evidence",
|
|
604
|
+
},
|
|
605
|
+
// execute-phase → planning and execution, max 1
|
|
606
|
+
{
|
|
607
|
+
key: "execute-phase",
|
|
608
|
+
allowed: [
|
|
609
|
+
"design-feature",
|
|
610
|
+
"plan-feature",
|
|
611
|
+
"plan-fix",
|
|
612
|
+
"triage-issue",
|
|
613
|
+
"review-change",
|
|
614
|
+
"loop-review-fold",
|
|
615
|
+
"audit-pr",
|
|
616
|
+
"ask-human",
|
|
617
|
+
"stop",
|
|
618
|
+
],
|
|
619
|
+
condition: "0..1 allowed; each must be a plan/execute skill or ask-human/stop;"
|
|
620
|
+
+ ">1 → stop-forbidden-transition",
|
|
621
|
+
},
|
|
622
|
+
// review-change → planning and execution
|
|
623
|
+
{
|
|
624
|
+
key: "review-change",
|
|
625
|
+
allowed: [
|
|
626
|
+
"plan-feature",
|
|
627
|
+
"plan-fix",
|
|
628
|
+
"triage-issue",
|
|
629
|
+
"execute-phase",
|
|
630
|
+
"review-change",
|
|
631
|
+
"loop-review-fold",
|
|
632
|
+
"audit-pr",
|
|
633
|
+
"ask-human",
|
|
634
|
+
"stop",
|
|
635
|
+
],
|
|
636
|
+
condition: "0..n allowed, each must be a plan/execute/review skill or ask-human/stop;"
|
|
637
|
+
+ " non-allowed target → stop-forbidden-transition",
|
|
638
|
+
},
|
|
639
|
+
// loop-review-fold → planning and execution
|
|
640
|
+
{
|
|
641
|
+
key: "loop-review-fold",
|
|
642
|
+
allowed: [
|
|
643
|
+
"plan-feature",
|
|
644
|
+
"plan-fix",
|
|
645
|
+
"triage-issue",
|
|
646
|
+
"execute-phase",
|
|
647
|
+
"review-change",
|
|
648
|
+
"loop-review-fold",
|
|
649
|
+
"audit-pr",
|
|
650
|
+
"ask-human",
|
|
651
|
+
"stop",
|
|
652
|
+
],
|
|
653
|
+
condition: "0..n allowed, each must be a plan/execute/review skill or ask-human/stop;"
|
|
654
|
+
+ " non-allowed target → stop-forbidden-transition",
|
|
655
|
+
},
|
|
656
|
+
// audit-pr → merge, execute-phase, or stop
|
|
657
|
+
{
|
|
658
|
+
key: "audit-pr",
|
|
659
|
+
allowed: ["merge", "execute-phase", "ask-human", "stop"],
|
|
660
|
+
condition: "exactly 1 allowed: merge, execute-phase, ask-human, or stop;"
|
|
661
|
+
+ ">1 → stop-forbidden-transition",
|
|
662
|
+
},
|
|
663
|
+
// merge → none (end of pipeline)
|
|
664
|
+
{
|
|
665
|
+
key: "merge",
|
|
666
|
+
allowed: [],
|
|
667
|
+
condition: "merge is the terminal action; no allowed transitions;"
|
|
668
|
+
+ " any target → stop-forbidden-transition",
|
|
669
|
+
},
|
|
670
|
+
]);
|
|
671
|
+
// ---------------------------------------------------------------------------
|
|
672
|
+
// Workflow transition decider — decideWorkflowAction pipeline
|
|
673
|
+
// ---------------------------------------------------------------------------
|
|
674
|
+
/** Build evidence refs from snapshot provenance and contradictions. */
|
|
675
|
+
function buildEvidenceRefs(snapshot, lastOutcome) {
|
|
676
|
+
const refs = [];
|
|
677
|
+
for (const p of snapshot.provenance) {
|
|
678
|
+
refs.push(`${p.field}@${p.source}:${p.line}`);
|
|
679
|
+
}
|
|
680
|
+
for (const c of snapshot.contradictions) {
|
|
681
|
+
refs.push(`contradiction:${c.field}`);
|
|
682
|
+
}
|
|
683
|
+
if (lastOutcome && lastOutcome.evidence_refs.length > 0) {
|
|
684
|
+
refs.push(...lastOutcome.evidence_refs);
|
|
685
|
+
}
|
|
686
|
+
return refs;
|
|
687
|
+
}
|
|
688
|
+
/** Check effect authorization: the target skill must declare at least one effect.
|
|
689
|
+
* Built-in terminal actions without a capability profile are allowed.
|
|
690
|
+
*/
|
|
691
|
+
function checkEffectAuth(intent) {
|
|
692
|
+
const profile = workflowSkillProfile(intent);
|
|
693
|
+
if (profile === undefined)
|
|
694
|
+
return true; // no profile → allowed (built-in terminal)
|
|
695
|
+
return profile.capabilities !== undefined && profile.capabilities.effects.length > 0;
|
|
696
|
+
}
|
|
697
|
+
/** Check evidence authorization: all required evidence must be present.
|
|
698
|
+
* Intents without a capability profile are allowed (no required evidence).
|
|
699
|
+
*/
|
|
700
|
+
function checkEvidenceAuth(intent, evidenceRefs) {
|
|
701
|
+
const profile = workflowSkillProfile(intent);
|
|
702
|
+
if (profile === undefined)
|
|
703
|
+
return true; // no profile → allowed
|
|
704
|
+
const required = profile.capabilities?.requiredEvidence;
|
|
705
|
+
if (required === undefined || required.length === 0)
|
|
706
|
+
return true;
|
|
707
|
+
for (const req of required) {
|
|
708
|
+
if (!evidenceRefs.includes(req))
|
|
709
|
+
return false;
|
|
710
|
+
}
|
|
711
|
+
return true;
|
|
712
|
+
}
|
|
713
|
+
/** Policy gate: check allowed intents and forge-write authorization. */
|
|
714
|
+
function checkPolicyGate(intent, policy) {
|
|
715
|
+
if (!policy.allowedIntents.includes(intent))
|
|
716
|
+
return false;
|
|
717
|
+
if (policy.forgeWriteAuthorized === false && intent === "merge")
|
|
718
|
+
return false;
|
|
719
|
+
return true;
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Decide whether a headless consumer may invoke the next skill, must refresh
|
|
723
|
+
* with workflow-status, or must stop.
|
|
724
|
+
*
|
|
725
|
+
* Pure, deterministic, fail-closed — no I/O, no randomness, no locale.
|
|
726
|
+
*/
|
|
727
|
+
export function decideWorkflowAction(input) {
|
|
728
|
+
// Defensive: malformed input never throws
|
|
729
|
+
if (typeof input !== "object" || input === null ||
|
|
730
|
+
!("snapshot" in input) || !("lastOutcome" in input) || !("policy" in input)) {
|
|
731
|
+
return { kind: "sense", intent: "status", targets: [], reasonCode: "sense-missing-evidence", evidenceRefs: [], detail: "malformed input" };
|
|
732
|
+
}
|
|
733
|
+
const policy = input.policy;
|
|
734
|
+
if (typeof policy !== "object" || policy === null || !("allowedIntents" in policy) || !("forgeWriteAuthorized" in policy)) {
|
|
735
|
+
return { kind: "stop", intent: "stop", targets: [], reasonCode: "stop-policy-denied", evidenceRefs: [], detail: "malformed policy" };
|
|
736
|
+
}
|
|
737
|
+
const typedPolicy = policy;
|
|
738
|
+
// Validate snapshot
|
|
739
|
+
const snapshotResult = validateWorkflowSnapshotV1(input.snapshot);
|
|
740
|
+
if (!snapshotResult.ok) {
|
|
741
|
+
return { kind: "sense", intent: "status", targets: [], reasonCode: "sense-missing-evidence", evidenceRefs: [], detail: `malformed snapshot: ${snapshotResult.errors.join(", ")}` };
|
|
742
|
+
}
|
|
743
|
+
const snapshot = snapshotResult.snapshot;
|
|
744
|
+
// Initial: no last outcome
|
|
745
|
+
if (input.lastOutcome === null) {
|
|
746
|
+
return { kind: "sense", intent: "status", targets: [], reasonCode: "sense-initial", evidenceRefs: [], detail: "no last validated outcome" };
|
|
747
|
+
}
|
|
748
|
+
// Freshness: stale revision
|
|
749
|
+
if (input.lastOutcomeSourceRevision !== null &&
|
|
750
|
+
snapshot.sourceRevision !== input.lastOutcomeSourceRevision) {
|
|
751
|
+
return { kind: "sense", intent: "status", targets: [], reasonCode: "sense-stale-revision", evidenceRefs: [], detail: `outcome from revision ${input.lastOutcomeSourceRevision} does not match current ${snapshot.sourceRevision}` };
|
|
752
|
+
}
|
|
753
|
+
// Build evidence refs
|
|
754
|
+
const evidenceRefs = buildEvidenceRefs(snapshot, input.lastOutcome);
|
|
755
|
+
// Outcome-status stop routing
|
|
756
|
+
const status = input.lastOutcome.status;
|
|
757
|
+
if (status === "blocked") {
|
|
758
|
+
return { kind: "stop", intent: "stop", targets: input.lastOutcome.blockers.map((b) => b.id), reasonCode: "stop-blocked", evidenceRefs: [], detail: "outcome blocked" };
|
|
759
|
+
}
|
|
760
|
+
if (status === "needs-input") {
|
|
761
|
+
return { kind: "stop", intent: "stop", targets: input.lastOutcome.questions.map((q) => q.id), reasonCode: "stop-needs-input", evidenceRefs: [], detail: "outcome needs input" };
|
|
762
|
+
}
|
|
763
|
+
if (status === "failed") {
|
|
764
|
+
const targets = input.lastOutcome.discoveries.length > 0
|
|
765
|
+
? input.lastOutcome.discoveries.map((d) => d.summary)
|
|
766
|
+
: [];
|
|
767
|
+
return { kind: "stop", intent: "stop", targets, reasonCode: "stop-failed", evidenceRefs: [], detail: "outcome failed" };
|
|
768
|
+
}
|
|
769
|
+
// Contradiction routing
|
|
770
|
+
if (snapshot.contradictions.length > 0) {
|
|
771
|
+
const proposal = input.lastOutcome.next.intent;
|
|
772
|
+
if (proposal === "resolve-repository-state") {
|
|
773
|
+
const contradictionFields = snapshot.contradictions.map((c) => c.field);
|
|
774
|
+
const allowedContradictionTargets = contradictionFields.length > 0
|
|
775
|
+
? ["resolve-repository-state"]
|
|
776
|
+
: [];
|
|
777
|
+
if (allowedContradictionTargets.includes(proposal)) {
|
|
778
|
+
return {
|
|
779
|
+
kind: "stop", intent: "stop", targets: contradictionFields,
|
|
780
|
+
reasonCode: "stop-contradiction",
|
|
781
|
+
evidenceRefs: snapshot.contradictions.map((c) => `contradiction:${c.field}`),
|
|
782
|
+
detail: "snapshot contradictions present",
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
// Non-matching proposal under contradiction
|
|
787
|
+
return {
|
|
788
|
+
kind: "stop", intent: "stop", targets: [],
|
|
789
|
+
reasonCode: "stop-contradiction",
|
|
790
|
+
evidenceRefs: snapshot.contradictions.map((c) => `contradiction:${c.field}`),
|
|
791
|
+
detail: "snapshot contradictions present",
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
// Recommendation → closed-table match
|
|
795
|
+
const proposal = input.lastOutcome.next.intent;
|
|
796
|
+
const targets = input.lastOutcome.next.targets || [];
|
|
797
|
+
const lastSkill = input.lastOutcome.skill;
|
|
798
|
+
const entry = WORKFLOW_TRANSITION_TABLE.find((r) => r.key === lastSkill);
|
|
799
|
+
if (entry === undefined) {
|
|
800
|
+
return { kind: "sense", intent: "status", targets: [], reasonCode: "sense-unlisted-transition", evidenceRefs: [], detail: `unlisted transition: ${lastSkill}` };
|
|
801
|
+
}
|
|
802
|
+
// Check if proposal is in the allowed list for the last skill
|
|
803
|
+
if (!entry.allowed.includes(proposal)) {
|
|
804
|
+
return { kind: "sense", intent: "status", targets: [], reasonCode: "sense-unlisted-transition", evidenceRefs: [], detail: `${proposal} not allowed after ${entry.key}` };
|
|
805
|
+
}
|
|
806
|
+
// Row condition checks
|
|
807
|
+
if (proposal === "discover-repository-state") {
|
|
808
|
+
if (snapshot.repositoryState !== "frozen") {
|
|
809
|
+
return { kind: "sense", intent: "status", targets: [], reasonCode: "sense-missing-evidence", evidenceRefs: [], detail: "repository not frozen" };
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
if (lastSkill === "resolve-repository-state") {
|
|
813
|
+
const contradictionFields = snapshot.contradictions.map((c) => c.field);
|
|
814
|
+
if (contradictionFields.length > 0 && !contradictionFields.includes(targets[0])) {
|
|
815
|
+
return { kind: "stop", intent: "stop", targets, reasonCode: "stop-forbidden-transition", evidenceRefs: [], detail: `target ${targets[0]} does not match contradiction fields` };
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
// Effect authorization
|
|
819
|
+
if (!checkEffectAuth(proposal)) {
|
|
820
|
+
return { kind: "stop", intent: "stop", targets: [], reasonCode: "stop-forbidden-transition", evidenceRefs: [], detail: "unauthorized effect" };
|
|
821
|
+
}
|
|
822
|
+
// Evidence authorization
|
|
823
|
+
if (!checkEvidenceAuth(proposal, evidenceRefs)) {
|
|
824
|
+
return { kind: "sense", intent: "status", targets: [], reasonCode: "sense-missing-evidence", evidenceRefs: [], detail: "missing required evidence" };
|
|
825
|
+
}
|
|
826
|
+
// Policy gate
|
|
827
|
+
if (!checkPolicyGate(proposal, typedPolicy)) {
|
|
828
|
+
return { kind: "stop", intent: "stop", targets: [], reasonCode: "stop-policy-denied", evidenceRefs: [], detail: "policy denied" };
|
|
829
|
+
}
|
|
830
|
+
// Non-invocable intents can never reach invoke
|
|
831
|
+
if (proposal === "status" || proposal === "ask-human" || proposal === "stop" || proposal === "none") {
|
|
832
|
+
return { kind: "stop", intent: "stop", targets: [], reasonCode: "stop-forbidden-transition", evidenceRefs: [], detail: "non-invocable intent" };
|
|
833
|
+
}
|
|
834
|
+
// Target count validation for audit-pr: exactly 1 target
|
|
835
|
+
if (lastSkill === "audit-pr" && targets.length !== 1) {
|
|
836
|
+
return { kind: "stop", intent: "stop", targets, reasonCode: "stop-forbidden-transition", evidenceRefs: [], detail: targets.length === 0 ? "missing target" : "extra targets" };
|
|
837
|
+
}
|
|
838
|
+
// Proven transition — invoke
|
|
839
|
+
const invocable = proposal;
|
|
840
|
+
// Proven transition — invoke
|
|
841
|
+
return {
|
|
842
|
+
kind: "invoke", intent: invocable,
|
|
843
|
+
targets: targets.length > 0 ? targets : [],
|
|
844
|
+
reasonCode: "invoke-proven-transition",
|
|
845
|
+
evidenceRefs,
|
|
846
|
+
detail: `invoke-proven-transition: ${proposal} to [${targets.join(", ") || "*"}]`,
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
// ---------------------------------------------------------------------------
|
|
448
850
|
// Capability metadata — closed vocabularies, immutable exports (issue #136)
|
|
449
851
|
// ---------------------------------------------------------------------------
|
|
450
852
|
/** Role a built-in skill plays in the workflow pipeline. */
|
|
@@ -1415,3 +1817,577 @@ export function compileWorkflowSnapshot(input) {
|
|
|
1415
1817
|
? { ok: true, snapshot: validation.snapshot }
|
|
1416
1818
|
: { ok: false, errors: validation.errors };
|
|
1417
1819
|
}
|
|
1820
|
+
// ===========================================================================
|
|
1821
|
+
// Content-bound review receipts — CandidateSnapshot v1
|
|
1822
|
+
// ===========================================================================
|
|
1823
|
+
/** Contract identifier for CandidateSnapshot v1. */
|
|
1824
|
+
export const CANDIDATE_SNAPSHOT_CONTRACT_ID = "agentic-workflow/candidate-snapshot@1";
|
|
1825
|
+
// ---------------------------------------------------------------------------
|
|
1826
|
+
// Internal helpers
|
|
1827
|
+
// ---------------------------------------------------------------------------
|
|
1828
|
+
const SHA1_RE = /^[a-f0-9]{40}$/;
|
|
1829
|
+
const SHA256_RE = /^[a-f0-9]{64}$/;
|
|
1830
|
+
const FP_RE = /^[a-f0-9]{64}$/;
|
|
1831
|
+
const VALID_MODES = new Set(["100644", "100755", "120000", "160000"]);
|
|
1832
|
+
const VALID_STATUSES = new Set(["added", "modified", "deleted", "renamed", "copied", "type-changed"]);
|
|
1833
|
+
function isGitObjectId(v) {
|
|
1834
|
+
if (!isObj(v))
|
|
1835
|
+
return false;
|
|
1836
|
+
const keys = Object.keys(v);
|
|
1837
|
+
if (keys.length !== 2)
|
|
1838
|
+
return false;
|
|
1839
|
+
if (v.algorithm !== "sha1" && v.algorithm !== "sha256")
|
|
1840
|
+
return false;
|
|
1841
|
+
if (v.hex === undefined || typeof v.hex !== "string")
|
|
1842
|
+
return false;
|
|
1843
|
+
if (v.algorithm === "sha1" && !SHA1_RE.test(v.hex))
|
|
1844
|
+
return false;
|
|
1845
|
+
if (v.algorithm === "sha256" && !SHA256_RE.test(v.hex))
|
|
1846
|
+
return false;
|
|
1847
|
+
return true;
|
|
1848
|
+
}
|
|
1849
|
+
function hasUndeclaredKeys(actual, known) {
|
|
1850
|
+
return Object.keys(actual).filter((k) => !known.includes(k));
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Compare two UTF-8 strings in ascending unsigned-byte order.
|
|
1854
|
+
* Returns < 0 if a < b, > 0 if a > b, 0 if equal.
|
|
1855
|
+
*/
|
|
1856
|
+
const _utf8Encoder = new TextEncoder();
|
|
1857
|
+
function utf8ByteCompare(a, b) {
|
|
1858
|
+
const ba = _utf8Encoder.encode(a);
|
|
1859
|
+
const bb = _utf8Encoder.encode(b);
|
|
1860
|
+
const len = Math.min(ba.length, bb.length);
|
|
1861
|
+
for (let i = 0; i < len; i++) {
|
|
1862
|
+
const diff = ba[i] - bb[i];
|
|
1863
|
+
if (diff !== 0)
|
|
1864
|
+
return diff;
|
|
1865
|
+
}
|
|
1866
|
+
return ba.length - bb.length;
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1869
|
+
* Structural validation of a CandidateSnapshot v1.
|
|
1870
|
+
* Rejects undeclared fields, enforces GitObjectId format, path-byte ordering,
|
|
1871
|
+
* null-applicability matrix, and the empty-diff rule.
|
|
1872
|
+
*/
|
|
1873
|
+
export function validateCandidateSnapshotV1(value) {
|
|
1874
|
+
const errors = [];
|
|
1875
|
+
if (!isObj(value)) {
|
|
1876
|
+
return { ok: false, errors: ["candidate snapshot is not a JSON object"] };
|
|
1877
|
+
}
|
|
1878
|
+
// --- contract id ---
|
|
1879
|
+
if (value.contract !== CANDIDATE_SNAPSHOT_CONTRACT_ID) {
|
|
1880
|
+
errors.push(`contract must be "${CANDIDATE_SNAPSHOT_CONTRACT_ID}" (got: ${String(value.contract)})`);
|
|
1881
|
+
}
|
|
1882
|
+
// --- top-level undeclared keys ---
|
|
1883
|
+
const knownTopKeys = [
|
|
1884
|
+
"contract", "objectFormat", "baseCommit", "candidateCommit",
|
|
1885
|
+
"baseTree", "candidateTree", "acceptanceFingerprint", "changedPaths",
|
|
1886
|
+
];
|
|
1887
|
+
const topExtra = hasUndeclaredKeys(value, knownTopKeys);
|
|
1888
|
+
for (const k of topExtra) {
|
|
1889
|
+
errors.push(`${k} is not a valid candidate-snapshot field`);
|
|
1890
|
+
}
|
|
1891
|
+
// --- objectFormat ---
|
|
1892
|
+
const objectFormat = value.objectFormat;
|
|
1893
|
+
if (objectFormat !== "sha1" && objectFormat !== "sha256") {
|
|
1894
|
+
errors.push(`objectFormat must be "sha1" | "sha256" (got: ${String(objectFormat)})`);
|
|
1895
|
+
}
|
|
1896
|
+
// --- GitObjectId fields (baseCommit, candidateCommit, baseTree, candidateTree) ---
|
|
1897
|
+
for (const key of ["baseCommit", "candidateCommit", "baseTree", "candidateTree"]) {
|
|
1898
|
+
if (!isGitObjectId(value[key])) {
|
|
1899
|
+
errors.push(`${key} must be a GitObjectId {algorithm:"${objectFormat}", hex:/^[a-f0-9]{${objectFormat === "sha1" ? 40 : 64}}$/}`);
|
|
1900
|
+
}
|
|
1901
|
+
else if (value[key].algorithm !== objectFormat) {
|
|
1902
|
+
errors.push(`${key}.algorithm must match objectFormat "${objectFormat}" (got: ${value[key].algorithm})`);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
// --- acceptanceFingerprint ---
|
|
1906
|
+
if (typeof value.acceptanceFingerprint !== "string" || !FP_RE.test(value.acceptanceFingerprint)) {
|
|
1907
|
+
errors.push("acceptanceFingerprint must be a lowercase SHA-256 hex string (64 chars)");
|
|
1908
|
+
}
|
|
1909
|
+
// --- changedPaths ---
|
|
1910
|
+
if (!Array.isArray(value.changedPaths)) {
|
|
1911
|
+
errors.push("changedPaths must be an array");
|
|
1912
|
+
}
|
|
1913
|
+
else {
|
|
1914
|
+
const entries = value.changedPaths;
|
|
1915
|
+
let seenPaths = new Set();
|
|
1916
|
+
let prevPath = "";
|
|
1917
|
+
for (let i = 0; i < entries.length; i++) {
|
|
1918
|
+
const entry = entries[i];
|
|
1919
|
+
const prefix = `changedPaths[${i}]`;
|
|
1920
|
+
if (!isObj(entry)) {
|
|
1921
|
+
errors.push(`${prefix} must be an object`);
|
|
1922
|
+
continue;
|
|
1923
|
+
}
|
|
1924
|
+
// Unknown keys
|
|
1925
|
+
const knownEntryKeys = ["path", "status", "oldPath", "mode", "objectSha", "sizeBytes", "binary"];
|
|
1926
|
+
const extra = hasUndeclaredKeys(entry, knownEntryKeys);
|
|
1927
|
+
for (const k of extra) {
|
|
1928
|
+
errors.push(`${prefix}.${k} is not a valid field`);
|
|
1929
|
+
}
|
|
1930
|
+
// path
|
|
1931
|
+
if (typeof entry.path !== "string") {
|
|
1932
|
+
errors.push(`${prefix}.path must be a string`);
|
|
1933
|
+
}
|
|
1934
|
+
else {
|
|
1935
|
+
if (entry.path.includes("\0")) {
|
|
1936
|
+
errors.push(`${prefix}.path must not contain NUL`);
|
|
1937
|
+
}
|
|
1938
|
+
if (entry.path.startsWith("/")) {
|
|
1939
|
+
errors.push(`${prefix}.path must not be absolute`);
|
|
1940
|
+
}
|
|
1941
|
+
const segments = entry.path.split("/");
|
|
1942
|
+
if (segments.some((s) => s === ".." || s.startsWith(".."))) {
|
|
1943
|
+
errors.push(`${prefix}.path must not contain a ".." segment`);
|
|
1944
|
+
}
|
|
1945
|
+
// Byte-order check
|
|
1946
|
+
if (utf8ByteCompare(entry.path, prevPath) < 0) {
|
|
1947
|
+
errors.push(`${prefix}.path is not in ascending byte order`);
|
|
1948
|
+
}
|
|
1949
|
+
prevPath = entry.path;
|
|
1950
|
+
// Duplicate check
|
|
1951
|
+
if (seenPaths.has(entry.path)) {
|
|
1952
|
+
errors.push(`${prefix}.path is a duplicate`);
|
|
1953
|
+
}
|
|
1954
|
+
seenPaths.add(entry.path);
|
|
1955
|
+
}
|
|
1956
|
+
// status
|
|
1957
|
+
if (typeof entry.status !== "string" || !VALID_STATUSES.has(entry.status)) {
|
|
1958
|
+
errors.push(`${prefix}.status must be one of added|modified|deleted|renamed|copied|type-changed (got: ${String(entry.status)})`);
|
|
1959
|
+
}
|
|
1960
|
+
// oldPath
|
|
1961
|
+
const status = entry.status;
|
|
1962
|
+
if ((status === "renamed" || status === "copied") && entry.oldPath === null) {
|
|
1963
|
+
errors.push(`${prefix}.renamed/copied entries require a non-null oldPath`);
|
|
1964
|
+
}
|
|
1965
|
+
else if ((status !== "renamed" && status !== "copied") && entry.oldPath !== null) {
|
|
1966
|
+
errors.push(`${prefix}.oldPath must be null when status is ${status}`);
|
|
1967
|
+
}
|
|
1968
|
+
// objectSha
|
|
1969
|
+
if (status === "deleted" && entry.objectSha !== null) {
|
|
1970
|
+
errors.push(`${prefix}.objectSha must be null for deleted entries`);
|
|
1971
|
+
}
|
|
1972
|
+
else if (status !== "deleted" && !isGitObjectId(entry.objectSha)) {
|
|
1973
|
+
// For non-deleted, objectSha should be a GitObjectId
|
|
1974
|
+
if (entry.objectSha !== null && !isGitObjectId(entry.objectSha)) {
|
|
1975
|
+
errors.push(`${prefix}.objectSha must be a GitObjectId or null`);
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
// mode
|
|
1979
|
+
if (entry.mode !== null && !VALID_MODES.has(entry.mode)) {
|
|
1980
|
+
errors.push(`${prefix}.mode must be one of 100644|100755|120000|160000 or null (got: ${String(entry.mode)})`);
|
|
1981
|
+
}
|
|
1982
|
+
// sizeBytes
|
|
1983
|
+
if (entry.sizeBytes !== null) {
|
|
1984
|
+
if (typeof entry.sizeBytes !== "number" || entry.sizeBytes < 0 || !Number.isInteger(entry.sizeBytes)) {
|
|
1985
|
+
errors.push(`${prefix}.sizeBytes must be a non-negative integer or null`);
|
|
1986
|
+
}
|
|
1987
|
+
else if (entry.mode === "160000") {
|
|
1988
|
+
errors.push(`${prefix}.sizeBytes must be null for gitlinks (mode 160000)`);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
// binary
|
|
1992
|
+
if (entry.binary !== null && typeof entry.binary !== "boolean") {
|
|
1993
|
+
errors.push(`${prefix}.binary must be a boolean or null`);
|
|
1994
|
+
}
|
|
1995
|
+
else if (entry.mode === "160000" && entry.binary !== null) {
|
|
1996
|
+
errors.push(`${prefix}.binary must be null for gitlinks (mode 160000)`);
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
// --- Empty-diff rule ---
|
|
2001
|
+
if (Array.isArray(value.changedPaths) && value.changedPaths.length === 0) {
|
|
2002
|
+
// Check if baseTree equals candidateTree
|
|
2003
|
+
if (isGitObjectId(value.baseTree) && isGitObjectId(value.candidateTree)) {
|
|
2004
|
+
if (value.baseTree.hex !== value.candidateTree.hex) {
|
|
2005
|
+
errors.push("empty changedPaths requires baseTree and candidateTree to be identical (empty diff rule)");
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
if (errors.length > 0) {
|
|
2010
|
+
return { ok: false, errors };
|
|
2011
|
+
}
|
|
2012
|
+
return { ok: true, snapshot: value };
|
|
2013
|
+
}
|
|
2014
|
+
// ===========================================================================
|
|
2015
|
+
// Content-bound review receipts — ReviewReceipt v1
|
|
2016
|
+
// ===========================================================================
|
|
2017
|
+
/** Contract identifier for ReviewReceipt v1. */
|
|
2018
|
+
export const REVIEW_RECEIPT_CONTRACT_ID = "agentic-workflow/review-receipt@1";
|
|
2019
|
+
/** All review kinds supported by the workflow. */
|
|
2020
|
+
export const REVIEW_KINDS = [
|
|
2021
|
+
"implementation", "security", "verification", "debt",
|
|
2022
|
+
"design", "accessibility", "brand", "performance", "seo", "audit",
|
|
2023
|
+
];
|
|
2024
|
+
/** Finding severity levels. */
|
|
2025
|
+
export const FINDING_SEVERITIES = [
|
|
2026
|
+
"info", "low", "medium", "high", "critical",
|
|
2027
|
+
];
|
|
2028
|
+
const REVIEW_KINDS_SET = new Set(REVIEW_KINDS);
|
|
2029
|
+
const FINDING_SEVERITIES_SET = new Set(FINDING_SEVERITIES);
|
|
2030
|
+
// ---------------------------------------------------------------------------
|
|
2031
|
+
// Validator: validateReviewReceiptV1
|
|
2032
|
+
// ---------------------------------------------------------------------------
|
|
2033
|
+
const DIGEST_RE = /^[a-f0-9]{64}$/;
|
|
2034
|
+
const ISO_8601_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
|
|
2035
|
+
/**
|
|
2036
|
+
* Structural validation of a ReviewReceipt v1.
|
|
2037
|
+
* Rejects undeclared fields, enforces closed vocabularies, format rules,
|
|
2038
|
+
* and constraints on timestamps and finding structure.
|
|
2039
|
+
*/
|
|
2040
|
+
export function validateReviewReceiptV1(value) {
|
|
2041
|
+
const errors = [];
|
|
2042
|
+
if (!isObj(value)) {
|
|
2043
|
+
return { ok: false, errors: ["review receipt is not a JSON object"] };
|
|
2044
|
+
}
|
|
2045
|
+
// --- contract id ---
|
|
2046
|
+
if (value.contract !== REVIEW_RECEIPT_CONTRACT_ID) {
|
|
2047
|
+
errors.push(`contract must be "${REVIEW_RECEIPT_CONTRACT_ID}" (got: ${String(value.contract)})`);
|
|
2048
|
+
}
|
|
2049
|
+
// --- top-level undeclared keys ---
|
|
2050
|
+
const knownReceiptKeys = [
|
|
2051
|
+
"contract", "id", "candidateSnapshotDigest", "kind", "verdict",
|
|
2052
|
+
"findings", "reviewer", "sessionId", "startedAt", "finishedAt",
|
|
2053
|
+
"diagnostics", "policyVersion",
|
|
2054
|
+
];
|
|
2055
|
+
const topExtra = hasUndeclaredKeys(value, knownReceiptKeys);
|
|
2056
|
+
for (const k of topExtra) {
|
|
2057
|
+
errors.push(`${k} is not a valid review-receipt field`);
|
|
2058
|
+
}
|
|
2059
|
+
// --- id ---
|
|
2060
|
+
if (typeof value.id !== "string" || value.id.length === 0) {
|
|
2061
|
+
errors.push("id must be a non-empty string");
|
|
2062
|
+
}
|
|
2063
|
+
// --- candidateSnapshotDigest ---
|
|
2064
|
+
if (typeof value.candidateSnapshotDigest !== "string" || !DIGEST_RE.test(value.candidateSnapshotDigest)) {
|
|
2065
|
+
errors.push("candidateSnapshotDigest must be a lowercase SHA-256 hex string (64 chars)");
|
|
2066
|
+
}
|
|
2067
|
+
// --- kind ---
|
|
2068
|
+
if (typeof value.kind !== "string" || !REVIEW_KINDS_SET.has(value.kind)) {
|
|
2069
|
+
errors.push(`kind must be one of ${REVIEW_KINDS.join("|")} (got: ${String(value.kind)})`);
|
|
2070
|
+
}
|
|
2071
|
+
// --- verdict ---
|
|
2072
|
+
if (value.verdict !== "pass" && value.verdict !== "fail") {
|
|
2073
|
+
errors.push(`verdict must be "pass" | "fail" (got: ${String(value.verdict)})`);
|
|
2074
|
+
}
|
|
2075
|
+
// --- findings ---
|
|
2076
|
+
if (!Array.isArray(value.findings)) {
|
|
2077
|
+
errors.push("findings must be an array");
|
|
2078
|
+
}
|
|
2079
|
+
else {
|
|
2080
|
+
const findings = value.findings;
|
|
2081
|
+
let seenFindingIds = new Set();
|
|
2082
|
+
for (let i = 0; i < findings.length; i++) {
|
|
2083
|
+
const f = findings[i];
|
|
2084
|
+
const prefix = `findings[${i}]`;
|
|
2085
|
+
if (!isObj(f)) {
|
|
2086
|
+
errors.push(`${prefix} must be an object`);
|
|
2087
|
+
continue;
|
|
2088
|
+
}
|
|
2089
|
+
// Unknown keys on finding
|
|
2090
|
+
const knownFindingKeys = ["id", "severity", "summary", "evidence", "refs"];
|
|
2091
|
+
const findingExtra = hasUndeclaredKeys(f, knownFindingKeys);
|
|
2092
|
+
for (const k of findingExtra) {
|
|
2093
|
+
errors.push(`${prefix}.${k} is not a valid field`);
|
|
2094
|
+
}
|
|
2095
|
+
// id
|
|
2096
|
+
if (typeof f.id !== "string" || f.id.length === 0) {
|
|
2097
|
+
errors.push(`${prefix}.id must be a non-empty string`);
|
|
2098
|
+
}
|
|
2099
|
+
else {
|
|
2100
|
+
if (seenFindingIds.has(f.id)) {
|
|
2101
|
+
errors.push(`${prefix}.id is a duplicate`);
|
|
2102
|
+
}
|
|
2103
|
+
seenFindingIds.add(f.id);
|
|
2104
|
+
}
|
|
2105
|
+
// severity
|
|
2106
|
+
if (typeof f.severity !== "string" || !FINDING_SEVERITIES_SET.has(f.severity)) {
|
|
2107
|
+
errors.push(`${prefix}.severity must be one of ${FINDING_SEVERITIES.join("|")} (got: ${String(f.severity)})`);
|
|
2108
|
+
}
|
|
2109
|
+
// summary
|
|
2110
|
+
if (typeof f.summary !== "string" || f.summary.length === 0) {
|
|
2111
|
+
errors.push(`${prefix}.summary must be a non-empty string`);
|
|
2112
|
+
}
|
|
2113
|
+
// evidence
|
|
2114
|
+
if (f.evidence !== undefined && f.evidence !== null) {
|
|
2115
|
+
if (isObj(f.evidence)) {
|
|
2116
|
+
const evidenceKeys = Object.keys(f.evidence);
|
|
2117
|
+
const knownEvidenceKeys = ["path", "line"];
|
|
2118
|
+
const evidenceExtra = hasUndeclaredKeys(f.evidence, knownEvidenceKeys);
|
|
2119
|
+
for (const k of evidenceExtra) {
|
|
2120
|
+
errors.push(`${prefix}.evidence.${k} is not a valid field`);
|
|
2121
|
+
}
|
|
2122
|
+
if (typeof f.evidence.path !== "string") {
|
|
2123
|
+
errors.push(`${prefix}.evidence.path must be a string`);
|
|
2124
|
+
}
|
|
2125
|
+
if (f.evidence.line !== undefined && f.evidence.line !== null) {
|
|
2126
|
+
if (typeof f.evidence.line !== "number" || !Number.isInteger(f.evidence.line) || f.evidence.line < 1) {
|
|
2127
|
+
errors.push(`${prefix}.evidence.line must be an integer >= 1`);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
else {
|
|
2132
|
+
errors.push(`${prefix}.evidence must be an object or null`);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
// refs
|
|
2136
|
+
if (!Array.isArray(f.refs)) {
|
|
2137
|
+
errors.push(`${prefix}.refs must be an array`);
|
|
2138
|
+
}
|
|
2139
|
+
else {
|
|
2140
|
+
for (let j = 0; j < f.refs.length; j++) {
|
|
2141
|
+
if (typeof f.refs[j] !== "string") {
|
|
2142
|
+
errors.push(`${prefix}.refs[${j}] must be a string`);
|
|
2143
|
+
break;
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
// --- reviewer ---
|
|
2150
|
+
if (typeof value.reviewer !== "string" || value.reviewer.length === 0) {
|
|
2151
|
+
errors.push("reviewer must be a non-empty string");
|
|
2152
|
+
}
|
|
2153
|
+
// --- sessionId ---
|
|
2154
|
+
if (typeof value.sessionId !== "string" || value.sessionId.length === 0) {
|
|
2155
|
+
errors.push("sessionId must be a non-empty string");
|
|
2156
|
+
}
|
|
2157
|
+
// --- startedAt / finishedAt (ISO-8601 UTC) ---
|
|
2158
|
+
if (typeof value.startedAt !== "string" || !ISO_8601_RE.test(value.startedAt)) {
|
|
2159
|
+
errors.push("startedAt must be an ISO-8601 UTC timestamp");
|
|
2160
|
+
}
|
|
2161
|
+
if (typeof value.finishedAt !== "string" || !ISO_8601_RE.test(value.finishedAt)) {
|
|
2162
|
+
errors.push("finishedAt must be an ISO-8601 UTC timestamp");
|
|
2163
|
+
}
|
|
2164
|
+
// finishedAt >= startedAt — Date.parse is safe because the regex only
|
|
2165
|
+
// accepts Z-suffix (UTC) so no mixed-offset ambiguity remains.
|
|
2166
|
+
if (typeof value.startedAt === "string" && typeof value.finishedAt === "string" &&
|
|
2167
|
+
ISO_8601_RE.test(value.startedAt) && ISO_8601_RE.test(value.finishedAt)) {
|
|
2168
|
+
if (Date.parse(value.finishedAt) < Date.parse(value.startedAt)) {
|
|
2169
|
+
errors.push("finishedAt must be >= startedAt");
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
// --- diagnostics ---
|
|
2173
|
+
if (!Array.isArray(value.diagnostics)) {
|
|
2174
|
+
errors.push("diagnostics must be an array");
|
|
2175
|
+
}
|
|
2176
|
+
else {
|
|
2177
|
+
for (let i = 0; i < value.diagnostics.length; i++) {
|
|
2178
|
+
if (typeof value.diagnostics[i] !== "string") {
|
|
2179
|
+
errors.push(`diagnostics[${i}] must be a string`);
|
|
2180
|
+
break;
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
// --- policyVersion ---
|
|
2185
|
+
if (typeof value.policyVersion !== "string" || value.policyVersion.length === 0) {
|
|
2186
|
+
errors.push("policyVersion must be a non-empty string");
|
|
2187
|
+
}
|
|
2188
|
+
if (errors.length > 0) {
|
|
2189
|
+
return { ok: false, errors };
|
|
2190
|
+
}
|
|
2191
|
+
return { ok: true, receipt: value };
|
|
2192
|
+
}
|
|
2193
|
+
// ===========================================================================
|
|
2194
|
+
// Canonical content-binding core (D2, D4, D1)
|
|
2195
|
+
// ===========================================================================
|
|
2196
|
+
/** Staleness reason codes — one per detectable dimension. */
|
|
2197
|
+
export const STALE_REASON_CODES = [
|
|
2198
|
+
"stale-base-tree",
|
|
2199
|
+
"stale-candidate-tree",
|
|
2200
|
+
"stale-manifest",
|
|
2201
|
+
"stale-acceptance-fingerprint",
|
|
2202
|
+
"stale-review-policy",
|
|
2203
|
+
];
|
|
2204
|
+
// ---------------------------------------------------------------------------
|
|
2205
|
+
// D4 — Canonical serialization helpers
|
|
2206
|
+
// ---------------------------------------------------------------------------
|
|
2207
|
+
function canonicalJSONValue(v) {
|
|
2208
|
+
if (v === null)
|
|
2209
|
+
return "null";
|
|
2210
|
+
if (typeof v === "string")
|
|
2211
|
+
return JSON.stringify(v);
|
|
2212
|
+
if (typeof v === "number")
|
|
2213
|
+
return JSON.stringify(v);
|
|
2214
|
+
if (typeof v === "boolean")
|
|
2215
|
+
return JSON.stringify(v);
|
|
2216
|
+
if (Array.isArray(v)) {
|
|
2217
|
+
return "[" + v.map(canonicalJSONValue).join(",") + "]";
|
|
2218
|
+
}
|
|
2219
|
+
if (typeof v === "object") {
|
|
2220
|
+
const keys = Object.keys(v).sort();
|
|
2221
|
+
return "{" + keys.map(k => JSON.stringify(k) + ":" + canonicalJSONValue(v[k])).join(",") + "}";
|
|
2222
|
+
}
|
|
2223
|
+
return JSON.stringify(v);
|
|
2224
|
+
}
|
|
2225
|
+
/**
|
|
2226
|
+
* D4 — Canonicalize a CandidateSnapshotV1.
|
|
2227
|
+
* Produces deterministic JSON with declaration-order keys and sorted changedPaths.
|
|
2228
|
+
*/
|
|
2229
|
+
export function canonicalizeCandidateSnapshot(snapshot) {
|
|
2230
|
+
const sortedPaths = [...snapshot.changedPaths].sort((a, b) => utf8ByteCompare(a.path, b.path));
|
|
2231
|
+
const obj = {
|
|
2232
|
+
contract: snapshot.contract,
|
|
2233
|
+
objectFormat: snapshot.objectFormat,
|
|
2234
|
+
baseCommit: snapshot.baseCommit,
|
|
2235
|
+
candidateCommit: snapshot.candidateCommit,
|
|
2236
|
+
baseTree: snapshot.baseTree,
|
|
2237
|
+
candidateTree: snapshot.candidateTree,
|
|
2238
|
+
acceptanceFingerprint: snapshot.acceptanceFingerprint,
|
|
2239
|
+
changedPaths: sortedPaths,
|
|
2240
|
+
};
|
|
2241
|
+
return canonicalJSONValue(obj);
|
|
2242
|
+
}
|
|
2243
|
+
/**
|
|
2244
|
+
* D4 — Canonicalize a ReviewReceiptV1.
|
|
2245
|
+
* Findings are sorted by ascending byte order of their stable ids.
|
|
2246
|
+
*/
|
|
2247
|
+
export function canonicalizeReviewReceipt(receipt) {
|
|
2248
|
+
const sortedFindings = [...receipt.findings].sort((a, b) => utf8ByteCompare(a.id, b.id));
|
|
2249
|
+
const obj = {
|
|
2250
|
+
contract: receipt.contract,
|
|
2251
|
+
id: receipt.id,
|
|
2252
|
+
candidateSnapshotDigest: receipt.candidateSnapshotDigest,
|
|
2253
|
+
kind: receipt.kind,
|
|
2254
|
+
verdict: receipt.verdict,
|
|
2255
|
+
findings: sortedFindings,
|
|
2256
|
+
reviewer: receipt.reviewer,
|
|
2257
|
+
sessionId: receipt.sessionId,
|
|
2258
|
+
startedAt: receipt.startedAt,
|
|
2259
|
+
finishedAt: receipt.finishedAt,
|
|
2260
|
+
diagnostics: receipt.diagnostics,
|
|
2261
|
+
policyVersion: receipt.policyVersion,
|
|
2262
|
+
};
|
|
2263
|
+
return canonicalJSONValue(obj);
|
|
2264
|
+
}
|
|
2265
|
+
// ---------------------------------------------------------------------------
|
|
2266
|
+
// SHA-256 hashing
|
|
2267
|
+
// ---------------------------------------------------------------------------
|
|
2268
|
+
/** D4 — SHA-256 hex digest (async via Web Crypto). */
|
|
2269
|
+
async function sha256Hex(data) {
|
|
2270
|
+
const encoder = new TextEncoder();
|
|
2271
|
+
const buf = encoder.encode(data);
|
|
2272
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", buf);
|
|
2273
|
+
const hashArray = new Uint8Array(hashBuffer);
|
|
2274
|
+
return Array.from(hashArray).map(b => b.toString(16).padStart(2, "0")).join("");
|
|
2275
|
+
}
|
|
2276
|
+
/** D4 — Digest a CandidateSnapshotV1 via canonical serialization. */
|
|
2277
|
+
export async function digestCandidateSnapshot(snapshot) {
|
|
2278
|
+
return sha256Hex(canonicalizeCandidateSnapshot(snapshot));
|
|
2279
|
+
}
|
|
2280
|
+
/** D4 — Digest a ReviewReceiptV1 via canonical serialization. */
|
|
2281
|
+
export async function digestReviewReceipt(receipt) {
|
|
2282
|
+
return sha256Hex(canonicalizeReviewReceipt(receipt));
|
|
2283
|
+
}
|
|
2284
|
+
// ---------------------------------------------------------------------------
|
|
2285
|
+
// D2 — Acceptance fingerprint
|
|
2286
|
+
// ---------------------------------------------------------------------------
|
|
2287
|
+
/**
|
|
2288
|
+
* D2 — Compute the acceptance fingerprint from an ordered array of
|
|
2289
|
+
* {id, blobSha256} entries. Returns lowercase hex SHA-256 over their
|
|
2290
|
+
* canonical serialization (sorted by byte-order of id).
|
|
2291
|
+
*/
|
|
2292
|
+
export async function computeAcceptanceFingerprint(inputs) {
|
|
2293
|
+
const sorted = [...inputs].sort((a, b) => utf8ByteCompare(a.id, b.id));
|
|
2294
|
+
const obj = {
|
|
2295
|
+
inputs: sorted,
|
|
2296
|
+
};
|
|
2297
|
+
return sha256Hex(canonicalJSONValue(obj));
|
|
2298
|
+
}
|
|
2299
|
+
// ---------------------------------------------------------------------------
|
|
2300
|
+
// D1 — Freshness predicate
|
|
2301
|
+
// ---------------------------------------------------------------------------
|
|
2302
|
+
/** Deep- equality for two JSON values. */
|
|
2303
|
+
function deepEqual(a, b) {
|
|
2304
|
+
if (a === b)
|
|
2305
|
+
return true;
|
|
2306
|
+
if (typeof a !== typeof b)
|
|
2307
|
+
return false;
|
|
2308
|
+
if (a === null || b === null)
|
|
2309
|
+
return a === b;
|
|
2310
|
+
if (typeof a !== "object")
|
|
2311
|
+
return false;
|
|
2312
|
+
if (Array.isArray(a) !== Array.isArray(b))
|
|
2313
|
+
return false;
|
|
2314
|
+
if (Array.isArray(a)) {
|
|
2315
|
+
const bArr = b;
|
|
2316
|
+
if (a.length !== bArr.length)
|
|
2317
|
+
return false;
|
|
2318
|
+
for (let i = 0; i < a.length; i++) {
|
|
2319
|
+
if (!deepEqual(a[i], bArr[i]))
|
|
2320
|
+
return false;
|
|
2321
|
+
}
|
|
2322
|
+
return true;
|
|
2323
|
+
}
|
|
2324
|
+
const aObj = a;
|
|
2325
|
+
const bObj = b;
|
|
2326
|
+
const ka = Object.keys(aObj);
|
|
2327
|
+
const kb = Object.keys(bObj);
|
|
2328
|
+
if (ka.length !== kb.length)
|
|
2329
|
+
return false;
|
|
2330
|
+
ka.sort();
|
|
2331
|
+
kb.sort();
|
|
2332
|
+
for (let i = 0; i < ka.length; i++) {
|
|
2333
|
+
if (ka[i] !== kb[i])
|
|
2334
|
+
return false;
|
|
2335
|
+
if (!deepEqual(aObj[ka[i]], bObj[kb[i]]))
|
|
2336
|
+
return false;
|
|
2337
|
+
}
|
|
2338
|
+
return true;
|
|
2339
|
+
}
|
|
2340
|
+
/**
|
|
2341
|
+
* D1 — Compare a receipt against the current candidate snapshot and
|
|
2342
|
+
* acceptance fingerprint. Returns exactly one stable reason code per stale
|
|
2343
|
+
* dimension, or `{fresh: true}` when everything matches.
|
|
2344
|
+
*
|
|
2345
|
+
* Comparison order (per spec): baseCommit → candidateCommit → changedPaths
|
|
2346
|
+
* (canonical equality) → acceptanceFingerprint → policyVersion.
|
|
2347
|
+
* Everything equal AND snapshot digest === receipt.candidateSnapshotDigest → fresh.
|
|
2348
|
+
*/
|
|
2349
|
+
export async function compareReceiptToCurrentSnapshot(receipt, snapshot, acceptanceInputs, policyVersion) {
|
|
2350
|
+
// 1. policyVersion — O(1) short-circuit (per comparison order: baseCommit →
|
|
2351
|
+
// candidateCommit → changedPaths → acceptanceFingerprint → policyVersion;
|
|
2352
|
+
// policyVersion is checked last in order but is the cheapest so we
|
|
2353
|
+
// short-circuit first; the remaining base/candidate/manifest dimensions
|
|
2354
|
+
// are conflated into stale-base-tree because the receipt only stores the
|
|
2355
|
+
// single candidateSnapshotDigest and cannot carry individual field values).
|
|
2356
|
+
if (policyVersion !== receipt.policyVersion) {
|
|
2357
|
+
return { fresh: false, reasonCode: "stale-review-policy" };
|
|
2358
|
+
}
|
|
2359
|
+
// 2. acceptance fingerprint — compare computed from current inputs against
|
|
2360
|
+
// the snapshot's stored fingerprint.
|
|
2361
|
+
const currentFP = await computeAcceptanceFingerprint(acceptanceInputs);
|
|
2362
|
+
if (currentFP !== snapshot.acceptanceFingerprint) {
|
|
2363
|
+
return { fresh: false, reasonCode: "stale-acceptance-fingerprint" };
|
|
2364
|
+
}
|
|
2365
|
+
// 3. digest — baseCommit / candidateCommit / changedPaths dimension.
|
|
2366
|
+
// The receipt carries only the single candidateSnapshotDigest so we
|
|
2367
|
+
// cannot distinguish which sub-field changed; return the first dimension
|
|
2368
|
+
// in the canonical comparison order.
|
|
2369
|
+
const currentDigest = await digestCandidateSnapshot(snapshot);
|
|
2370
|
+
if (currentDigest !== receipt.candidateSnapshotDigest) {
|
|
2371
|
+
return { fresh: false, reasonCode: "stale-base-tree" };
|
|
2372
|
+
}
|
|
2373
|
+
return { fresh: true };
|
|
2374
|
+
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Published frozen canonical vectors. Each vector is a minimal valid value
|
|
2377
|
+
* whose canonical digest is deterministic and reproducible.
|
|
2378
|
+
*
|
|
2379
|
+
* These vectors lock the canonicalization rules (D4) in place.
|
|
2380
|
+
* Changing any vector's expected digest would be a reviewed contract change.
|
|
2381
|
+
*/
|
|
2382
|
+
export const CANONICAL_VECTORS = Object.freeze([
|
|
2383
|
+
{
|
|
2384
|
+
contract: "agentic-workflow/candidate-snapshot@1",
|
|
2385
|
+
digest: "d85671a09c73836fea421013c0d2537dfc233988083d981f7daca869af55ec7a",
|
|
2386
|
+
description: "minimal valid snapshot (empty diff, sha1)",
|
|
2387
|
+
},
|
|
2388
|
+
{
|
|
2389
|
+
contract: "agentic-workflow/review-receipt@1",
|
|
2390
|
+
digest: "8ae86246d83da2611380098910920b8850779a77613897e5d8efa4dd197d16e6",
|
|
2391
|
+
description: "minimal valid receipt (single finding)",
|
|
2392
|
+
},
|
|
2393
|
+
]);
|