@agenticprimitives/coordination 0.0.0-alpha.3 → 0.0.0-alpha.30

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 (61) hide show
  1. package/README.md +7 -1
  2. package/dist/attribution/index.d.ts +69 -0
  3. package/dist/attribution/index.d.ts.map +1 -0
  4. package/dist/attribution/index.js +165 -0
  5. package/dist/attribution/index.js.map +1 -0
  6. package/dist/attribution/scenarios.d.ts +26 -0
  7. package/dist/attribution/scenarios.d.ts.map +1 -0
  8. package/dist/attribution/scenarios.js +59 -0
  9. package/dist/attribution/scenarios.js.map +1 -0
  10. package/dist/core/commands.d.ts +53 -3
  11. package/dist/core/commands.d.ts.map +1 -1
  12. package/dist/core/commands.js +6 -0
  13. package/dist/core/commands.js.map +1 -1
  14. package/dist/core/events.d.ts +47 -3
  15. package/dist/core/events.d.ts.map +1 -1
  16. package/dist/core/ids.d.ts +4 -0
  17. package/dist/core/ids.d.ts.map +1 -1
  18. package/dist/core/ids.js +2 -0
  19. package/dist/core/ids.js.map +1 -1
  20. package/dist/core/index.d.ts +3 -3
  21. package/dist/core/index.d.ts.map +1 -1
  22. package/dist/core/index.js +1 -1
  23. package/dist/core/index.js.map +1 -1
  24. package/dist/core/provenance.d.ts.map +1 -1
  25. package/dist/core/provenance.js +44 -1
  26. package/dist/core/provenance.js.map +1 -1
  27. package/dist/core/reducer.d.ts +21 -2
  28. package/dist/core/reducer.d.ts.map +1 -1
  29. package/dist/core/reducer.js +450 -32
  30. package/dist/core/reducer.js.map +1 -1
  31. package/dist/decisions/index.d.ts +2 -8
  32. package/dist/decisions/index.d.ts.map +1 -1
  33. package/dist/decisions/index.js +1 -1
  34. package/dist/decisions/index.js.map +1 -1
  35. package/dist/decisions/types.d.ts +53 -1
  36. package/dist/decisions/types.d.ts.map +1 -1
  37. package/dist/index.d.ts +9 -4
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +6 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/participation/index.d.ts +2 -0
  42. package/dist/participation/index.d.ts.map +1 -1
  43. package/dist/participation/index.js +1 -1
  44. package/dist/participation/index.js.map +1 -1
  45. package/dist/participation/payload.d.ts +17 -0
  46. package/dist/participation/payload.d.ts.map +1 -0
  47. package/dist/participation/payload.js +35 -0
  48. package/dist/participation/payload.js.map +1 -0
  49. package/dist/participation/types.d.ts +1 -1
  50. package/dist/participation/types.d.ts.map +1 -1
  51. package/dist/planning/types.d.ts +2 -0
  52. package/dist/planning/types.d.ts.map +1 -1
  53. package/dist/projections/continuation.d.ts +53 -0
  54. package/dist/projections/continuation.d.ts.map +1 -0
  55. package/dist/projections/continuation.js +44 -0
  56. package/dist/projections/continuation.js.map +1 -0
  57. package/dist/projections/index.d.ts +2 -0
  58. package/dist/projections/index.d.ts.map +1 -1
  59. package/dist/projections/index.js +5 -1
  60. package/dist/projections/index.js.map +1 -1
  61. package/package.json +20 -6
@@ -3,6 +3,8 @@
3
3
  // Deterministic: ids and instants come from commands/events, never from this module.
4
4
  import { COORDINATION_COMMAND_KINDS } from './commands.js';
5
5
  import { planContentHash } from '../planning/hash.js';
6
+ import { jcsCanonicalize } from '@agenticprimitives/situations';
7
+ import { commitmentPayloadHash } from '../participation/payload.js';
6
8
  import { validatePlanContent } from '../planning/validate.js';
