@spellkave/sdk 0.0.0-bootstrap → 0.0.0-stage

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 (144) hide show
  1. package/README.md +2 -155
  2. package/package.json +4 -63
  3. package/LICENSE +0 -89
  4. package/src/binding_rows.ts +0 -186
  5. package/src/connection.ts +0 -964
  6. package/src/core/actor.ts +0 -62
  7. package/src/core/actor_control.ts +0 -193
  8. package/src/core/actor_control_query_methods.ts +0 -101
  9. package/src/core/actor_control_reaction_methods.ts +0 -79
  10. package/src/core/actor_control_sense_methods.ts +0 -81
  11. package/src/core/actor_control_source.ts +0 -57
  12. package/src/core/actor_session_methods.ts +0 -226
  13. package/src/core/binding_drift.ts +0 -301
  14. package/src/core/credential.ts +0 -259
  15. package/src/core/driver_control.ts +0 -54
  16. package/src/core/effective_environment_state.ts +0 -71
  17. package/src/core/factored_manipulation_attempt.ts +0 -158
  18. package/src/core/ids.ts +0 -60
  19. package/src/core/interaction/canonical.ts +0 -15
  20. package/src/core/interaction/fingerprint.ts +0 -118
  21. package/src/core/interaction/index.ts +0 -31
  22. package/src/core/interaction/intent.ts +0 -284
  23. package/src/core/interaction/outcome.ts +0 -67
  24. package/src/core/interaction/rejection_ledger.ts +0 -108
  25. package/src/core/kernel_contract.generated.ts +0 -10
  26. package/src/core/log.ts +0 -23
  27. package/src/core/movement.ts +0 -111
  28. package/src/core/node-io.ts +0 -208
  29. package/src/core/paths.ts +0 -220
  30. package/src/core/profile.ts +0 -270
  31. package/src/core/profiles.ts +0 -9
  32. package/src/core/provenance_buffer.ts +0 -102
  33. package/src/core/readers/_helpers.ts +0 -273
  34. package/src/core/readers/action_description.ts +0 -17
  35. package/src/core/readers/action_economy_events.ts +0 -149
  36. package/src/core/readers/actor_body_swaps.ts +0 -62
  37. package/src/core/readers/actor_snapshot.ts +0 -197
  38. package/src/core/readers/actor_states.ts +0 -163
  39. package/src/core/readers/actors_and_bodies.ts +0 -179
  40. package/src/core/readers/affordance_cue.ts +0 -59
  41. package/src/core/readers/affordance_defaults.ts +0 -158
  42. package/src/core/readers/affordance_group_membership.ts +0 -67
  43. package/src/core/readers/affordance_input.ts +0 -129
  44. package/src/core/readers/affordance_reference.ts +0 -41
  45. package/src/core/readers/apply_consequences.ts +0 -54
  46. package/src/core/readers/audience_trace_presentation.ts +0 -62
  47. package/src/core/readers/bounded_collection.ts +0 -29
  48. package/src/core/readers/bundle_definitions.ts +0 -74
  49. package/src/core/readers/bundle_entities.ts +0 -62
  50. package/src/core/readers/co_location.ts +0 -71
  51. package/src/core/readers/combat_session.ts +0 -124
  52. package/src/core/readers/combat_session_active.ts +0 -44
  53. package/src/core/readers/combat_session_feedback.ts +0 -37
  54. package/src/core/readers/combat_session_grid.ts +0 -117
  55. package/src/core/readers/combat_session_roster.ts +0 -98
  56. package/src/core/readers/combat_session_types.ts +0 -51
  57. package/src/core/readers/condition_deltas.ts +0 -53
  58. package/src/core/readers/container_contents.ts +0 -92
  59. package/src/core/readers/dialogue_guide.ts +0 -99
  60. package/src/core/readers/dialogue_prompt_presentation.ts +0 -90
  61. package/src/core/readers/driver_control.ts +0 -64
  62. package/src/core/readers/entity_art.ts +0 -219
  63. package/src/core/readers/entity_containment.ts +0 -119
  64. package/src/core/readers/equipment.ts +0 -99
  65. package/src/core/readers/intervention_windows.ts +0 -136
  66. package/src/core/readers/inventory_query.ts +0 -145
  67. package/src/core/readers/item_detail.ts +0 -198
  68. package/src/core/readers/location_snapshot.ts +0 -216
  69. package/src/core/readers/manifest_apply_provenance.ts +0 -32
  70. package/src/core/readers/manifest_export.ts +0 -81
  71. package/src/core/readers/manipulation_context.ts +0 -475
  72. package/src/core/readers/map_layers.ts +0 -49
  73. package/src/core/readers/metadata_rows.ts +0 -56
  74. package/src/core/readers/object_state.ts +0 -124
  75. package/src/core/readers/observer_knowledge.ts +0 -41
  76. package/src/core/readers/observer_place_knowledge.ts +0 -37
  77. package/src/core/readers/observer_trace_knowledge.ts +0 -45
  78. package/src/core/readers/outcome_template.ts +0 -41
  79. package/src/core/readers/place_topology.ts +0 -109
  80. package/src/core/readers/reaction_options.ts +0 -156
  81. package/src/core/readers/resource_deltas.ts +0 -47
  82. package/src/core/readers/scene.ts +0 -275
  83. package/src/core/readers/seats.ts +0 -33
  84. package/src/core/readers/self.ts +0 -245
  85. package/src/core/readers/self_capabilities.ts +0 -159
  86. package/src/core/readers/self_economy.ts +0 -101
  87. package/src/core/readers/self_economy_budget.ts +0 -93
  88. package/src/core/readers/self_evaluations.ts +0 -128
  89. package/src/core/readers/self_identity.ts +0 -104
  90. package/src/core/readers/sense_context.ts +0 -112
  91. package/src/core/readers/session.ts +0 -207
  92. package/src/core/readers/session_detail.ts +0 -211
  93. package/src/core/readers/session_status.ts +0 -68
  94. package/src/core/readers/spatial_environment_state.ts +0 -74
  95. package/src/core/readers/spatial_niche_attachments.ts +0 -28
  96. package/src/core/readers/substrate_definitions.ts +0 -27
  97. package/src/core/readers/suggest_next_action.ts +0 -72
  98. package/src/core/readers/surface_membership.ts +0 -78
  99. package/src/core/readers/tag_reads.ts +0 -54
  100. package/src/core/readers/trace_query.ts +0 -120
  101. package/src/core/readers/trace_response.ts +0 -80
  102. package/src/core/readers/traces.ts +0 -124
  103. package/src/core/readers/travel_session.ts +0 -88
  104. package/src/core/readers/turn_state.ts +0 -34
  105. package/src/core/readers/world_events.ts +0 -43
  106. package/src/core/readers/world_status.ts +0 -63
  107. package/src/core/reducers/manipulation_args.ts +0 -239
  108. package/src/core/reducers/manipulation_receipt.ts +0 -66
  109. package/src/core/reducers/r_actor_wake_up.ts +0 -32
  110. package/src/core/reducers/r_inscribe_trace.ts +0 -109
  111. package/src/core/reducers/r_manipulate.ts +0 -163
  112. package/src/core/reducers/r_move.ts +0 -155
  113. package/src/core/reducers/r_react.ts +0 -143
  114. package/src/core/reducers/r_release_claim.ts +0 -81
  115. package/src/core/reducers/r_sense.ts +0 -84
  116. package/src/core/reducers/r_session_close.ts +0 -130
  117. package/src/core/reducers/r_session_move.ts +0 -116
  118. package/src/core/reducers/r_session_open.ts +0 -91
  119. package/src/core/reducers/session_lookup.ts +0 -64
  120. package/src/core/reducers/tick.ts +0 -65
  121. package/src/core/reducers/trace_lookup.ts +0 -29
  122. package/src/core/reducers/transport.ts +0 -84
  123. package/src/core/resolve.ts +0 -228
  124. package/src/core/shape_telemetry.ts +0 -146
  125. package/src/core/snapshot_rows.ts +0 -109
  126. package/src/core/tick_cadence.ts +0 -61
  127. package/src/core/types.ts +0 -501
  128. package/src/core/watch_provenance.ts +0 -113
  129. package/src/core/world-contract/classify.ts +0 -38
  130. package/src/core/world-contract/index.ts +0 -12
  131. package/src/core/world-contract/normalise.ts +0 -574
  132. package/src/core/world-contract/runtime.ts +0 -144
  133. package/src/core/world-contract/served.ts +0 -173
  134. package/src/core/world-contract/strict-reducers.ts +0 -14
  135. package/src/core/world-contract/typetext.ts +0 -94
  136. package/src/core/world_time.ts +0 -22
  137. package/src/index.ts +0 -262
  138. package/src/manifest-apply.ts +0 -497
  139. package/src/provenance.ts +0 -568
  140. package/src/reader-manifest.ts +0 -338
  141. package/src/readers.ts +0 -392
  142. package/src/replay.ts +0 -515
  143. package/src/watch-buffer.ts +0 -438
  144. package/src/world-events/builder.ts +0 -1042
