@unson/brainbase-mcp 0.50.31 → 0.51.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.
Files changed (51) hide show
  1. package/contracts/canonical-task/store-schema.sql +3 -0
  2. package/dist/automation-run.js +3 -2
  3. package/dist/canonical-task-postgres.js +3 -0
  4. package/dist/canonical-task-service.d.ts +6 -0
  5. package/dist/canonical-task-service.js +40 -1
  6. package/dist/company-os-learning-adoption.d.ts +9 -0
  7. package/dist/company-os-learning-adoption.js +50 -1
  8. package/dist/durable-waits.d.ts +30 -0
  9. package/dist/durable-waits.js +100 -94
  10. package/dist/foundation-public-provider.d.ts +3 -1
  11. package/dist/foundation-public-provider.js +2 -2
  12. package/dist/graph-corrections.d.ts +46 -1
  13. package/dist/graph-corrections.js +172 -1
  14. package/dist/judgment-event-outbox.d.ts +24 -2
  15. package/dist/judgment-event-outbox.js +92 -10
  16. package/dist/judgment-frame.js +2 -2
  17. package/dist/judgment-host.d.ts +4 -1
  18. package/dist/judgment-host.js +126 -14
  19. package/dist/judgment-task-progress.d.ts +41 -0
  20. package/dist/judgment-task-progress.js +18 -0
  21. package/dist/knowledge-continuation.js +7 -1
  22. package/dist/knowledge-lookup.js +43 -58
  23. package/dist/mcp-runtime.d.ts +9 -0
  24. package/dist/mcp-runtime.js +12 -4
  25. package/dist/meeting-automation-runtime.d.ts +52 -0
  26. package/dist/meeting-automation-runtime.js +46 -0
  27. package/dist/queue-task-tools.js +2 -2
  28. package/dist/routine-liveness.js +0 -1
  29. package/dist/routine-runtime.js +1 -1
  30. package/dist/server.d.ts +59 -85
  31. package/dist/server.js +44 -36
  32. package/dist/ssot.js +1 -1
  33. package/dist/testing/queue-task-tools-contract.js +1 -1
  34. package/dist/world-model-impact-index.d.ts +132 -0
  35. package/dist/world-model-impact-index.js +901 -0
  36. package/package.json +6 -18
  37. package/ui/judgment-history.css +13 -0
  38. package/ui/objective-editor.css +19 -2
  39. package/ui/objective-editor.js +6 -3
  40. package/ui/project-workspace.css +33 -26
  41. package/ui/workspace-kit.js +9 -7
  42. package/ui/world/world-view.css +65 -46
  43. package/ui/world/world-view.js +27 -18
  44. package/dist/execution-authority-http.d.ts +0 -30
  45. package/dist/execution-authority-http.js +0 -454
  46. package/dist/execution-authority.d.ts +0 -282
  47. package/dist/execution-authority.js +0 -867
  48. package/dist/resource-reservation-http.d.ts +0 -31
  49. package/dist/resource-reservation-http.js +0 -371
  50. package/dist/resource-reservations.d.ts +0 -221
  51. package/dist/resource-reservations.js +0 -577
@@ -137,3 +137,6 @@ CREATE INDEX IF NOT EXISTS canonical_tasks_project_codes_idx
137
137
  ON canonical_tasks USING GIN (project_codes);
138
138
  CREATE INDEX IF NOT EXISTS canonical_tasks_claimed_by_until_idx
139
139
  ON canonical_tasks (claimed_by, claimed_until) WHERE claimed_by IS NOT NULL;
140
+
141
+ -- Planned start of the work; NULL when unplanned. Additive so older rows and callers stay valid.
142
+ ALTER TABLE canonical_tasks ADD COLUMN IF NOT EXISTS start_at TIMESTAMPTZ;
@@ -345,14 +345,15 @@ export class AutomationRunService {
345
345
  }
346
346
  let phase = 'claimed';