7
9
  export function initialCoordinationState() {
8
10
  return {
@@ -14,7 +16,10 @@ export function initialCoordinationState() {
14
16
  commitments: {},
15
17
  milestones: {},
16
18
  satisfiedSteps: {},
19
+ attachedRuns: {},
17
20
  recommendations: {},
21
+ decisionRequests: {},
22
+ decisions: {},
18
23
  };
19
24
  }
20
25
  export class CoordinationEventError extends Error {
@@ -26,6 +31,20 @@ export const planKey = (planId, revision) => `${planId}@${revision}`;
26
31
  const TERMINAL_LIFECYCLES = new Set(['satisfied', 'abandoned']);
27
32
  const eventId = (revision, kind) => `evt_${String(revision).padStart(4, '0')}_${kind}`;
28
33
  const reject = (reason) => ({ ok: false, reason });
34
+ /** OWN-PROPERTY lookup (spec 445 / REM-15). Every map here is keyed by a caller-supplied id; a bare `map[id]`
35
+ * answers `constructor` / `toString` / `__proto__` with an inherited member, which reads as "already exists". */
36
+ function own(map, key) {
37
+ return Object.hasOwn(map, key) ? map[key] : undefined;
38
+ }
39
+ /** Two definitions are THE SAME only when their RFC 8785 bytes are (spec 445 / REM-7). */
40
+ const sameContent = (a, b) => a !== undefined && b !== undefined && jcsCanonicalize(a) === jcsCanonicalize(b);
41
+ /** The step `stepId` as plan revision `ref` defined it, or undefined. */
42
+ function stepIn(state, ref, stepId) {
43
+ if (!ref)
44
+ return undefined;
45
+ const plan = own(state.plans, planKey(ref.planId, ref.revision));
46
+ return plan && plan.contentHash === ref.hash ? plan.steps.find((s) => s.stepId === stepId) : undefined;
47
+ }
29
48
  function activeRoles(state, address) {
30
49
  const roles = new Set();
31
50
  for (const p of Object.values(state.participations)) {
@@ -48,7 +67,12 @@ function participationStatus(state, address) {
48
67
  }
49
68
  function isSteward(state, address) {
50
69
  const roles = activeRoles(state, address);
51
- return roles.has('coordinator') || roles.has('sponsor');
70
+ // Spec 382 — THE MANAGING PRINCIPAL STEWARDS ITS OWN ENDEAVOR. The organization acting through its own
71
+ // agent (ADR-0054) may invite and allocate on the endeavor it manages, exactly as its coordinator may;
72
+ // adoption asserted the coordinator's participation, never the organization's, so a member's offer
73
+ // could not be admitted by anyone at the organization's own door. Nothing here is authority: an invite
74
+ // or an allocation grants no capability (spec 332 §9 rule 1).
75
+ return roles.has('coordinator') || roles.has('sponsor') || state.endeavor?.managingPrincipal === address;
52
76
  }
53
77
  function endeavorContext(state, endeavorId) {
54
78
  if (!state.endeavor)
@@ -64,7 +88,7 @@ function adoptedPlan(state) {
64
88
  const ref = state.endeavor?.adoptedPlanRef;
65
89
  if (!ref)
66
90
  return undefined;
67
- return state.plans[planKey(ref.planId, ref.revision)];
91
+ return own(state.plans, planKey(ref.planId, ref.revision));
68
92
  }
69
93
  function samePlanRef(a, b) {
70
94
  return a.planId === b.planId && a.revision === b.revision && a.hash === b.hash;
@@ -72,6 +96,20 @@ function samePlanRef(a, b) {
72
96
  export function validateCoordinationCommand(state, command) {
73
97
  const nextRevision = state.revision + 1;
74
98
  const at = command.issuedAt;
99
+ // Unknown kinds are refused FIRST and in their own words (conversation never mutates state).
100
+ if (!COORDINATION_COMMAND_KINDS.has(command.kind ?? '')) {
101
+ return reject(`unknown command kind ${command.kind ?? '<none>'}`);
102
+ }
103
+ // THE CLOCK (spec 445 / REM-5). `issuedAt` is the SERVING PLANE's instant, never the caller's: it must be a
104
+ // real instant, and it may not precede the last event applied. Every time-bound rule below (a decision
105
+ // window, a breach's deadline) is judged against it, so a back-dated or post-dated command is refused here
106
+ // rather than believed there.
107
+ const atMs = typeof at === 'string' ? Date.parse(at) : Number.NaN;
108
+ if (Number.isNaN(atMs))
109
+ return reject('issuedAt must be an ISO-8601 instant — the serving plane stamps it');
110
+ if (state.lastEventAt !== undefined && atMs < Date.parse(state.lastEventAt)) {
111
+ return reject(`issuedAt ${at} precedes the last recorded event (${state.lastEventAt}) — an instant is stamped by the serving plane and never runs backwards`);
112
+ }
75
113
  switch (command.kind) {
76
114
  case 'SubmitEndeavorRequest': {
77
115
  if (state.request)
@@ -235,7 +273,7 @@ export function validateCoordinationCommand(state, command) {
235
273
  const structural = validatePlanContent(content);
236
274
  if (!structural.ok)
237
275
  return reject(structural.reason);
238
- if (state.plans[planKey(command.planId, command.revision)]) {
276
+ if (own(state.plans, planKey(command.planId, command.revision))) {
239
277
  return reject(`plan revision ${planKey(command.planId, command.revision)} already exists`);
240
278
  }
241
279
  let maxRevision = 0;
@@ -272,7 +310,7 @@ export function validateCoordinationCommand(state, command) {
272
310
  return reject(ctx.reason);
273
311
  if (!isSteward(state, command.actor))
274
312
  return reject('only a sponsor/coordinator may adopt a plan');
275
- const plan = state.plans[planKey(command.planRef.planId, command.planRef.revision)];
313
+ const plan = own(state.plans, planKey(command.planRef.planId, command.planRef.revision));
276
314
  if (!plan)
277
315
  return reject(`unknown plan revision ${planKey(command.planRef.planId, command.planRef.revision)}`);
278
316
  if (plan.status !== 'proposed')
@@ -303,7 +341,7 @@ export function validateCoordinationCommand(state, command) {
303
341
  return reject(ctx.reason);
304
342
  if (!isSteward(state, command.actor))
305
343
  return reject('only a sponsor/coordinator may reject a plan');
306
- const plan = state.plans[planKey(command.planId, command.revision)];
344
+ const plan = own(state.plans, planKey(command.planId, command.revision));
307
345
  if (!plan)
308
346
  return reject(`unknown plan revision ${planKey(command.planId, command.revision)}`);
309
347
  if (plan.status !== 'proposed')
@@ -331,7 +369,7 @@ export function validateCoordinationCommand(state, command) {
331
369
  return reject(ctx.reason);
332
370
  if (!isSteward(state, command.actor))
333
371
  return reject('only a sponsor/coordinator may invite');
334
- if (state.participations[command.participationId]) {
372
+ if (own(state.participations, command.participationId)) {
335
373
  return reject(`participation ${command.participationId} already exists`);
336
374
  }
337
375
  return {
@@ -356,7 +394,7 @@ export function validateCoordinationCommand(state, command) {
356
394
  const ctx = endeavorContext(state, command.endeavorId);
357
395
  if ('reason' in ctx)
358
396
  return reject(ctx.reason);
359
- const participation = state.participations[command.participationId];
397
+ const participation = own(state.participations, command.participationId);
360
398
  if (!participation)
361
399
  return reject(`unknown participation ${command.participationId}`);
362
400
  if (participation.status !== 'invited')
@@ -385,7 +423,7 @@ export function validateCoordinationCommand(state, command) {
385
423
  const ctx = endeavorContext(state, command.endeavorId);
386
424
  if ('reason' in ctx)
387
425
  return reject(ctx.reason);
388
- const participation = state.participations[command.participationId];
426
+ const participation = own(state.participations, command.participationId);
389
427
  if (!participation)
390
428
  return reject(`unknown participation ${command.participationId}`);
391
429
  if (participation.status !== 'active')
@@ -413,9 +451,9 @@ export function validateCoordinationCommand(state, command) {
413
451
  if (participationStatus(state, command.actor) === 'none') {
414
452
  return reject('contribution proposer must be a participant or invitee');
415
453
  }
416
- if (state.proposals[command.proposalId])
454
+ if (own(state.proposals, command.proposalId))
417
455
  return reject(`proposal ${command.proposalId} already exists`);
418
- const plan = state.plans[planKey(command.planRef.planId, command.planRef.revision)];
456
+ const plan = own(state.plans, planKey(command.planRef.planId, command.planRef.revision));
419
457
  if (!plan)
420
458
  return reject(`unknown plan revision ${planKey(command.planRef.planId, command.planRef.revision)}`);
421
459
  if (command.planRef.hash !== plan.contentHash)
@@ -451,16 +489,18 @@ export function validateCoordinationCommand(state, command) {
451
489
  return reject(ctx.reason);
452
490
  if (!isSteward(state, command.actor))
453
491
  return reject('only a sponsor/coordinator may allocate');
454
- const proposal = state.proposals[command.proposalRef];
492
+ const proposal = own(state.proposals, command.proposalRef);
455
493
  if (!proposal)
456
494
  return reject(`unknown proposal ${command.proposalRef}`);
457
495
  if (proposal.status !== 'open')
458
496
  return reject(`proposal is ${proposal.status}, not open`);
459
- if (state.allocations[command.allocationId])
497
+ if (own(state.allocations, command.allocationId))
460
498
  return reject(`allocation ${command.allocationId} already exists`);
461
499
  if (participationStatus(state, command.participant) === 'none') {
462
500
  return reject('allocated participant must be a participant or invitee');
463
501
  }
502
+ if (command.steps.length === 0)
503
+ return reject('an allocation must name at least one step');
464
504
  const proposed = new Set(proposal.steps);
465
505
  for (const stepId of command.steps) {
466
506
  if (!proposed.has(stepId))
@@ -488,7 +528,7 @@ export function validateCoordinationCommand(state, command) {
488
528
  const ctx = endeavorContext(state, command.endeavorId);
489
529
  if ('reason' in ctx)
490
530
  return reject(ctx.reason);
491
- const allocation = state.allocations[command.allocationRef];
531
+ const allocation = own(state.allocations, command.allocationRef);
492
532
  if (!allocation)
493
533
  return reject(`unknown allocation ${command.allocationRef}`);
494
534
  if (allocation.status !== 'allocated')
@@ -498,7 +538,7 @@ export function validateCoordinationCommand(state, command) {
498
538
  if (participationStatus(state, command.actor) === 'none') {
499
539
  return reject('commitment requires an existing participation or invitation');
500
540
  }
501
- if (state.commitments[command.commitmentId])
541
+ if (own(state.commitments, command.commitmentId))
502
542
  return reject(`commitment ${command.commitmentId} already exists`);
503
543
  const adopted = ctx.endeavor.adoptedPlanRef;
504
544
  if (!adopted)
@@ -506,6 +546,8 @@ export function validateCoordinationCommand(state, command) {
506
546
  if (!samePlanRef(command.planRef, adopted)) {
507
547
  return reject('commitment plan revision hash is stale — commitments bind the adopted revision hash');
508
548
  }
549
+ if (command.steps.length === 0)
550
+ return reject('a commitment must name at least one step');
509
551
  const allocated = new Set(allocation.steps);
510
552
  for (const stepId of command.steps) {
511
553
  if (!allocated.has(stepId))
@@ -513,6 +555,17 @@ export function validateCoordinationCommand(state, command) {
513
555
  }
514
556
  if (command.signature.signer !== command.actor)
515
557
  return reject('commitment signature signer must be the actor');
558
+ // A deadline is what a breach is later judged against: it is an instant, and it is still ahead.
559
+ if (command.bounds?.deadline !== undefined && !(Date.parse(command.bounds.deadline) > atMs)) {
560
+ return reject('a commitment deadline must be an ISO-8601 instant after the commitment itself');
561
+ }
562
+ // THE SIGNED PREIMAGE (spec 445 / REM-8): the hash the participant signed must be THIS commitment's —
563
+ // endeavor, allocation, the exact adopted revision, the steps and the bounds. "Some hash this signer
564
+ // once signed" is not a commitment.
565
+ const expectedPayloadHash = commitmentPayloadHash({ endeavorId: command.endeavorId, allocationRef: command.allocationRef, planRef: command.planRef, steps: command.steps, ...(command.bounds ? { bounds: command.bounds } : {}) });
566
+ if (typeof command.signature.payloadHash !== 'string' || command.signature.payloadHash.toLowerCase() !== expectedPayloadHash) {
567
+ return reject('commitment signature payloadHash is not the canonical commitment payload hash (commitmentPayloadHash) — the signature must be over THIS commitment');
568
+ }
516
569
  return {
517
570
  ok: true,
518
571
  events: [
@@ -537,7 +590,7 @@ export function validateCoordinationCommand(state, command) {
537
590
  const ctx = endeavorContext(state, command.endeavorId);
538
591
  if ('reason' in ctx)
539
592
  return reject(ctx.reason);
540
- const commitment = state.commitments[command.commitmentId];
593
+ const commitment = own(state.commitments, command.commitmentId);
541
594
  if (!commitment)
542
595
  return reject(`unknown commitment ${command.commitmentId}`);
543
596
  if (commitment.status !== 'active')
@@ -565,13 +618,13 @@ export function validateCoordinationCommand(state, command) {
565
618
  return reject(ctx.reason);
566
619
  if (!isSteward(state, command.actor))
567
620
  return reject('only a sponsor/coordinator may reallocate');
568
- const commitment = state.commitments[command.commitmentId];
621
+ const commitment = own(state.commitments, command.commitmentId);
569
622
  if (!commitment)
570
623
  return reject(`unknown commitment ${command.commitmentId}`);
571
624
  if (commitment.status !== 'active' && commitment.status !== 'withdrawn') {
572
625
  return reject(`commitment is ${commitment.status}; only active/withdrawn commitments reallocate`);
573
626
  }
574
- if (state.allocations[command.allocationId])
627
+ if (own(state.allocations, command.allocationId))
575
628
  return reject(`allocation ${command.allocationId} already exists`);
576
629
  if (participationStatus(state, command.participant) === 'none') {
577
630
  return reject('reallocated participant must be a participant or invitee');
@@ -593,6 +646,141 @@ export function validateCoordinationCommand(state, command) {
593
646
  ],
594
647
  };
595
648
  }
649
+ // ═══ Spec 438 §3 ═══════════════════════════════════════════════════════════════════════════════
650
+ case 'AttachRun': {
651
+ const ctx = endeavorContext(state, command.endeavorId);
652
+ if ('reason' in ctx)
653
+ return reject(ctx.reason);
654
+ if (command.runRef.trim().length === 0)
655
+ return reject('attaching a run requires a runRef');
656
+ if (command.actor !== ctx.endeavor.managingPrincipal &&
657
+ participationStatus(state, command.actor) !== 'active') {
658
+ return reject('a run is attached by the managing principal or an active participant');
659
+ }
660
+ const already = own(state.attachedRuns, command.runRef);
661
+ if (already) {
662
+ // IDEMPOTENT, but only for the SAME record. Re-attaching the same run is the same assertion made
663
+ // twice. A different digest under the same runRef is a different claim and is refused rather than
664
+ // silently overwritten — the attached digest is how a reader tells whether it is the same record.
665
+ if (already.recordDigest !== command.recordDigest) {
666
+ return reject(`run ${command.runRef} is already attached with a different record digest`);
667
+ }
668
+ return { ok: true, events: [] };
669
+ }
670
+ return {
671
+ ok: true,
672
+ events: [
673
+ {
674
+ kind: 'RunAttached',
675
+ eventId: eventId(nextRevision, 'RunAttached'),
676
+ occurredAt: at,
677
+ revision: nextRevision,
678
+ endeavorId: command.endeavorId,
679
+ runRef: command.runRef,
680
+ recordDigest: command.recordDigest,
681
+ attachedBy: command.actor,
682
+ },
683
+ ],
684
+ };
685
+ }
686
+ case 'DischargeCommitment': {
687
+ const ctx = endeavorContext(state, command.endeavorId);
688
+ if ('reason' in ctx)
689
+ return reject(ctx.reason);
690
+ const c = own(state.commitments, command.commitmentId);
691
+ if (!c)
692
+ return reject(`unknown commitment ${command.commitmentId}`);
693
+ if (c.status !== 'active')
694
+ return reject(`commitment is ${c.status}; only an active commitment discharges`);
695
+ // The rule that gives a discharge its meaning: it CITES something. Without this a discharge is a
696
+ // participant saying "done", which is exactly the claim the evidence was supposed to support.
697
+ if (command.evidenceRefs.length === 0)
698
+ return reject('a discharge must cite receipt references or a satisfied plan step');
699
+ if (command.actor !== c.participant)
700
+ return reject('only the committing participant may discharge their own commitment');
701
+ // A participant who has WITHDRAWN no longer writes to this endeavor's record (spec 445 / REM-6): what is
702
+ // left of their commitment is the steward's to record as a lapse.
703
+ if (participationStatus(state, command.actor) === 'none') {
704
+ return reject('a discharge is recorded by a current participant — a withdrawn participant\'s commitment is the steward\'s to record as lapsed');
705
+ }
706
+ return {
707
+ ok: true,
708
+ events: [
709
+ {
710
+ kind: 'CommitmentDischarged',
711
+ eventId: eventId(nextRevision, 'CommitmentDischarged'),
712
+ occurredAt: at,
713
+ revision: nextRevision,
714
+ endeavorId: command.endeavorId,
715
+ commitmentId: command.commitmentId,
716
+ evidenceRefs: command.evidenceRefs,
717
+ dischargedBy: command.actor,
718
+ },
719
+ ],
720
+ };
721
+ }
722
+ case 'DeclareBreach': {
723
+ const ctx = endeavorContext(state, command.endeavorId);
724
+ if ('reason' in ctx)
725
+ return reject(ctx.reason);
726
+ const c = own(state.commitments, command.commitmentId);
727
+ if (!c)
728
+ return reject(`unknown commitment ${command.commitmentId}`);
729
+ if (c.status !== 'active')
730
+ return reject(`commitment is ${c.status}; only an active commitment is breached`);
731
+ if (!isSteward(state, command.actor))
732
+ return reject('only a sponsor/coordinator may declare a breach');
733
+ // A BREACH IS A JUDGMENT ABOUT CONDUCT, so it needs a deadline that has actually passed — and a
734
+ // commitment with no deadline has nothing to be late for. Nothing in this reducer DERIVES a breach:
735
+ // the deadline passing is a precondition of the declaration, never the declaration itself.
736
+ if (!c.bounds?.deadline)
737
+ return reject('this commitment has no deadline; there is nothing to have missed');
738
+ if (!(Date.parse(at) > Date.parse(c.bounds.deadline))) {
739
+ return reject(`the deadline ${c.bounds.deadline} has not passed`);
740
+ }
741
+ return {
742
+ ok: true,
743
+ events: [
744
+ {
745
+ kind: 'CommitmentBreached',
746
+ eventId: eventId(nextRevision, 'CommitmentBreached'),
747
+ occurredAt: at,
748
+ revision: nextRevision,
749
+ endeavorId: command.endeavorId,
750
+ commitmentId: command.commitmentId,
751
+ declaredBy: command.actor,
752
+ ...(command.reason ? { reason: command.reason } : {}),
753
+ },
754
+ ],
755
+ };
756
+ }
757
+ case 'RecordLapse': {
758
+ const ctx = endeavorContext(state, command.endeavorId);
759
+ if ('reason' in ctx)
760
+ return reject(ctx.reason);
761
+ const c = own(state.commitments, command.commitmentId);
762
+ if (!c)
763
+ return reject(`unknown commitment ${command.commitmentId}`);
764
+ if (c.status !== 'active')
765
+ return reject(`commitment is ${c.status}; only an active commitment lapses`);
766
+ if (!isSteward(state, command.actor))
767
+ return reject('only a sponsor/coordinator may record a lapse');
768
+ return {
769
+ ok: true,
770
+ events: [
771
+ {
772
+ kind: 'CommitmentLapsed',
773
+ eventId: eventId(nextRevision, 'CommitmentLapsed'),
774
+ occurredAt: at,
775
+ revision: nextRevision,
776
+ endeavorId: command.endeavorId,
777
+ commitmentId: command.commitmentId,
778
+ recordedBy: command.actor,
779
+ ...(command.reason ? { reason: command.reason } : {}),
780
+ },
781
+ ],
782
+ };
783
+ }
596
784
  case 'RecordStepSatisfied': {
597
785
  const ctx = endeavorContext(state, command.endeavorId);
598
786
  if ('reason' in ctx)
@@ -601,10 +789,15 @@ export function validateCoordinationCommand(state, command) {
601
789
  const adopted = ctx.endeavor.adoptedPlanRef;
602
790
  if (!plan || !adopted)
603
791
  return reject('no adopted plan');
604
- if (!plan.steps.some((s) => s.stepId === command.stepId)) {
792
+ const step = plan.steps.find((s) => s.stepId === command.stepId);
793
+ if (!step)
605
794
  return reject(`step ${command.stepId} is not in the adopted plan`);
795
+ // A DECISION step is satisfied by a decision of its DECLARED approvers and by nothing else (spec 393 /
796
+ // spec 445 NAME-12): recorded directly, any participant could clear a checkpoint alone.
797
+ if (step.kind === 'decision') {
798
+ return reject(`step ${command.stepId} is a decision step — it is satisfied only by a decision of its declared approvers (RaiseDecisionRequest → RecordDecision)`);
606
799
  }
607
- if (state.satisfiedSteps[command.stepId])
800
+ if (own(state.satisfiedSteps, command.stepId))
608
801
  return reject(`step ${command.stepId} already satisfied`);
609
802
  if (command.evidenceRefs.length === 0)
610
803
  return reject('step satisfaction requires completion evidence');
@@ -639,10 +832,15 @@ export function validateCoordinationCommand(state, command) {
639
832
  if (!plan.milestones.some((m) => m.milestoneId === command.milestoneId)) {
640
833
  return reject(`milestone ${command.milestoneId} is not in the adopted plan`);
641
834
  }
642
- if (state.milestones[command.milestoneId])
835
+ if (own(state.milestones, command.milestoneId))
643
836
  return reject(`milestone ${command.milestoneId} already achieved`);
644
837
  if (command.evidenceRefs.length === 0)
645
838
  return reject('milestone achievement requires criteria evidence');
839
+ // The same gate as a step (spec 445 / REM-6): the first writer fixes the evidence, so it is not a stranger.
840
+ if (command.actor !== ctx.endeavor.managingPrincipal &&
841
+ participationStatus(state, command.actor) !== 'active') {
842
+ return reject('milestone achievement must be recorded by the managing principal or an active participant');
843
+ }
646
844
  return {
647
845
  ok: true,
648
846
  events: [
@@ -651,6 +849,7 @@ export function validateCoordinationCommand(state, command) {
651
849
  eventId: eventId(nextRevision, 'MilestoneAchieved'),
652
850
  endeavorId: command.endeavorId,
653
851
  milestoneId: command.milestoneId,
852
+ ...(ctx.endeavor.adoptedPlanRef ? { planRef: ctx.endeavor.adoptedPlanRef } : {}),
654
853
  evidenceRefs: command.evidenceRefs,
655
854
  recordedBy: command.actor,
656
855
  occurredAt: at,
@@ -704,7 +903,7 @@ export function validateCoordinationCommand(state, command) {
704
903
  };
705
904
  }
706
905
  case 'ProposeRecommendation': {
707
- if (state.recommendations[command.recommendationId]) {
906
+ if (own(state.recommendations, command.recommendationId)) {
708
907
  return reject(`recommendation ${command.recommendationId} already exists`);
709
908
  }
710
909
  if (command.recommendationKind.trim().length === 0)
@@ -770,8 +969,139 @@ export function validateCoordinationCommand(state, command) {
770
969
  ],
771
970
  };
772
971
  }
972
+ case 'RaiseDecisionRequest': {
973
+ const ctx = endeavorContext(state, command.endeavorId);
974
+ if ('reason' in ctx)
975
+ return reject(ctx.reason);
976
+ // Who may raise: the organization (its managing principal, or a steward acting as it) or an active participant.
977
+ if (command.actor !== ctx.endeavor.managingPrincipal && !isSteward(state, command.actor) && participationStatus(state, command.actor) !== 'active') {
978
+ return reject('only the managing principal, a steward or an active participant may raise a decision');
979
+ }
980
+ if (own(state.decisionRequests, command.decisionId))
981
+ return reject(`decision ${command.decisionId} already raised`);
982
+ const approvers = [...new Set(command.approvers.map((a) => a.toLowerCase()))];
983
+ if (approvers.length === 0)
984
+ return reject('a decision names at least one approver');
985
+ if (!approvers.every((a) => /^0x[0-9a-f]{40}$/.test(a)))
986
+ return reject('an approver is an address');
987
+ if (command.quorum !== undefined && (!Number.isInteger(command.quorum) || command.quorum < 1 || command.quorum > approvers.length))
988
+ return reject('quorum must be between 1 and the number of approvers');
989
+ if (!command.title.trim())
990
+ return reject('a decision has a title');
991
+ // A window is an instant that is still ahead; one that does not parse would never expire (REM-5).
992
+ if (command.dueAt !== undefined && !(Date.parse(command.dueAt) > atMs))
993
+ return reject('dueAt must be an ISO-8601 instant after the request itself');
994
+ const scopedPlanRef = command.stepIds?.length ? ctx.endeavor.adoptedPlanRef : undefined;
995
+ if (command.stepIds?.length) {
996
+ const plan = adoptedPlan(state);
997
+ const known = new Set(plan?.steps.map((st) => st.stepId) ?? []);
998
+ for (const id of command.stepIds)
999
+ if (!known.has(id))
1000
+ return reject(`step ${id} is not in the adopted plan`);
1001
+ // A decision SCOPED TO PLAN STEPS has a consequence — its approval satisfies the plan's checkpoints —
1002
+ // so who may choose its approvers is narrower than who may ask a question (spec 445 / NAME-12): the
1003
+ // organization or a steward raises it, and whoever raises it is not among those who decide it.
1004
+ if (command.actor !== ctx.endeavor.managingPrincipal && !isSteward(state, command.actor)) {
1005
+ return reject('only the managing principal or a steward may raise a decision scoped to plan steps');
1006
+ }
1007
+ if (approvers.includes(command.actor.toLowerCase())) {
1008
+ return reject('the requester of a decision scoped to plan steps is not one of its approvers — a requester never approves their own request');
1009
+ }
1010
+ }
1011
+ const request = {
1012
+ schema: 'apcoord/DecisionRequestV1',
1013
+ decisionId: command.decisionId,
1014
+ endeavorId: command.endeavorId,
1015
+ decisionKind: command.decisionKind.trim() || 'decision',
1016
+ title: command.title.trim(),
1017
+ ...(command.summary?.trim() ? { summary: command.summary.trim() } : {}),
1018
+ requestedBy: command.actor,
1019
+ requirement: { schema: 'apcoord/ApprovalRequirementV1', approvers, ...(command.quorum !== undefined ? { quorum: command.quorum } : {}) },
1020
+ // The scope binds the EXACT plan revision the steps were read from (spec 445 / REM-7): an approval given
1021
+ // for one plan is never read as given for its successor.
1022
+ scope: { ...(command.stepIds?.length ? { stepIds: [...command.stepIds] } : {}), ...(scopedPlanRef ? { planRef: scopedPlanRef } : {}) },
1023
+ requestedAt: at,
1024
+ ...(command.dueAt ? { dueAt: command.dueAt } : {}),
1025
+ status: 'pending',
1026
+ };
1027
+ return { ok: true, events: [{ kind: 'DecisionRequested', eventId: eventId(nextRevision, 'DecisionRequested'), endeavorId: command.endeavorId, decisionId: command.decisionId, request, occurredAt: at, revision: nextRevision }] };
1028
+ }
1029
+ case 'RecordDecision': {
1030
+ const ctx = endeavorContext(state, command.endeavorId);
1031
+ if ('reason' in ctx)
1032
+ return reject(ctx.reason);
1033
+ const request = own(state.decisionRequests, command.decisionId);
1034
+ if (!request)
1035
+ return reject(`unknown decision ${command.decisionId}`);
1036
+ if (request.status !== 'pending')
1037
+ return reject(`decision ${command.decisionId} is already decided — a reversal is a new request`);
1038
+ // Fail closed: a window that cannot be read is a window that has closed (REM-5).
1039
+ if (request.dueAt !== undefined && !(atMs <= Date.parse(request.dueAt)))
1040
+ return reject(`decision ${command.decisionId} expired at ${request.dueAt}`);
1041
+ // THE DECLARED APPROVER, AND ONLY THEM. The managing principal counts when the organization was named
1042
+ // (a steward decides as it — the door set the actor); a steward who is not named, whose organization
1043
+ // is not named, is refused here in those words. Standing is the door's question; naming is this one's.
1044
+ const actor = command.actor.toLowerCase();
1045
+ const named = request.requirement.approvers.includes(actor);
1046
+ if (!named) {
1047
+ const steward = isSteward(state, command.actor);
1048
+ return reject(steward ? `${command.actor} is a steward but not a declared approver of decision ${command.decisionId} — steward standing never substitutes` : `${command.actor} is not a declared approver of decision ${command.decisionId}`);
1049
+ }
1050
+ if (!command.rationale.trim())
1051
+ return reject('a decision carries its rationale');
1052
+ // ON WHOSE BEHALF is not the caller's to choose (spec 445 / COV-1): a record is the actor's own, or the
1053
+ // organization's when a steward decided as it. Anything else is a claim about a third party.
1054
+ if (command.principal !== undefined && command.principal !== command.actor) {
1055
+ const asOrganization = command.principal === ctx.endeavor.managingPrincipal && isSteward(state, command.actor);
1056
+ if (!asOrganization)
1057
+ return reject(`${command.actor} may record a decision on its own behalf, or on the organization's when it is a steward — not on behalf of ${command.principal}`);
1058
+ }
1059
+ const prior = own(state.decisions, command.decisionId) ?? [];
1060
+ if (prior.some((r) => r.actor.toLowerCase() === actor && r.outcome !== 'deferred')) {
1061
+ return reject(`${command.actor} already recorded their decision on ${command.decisionId} — a reversal is a new request`);
1062
+ }
1063
+ const record = {
1064
+ schema: 'apcoord/DecisionRecordV1',
1065
+ decisionId: command.decisionId,
1066
+ requestRef: command.decisionId,
1067
+ actor: command.actor,
1068
+ principal: command.principal ?? command.actor,
1069
+ outcome: command.outcome,
1070
+ rationale: command.rationale.trim(),
1071
+ evidenceRefs: command.evidenceRefs ?? [],
1072
+ scope: { endeavorId: command.endeavorId, ...(request.scope.stepIds?.length ? { stepIds: [...request.scope.stepIds] } : {}) },
1073
+ decidedAt: at,
1074
+ };
1075
+ // THE QUORUM, COUNTED (W2): distinct approvers who approved reach it → approved; the approvals still
1076
+ // possible cannot reach it → rejected; else the request stays pending for the others. A deferral counts
1077
+ // for nothing. Arithmetic over immutable records — the reducer holds no vote.
1078
+ const quorum = request.requirement.quorum ?? 1;
1079
+ const counted = [...prior.filter((r) => r.outcome !== 'deferred'), record];
1080
+ const approved = new Set(counted.filter((r) => r.outcome === 'approved').map((r) => r.actor.toLowerCase())).size;
1081
+ const rejected = new Set(counted.filter((r) => r.outcome === 'rejected').map((r) => r.actor.toLowerCase())).size;
1082
+ const resolution = command.outcome === 'deferred' ? undefined : approved >= quorum ? 'approved' : request.requirement.approvers.length - rejected < quorum ? 'rejected' : undefined;
1083
+ const events = [{ kind: 'DecisionRecorded', eventId: eventId(nextRevision, 'DecisionRecorded'), endeavorId: command.endeavorId, decisionId: command.decisionId, record, ...(resolution ? { resolution } : {}), occurredAt: at, revision: nextRevision }];
1084
+ // A DECLARED CONSEQUENCE (spec 360 / 393 W2): an approval satisfies the DECISION-kind steps the request
1085
+ // was scoped to, citing the record as the evidence — never a contribution step, which is someone's work.
1086
+ if (resolution === 'approved' && request.scope.stepIds?.length) {
1087
+ const plan = adoptedPlan(state);
1088
+ for (const stepId of request.scope.stepIds) {
1089
+ const step = plan?.steps.find((st) => st.stepId === stepId);
1090
+ if (!step || step.kind !== 'decision' || own(state.satisfiedSteps, stepId) || !ctx.endeavor.adoptedPlanRef)
1091
+ continue;
1092
+ // The approval was given for the step AS THE PLAN IT WAS RAISED AGAINST defined it (REM-7). A later
1093
+ // revision that redefined the step under the same id is not what was approved; a request with no
1094
+ // bound revision (a log that predates the binding) satisfies nothing — raise it again.
1095
+ if (!sameContent(stepIn(state, request.scope.planRef, stepId), step))
1096
+ continue;
1097
+ const rev = nextRevision + events.length;
1098
+ events.push({ kind: 'PlanStepSatisfied', eventId: eventId(rev, 'PlanStepSatisfied'), endeavorId: command.endeavorId, stepId, planRef: ctx.endeavor.adoptedPlanRef, evidenceRefs: [{ kind: 'resource', iri: `urn:ap:decision:${command.decisionId}` }], recordedBy: command.actor, occurredAt: at, revision: rev });
1099
+ }
1100
+ }
1101
+ return { ok: true, events };
1102
+ }
773
1103
  case 'ResolveRecommendation': {
774
- const rec = state.recommendations[command.recommendationId];
1104
+ const rec = own(state.recommendations, command.recommendationId);
775
1105
  if (!rec)
776
1106
  return reject(`unknown recommendation ${command.recommendationId}`);
777
1107
  if (rec.status !== 'proposed')
@@ -816,7 +1146,16 @@ export function validateCoordinationCommand(state, command) {
816
1146
  return reject(`unknown command kind ${command.kind ?? '<none>'}`);
817
1147
  }
818
1148
  }
1149
+ /** Apply one event. The ONLY state-transition path; also advances the log's clock (`lastEventAt`, REM-5). */
819
1150
  export function applyCoordinationEvent(state, event) {
1151
+ const next = applyEvent(state, event);
1152
+ const occurred = Date.parse(event.occurredAt);
1153
+ if (Number.isNaN(occurred))
1154
+ return next;
1155
+ const prior = state.lastEventAt !== undefined ? Date.parse(state.lastEventAt) : Number.NaN;
1156
+ return { ...next, lastEventAt: Number.isNaN(prior) || occurred >= prior ? event.occurredAt : state.lastEventAt };
1157
+ }
1158
+ function applyEvent(state, event) {
820
1159
  if (event.revision !== state.revision + 1) {
821
1160
  throw new CoordinationEventError(`non-monotonic revision: state at ${state.revision}, event ${event.kind} carries ${event.revision}`);
822
1161
  }
@@ -896,26 +1235,44 @@ export function applyCoordinationEvent(state, event) {
896
1235
  }
897
1236
  case 'PlanAdopted': {
898
1237
  const key = planKey(event.planRef.planId, event.planRef.revision);
899
- const plan = state.plans[key];
1238
+ const plan = own(state.plans, key);
900
1239
  if (!plan)
901
1240
  throw new CoordinationEventError(`PlanAdopted for unknown plan revision ${key}`);
902
1241
  const plans = { ...state.plans, [key]: { ...plan, status: 'adopted' } };
903
1242
  if (event.supersededPlanRef) {
904
1243
  const priorKey = planKey(event.supersededPlanRef.planId, event.supersededPlanRef.revision);
905
- const prior = plans[priorKey];
1244
+ const prior = own(plans, priorKey);
906
1245
  if (prior)
907
1246
  plans[priorKey] = { ...prior, status: 'superseded' };
908
1247
  }
1248
+ // SATISFACTION DOES NOT SURVIVE A CHANGE OF MEANING (spec 445 / REM-7). A step or milestone recorded
1249
+ // under the prior revision stays recorded only when the NEW revision defines it byte-for-byte the same
1250
+ // (RFC 8785); one the new plan redefined — or dropped — is cleared, so an approval or a completion given
1251
+ // for one plan never reads as given for its successor. The events stay in the log.
1252
+ const satisfiedSteps = {};
1253
+ for (const [stepId, rec] of Object.entries(state.satisfiedSteps)) {
1254
+ if (sameContent(stepIn(state, rec.planRef, stepId), plan.steps.find((s) => s.stepId === stepId)))
1255
+ satisfiedSteps[stepId] = rec;
1256
+ }
1257
+ const milestones = {};
1258
+ for (const [milestoneId, rec] of Object.entries(state.milestones)) {
1259
+ const ref = rec.planRef ?? event.supersededPlanRef;
1260
+ const priorPlan = ref ? own(state.plans, planKey(ref.planId, ref.revision)) : undefined;
1261
+ if (sameContent(priorPlan?.milestones.find((m) => m.milestoneId === milestoneId), plan.milestones.find((m) => m.milestoneId === milestoneId)))
1262
+ milestones[milestoneId] = rec;
1263
+ }
909
1264
  return {
910
1265
  ...state,
911
1266
  revision: event.revision,
912
1267
  endeavor: { ...endeavorAt(event.revision), adoptedPlanRef: event.planRef, lifecycle: 'active' },
913
1268
  plans,
1269
+ satisfiedSteps,
1270
+ milestones,
914
1271
  };
915
1272
  }
916
1273
  case 'PlanRejected': {
917
1274
  const key = planKey(event.planId, event.planRevision);
918
- const plan = state.plans[key];
1275
+ const plan = own(state.plans, key);
919
1276
  if (!plan)
920
1277
  throw new CoordinationEventError(`PlanRejected for unknown plan revision ${key}`);
921
1278
  return {
@@ -964,7 +1321,7 @@ export function applyCoordinationEvent(state, event) {
964
1321
  };
965
1322
  }
966
1323
  case 'ParticipationWithdrawn': {
967
- const participation = state.participations[event.participationId];
1324
+ const participation = own(state.participations, event.participationId);
968
1325
  if (!participation) {
969
1326
  throw new CoordinationEventError(`ParticipationWithdrawn for unknown participation ${event.participationId}`);
970
1327
  }
@@ -1002,7 +1359,7 @@ export function applyCoordinationEvent(state, event) {
1002
1359
  };
1003
1360
  }
1004
1361
  case 'ContributionAllocated': {
1005
- const proposal = state.proposals[event.proposalRef];
1362
+ const proposal = own(state.proposals, event.proposalRef);
1006
1363
  if (!proposal)
1007
1364
  throw new CoordinationEventError(`ContributionAllocated for unknown proposal ${event.proposalRef}`);
1008
1365
  const allocation = {
@@ -1024,8 +1381,54 @@ export function applyCoordinationEvent(state, event) {
1024
1381
  allocations: { ...state.allocations, [event.allocationId]: allocation },
1025
1382
  };
1026
1383
  }
1384
+ case 'RunAttached': {
1385
+ // Idempotent by runRef: attaching the same run twice is the same assertion, not two.
1386
+ return {
1387
+ ...state,
1388
+ revision: event.revision,
1389
+ endeavor: endeavorAt(event.revision),
1390
+ attachedRuns: {
1391
+ ...state.attachedRuns,
1392
+ [event.runRef]: { runRef: event.runRef, recordDigest: event.recordDigest, attachedBy: event.attachedBy, attachedAt: event.occurredAt },
1393
+ },
1394
+ };
1395
+ }
1396
+ case 'CommitmentDischarged': {
1397
+ const c = own(state.commitments, event.commitmentId);
1398
+ if (!c)
1399
+ throw new CoordinationEventError(`CommitmentDischarged for unknown commitment ${event.commitmentId}`);
1400
+ // `fulfilled` is the state the reducer has always persisted; discharge is the act that reaches it.
1401
+ return {
1402
+ ...state,
1403
+ revision: event.revision,
1404
+ endeavor: endeavorAt(event.revision),
1405
+ commitments: { ...state.commitments, [event.commitmentId]: { ...c, status: 'fulfilled' } },
1406
+ };
1407
+ }
1408
+ case 'CommitmentBreached': {
1409
+ const c = own(state.commitments, event.commitmentId);
1410
+ if (!c)
1411
+ throw new CoordinationEventError(`CommitmentBreached for unknown commitment ${event.commitmentId}`);
1412
+ return {
1413
+ ...state,
1414
+ revision: event.revision,
1415
+ endeavor: endeavorAt(event.revision),
1416
+ commitments: { ...state.commitments, [event.commitmentId]: { ...c, status: 'breached' } },
1417
+ };
1418
+ }
1419
+ case 'CommitmentLapsed': {
1420
+ const c = own(state.commitments, event.commitmentId);
1421
+ if (!c)
1422
+ throw new CoordinationEventError(`CommitmentLapsed for unknown commitment ${event.commitmentId}`);
1423
+ return {
1424
+ ...state,
1425
+ revision: event.revision,
1426
+ endeavor: endeavorAt(event.revision),
1427
+ commitments: { ...state.commitments, [event.commitmentId]: { ...c, status: 'lapsed' } },
1428
+ };
1429
+ }
1027
1430
  case 'ContributionCommitted': {
1028
- const allocation = state.allocations[event.allocationRef];
1431
+ const allocation = own(state.allocations, event.allocationRef);
1029
1432
  if (!allocation)
1030
1433
  throw new CoordinationEventError(`ContributionCommitted for unknown allocation ${event.allocationRef}`);
1031
1434
  const commitment = {
@@ -1049,7 +1452,7 @@ export function applyCoordinationEvent(state, event) {
1049
1452
  };
1050
1453
  }
1051
1454
  case 'CommitmentWithdrawn': {
1052
- const commitment = state.commitments[event.commitmentId];
1455
+ const commitment = own(state.commitments, event.commitmentId);
1053
1456
  if (!commitment)
1054
1457
  throw new CoordinationEventError(`CommitmentWithdrawn for unknown commitment ${event.commitmentId}`);
1055
1458
  return {
@@ -1060,10 +1463,10 @@ export function applyCoordinationEvent(state, event) {
1060
1463
  };
1061
1464
  }
1062
1465
  case 'ContributionReallocated': {
1063
- const commitment = state.commitments[event.commitmentId];
1466
+ const commitment = own(state.commitments, event.commitmentId);
1064
1467
  if (!commitment)
1065
1468
  throw new CoordinationEventError(`ContributionReallocated for unknown commitment ${event.commitmentId}`);
1066
- const priorAllocation = state.allocations[commitment.allocationRef];
1469
+ const priorAllocation = own(state.allocations, commitment.allocationRef);
1067
1470
  if (!priorAllocation) {
1068
1471
  throw new CoordinationEventError(`ContributionReallocated: commitment ${event.commitmentId} references unknown allocation ${commitment.allocationRef}`);
1069
1472
  }
@@ -1107,6 +1510,7 @@ export function applyCoordinationEvent(state, event) {
1107
1510
  schema: 'apcoord/MilestoneAchievementV1',
1108
1511
  milestoneId: event.milestoneId,
1109
1512
  endeavorId: event.endeavorId,
1513
+ ...(event.planRef ? { planRef: event.planRef } : {}),
1110
1514
  evidenceRefs: event.evidenceRefs,
1111
1515
  achievedAt: event.occurredAt,
1112
1516
  };
@@ -1129,6 +1533,20 @@ export function applyCoordinationEvent(state, event) {
1129
1533
  revision: event.revision,
1130
1534
  endeavor: { ...endeavorAt(event.revision), lifecycle: 'abandoned' },
1131
1535
  };
1536
+ case 'DecisionRequested':
1537
+ return { ...state, revision: event.revision, endeavor: endeavorAt(event.revision), decisionRequests: { ...state.decisionRequests, [event.decisionId]: event.request } };
1538
+ case 'DecisionRecorded': {
1539
+ const request = own(state.decisionRequests, event.decisionId);
1540
+ if (!request)
1541
+ throw new CoordinationEventError(`DecisionRecorded for unknown decision ${event.decisionId}`);
1542
+ return {
1543
+ ...state,
1544
+ revision: event.revision,
1545
+ endeavor: endeavorAt(event.revision),
1546
+ decisionRequests: { ...state.decisionRequests, [event.decisionId]: event.resolution ? { ...request, status: 'decided', outcome: event.resolution } : request },
1547
+ decisions: { ...state.decisions, [event.decisionId]: [...(own(state.decisions, event.decisionId) ?? []), event.record] },
1548
+ };
1549
+ }
1132
1550
  case 'RecommendationProposed':
1133
1551
  return {
1134
1552
  ...state,
@@ -1137,7 +1555,7 @@ export function applyCoordinationEvent(state, event) {
1137
1555
  };
1138
1556
  case 'RecommendationAccepted':
1139
1557
  case 'RecommendationRejected': {
1140
- const rec = state.recommendations[event.recommendationId];
1558
+ const rec = own(state.recommendations, event.recommendationId);
1141
1559
  if (!rec)
1142
1560
  throw new CoordinationEventError(`${event.kind} for unknown recommendation ${event.recommendationId}`);
1143
1561
  return {