@@ -1,118 +0,0 @@
1
- // Deterministic identity for one dispatch-shaped `IntentDraft` inside one
2
- // `ObservationEpoch`. Used by `RejectionLedger` to recognise "the exact
3
- // rejected attempt" for ADR-0141 D-6 suppression — nothing here evaluates
4
- // eligibility or compares drafts for similarity, only exact wire identity.
5
- // `facts_revision` deliberately does not enter this fingerprint: the ledger
6
- // pairs revision with fingerprint separately, so the same syntax at two
7
- // different revisions is still recognisably "the same attempt" for counting
8
- // purposes, even though only a matching revision suppresses it.
9
-
10
- import { sortKeysDeep } from "./canonical";
11
- import type { IntentDraft, ObservationEpoch } from "./intent";
12
-
13
- // A present-vs-absent tag, not a natural JSON shape a caller's own data could
14
- // produce by accident: `t: 0` (absent) can never equal `t: 1`/`t: 2`
15
- // (present, well-formed/malformed) regardless of what value or text a caller
16
- // supplies. This is what lets the fingerprint tell "field omitted" apart from
17
- // "field present but empty" — undefined `args_json` from `"{}"`, undefined
18
- // `utterance` from `""`, undefined `input_values` from `{}`.
19
- const ABSENT = { t: 0 } as const;
20
- function present(v: unknown) {
21
- return { t: 1, v };
22
- }
23
- function malformedText(text: string) {
24
- return { t: 2, text };
25
- }
26
-
27
- /** Canonicalizes `args_json` and extracts an effective `participant_context`
28
- * from it. `participant_context` carried as a draft field and as the
29
- * `participant_context` key inside `args_json` are the same fact: whichever
30
- * is present (draft field wins when both are) is folded into one value and
31
- * removed from the canonical args value, so the two spellings fingerprint
32
- * identically. */
33
- function canonicalizeArgs(argsJson: string | undefined): {
34
- canonical: unknown;
35
- participantContext?: string;
36
- } {
37
- if (argsJson === undefined) return { canonical: ABSENT };
38
- const text = argsJson.trim();
39
- if (text === "") return { canonical: present({}) };
40
-
41
- let parsed: unknown;
42
- try {
43
- parsed = JSON.parse(text);
44
- } catch {
45
- // Malformed args are not silently dropped: the raw trimmed text still
46
- // participates in the fingerprint, tagged distinctly from any
47
- // well-formed value, so a malformed and a well-formed draft are never
48
- // mistaken for the same attempt.
49
- return { canonical: malformedText(text) };
50
- }
51
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
52
- return { canonical: present(sortKeysDeep(parsed)) };
53
- }
54
-
55
- const obj = { ...(parsed as Record<string, unknown>) };
56
- let participantContext: string | undefined;
57
- const raw = obj.participant_context;
58
- if (typeof raw === "string" && raw.trim() !== "") participantContext = raw.trim();
59
- delete obj.participant_context;
60
-
61
- return {
62
- canonical: present(sortKeysDeep(obj)),
63
- ...(participantContext === undefined ? {} : { participantContext }),
64
- };
65
- }
66
-
67
- function canonicalizeInputValues(values: IntentDraft["input_values"]): unknown {
68
- return values === undefined ? ABSENT : present(sortKeysDeep(values));
69
- }
70
-
71
- function canonicalizeUtterance(draft: IntentDraft): unknown {
72
- const utterance = draft.kind === "communicate" ? draft.utterance : undefined;
73
- return utterance === undefined ? ABSENT : present(utterance);
74
- }
75
-
76
- function canonicalizeSemanticContext(draft: IntentDraft): unknown {
77
- const semanticContext = draft.semantic_context;
78
- return semanticContext === undefined
79
- ? ABSENT
80
- : present({
81
- source_ref: semanticContext.source_ref.trim(),
82
- occurrence_id: semanticContext.occurrence_id.trim(),
83
- });
84
- }
85
-
86
- function trimOr(value: string | undefined): string {
87
- return value?.trim() ?? "";
88
- }
89
-
90
- /** A deterministic string over every field that distinguishes one draft's
91
- * dispatch, plus the epoch it would dispatch into. Computed from the
92
- * immutable snapshot `createAttempt` freezes — never from a caller's live,
93
- * mutable object. Two drafts differing only in `args_json`/`input_values` key
94
- * order, or in `participant_context` spelling (draft field vs. the
95
- * `participant_context` key inside `args_json`), fingerprint identically;
96
- * differing `utterance`, `target_ref`, `semantic_context`, or epoch never do,
97
- * and a field's absence never fingerprints the same as its
98
- * explicitly-empty presence (see `canonicalizeArgs`/`canonicalizeInputValues`/
99
- * `canonicalizeUtterance`). The tuple is joined via `JSON.stringify` of an
100
- * ordered array so no field boundary can be crossed by string
101
- * concatenation. */
102
- export function attemptFingerprint(draft: IntentDraft, epoch: ObservationEpoch): string {
103
- const { canonical: argsCanonical, participantContext } = canonicalizeArgs(draft.args_json);
104
- const effectiveParticipantContext = trimOr(draft.participant_context) || participantContext || "";
105
- const primaryId = draft.kind === "manipulate" ? draft.action_id : draft.speech_act_id;
106
-
107
- return JSON.stringify([
108
- draft.kind,
109
- trimOr(primaryId),
110
- trimOr(draft.target_ref),
111
- argsCanonical,
112
- canonicalizeInputValues(draft.input_values),
113
- canonicalizeUtterance(draft),
114
- effectiveParticipantContext,
115
- canonicalizeSemanticContext(draft),
116
- epoch,
117
- ]);
118
- }
@@ -1,31 +0,0 @@
1
- // ADR-0140/ADR-0141 shared interaction vocabulary: WorldFacts -> IntentDraft
2
- // -> Attempt -> Outcome. Both the Play web app and NPC brains compose ONE
3
- // fallible direct attempt from disclosed facts; the server alone decides
4
- // admission ("disclosure is not eligibility"). This module is PURE: no DB, no
5
- // network, no ranking, no eligibility evaluation, no second resolver. Direct
6
- // manipulation still goes through `composeFactoredManipulationAttempt`.
7
-
8
- export { attemptFingerprint } from "./fingerprint";
9
- export type {
10
- AttemptKind,
11
- CommunicateDraft,
12
- ContextGenerationInput,
13
- DraftCheck,
14
- DraftMissingPart,
15
- IntentDraft,
16
- IntentInputValues,
17
- IntentSemanticContext,
18
- ManipulateDraft,
19
- ObservationEpoch,
20
- } from "./intent";
21
- export {
22
- checkDraft,
23
- inputValuesToText,
24
- nextContextGeneration,
25
- observationEpoch,
26
- utteranceFromInputValues,
27
- } from "./intent";
28
- export type { Attempt, Outcome } from "./outcome";
29
- export { createAttempt } from "./outcome";
30
- export type { LastRejection, RejectionLedger } from "./rejection_ledger";
31
- export { createRejectionLedger } from "./rejection_ledger";
@@ -1,284 +0,0 @@
1
- // ADR-0140/ADR-0141 shared interaction vocabulary: WorldFacts -> IntentDraft
2
- // -> Attempt -> Outcome. The server no longer publishes evaluated
3
- // action×target offers ("disclosure is not eligibility"); a client composes
4
- // exactly one local, fallible `IntentDraft` from disclosed facts, and the
5
- // server alone decides admission. This file is the draft half of that
6
- // vocabulary: syntax-only shaping and completeness, never an eligibility
7
- // claim.
8
-
9
- import type { AffordanceInputField, AffordanceInputSchema } from "../readers/affordance_input";
10
- import { sortKeysDeep } from "./canonical";
11
-
12
- /** Transport families this vocabulary is scoped to, not a closed game-action
13
- * vocabulary. `IntentDraft` currently covers `manipulate` and `communicate`
14
- * only. `move`, `sense`, `react`, and `end_turn` keep their existing bounded
15
- * reducer contracts and will get their own named draft fields in a later
16
- * change — this module does not invent a generic shape for them yet. */
17
- export type AttemptKind = "manipulate" | "communicate" | "move" | "sense" | "react" | "end_turn";
18
-
19
- /** The speaker and occurrence an otherwise-identical utterance answers. Two
20
- * drafts with the same `utterance` text but different `semantic_context`
21
- * mean different things (e.g. two different dialogue prompts asking "yes or
22
- * no?"), so both parts enter the fingerprint. `occurrence_id` is the ADR-0142
23
- * D-2 server-allocated occurrence identity from the `manipulation_context`
24
- * projection's `prompts` (ADR-0142 D-6) — never client-derived. The wire
25
- * shape a caller forwards under `args_json`'s `semantic_context` key is
26
- * `{ source_ref, occurrence_id }` exactly (ADR-0142 D-3). */
27
- export interface IntentSemanticContext {
28
- source_ref: string;
29
- occurrence_id: string;
30
- }
31
-
32
- /** Structured form input shared by both draft kinds. Values are read-only:
33
- * an `IntentDraft` is a snapshot of caller intent, not a live form model. */
34
- export type IntentInputValues = Readonly<Record<string, string | number | boolean>>;
35
-
36
- interface IntentDraftCommon {
37
- /** A typed target string, exactly as disclosed. */
38
- target_ref?: string;
39
- /** JSON object text carrying authored input fields, forward-compatible
40
- * with fields `input_values` does not name. */
41
- args_json?: string;
42
- /** Structured form input. The one defined representation for authored
43
- * input fields — see `inputValuesToText` for its wire form. */
44
- input_values?: IntentInputValues;
45
- /** Select one disclosed mpc (multi-participant context) token. */
46
- participant_context?: string;
47
- semantic_context?: IntentSemanticContext;
48
- }
49
-
50
- /** manipulate: an authored action id and a disclosed target, going through
51
- * the existing `composeFactoredManipulationAttempt` machinery for direct
52
- * manipulation. */
53
- export interface ManipulateDraft extends IntentDraftCommon {
54
- kind: "manipulate";
55
- action_id?: string;
56
- }
57
-
58
- /** communicate: an authored speech act id and a disclosed target. `utterance`
59
- * is free text by default — see `checkDraft` for when it doubles as a JSON
60
- * field source. */
61
- export interface CommunicateDraft extends IntentDraftCommon {
62
- kind: "communicate";
63
- speech_act_id?: string;
64
- utterance?: string;
65
- }
66
-
67
- /**
68
- * A local, fallible candidate assembled from disclosed facts. An `IntentDraft`
69
- * is never a server offer and never implies admission — it only says what a
70
- * caller intends to send, shaped well enough to dispatch. Scoped to
71
- * `manipulate` and `communicate` for now; see `AttemptKind`.
72
- */
73
- export type IntentDraft = ManipulateDraft | CommunicateDraft;
74
-
75
- /** The exact wire form the Play app sends today for structured input (as
76
- * `utterance` / `dispatch_text`): key-sorted JSON text. Transports decide
77
- * where that text travels — this helper only shapes it. */
78
- export function inputValuesToText(values: IntentInputValues): string {
79
- return JSON.stringify(sortKeysDeep(values));
80
- }
81
-
82
- /** The utterance text for structured input: only fields whose authored
83
- * `channel` is `"utterance"` and that carry a non-blank value count. Exactly
84
- * one such field yields its bare text; several yield a key-sorted JSON object
85
- * string (the `inputValuesToText` form); none yields `""`. Additive beside
86
- * `inputValuesToText`, which keeps its all-values behaviour. */
87
- export function utteranceFromInputValues(
88
- fields: readonly AffordanceInputField[],
89
- values: IntentInputValues,
90
- ): string {
91
- const picked: Record<string, string | number | boolean> = {};
92
- for (const field of fields) {
93
- if (field.channel !== "utterance") continue;
94
- if (!(field.name in values)) continue;
95
- const value = values[field.name];
96
- if (value === undefined || (typeof value === "string" && value.trim() === "")) continue;
97
- picked[field.name] = value;
98
- }
99
- const names = Object.keys(picked);
100
- if (names.length === 0) return "";
101
- if (names.length === 1) return String(picked[names[0] as string]);
102
- return inputValuesToText(picked);
103
- }
104
-
105
- /**
106
- * One connected actor/world observation lifetime. Opaque to callers besides
107
- * `observationEpoch`; mint a new value after reconnect, actor change, world
108
- * reset, or context evict+rebuild. Never reused across those boundaries —
109
- * `RejectionLedger` suppression is scoped by this value precisely so a stale
110
- * epoch cannot suppress dispatch against facts the caller no longer holds.
111
- */
112
- export type ObservationEpoch = string;
113
-
114
- /** A stable, collision-safe join of the facts that bound one epoch.
115
- * `context_generation` exists because `connection_generation` alone cannot
116
- * promise freshness across a server-side context evict+rebuild (the context
117
- * `revision` restarts, but the transport connection does not change) — see
118
- * `nextContextGeneration`. */
119
- export function observationEpoch(parts: {
120
- world_instance_id: string;
121
- actor_id: string;
122
- connection_generation: number | string;
123
- context_generation: number | string;
124
- }): ObservationEpoch {
125
- return [
126
- parts.world_instance_id,
127
- parts.actor_id,
128
- String(parts.connection_generation),
129
- String(parts.context_generation),
130
- ]
131
- .map((part) => part.replaceAll("\\", "\\\\").replaceAll("|", "\\|"))
132
- .join("|");
133
- }
134
-
135
- /** The shape `nextContextGeneration` reads to decide whether a caller's
136
- * locally observed context is the same rebuild-generation as before. */
137
- export interface ContextGenerationInput {
138
- status: "ready" | "unavailable";
139
- revision: number | null;
140
- }
141
-
142
- interface ContextGenerationState extends ContextGenerationInput {
143
- generation: number;
144
- }
145
-
146
- /**
147
- * Conservative, client-side detection of a context evict+rebuild — a
148
- * substitute for a portable generation the server does not publish yet.
149
- * Returns `0` for an undefined `previous` (first observation). Otherwise
150
- * bumps by one when the context went `unavailable` -> `ready`, or when its
151
- * `revision` moved backwards (a lower revision than previously observed
152
- * implies the context was rebuilt from scratch); any other transition keeps
153
- * the previous generation. This detection is conservative: it can miss a
154
- * rebuild that happens not to satisfy either signal, but it never invents a
155
- * bump the caller did not observe.
156
- */
157
- export function nextContextGeneration(
158
- previous: ContextGenerationState | undefined,
159
- current: ContextGenerationInput,
160
- ): number {
161
- if (previous === undefined) return 0;
162
- const wentUnavailableToReady = previous.status === "unavailable" && current.status === "ready";
163
- const revisionWentBackwards =
164
- previous.revision !== null && current.revision !== null && current.revision < previous.revision;
165
- return wentUnavailableToReady || revisionWentBackwards
166
- ? previous.generation + 1
167
- : previous.generation;
168
- }
169
-
170
- export type DraftMissingPart = "action" | "target" | "required_input";
171
-
172
- /** Syntax completeness only. Never an eligibility claim — a "complete" draft
173
- * may still be rejected by the server for any live-state reason. `missing`
174
- * lists absent required syntax; `malformed` lists a present-but-unparsable
175
- * source. A draft that is `"incomplete"` has at least one non-empty array,
176
- * never both empty. */
177
- export type DraftCheck =
178
- | { status: "complete" }
179
- | {
180
- status: "incomplete";
181
- missing: DraftMissingPart[];
182
- malformed: Array<"args_json" | "utterance_json">;
183
- /** Names of the required input fields that carry no value. Present
184
- * only when `missing` includes `"required_input"`. */
185
- missing_fields?: string[];
186
- };
187
-
188
- function isBlank(value: string | undefined): boolean {
189
- return value === undefined || value.trim() === "";
190
- }
191
-
192
- /** Checks that a draft carries the syntax its `kind` needs to dispatch, that
193
- * `args_json` (when present) parses as a JSON object, and optionally that
194
- * every field an authored `AffordanceInputSchema` marks `required` has a
195
- * value. Required-field values are looked up in `input_values` first, then a
196
- * JSON object parsed from `utterance` (Play's historical wire form for form
197
- * values — `communicate` only, since `utterance` is not a `manipulate`
198
- * field), then `args_json`.
199
- *
200
- * `args_json` present and not a JSON object is `malformed`, never `missing`.
201
- * An `utterance` that fails to parse as JSON is NOT malformed — ordinary
202
- * speech is not JSON, so a parse failure there is silently ignored as a
203
- * field source rather than reported. `utterance_json` is kept in the
204
- * `malformed` vocabulary for a future draft kind that requires `utterance`
205
- * itself to carry structured input; nothing in this module produces it yet.
206
- * An absent schema, or one with an empty `fields` array, never yields
207
- * `required_input`. */
208
- export function checkDraft(draft: IntentDraft, input?: AffordanceInputSchema): DraftCheck {
209
- const missing: DraftMissingPart[] = [];
210
- const malformed: Array<"args_json" | "utterance_json"> = [];
211
-
212
- if (draft.kind === "manipulate") {
213
- if (isBlank(draft.action_id)) missing.push("action");
214
- } else {
215
- if (isBlank(draft.speech_act_id)) missing.push("action");
216
- }
217
- if (isBlank(draft.target_ref)) missing.push("target");
218
-
219
- const argsValues = parseJsonObjectOrReport(draft.args_json, () => malformed.push("args_json"));
220
- const utteranceText = draft.kind === "communicate" ? draft.utterance : undefined;
221
- // A parse failure here is deliberately swallowed: plain speech is not malformed.
222
- const utteranceValues = utteranceText === undefined ? undefined : parseJsonObject(utteranceText);
223
-
224
- let missingFields: string[] = [];
225
- if (input !== undefined && input.fields.some((field) => field.required === true)) {
226
- missingFields = input.fields
227
- .filter((field) => field.required === true)
228
- .filter(
229
- (field) =>
230
- !isPresent(fieldValue(field.name, draft.input_values, utteranceValues, argsValues)),
231
- )
232
- .map((field) => field.name);
233
- if (missingFields.length > 0) missing.push("required_input");
234
- }
235
-
236
- return missing.length === 0 && malformed.length === 0
237
- ? { status: "complete" }
238
- : {
239
- status: "incomplete",
240
- missing,
241
- malformed,
242
- ...(missingFields.length > 0 ? { missing_fields: missingFields } : {}),
243
- };
244
- }
245
-
246
- function fieldValue(
247
- name: string,
248
- inputValues: IntentInputValues | undefined,
249
- utteranceValues: Record<string, unknown> | undefined,
250
- argsValues: Record<string, unknown> | undefined,
251
- ): unknown {
252
- if (inputValues !== undefined && name in inputValues) return inputValues[name];
253
- if (utteranceValues !== undefined && name in utteranceValues) return utteranceValues[name];
254
- if (argsValues !== undefined && name in argsValues) return argsValues[name];
255
- return undefined;
256
- }
257
-
258
- function isPresent(value: unknown): boolean {
259
- if (value === undefined || value === null) return false;
260
- if (typeof value === "string") return value.trim() !== "";
261
- if (typeof value === "number") return Number.isFinite(value);
262
- return true;
263
- }
264
-
265
- function parseJsonObject(text: string): Record<string, unknown> | undefined {
266
- if (text.trim() === "") return undefined;
267
- try {
268
- const parsed: unknown = JSON.parse(text);
269
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
270
- return parsed as Record<string, unknown>;
271
- } catch {
272
- return undefined;
273
- }
274
- }
275
-
276
- function parseJsonObjectOrReport(
277
- text: string | undefined,
278
- reportMalformed: () => void,
279
- ): Record<string, unknown> | undefined {
280
- if (text === undefined || text.trim() === "") return undefined;
281
- const parsed = parseJsonObject(text);
282
- if (parsed === undefined) reportMalformed();
283
- return parsed;
284
- }
@@ -1,67 +0,0 @@
1
- // The `Attempt` a caller dispatches, and the `Outcome` vocabulary a
2
- // transport reports back. Both stay transport-free: this module never talks
3
- // to a connection, a reducer, or a table — it only shapes and stamps values a
4
- // transport-owning caller passes in and reads back.
5
-
6
- import { attemptFingerprint } from "./fingerprint";
7
- import type { IntentDraft, ObservationEpoch } from "./intent";
8
-
9
- /** One dispatched candidate: an immutable snapshot of a draft, the epoch it
10
- * was minted against, the facts revision the caller last observed (if the
11
- * transport tracks one), and its fingerprint. Created only at dispatch —
12
- * never speculatively. */
13
- export interface Attempt {
14
- draft: Readonly<IntentDraft>;
15
- epoch: ObservationEpoch;
16
- facts_revision: number | null;
17
- fingerprint: string;
18
- }
19
-
20
- /** Deep-copies and deep-freezes `draft` before stamping it: an `Attempt`
21
- * must stay a faithful record of what was dispatched even if the caller goes
22
- * on to mutate the `IntentDraft` object it built the attempt from (e.g. a
23
- * reused form-state object). Mutating the original after this call changes
24
- * neither `attempt.draft` nor `attempt.fingerprint`. */
25
- export function createAttempt(
26
- draft: IntentDraft,
27
- epoch: ObservationEpoch,
28
- factsRevision: number | null,
29
- ): Attempt {
30
- const snapshot = deepFreeze(structuredClone(draft));
31
- return {
32
- draft: snapshot,
33
- epoch,
34
- facts_revision: factsRevision,
35
- fingerprint: attemptFingerprint(snapshot, epoch),
36
- };
37
- }
38
-
39
- function deepFreeze<T>(value: T): T {
40
- if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
41
- Object.freeze(value);
42
- for (const key of Object.keys(value as Record<string, unknown>)) {
43
- deepFreeze((value as Record<string, unknown>)[key]);
44
- }
45
- }
46
- return value;
47
- }
48
-
49
- /**
50
- * `"sent"` means dispatched with no receipt observed yet; `"unobserved"`
51
- * means dispatch happened but no receipt or confirmation was ever observed
52
- * (distinct from `"sent"`'s in-flight moment — e.g. a transport that gives up
53
- * watching before a reply arrives). `"accepted"` means admission only — the
54
- * server took the attempt onto its resolution path, not that it succeeded.
55
- * `"rejected"` means a CONFIRMED server admission rejection only — never a
56
- * local/transport-side guess — and is the only status a `RejectionLedger`
57
- * records. `"pending"` covers an accepted attempt whose consequence or reply
58
- * is still outstanding.
59
- */
60
- export type Outcome =
61
- | { status: "sent" }
62
- | { status: "unobserved" }
63
- | { status: "accepted" }
64
- | { status: "rejected"; reason?: string; failure_detail?: string }
65
- | { status: "pending" }
66
- | { status: "observed_result"; summary?: string }
67
- | { status: "transport_error"; message: string };
@@ -1,108 +0,0 @@
1
- // ADR-0141 D-6: suppress automatic re-dispatch of the exact rejected attempt
2
- // while the facts a caller holds have not changed. This ledger is the only
3
- // place that memory lives — it is in-memory, unpersisted, and carries no
4
- // timers; a caller resets it explicitly on epoch boundaries via
5
- // `resetEpoch`.
6
- //
7
- // Suppression blocks AUTOMATIC re-dispatch, and an UNCHANGED-SUBMIT
8
- // re-dispatch of the exact rejected candidate (same fingerprint, same facts
9
- // revision), inside the epoch + facts-revision boundary. It is never a
10
- // display filter and never hides other syntax toward the same target: a
11
- // caller may still show the rejected option, offer other actions against the
12
- // same target, or let a person explicitly retry. `rejectionCount` and
13
- // `lastRejection` exist so a caller can keep the draft and its refusal
14
- // explanation on screen as a ranking/history signal, not hide it.
15
-
16
- import { attemptFingerprint } from "./fingerprint";
17
- import type { IntentDraft, ObservationEpoch } from "./intent";
18
- import type { Attempt, Outcome } from "./outcome";
19
-
20
- interface RejectionEntry {
21
- /** The `facts_revision` last recorded for this rejection. A later
22
- * rejection of the same fingerprint overwrites this, even at a different
23
- * revision — suppression always compares against the most recent one. */
24
- revision: number | null;
25
- /** All-time count of rejections for this fingerprint in this epoch,
26
- * across every revision. A ranking signal only — never used to decide
27
- * suppression. */
28
- count: number;
29
- reason?: string;
30
- failure_detail?: string;
31
- }
32
-
33
- /** The last recorded refusal for a fingerprint, for display/ranking. */
34
- export interface LastRejection {
35
- reason?: string;
36
- failure_detail?: string;
37
- facts_revision: number | null;
38
- }
39
-
40
- export interface RejectionLedger {
41
- /** Records a `"rejected"` outcome. Every other `Outcome` status —
42
- * `"unobserved"` and an accepted miss included — is not a confirmed
43
- * server rejection and never enters. */
44
- record(attempt: Attempt, outcome: Outcome): void;
45
- /** True iff the same fingerprint was rejected in this epoch and the
46
- * recorded `facts_revision` equals `factsRevision` (`null` equals
47
- * `null`). Any revision change lifts suppression. */
48
- isSuppressed(draft: IntentDraft, epoch: ObservationEpoch, factsRevision: number | null): boolean;
49
- /** All-time rejection count for this fingerprint in this epoch,
50
- * regardless of revision. A ranking signal only. */
51
- rejectionCount(draft: IntentDraft, epoch: ObservationEpoch): number;
52
- /** The most recently recorded rejection for this fingerprint in this
53
- * epoch, or `undefined` if none was recorded. A display/ranking signal —
54
- * callers keep showing the draft and this explanation, they do not hide
55
- * it. */
56
- lastRejection(draft: IntentDraft, epoch: ObservationEpoch): LastRejection | undefined;
57
- /** Drops every recorded rejection for one epoch. */
58
- resetEpoch(epoch: ObservationEpoch): void;
59
- }
60
-
61
- export function createRejectionLedger(): RejectionLedger {
62
- const byEpoch = new Map<ObservationEpoch, Map<string, RejectionEntry>>();
63
-
64
- function entryFor(draft: IntentDraft, epoch: ObservationEpoch): RejectionEntry | undefined {
65
- return byEpoch.get(epoch)?.get(attemptFingerprint(draft, epoch));
66
- }
67
-
68
- return {
69
- record(attempt, outcome) {
70
- if (outcome.status !== "rejected") return;
71
- let entries = byEpoch.get(attempt.epoch);
72
- if (entries === undefined) {
73
- entries = new Map();
74
- byEpoch.set(attempt.epoch, entries);
75
- }
76
- const existing = entries.get(attempt.fingerprint);
77
- entries.set(attempt.fingerprint, {
78
- revision: attempt.facts_revision,
79
- count: (existing?.count ?? 0) + 1,
80
- ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
81
- ...(outcome.failure_detail === undefined ? {} : { failure_detail: outcome.failure_detail }),
82
- });
83
- },
84
-
85
- isSuppressed(draft, epoch, factsRevision) {
86
- const entry = entryFor(draft, epoch);
87
- return entry !== undefined && entry.revision === factsRevision;
88
- },
89
-
90
- rejectionCount(draft, epoch) {
91
- return entryFor(draft, epoch)?.count ?? 0;
92
- },
93
-
94
- lastRejection(draft, epoch) {
95
- const entry = entryFor(draft, epoch);
96
- if (entry === undefined) return undefined;
97
- return {
98
- facts_revision: entry.revision,
99
- ...(entry.reason === undefined ? {} : { reason: entry.reason }),
100
- ...(entry.failure_detail === undefined ? {} : { failure_detail: entry.failure_detail }),
101
- };
102
- },
103
-
104
- resetEpoch(epoch) {
105
- byEpoch.delete(epoch);
106
- },
107
- };
108
- }