347
347
  try {
348
+ // The runner has not been invoked yet, so a failed host checkpoint leaves
349
+ // the run safe to retry. The phase stays claimed and release marks it
350
+ // retryable.
348
351
  if (lifecycle?.checkpoint) {
349
- phase = 'unknown';
350
352
  await lifecycle.checkpoint({
351
353
  ...preparedLifecycleInput(),
352
354
  phase: 'claimed',
353
355
  claimToken: claim.claimToken
354
356
  });
355
- phase = 'claimed';
356
357
  }
357
358
  // The marker is durable and precedes the external call. If it fails, the
358
359
  // state is unknown and must never be made retryable automatically.
@@ -10,6 +10,7 @@ const MUTABLE_COLUMNS = Object.freeze({
10
10
  priority: 'priority',
11
11
  assignee_person_id: 'assignee_person_id',
12
12
  assignee_display_name: 'assignee_display_name',
13
+ start_at: 'start_at',
13
14
  due_at: 'due_at',
14
15
  waiting_on: 'waiting_on',
15
16
  waiting_on_person_id: 'waiting_on_person_id',
@@ -247,6 +248,7 @@ export class CanonicalTaskPostgresRepository {
247
248
  completion_contract: row.completion_contract ?? null,
248
249
  assignee_person_id: row.assignee_person_id ?? null,
249
250
  assignee_display_name: row.assignee_display_name ?? null,
251
+ start_at: isoOrNull(row.start_at),
250
252
  due_at: isoOrNull(row.due_at),
251
253
  waiting_on: row.waiting_on ?? null,
252
254
  waiting_on_person_id: row.waiting_on_person_id ?? null,
@@ -452,6 +454,7 @@ export class CanonicalTaskPostgresRepository {
452
454
  // database where an additive column has not been added yet.
453
455
  ...(input.purpose_label != null ? [['purpose_label', input.purpose_label]] : []),
454
456
  ...(input.waiting_on_person_id != null ? [['waiting_on_person_id', input.waiting_on_person_id]] : []),
457
+ ...(input.start_at != null ? [['start_at', input.start_at]] : []),
455
458
  ...(input.completion_contract != null
456
459
  ? [['completion_contract', JSON.stringify(input.completion_contract), '::jsonb']]
457
460
  : []),
@@ -36,6 +36,8 @@ export interface CanonicalTaskRecord extends JsonRecord {
36
36
  priority: CanonicalTaskPriority;
37
37
  assignee_person_id?: string | null;
38
38
  assignee_display_name?: string | null;
39
+ /** When work is planned to begin; null when unplanned. Never later than due_at. */
40
+ start_at?: string | null;
39
41
  due_at?: string | null;
40
42
  waiting_on?: string | null;
41
43
  /** The Graph person a waiting task waits on; null when it waits on a condition or nobody in particular. */
@@ -61,6 +63,8 @@ export interface CanonicalTaskCreateInput extends JsonRecord {
61
63
  description?: string | null;
62
64
  priority?: CanonicalTaskPriority | string | null;
63
65
  assignee_person_id?: string | null;
66
+ /** When work is planned to begin; null when unplanned. Never later than due_at. */
67
+ start_at?: string | null;
64
68
  due_at?: string | null;
65
69
  waiting_on?: string | null;
66
70
  waiting_on_person_id?: string | null;
@@ -75,6 +79,8 @@ export interface CanonicalTaskUpdateInput extends JsonRecord {
75
79
  description?: string | null;
76
80
  priority?: CanonicalTaskPriority | string | null;
77
81
  assignee_person_id?: string | null;
82
+ /** When work is planned to begin; null when unplanned. Never later than due_at. */
83
+ start_at?: string | null;
78
84
  due_at?: string | null;
79
85
  waiting_on?: string | null;
80
86
  waiting_on_person_id?: string | null;
@@ -39,6 +39,7 @@ const CREATE_FIELDS = new Set([
39
39
  'description',
40
40
  'priority',
41
41
  'assignee_person_id',
42
+ 'start_at',
42
43
  'due_at',
43
44
  'waiting_on',
44
45
  'waiting_on_person_id',
@@ -54,6 +55,7 @@ const MUTABLE_FIELDS = new Set([
54
55
  'description',
55
56
  'priority',
56
57
  'assignee_person_id',
58
+ 'start_at',
57
59
  'due_at',
58
60
  'waiting_on',
59
61
  'waiting_on_person_id',
@@ -129,10 +131,28 @@ function normalizeCompletionContract(value) {
129
131
  });
130
132
  return { goal, criteria };
131
133
  }
134
+ function assertStartNotAfterDue(startAt, dueAt) {
135
+ if (startAt && dueAt && Date.parse(startAt) > Date.parse(dueAt)) {
136
+ fail('validation_error', 'start_at must not be later than due_at', 400, { fields: ['start_at', 'due_at'] });
137
+ }
138
+ }
132
139
  function normalizeIsoDate(value, field) {
133
140
  const text = normalizeString(value, field);
134
141
  if (text == null)
135
142
  return null;
143
+ if (field === 'start_at') {
144
+ const parts = /^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(text);
145
+ if (!parts)
146
+ fail('validation_error', `${field} must be an ISO date`, 400, { field });
147
+ const year = Number(parts[1]);
148
+ const month = Number(parts[2]);
149
+ const day = Number(parts[3]);
150
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
151
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
152
+ if (month < 1 || month > 12 || day < 1 || day > days[month - 1]) {
153
+ fail('validation_error', `${field} must be a valid calendar date`, 400, { field });
154
+ }
155
+ }
136
156
  const date = new Date(text);
137
157
  if (Number.isNaN(date.getTime()))
138
158
  fail('validation_error', `${field} must be an ISO date`, 400, { field });
@@ -809,8 +829,14 @@ export class CanonicalTaskService {
809
829
  const wasApplied = (candidate) => candidate.version === expectedVersion + 1
810
830
  && candidate._last_operation_key === operation
811
831
  && candidate._last_operation_fingerprint === operationFingerprint;
832
+ const assertEffectiveDates = (candidate) => {
833
+ if ('start_at' in input.patch || 'due_at' in input.patch) {
834
+ assertStartNotAfterDue(('start_at' in input.patch ? input.patch.start_at : candidate.start_at), ('due_at' in input.patch ? input.patch.due_at : candidate.due_at));
835
+ }
836
+ };
812
837
  if (!wasApplied(current)) {
813
838
  this.assertVersion(current, expectedVersion);
839
+ assertEffectiveDates(current);
814
840
  if (input.transitionStatus && !canTransitionCanonicalTaskStatus(current.status, input.transitionStatus)) {
815
841
  throw new CanonicalTaskError('invalid_transition', `Cannot transition task from ${current.status} to ${input.transitionStatus}`, 409, {
816
842
  from: current.status,
@@ -828,6 +854,7 @@ export class CanonicalTaskService {
828
854
  if (wasApplied(latest))
829
855
  return { recovered: true, result: this.normalizeResponse(latest) };
830
856
  this.assertVersion(latest, expectedVersion);
857
+ assertEffectiveDates(latest);
831
858
  if (input.transitionStatus && !canTransitionCanonicalTaskStatus(latest.status, input.transitionStatus)) {
832
859
  throw new CanonicalTaskError('invalid_transition', `Cannot transition task from ${latest.status} to ${input.transitionStatus}`, 409, {
833
860
  from: latest.status,
@@ -845,6 +872,7 @@ export class CanonicalTaskService {
845
872
  if (wasApplied(latest))
846
873
  return this.normalizeResponse(latest);
847
874
  this.assertVersion(latest, expectedVersion);
875
+ assertEffectiveDates(latest);
848
876
  if (input.transitionStatus && !canTransitionCanonicalTaskStatus(latest.status, input.transitionStatus)) {
849
877
  throw new CanonicalTaskError('invalid_transition', `Cannot transition task from ${latest.status} to ${input.transitionStatus}`, 409, {
850
878
  from: latest.status,
@@ -933,6 +961,9 @@ export class CanonicalTaskService {
933
961
  const purposeLabel = normalizePurposeLabel(input.purpose_label);
934
962
  const waitingOnPersonId = normalizeWaitingOnPersonId(input.waiting_on_person_id);
935
963
  const completionContract = normalizeCompletionContract(input.completion_contract);
964
+ const startAt = normalizeIsoDate(input.start_at, 'start_at');
965
+ const dueAt = normalizeIsoDate(input.due_at, 'due_at');
966
+ assertStartNotAfterDue(startAt, dueAt);
936
967
  return {
937
968
  record_kind: recordKind,
938
969
  ...(input.ledger_attributes != null ? { ledger_attributes: input.ledger_attributes } : {}),
@@ -942,13 +973,15 @@ export class CanonicalTaskService {
942
973
  description: normalizeString(input.description, 'description', { max: 10000, multiline: true }),
943
974
  priority,
944
975
  assignee_person_id: normalizeString(input.assignee_person_id, 'assignee_person_id', { max: 200 }),
945
- due_at: normalizeIsoDate(input.due_at, 'due_at'),
976
+ due_at: dueAt,
946
977
  waiting_on: normalizeString(input.waiting_on, 'waiting_on', { max: 500 }),
947
978
  review_at: normalizeIsoDate(input.review_at, 'review_at'),
948
979
  source_refs: normalizeSourceRefs(input.source_refs) ?? [],
949
980
  project_codes: normalizeProjectCodes(input.project_codes) ?? [],
950
981
  // Only a label that is there is written, so a store without the column still accepts unlabelled work.
951
982
  ...(purposeLabel ? { purpose_label: purposeLabel } : {}),
983
+ // Likewise only a start date that is there is written.
984
+ ...(startAt ? { start_at: startAt } : {}),
952
985
  // Likewise only a person that is there is written.
953
986
  ...(waitingOnPersonId ? { waiting_on_person_id: waitingOnPersonId } : {}),
954
987
  };
@@ -988,8 +1021,12 @@ export class CanonicalTaskService {
988
1021
  }
989
1022
  if ('assignee_person_id' in input)
990
1023
  patch.assignee_person_id = normalizeString(input.assignee_person_id, 'assignee_person_id', { max: 200 });
1024
+ if ('start_at' in input)
1025
+ patch.start_at = normalizeIsoDate(input.start_at, 'start_at');
991
1026
  if ('due_at' in input)
992
1027
  patch.due_at = normalizeIsoDate(input.due_at, 'due_at');
1028
+ if ('start_at' in patch && 'due_at' in patch)
1029
+ assertStartNotAfterDue(patch.start_at, patch.due_at);
993
1030
  if ('waiting_on' in input)
994
1031
  patch.waiting_on = normalizeString(input.waiting_on, 'waiting_on', { max: 500 });
995
1032
  if ('waiting_on_person_id' in input)
@@ -1198,6 +1235,8 @@ export class CanonicalTaskService {
1198
1235
  response.description = null;
1199
1236
  if (response.assignee_person_id === undefined)
1200
1237
  response.assignee_person_id = null;
1238
+ if (response.start_at === undefined)
1239
+ response.start_at = null;
1201
1240
  if (response.due_at === undefined)
1202
1241
  response.due_at = null;
1203
1242
  if (response.waiting_on === undefined)
@@ -54,6 +54,11 @@ export interface LearningEvaluationReference {
54
54
  readonly id: string;
55
55
  readonly digest: string;
56
56
  }
57
+ export interface LearningCompetingModel {
58
+ readonly ref?: string;
59
+ readonly hypothesis: string;
60
+ readonly comparison: string;
61
+ }
57
62
  export interface LearningCandidateInput {
58
63
  readonly id: string;
59
64
  readonly sourceEvaluationRef: LearningEvaluationReference;
@@ -65,6 +70,10 @@ export interface LearningCandidateInput {
65
70
  readonly uncertainty: readonly string[];
66
71
  readonly applicability: FoundationScope;
67
72
  readonly createdAt: string;
73
+ /** Explicit refutation record IDs from the prior model revision addressed by this candidate. */
74
+ readonly addressedRefutationIds?: readonly string[];
75
+ /** Comparison notes against competing world models or alternative hypotheses. */
76
+ readonly competingModels?: readonly LearningCompetingModel[];
68
77
  }
69
78
  export interface LearningCandidate extends LearningCandidateInput {
70
79
  readonly version: typeof COMPANY_OS_LEARNING_ADOPTION_RECORD_CATALOG_VERSION;
@@ -241,6 +241,8 @@ class GraphCompanyOsLearningAdoptionStore {
241
241
  counterexamples: [...input.counterexamples],
242
242
  uncertainty: [...input.uncertainty],
243
243
  applicability: cloneJson(input.applicability),
244
+ ...(input.addressedRefutationIds !== undefined ? { addressedRefutationIds: [...input.addressedRefutationIds] } : {}),
245
+ ...(input.competingModels !== undefined ? { competingModels: cloneJson(input.competingModels) } : {}),
244
246
  digest: ''
245
247
  };
246
248
  const completeCandidate = { ...candidate, digest: digestLearningRecord({ ...candidate, digest: '' }) };
@@ -642,6 +644,12 @@ function normalizeCandidateInput(request) {
642
644
  const uncertainty = normalizeTextArray(request.uncertainty, 'uncertainty', true);
643
645
  const applicability = normalizeScope(request.applicability);
644
646
  requireTimestamp(request.createdAt, 'createdAt');
647
+ const addressedRefutationIds = request.addressedRefutationIds === undefined
648
+ ? undefined
649
+ : normalizeTextArray(request.addressedRefutationIds, 'addressedRefutationIds', false);
650
+ const competingModels = request.competingModels === undefined
651
+ ? undefined
652
+ : normalizeCompetingModels(request.competingModels);
645
653
  return {
646
654
  id: request.id,
647
655
  sourceEvaluationRef,
@@ -651,9 +659,35 @@ function normalizeCandidateInput(request) {
651
659
  counterexamples,
652
660
  uncertainty,
653
661
  applicability,
654
- createdAt: request.createdAt
662
+ createdAt: request.createdAt,
663
+ ...(addressedRefutationIds !== undefined ? { addressedRefutationIds } : {}),
664
+ ...(competingModels !== undefined ? { competingModels } : {})
655
665
  };
656
666
  }
667
+ function normalizeCompetingModels(value) {
668
+ if (!Array.isArray(value)) {
669
+ throw new CompanyOsLearningAdoptionError('invalid_input', 'competingModels must be an array');
670
+ }
671
+ return value.map((item, index) => {
672
+ if (!isRecord(item)) {
673
+ throw new CompanyOsLearningAdoptionError('invalid_input', `competingModels[${index}] must be an object`);
674
+ }
675
+ if (item.ref !== undefined && !isNonEmptyString(item.ref)) {
676
+ throw new CompanyOsLearningAdoptionError('invalid_input', `competingModels[${index}].ref must be a non-empty string when provided`);
677
+ }
678
+ if (!isNonEmptyString(item.hypothesis)) {
679
+ throw new CompanyOsLearningAdoptionError('invalid_input', `competingModels[${index}].hypothesis is required`);
680
+ }
681
+ if (!isNonEmptyString(item.comparison)) {
682
+ throw new CompanyOsLearningAdoptionError('invalid_input', `competingModels[${index}].comparison is required`);
683
+ }
684
+ return {
685
+ ...(item.ref !== undefined ? { ref: item.ref } : {}),
686
+ hypothesis: item.hypothesis,
687
+ comparison: item.comparison
688
+ };
689
+ });
690
+ }
657
691
  function normalizeValidationInput(request) {
658
692
  requireId(request.id, 'validation id');
659
693
  const candidateRef = normalizeRecordReference(request.candidateRef, 'candidateRef');
@@ -907,6 +941,8 @@ function assertLedger(value) {
907
941
  uniqueIds(value.runUses, 'run-use');
908
942
  for (const candidate of value.candidates) {
909
943
  if (!isRecord(candidate) || candidate.version !== 1 || !isNonEmptyString(candidate.id) || !isDigest(candidate.digest)
944
+ || !isOptionalStringArrayShape(candidate.addressedRefutationIds)
945
+ || !isOptionalCompetingModelsShape(candidate.competingModels)
910
946
  || digestLearningRecord({ ...candidate, digest: '' }) !== candidate.digest)
911
947
  throw new CompanyOsLearningAdoptionError('corrupt_record', 'Learning candidate digest or shape is invalid');
912
948
  }
@@ -931,6 +967,19 @@ function assertLedger(value) {
931
967
  throw new CompanyOsLearningAdoptionError('corrupt_record', 'Learning run-use digest or shape is invalid');
932
968
  }
933
969
  }
970
+ function isOptionalStringArrayShape(value) {
971
+ return value === undefined || (Array.isArray(value) && value.every(isNonEmptyString));
972
+ }
973
+ function isOptionalCompetingModelsShape(value) {
974
+ if (value === undefined)
975
+ return true;
976
+ if (!Array.isArray(value))
977
+ return false;
978
+ return value.every((item) => (isRecord(item)
979
+ && (item.ref === undefined || isNonEmptyString(item.ref))
980
+ && isNonEmptyString(item.hypothesis)
981
+ && isNonEmptyString(item.comparison)));
982
+ }
934
983
  function isRunReceiptReferenceShape(value) {
935
984
  return isRecord(value) && isNonEmptyString(value.id) && isDigest(value.digest);
936
985
  }
@@ -72,6 +72,36 @@ export interface DurableWaitHistoryEntry {
72
72
  readonly detail?: string;
73
73
  readonly responsible?: DurableWaitResponsible;
74
74
  }
75
+ export interface DurableWaitTransitionRule {
76
+ /** States the action may start from. Empty only for `create`, which has no record yet. */
77
+ readonly from: readonly DurableWaitState[];
78
+ readonly to: readonly DurableWaitState[];
79
+ }
80
+ /**
81
+ * The wait state machine, written down once. Every state write goes through
82
+ * `transitionWait`, which refuses a step this table does not list.
83
+ *
84
+ * - `resumed`, `effect_confirmed`, `failed` and `cancelled` have no way out.
85
+ * - No action moves a wait to `failed` or `cancelled`; they stay in the type
86
+ * and are still read from a stored ledger.
87
+ * - `claim` from `claimed` is only reachable for a record that is `claimed`
88
+ * without a claim, which normal operation never writes. It is kept so a
89
+ * hand-edited ledger does not become stuck.
90
+ */
91
+ export declare const DURABLE_WAIT_TRANSITIONS: Readonly<Record<DurableWaitHistoryAction, DurableWaitTransitionRule>>;
92
+ export interface DurableWaitTransitionStep {
93
+ readonly action: Exclude<DurableWaitHistoryAction, 'create'>;
94
+ readonly to: DurableWaitState;
95
+ readonly at: string;
96
+ readonly principal: string;
97
+ readonly detail?: string;
98
+ readonly responsible?: DurableWaitResponsible;
99
+ }
100
+ /**
101
+ * The only writer of a wait's state after `create`. State, update time and the
102
+ * history entry come from the same step, so they cannot disagree.
103
+ */
104
+ export declare function transitionWait(record: DurableWaitRecord, step: DurableWaitTransitionStep, changes?: Partial<Omit<DurableWaitRecord, 'state' | 'updated_at' | 'history'>>): DurableWaitRecord;
75
105
  export interface DurableWaitReconciliation {
76
106
  readonly reason: string;
77
107
  readonly recorded_at: string;
@@ -7,6 +7,54 @@ import { initializePersonalOs, loadPersonalOs, mutatePersonalOsWithSidecar, read
7
7
  export const DURABLE_WAIT_VERSION = 'durable-wait.v1';
8
8
  export const DURABLE_WAIT_SIDECAR_PATH = 'durable-waits/ledger.json';
9
9
  export const DURABLE_WAIT_LEDGER_VERSION = DURABLE_WAIT_VERSION;
10
+ function transitionRule(from, to) {
11
+ return Object.freeze({ from: Object.freeze([...from]), to: Object.freeze([...to]) });
12
+ }
13
+ /**
14
+ * The wait state machine, written down once. Every state write goes through
15
+ * `transitionWait`, which refuses a step this table does not list.
16
+ *
17
+ * - `resumed`, `effect_confirmed`, `failed` and `cancelled` have no way out.
18
+ * - No action moves a wait to `failed` or `cancelled`; they stay in the type
19
+ * and are still read from a stored ledger.
20
+ * - `claim` from `claimed` is only reachable for a record that is `claimed`
21
+ * without a claim, which normal operation never writes. It is kept so a
22
+ * hand-edited ledger does not become stuck.
23
+ */
24
+ export const DURABLE_WAIT_TRANSITIONS = Object.freeze({
25
+ create: transitionRule([], ['waiting']),
26
+ claim: transitionRule(['waiting', 'claimed'], ['claimed']),
27
+ handoff: transitionRule(['claimed'], ['claimed']),
28
+ resume: transitionRule(['claimed'], ['resumed']),
29
+ premise_changed: transitionRule(['waiting', 'claimed', 'handoff_required'], ['handoff_required']),
30
+ effect_unknown: transitionRule(['waiting', 'claimed', 'handoff_required', 'reconciliation_wait'], ['reconciliation_wait']),
31
+ effect_reconciled: transitionRule(['reconciliation_wait'], ['effect_confirmed', 'waiting', 'reconciliation_wait'])
32
+ });
33
+ /**
34
+ * The only writer of a wait's state after `create`. State, update time and the
35
+ * history entry come from the same step, so they cannot disagree.
36
+ */
37
+ export function transitionWait(record, step, changes = {}) {
38
+ const rule = DURABLE_WAIT_TRANSITIONS[step.action];
39
+ if (rule === undefined || !rule.from.includes(record.state) || !rule.to.includes(step.to)) {
40
+ throw new DurableWaitError('state_conflict', `Wait ${record.wait_id} cannot ${step.action} from ${record.state} to ${step.to}`, record.wait_id);
41
+ }
42
+ return {
43
+ ...record,
44
+ ...changes,
45
+ state: step.to,
46
+ updated_at: step.at,
47
+ history: [...record.history, {
48
+ action: step.action,
49
+ occurred_at: step.at,
50
+ principal: step.principal,
51
+ from_state: record.state,
52
+ to_state: step.to,
53
+ ...(step.detail === undefined ? {} : { detail: step.detail }),
54
+ ...(step.responsible === undefined ? {} : { responsible: step.responsible })
55
+ }]
56
+ };
57
+ }
10
58
  export class DurableWaitError extends Error {
11
59
  code;
12
60
  wait_id;
@@ -275,19 +323,13 @@ export class DurableWaitStore {
275
323
  }
276
324
  const claim = makeClaim(normalized, this.nowFromMillis(normalized.nowMs), normalized.leaseMs);
277
325
  const now = this.timestamp(normalized.nowMs);
278
- const updated = updateRecord(record, {
279
- state: 'claimed',
280
- claim,
281
- updated_at: now,
282
- history: appendHistory(record, {
283
- action: 'claim',
284
- occurred_at: now,
285
- principal: normalized.principal,
286
- from_state: record.state,
287
- to_state: 'claimed',
288
- detail: normalized.trigger === 'event' ? `event:${normalized.event_type ?? ''}` : normalized.trigger
289
- })
290
- });
326
+ const updated = transitionWait(record, {
327
+ action: 'claim',
328
+ to: 'claimed',
329
+ at: now,
330
+ principal: normalized.principal,
331
+ detail: normalized.trigger === 'event' ? `event:${normalized.event_type ?? ''}` : normalized.trigger
332
+ }, { claim });
291
333
  replaceWait(ledger, updated);
292
334
  return {
293
335
  next: current,
@@ -329,21 +371,14 @@ export class DurableWaitStore {
329
371
  claimed_by: normalized.responsible.principal,
330
372
  claimed_at: now
331
373
  };
332
- const updated = updateRecord(record, {
333
- state: 'claimed',
334
- claim,
335
- responsible: normalized.responsible,
336
- updated_at: now,
337
- history: appendHistory(record, {
338
- action: 'handoff',
339
- occurred_at: now,
340
- principal: normalized.principal,
341
- from_state: record.state,
342
- to_state: 'claimed',
343
- detail: normalized.reason,
344
- responsible: normalized.responsible
345
- })
346
- });
374
+ const updated = transitionWait(record, {
375
+ action: 'handoff',
376
+ to: 'claimed',
377
+ at: now,
378
+ principal: normalized.principal,
379
+ detail: normalized.reason,
380
+ responsible: normalized.responsible
381
+ }, { claim, responsible: normalized.responsible });
347
382
  replaceWait(ledger, updated);
348
383
  return { next: current, sidecarContent: serializeLedger(ledger), result: freezeClone(updated) };
349
384
  });
@@ -387,18 +422,12 @@ export class DurableWaitStore {
387
422
  run_ref: record.run_ref,
388
423
  recorded_at: now
389
424
  };
390
- const updated = updateRecord(record, {
391
- state: 'resumed',
392
- resume_receipt: receipt,
393
- updated_at: now,
394
- history: appendHistory(record, {
395
- action: 'resume',
396
- occurred_at: now,
397
- principal: normalized.principal,
398
- from_state: record.state,
399
- to_state: 'resumed'
400
- })
401
- });
425
+ const updated = transitionWait(record, {
426
+ action: 'resume',
427
+ to: 'resumed',
428
+ at: now,
429
+ principal: normalized.principal
430
+ }, { resume_receipt: receipt });
402
431
  replaceWait(ledger, updated);
403
432
  return { next: current, sidecarContent: serializeLedger(ledger), result: freezeClone(receipt) };
404
433
  });
@@ -421,20 +450,16 @@ export class DurableWaitStore {
421
450
  throw new DurableWaitError('state_conflict', `Wait ${record.wait_id} is ${record.state}`, record.wait_id);
422
451
  }
423
452
  const now = this.now().toISOString();
424
- const updated = updateRecord(record, {
425
- state: 'handoff_required',
453
+ const updated = transitionWait(record, {
454
+ action: 'premise_changed',
455
+ to: 'handoff_required',
456
+ at: now,
457
+ principal: normalized.principal,
458
+ detail: normalized.reason,
459
+ responsible: normalized.responsible
460
+ }, {
426
461
  next_problem: normalized.new_problem_snapshot,
427
- ...(normalized.responsible === undefined ? {} : { responsible: normalized.responsible }),
428
- updated_at: now,
429
- history: appendHistory(record, {
430
- action: 'premise_changed',
431
- occurred_at: now,
432
- principal: normalized.principal,
433
- from_state: record.state,
434
- to_state: 'handoff_required',
435
- detail: normalized.reason,
436
- ...(normalized.responsible === undefined ? {} : { responsible: normalized.responsible })
437
- })
462
+ ...(normalized.responsible === undefined ? {} : { responsible: normalized.responsible })
438
463
  });
439
464
  replaceWait(ledger, updated);
440
465
  return { next: current, sidecarContent: serializeLedger(ledger), result: freezeClone(updated) };
@@ -482,20 +507,16 @@ export class DurableWaitStore {
482
507
  }
483
508
  const now = this.now().toISOString();
484
509
  const responsible = normalized.responsible ?? record.responsible;
485
- const updated = updateRecord(record, {
486
- state: 'reconciliation_wait',
510
+ const updated = transitionWait(record, {
511
+ action: 'effect_unknown',
512
+ to: 'reconciliation_wait',
513
+ at: now,
514
+ principal: normalized.principal,
515
+ detail: `${normalized.reason}:${externalOperationId}`,
516
+ responsible
517
+ }, {
487
518
  responsible,
488
- reconciliation: { reason: normalized.reason, recorded_at: now, responsible, external_operation_id: externalOperationId, claim_id: record.claim.claim_id, binding_status: bindingVerified ? 'verified' : 'unverified' },
489
- updated_at: now,
490
- history: appendHistory(record, {
491
- action: 'effect_unknown',
492
- occurred_at: now,
493
- principal: normalized.principal,
494
- from_state: record.state,
495
- to_state: 'reconciliation_wait',
496
- detail: `${normalized.reason}:${externalOperationId}`,
497
- responsible
498
- })
519
+ reconciliation: { reason: normalized.reason, recorded_at: now, responsible, external_operation_id: externalOperationId, claim_id: record.claim.claim_id, binding_status: bindingVerified ? 'verified' : 'unverified' }
499
520
  });
500
521
  replaceWait(ledger, updated);
501
522
  return { next: current, sidecarContent: serializeLedger(ledger), result: freezeClone(updated) };
@@ -516,20 +537,16 @@ export class DurableWaitStore {
516
537
  }
517
538
  const now = this.now().toISOString();
518
539
  const responsible = normalized.responsible ?? record.responsible;
519
- const updated = updateRecord(record, {
520
- state: 'reconciliation_wait',
540
+ const updated = transitionWait(record, {
541
+ action: 'effect_unknown',
542
+ to: 'reconciliation_wait',
543
+ at: now,
544
+ principal: normalized.principal,
545
+ detail: normalized.reason,
546
+ responsible
547
+ }, {
521
548
  responsible,
522
- reconciliation: { reason: normalized.reason, recorded_at: now, responsible },
523
- updated_at: now,
524
- history: appendHistory(record, {
525
- action: 'effect_unknown',
526
- occurred_at: now,
527
- principal: normalized.principal,
528
- from_state: record.state,
529
- to_state: 'reconciliation_wait',
530
- detail: normalized.reason,
531
- responsible
532
- })
549
+ reconciliation: { reason: normalized.reason, recorded_at: now, responsible }
533
550
  });
534
551
  replaceWait(ledger, updated);
535
552
  return { next: current, sidecarContent: serializeLedger(ledger), result: freezeClone(updated) };
@@ -603,15 +620,10 @@ export class DurableWaitStore {
603
620
  claim_id: binding.claim_id
604
621
  };
605
622
  const state = outcome === 'performed' ? 'effect_confirmed' : outcome === 'not_performed' ? 'waiting' : 'reconciliation_wait';
606
- const updated = updateRecord(record, {
607
- state,
608
- updated_at: now,
609
- reconciliation_receipts: [...(record.reconciliation_receipts ?? []), receipt],
610
- history: appendHistory(record, {
611
- action: 'effect_reconciled', occurred_at: now, principal: normalized.principal,
612
- from_state: 'reconciliation_wait', to_state: state, detail: `${outcome}:${normalized.external_operation_id}`
613
- })
614
- });
623
+ const updated = transitionWait(record, {
624
+ action: 'effect_reconciled', to: state, at: now, principal: normalized.principal,
625
+ detail: `${outcome}:${normalized.external_operation_id}`
626
+ }, { reconciliation_receipts: [...(record.reconciliation_receipts ?? []), receipt] });
615
627
  // A proven non-effect can be claimed again, but never with the old lease.
616
628
  if (outcome === 'not_performed')
617
629
  delete updated.claim;
@@ -984,12 +996,6 @@ function assertResumeBinding(record, input) {
984
996
  throw new DurableWaitError('unauthorized', `Resume lease does not match Wait ${record.wait_id}`, record.wait_id);
985
997
  }
986
998
  }
987
- function updateRecord(record, changes) {
988
- return { ...record, ...changes };
989
- }
990
- function appendHistory(record, entry) {
991
- return [...record.history, entry];
992
- }
993
999
  function findWait(ledger, waitId) {
994
1000
  const record = ledger.waits.find((wait) => wait.wait_id === waitId);
995
1001
  if (record === undefined)
@@ -111,7 +111,8 @@ export declare const foundationPublicToolDefinitions: readonly [{
111
111
  readonly type: "string";
112
112
  };
113
113
  readonly valid_to: {
114
- readonly type: readonly ["string", "null"];
114
+ readonly type: "string";
115
+ readonly description: "Optional RFC 3339 end of validity window. Omit when open-ended.";
115
116
  };
116
117
  };
117
118
  };
@@ -130,6 +131,7 @@ export declare const foundationPublicToolDefinitions: readonly [{
130
131
  readonly properties: {
131
132
  readonly snapshot: {
132
133
  readonly type: "object";
134
+ readonly additionalProperties: true;
133
135
  };
134
136
  };
135
137
  readonly additionalProperties: false;
@@ -123,9 +123,9 @@ export const foundationPublicToolDefinitions = [
123
123
  { name: 'foundation_validate_reference', description: 'Validate an exact foundation or philosophy reference for judgment, including its dependencies.', inputSchema: {
124
124
  type: 'object', required: ['reference'], additionalProperties: false,
125
125
  properties: { reference: { type: 'object', required: ['kind', 'id', 'revision', 'digest', 'scope', 'valid_from'], additionalProperties: false,
126
- properties: { kind: { type: 'string', enum: ['objective', 'variable', 'model', 'constraint', 'philosophy'] }, id: { type: 'string' }, revision: { type: 'string' }, digest: { type: 'string' }, scope: { type: 'object', required: ['type', 'id'], additionalProperties: false, properties: { type: { type: 'string', enum: ['personal', 'project', 'organization'] }, id: { type: 'string' } } }, valid_from: { type: 'string' }, valid_to: { type: ['string', 'null'] } } }, phase: { type: 'string', enum: ['read', 'historical_read'] } }
126
+ properties: { kind: { type: 'string', enum: ['objective', 'variable', 'model', 'constraint', 'philosophy'] }, id: { type: 'string' }, revision: { type: 'string' }, digest: { type: 'string' }, scope: { type: 'object', required: ['type', 'id'], additionalProperties: false, properties: { type: { type: 'string', enum: ['personal', 'project', 'organization'] }, id: { type: 'string' } } }, valid_from: { type: 'string' }, valid_to: { type: 'string', description: 'Optional RFC 3339 end of validity window. Omit when open-ended.' } } }, phase: { type: 'string', enum: ['read', 'historical_read'] } }
127
127
  } },
128
- { name: 'foundation_validate_problem', description: 'Validate a complete judgment snapshot and canonical observation measurement conditions. Grants no execution permission.', inputSchema: { type: 'object', required: ['snapshot'], properties: { snapshot: { type: 'object' } }, additionalProperties: false } }
128
+ { name: 'foundation_validate_problem', description: 'Validate a complete judgment snapshot and canonical observation measurement conditions. Grants no execution permission.', inputSchema: { type: 'object', required: ['snapshot'], properties: { snapshot: { type: 'object', additionalProperties: true } }, additionalProperties: false } }
129
129
  ];
130
130
  export async function callFoundationPublicTool(name, args, connection) {
131
131
  if (!connection)