@cobol-ts/system-identification 0.0.0-stage → 0.0.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,315 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @cobol-ts/system-identification
2
+
3
+ We use the graph engine we have already built to calculate the initial conditions for that same engine.
4
+
5
+ ## Phase 1 — previous values
6
+
7
+ A business graph and a deterministic identification graph are separate authored graphs. The latter receives the ordered, detached observations of one entity, including the published outputs of the legacy system. It calculates candidate initial scalar values; replaying the business graph is what establishes satisfaction. The original hidden state need not be recovered.
8
+
9
+ `discoverPreviousValues(business)` returns the distinct scalar nodes referenced by `prev`, including self-references and targets shared by multiple consumers. It uses CEL free identifiers rather than ordinary canonical dependencies, from which previous-value references have been removed. Rolling-window seeds are not part of phase 1; an explicit `prev` read of a window is reported as unsupported.
10
+
11
+ `preparePreviousValueIdentification(business, identification, projection)` prepares the ordinary CEL graph once and returns an `IdentifyPreviousValues` function. Invoke it once for each entity, passing the available history in execution order. It allocates fresh execution state for every call and projects the outputs onto the required seed names. The resulting `AccumulatorInitial` has the same contract as an authored initial accumulator. The existing runtime validates the scalar types. Intermediate calculation nodes are not returned.
12
+
13
+ ## Example
14
+
15
+ A published integer change flag reports whether the SIC code changed:
16
+
17
+ ```yaml
18
+ # business graph
19
+ sic:
20
+ type: cel
21
+ cel: input.sic
22
+ metadata: {type: string}
23
+ changed:
24
+ type: cel
25
+ cel: 'prev.sic != input.sic ? 1 : 0'
26
+ metadata: {type: number}
27
+ ```
28
+
29
+ An identification graph can calculate a compatible previous SIC using the first observation:
30
+
31
+ ```yaml
32
+ sic:
33
+ type: cel
34
+ cel: >-
35
+ input.observations[0].output.changed == 0
36
+ ? input.observations[0].input.sic
37
+ : (input.observations[0].input.sic == "62020" ? "62010" : "62020")
38
+ metadata: {type: string}
39
+ ```
40
+
41
+ The alternative SIC values are illustrative; real identification expressions must select admissible values for their domain. The previous code is uniquely determined if unchanged; if changed, this calculation chooses one compatible value rather than claiming to recover the historical code.
42
+
43
+ ```typescript
44
+ const projection: ProjectionAuthoring = {
45
+ observations: {type: 'array', element: {
46
+ date: {type: 'string'}, periodicity: {type: 'string'},
47
+ input: {type: 'object', fields: {sic: {type: 'string'}}},
48
+ output: {type: 'object', fields: {changed: {type: 'integer'}}}
49
+ }}
50
+ }
51
+ const identify = valueOrThrow(preparePreviousValueIdentification(business, identification, projection))
52
+ const seed = valueOrThrow(identify([{
53
+ date: '2026-01-31', periodicity: 'monthly',
54
+ input: {sic: '62020'}, output: {changed: 1}
55
+ }]))
56
+ // {sic: '62010'}
57
+ ```
58
+
59
+ Use the existing JSON projection vocabulary to declare the observation fields referenced by CEL. It supports strings and JSON numbers, not native boolean or exact bigint input fields: normalise published flags explicitly to 0/1 (or a string) and do not coerce unsafe integers into numbers. The identification graph can still calculate a boolean seed or use the runtime's bigint representation for suitable projected integers. A period-specific expression can select relevant observations, e.g. `input.observations.filter(o, o.periodicity == "monthly").map(o, o.output.changed)[0]`. Supply only the identification interval; do not pass held-out observations.
60
+
61
+ Missing seed definitions, incompatible types, empty history when a seed is required, execution errors and absent/null calculated seeds are reported via `ErrorsOr`. The identification graph must contain ordinary stateless scalar CEL nodes. It must not read `prev`, schedule nodes, reset state, contain windows or native aggregates. A business graph may still contain rolling windows, but their initial values remain outside this phase.
62
+
63
+ ## Verification
64
+
65
+ The colocated Jest tests generate synthetic legacy observations by executing the real business graph with a hidden seed. They run the identification graph and replay the business graph with the candidate seed, compare all selected published outputs, test held-out predictions, and include a contradictory observation that replay fails to satisfy. Identification calculates a candidate; it does not claim a proof of feasibility, nor does it silently correct contradictory observations. The caller remains responsible for replay and reporting mismatches.
66
+
67
+ Phase 1 does not add a CLI, validation reader integration, persistence, an AI workflow or changes to the production graph executor. Subsequent phases add logical rolling histories, structured observations and multiple aggregate outputs as test cases demand.
68
+
69
+ ## Three-graph identification workflow
70
+
71
+ The new `prepareSystemIdentification(business, evidence, identification, observationProjection)` API supersedes the raw-history phase-1 example for new work. The phase-1 API remains available for existing callers.
72
+
73
+ 1. The **evidence graph** contains only CEL rolling-window nodes with `stopWhenFull: true`. It runs over the ordered observations for one entity. A size-one window without periodicity captures the first execution; a periodic window captures the first N matching executions. Expressions retain only the scalar values needed for identification. No borrowed source-record references are retained.
74
+ 2. The **identification graph** runs once on that entity's evidence accumulator. `input.<evidenceName>` is a typed, logically ordered collection backed by the gathered ring. Ordinary CEL nodes calculate scalars, and terminal CEL nodes with `metadata.array: true` calculate logical arrays. Scalar intermediate nodes are accessible via `now.<name>`; terminal arrays are not intermediate dependencies in this phase. Evidence preserves number, bigint, string and boolean representations without a JSON round trip.
75
+ 3. The **business graph** is replayed using the logical seeds returned as `AccumulatorInitial`. `validateInitialAccumulator` converts the arrays into the existing ring-buffer representation and checks capacity and element types. Native aggregate caches are derived from the window. Explicit previous-value references to native aggregates are not supported by this workflow yet, because those caches must be consistent with the initial window.
76
+
77
+ Example evidence graph for a scalar lifetime counter and a three-month rolling sum:
78
+
79
+ ```yaml
80
+ firstAmount:
81
+ type: cel
82
+ cel: input.input.amount
83
+ metadata:
84
+ type: number
85
+ rollingWindow: {size: 1, stopWhenFull: true}
86
+ firstTotal:
87
+ type: cel
88
+ cel: input.output.total
89
+ metadata:
90
+ type: number
91
+ rollingWindow: {size: 1, stopWhenFull: true}
92
+ monthlyAmounts:
93
+ type: cel
94
+ cel: input.input.amount
95
+ metadata:
96
+ type: number
97
+ rollingWindow: {size: 3, periodicity: monthly, stopWhenFull: true}
98
+ monthlySums:
99
+ type: cel
100
+ cel: input.output.sum
101
+ metadata:
102
+ type: number
103
+ rollingWindow: {size: 3, periodicity: monthly, stopWhenFull: true}
104
+ ```
105
+
106
+ Identification graph, assuming a full initial window, at least two monthly observations and a post-update sum published on monthly runs only:
107
+
108
+ ```yaml
109
+ total:
110
+ type: cel
111
+ cel: input.firstTotal[0] - input.firstAmount[0]
112
+ metadata: {type: number}
113
+ expired:
114
+ type: cel
115
+ cel: input.monthlySums[0] + input.monthlyAmounts[1] - input.monthlySums[1]
116
+ metadata: {type: number}
117
+ remaining:
118
+ type: cel
119
+ cel: input.monthlySums[0] - input.monthlyAmounts[0] - now.expired
120
+ metadata: {type: number}
121
+ history:
122
+ type: cel
123
+ cel: '[0, now.expired, now.remaining]'
124
+ metadata: {type: number, array: true}
125
+ ```
126
+
127
+ The zero represents the unobservable oldest initial slot in this example; if an earlier observation exposes the pre-update window, the identification expression must incorporate that evidence too. The author owns incomplete-history semantics. A calculation indexing an absent observation reports an error rather than silently making up evidence.
128
+
129
+ ```typescript
130
+ const identify = valueOrThrow(prepareSystemIdentification(
131
+ business, evidence, identification, observationProjection))
132
+ const seed = valueOrThrow(identify(observationsForOneEntity))
133
+ // {total: 100, history: [0, 15, 20]}
134
+ ```
135
+
136
+ `observationProjection` is the existing JSON projection of a single `{date, periodicity, input, output}` observation. Evidence CEL expressions may project nested arrays before gathering scalars. The current JSON projection cannot directly read boolean or unsafe-bigint source fields; it can calculate boolean or bigint results, and the bridge to the identification graph preserves them exactly.
137
+
138
+ For YAML authoring of the identification graph, use `parseAuthoringGraph(source, yaml, {allowTerminalCollections: true})`; ordinary business graph parsing still rejects collection result declarations. `prepareStatelessCelGraph` implements the terminal collection path. Both graphs are prepared once; evidence and calculation state are fresh for each entity. Pass only the fitting interval if testing prediction on held-out observations. The caller still owns business replay and comparison. No CLI, GUI, production dataset integration or early exit when all windows fill has been introduced.
139
+
140
+ ## Phase 3 — evidence from structured input
141
+
142
+ The evidence graph projects structured records to scalar observations before retaining them. No new window type, array-of-records accumulator or identification algorithm is required. For example, the business window can contain the monthly sum of cash withdrawals across active accounts:
143
+
144
+ ```yaml
145
+ history:
146
+ type: cel
147
+ cel: >-
148
+ input.accounts.filter(a, a.status == "A")
149
+ .map(a, a.transactions.filter(t, t.kind == "cash")
150
+ .map(t, t.amount).sum()).sum()
151
+ metadata:
152
+ type: number
153
+ rollingWindow: {size: 3, periodicity: monthly}
154
+ sum:
155
+ type: aggregate
156
+ window: history
157
+ operation: sum
158
+ ```
159
+
160
+ The evidence graph uses the same projection of the original input, addressed through the observation's `input` object, and captures the published sum alongside it:
161
+
162
+ ```yaml
163
+ amounts:
164
+ type: cel
165
+ cel: >-
166
+ input.input.accounts.filter(a, a.status == "A")
167
+ .map(a, a.transactions.filter(t, t.kind == "cash")
168
+ .map(t, t.amount).sum()).sum()
169
+ metadata:
170
+ type: number
171
+ rollingWindow: {size: 3, periodicity: monthly, stopWhenFull: true}
172
+ sums:
173
+ type: cel
174
+ cel: input.output.sum
175
+ metadata:
176
+ type: number
177
+ rollingWindow: {size: 3, periodicity: monthly, stopWhenFull: true}
178
+ ```
179
+
180
+ Declare the nested account and transaction arrays in the observation projection using the existing projection vocabulary. The scalar identification calculation from the preceding example is unchanged except for the evidence names (`input.amounts` and `input.sums` instead of `input.monthlyAmounts` and `input.monthlySums`); omit `total` because this business graph has no `prev` reference.
181
+
182
+ For example, monthly projected withdrawals of `[10, 10, 0, 20]` with a hidden full window `[55, 4, 8]` publish sums `[22, 28, 20, 30]`. The first two observations determine the relevant seed entries: `22 + 10 - 28 = 4`, and `22 - 10 - 4 = 8`. The identification graph returns `[0, 4, 8]`, which reproduces all four outputs. Only the first two observations were used for fitting; the remaining two are held-out checks.
183
+
184
+ The tests also cover mixed periodicities, empty collections (a real zero, not a missing month), repeated scalar observations, reuse across entities, and a synchronous producer that reuses its structured source objects between yields. The evidence accumulator holds only scalar values. Insufficient monthly evidence fails this particular identification expression explicitly; other expressions may support shorter histories. The projection in the evidence graph and the business graph must have matching semantics. We deliberately leave automatic expression reuse and real cursor integration for later.
185
+
186
+ ## Phase 4 — one window, multiple published outputs
187
+
188
+ The business graph may publish several native aggregates of the same window. Do not reconstruct independent histories for each aggregate: one initial history must reproduce every published characteristic. The authored CEL graphs in `src/multiple.outputs.spec.ts` demonstrate this without new production code, a solver or AI at execution time.
189
+
190
+ ### Full six-month window; three observations
191
+
192
+ For this example, monthly inputs `[15, 25, 35]` are observed after a hidden full initial window `[99, 50, 5, 30, 20, 10]`. The published sums are `[130, 105, 135]`, maxima `[50, 30, 35]` and minima `[5, 5, 10]`. The evidence graph captures the first three monthly values of each relevant characteristic using `stopWhenFull`. For an input-derived window the same equations work whether the observations were projected from scalar fields or nested records.
193
+
194
+ Consecutive sums determine the two expiring historical values:
195
+
196
+ - `a = 130 + 25 - 105 = 50`
197
+ - `b = 105 + 35 - 135 = 5`
198
+ - `remaining = 130 - 15 - 50 - 5 = 60`
199
+
200
+ The three remaining historical values survive all three observations, so every one must lie between the largest observed minimum (`10`) and smallest observed maximum (`30`). Allocate the residual above the lower bound deterministically, filling each slot up to the upper bound before proceeding to the next slot. This construction also supplies required extrema for feasible observations in this bounded integer example. The other values in the window may themselves supply an extremum. Replay is the final check.
201
+
202
+ ```yaml
203
+ a:
204
+ type: cel
205
+ cel: input.sums[0] + input.amounts[1] - input.sums[1]
206
+ metadata: {type: number}
207
+ b:
208
+ type: cel
209
+ cel: input.sums[1] + input.amounts[2] - input.sums[2]
210
+ metadata: {type: number}
211
+ remaining:
212
+ type: cel
213
+ cel: input.sums[0] - input.amounts[0] - now.a - now.b
214
+ metadata: {type: number}
215
+ lower:
216
+ type: cel
217
+ cel: input.mins.max()
218
+ metadata: {type: number}
219
+ upper:
220
+ type: cel
221
+ cel: input.maxs.min()
222
+ metadata: {type: number}
223
+ extra:
224
+ type: cel
225
+ cel: now.remaining - 3 * now.lower
226
+ metadata: {type: number}
227
+ capacity:
228
+ type: cel
229
+ cel: now.upper - now.lower
230
+ metadata: {type: number}
231
+ firstExtra:
232
+ type: cel
233
+ cel: '[now.extra, now.capacity].min()'
234
+ metadata: {type: number}
235
+ secondExtra:
236
+ type: cel
237
+ cel: '[now.extra - now.firstExtra, now.capacity].min()'
238
+ metadata: {type: number}
239
+ history:
240
+ type: cel
241
+ cel: >-
242
+ [0, now.a, now.b, now.lower + now.firstExtra,
243
+ now.lower + now.secondExtra,
244
+ now.lower + now.extra - now.firstExtra - now.secondExtra]
245
+ metadata: {type: number, array: true}
246
+ ```
247
+
248
+ The result is `[0, 50, 5, 30, 20, 10]`. The oldest slot is unobservable under the example's post-update publishing semantics. If we only use sum and maximum and assume non-negative values, `[0, 50, 5, 30, 30, 0]` also fits the first three months. It can fail later before the synthetic history expires. The tests explicitly demonstrate both outcomes; agreement on fitting data is not a guarantee of prediction.
249
+
250
+ ### Count and partially populated windows
251
+
252
+ The first published count minus one gives the number of relevant initial values when the first observation inserts one value. If the window is already full, the unobservable oldest slot can be omitted; a five-element seed becomes full on its first update just like a six-element seed. Do not pad a partial window with zeros, because zero is a real observation and changes count and potentially extrema.
253
+
254
+ For one to three monthly observations, the `countedExtrema` authored graph in the test suite uses count to decide whether the second and third updates expired a value. Each expired value is reconstructed from consecutive sums. The remaining unknown slots share bounds from the published minima and maxima, and the terminal CEL array uses `filter` and `map` to emit exactly the required occupancy. The same graph works with empty, partially populated and full histories, signed values, and repeated extrema. It fits all four aggregates simultaneously and uses the existing logical-array initialisation contract.
255
+
256
+ These are authored examples for six-slot windows, up to three consecutive monthly fitting updates, integer arithmetic within the runtime's supported range, and post-update published aggregates. The count-based example supports one, two or three observations; the full-window examples require three. They are not a general inversion engine. Other window sizes, missing updates, non-contiguous fitting observations, different numeric/rounding semantics, overlapping windows and state-dependent observations need appropriate authored identification logic and tests. Inconsistent evidence may produce a type-correct candidate that fails replay; candidate calculation alone is not a proof of feasibility. AI can author the evidence and identification graphs; runtime execution and verification are deterministic. Automatic graph generation is deliberately deferred.
257
+
258
+
259
+ ### Streaming evidence across layouts
260
+
261
+ `prepareStreamingSystemIdentification` accepts named observation projections. Prepare once, then create a session per entity. Call `session.observe(composition, observation)` in manifest execution order and `session.finish()` to calculate the logical seed. All layout executors share the same bounded evidence accumulator; a different periodicity or composition does not restart the window. No raw historical records need be retained. The original iterable `prepareSystemIdentification` API is a convenience wrapper over the same workflow.
262
+
263
+ ### Composing independently authored identification graphs
264
+
265
+ `composeIdentificationGraphs(business, fragments, layouts)` accepts one `{target, evidence, identification}` fragment for each discovered historical requirement. It returns a single `{evidence, identification}` pair. Each fragment is compiled independently against the supplied logical observation layouts; a missing reference cannot accidentally bind to another experiment's helper. The complete pair is then compiled against the same layouts.
266
+
267
+ Evidence names and private identification calculation names are namespaced with deterministic, collision-free names derived from their target. The actual seed name is preserved. CEL references are rewritten by the CEL parser, not text replacement: `input` references in the identification graph follow renamed evidence windows, and `now` references follow renamed calculation nodes. Real observation field names, literals and lexical collection variables are unaffected. Declared dependency paths are renamed consistently. The original candidates are not modified. Selection order does not affect the result.
268
+
269
+ All historical requirements must be present exactly once; unknown, duplicate or missing targets are errors. This phase does not choose experiments, deduplicate equivalent evidence windows, solve interdependent latent-state groups, materialise seeds for a dataset or establish joint empirical satisfaction. The composed graphs can be passed directly to `prepareStreamingSystemIdentification` to calculate a complete initial accumulator once per entity.
270
+
271
+ ## Phase 3 — evidence from structured input
272
+
273
+ The evidence graph projects structured records to scalar observations before retaining them. No new window type, array-of-records accumulator or identification algorithm is required. For example, the business window can contain the monthly sum of cash withdrawals across active accounts:
274
+
275
+ ```yaml
276
+ history:
277
+ type: cel
278
+ cel: >-
279
+ input.accounts.filter(a, a.status == "A")
280
+ .map(a, a.transactions.filter(t, t.kind == "cash")
281
+ .map(t, t.amount).sum()).sum()
282
+ metadata:
283
+ type: number
284
+ rollingWindow: {size: 3, periodicity: monthly}
285
+ sum:
286
+ type: aggregate
287
+ window: history
288
+ operation: sum
289
+ ```
290
+
291
+ The evidence graph uses the same projection of the original input, addressed through the observation's `input` object, and captures the published sum alongside it:
292
+
293
+ ```yaml
294
+ amounts:
295
+ type: cel
296
+ cel: >-
297
+ input.input.accounts.filter(a, a.status == "A")
298
+ .map(a, a.transactions.filter(t, t.kind == "cash")
299
+ .map(t, t.amount).sum()).sum()
300
+ metadata:
301
+ type: number
302
+ rollingWindow: {size: 3, periodicity: monthly, stopWhenFull: true}
303
+ sums:
304
+ type: cel
305
+ cel: input.output.sum
306
+ metadata:
307
+ type: number
308
+ rollingWindow: {size: 3, periodicity: monthly, stopWhenFull: true}
309
+ ```
310
+
311
+ Declare the nested account and transaction arrays in the observation projection using the existing projection vocabulary. The scalar identification calculation from the preceding example is unchanged except for the evidence names (`input.amounts` and `input.sums` instead of `input.monthlyAmounts` and `input.monthlySums`); omit `total` because this business graph has no `prev` reference.
312
+
313
+ For example, monthly projected withdrawals of `[10, 10, 0, 20]` with a hidden full window `[55, 4, 8]` publish sums `[22, 28, 20, 30]`. The first two observations determine the relevant seed entries: `22 + 10 - 28 = 4`, and `22 - 10 - 4 = 8`. The identification graph returns `[0, 4, 8]`, which reproduces all four outputs. Only the first two observations were used for fitting; the remaining two are held-out checks.
314
+
315
+ The tests also cover mixed periodicities, empty collections (a real zero, not a missing month), repeated scalar observations, reuse across entities, and a synchronous producer that reuses its structured source objects between yields. The evidence accumulator holds only scalar values. Insufficient monthly evidence fails this particular identification expression explicitly; other expressions may support shorter histories. The projection in the evidence graph and the business graph must have matching semantics. We deliberately leave automatic expression reuse and real cursor integration for later.
@@ -0,0 +1,3 @@
1
+ export * from './src/previous.values';
2
+ export * from './src/identification';
3
+ export * from './src/identification.compose';
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./src/previous.values"), exports);
18
+ __exportStar(require("./src/identification"), exports);
19
+ __exportStar(require("./src/identification.compose"), exports);
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wDAAqC;AACrC,uDAAoC;AACpC,+DAA4C"}
@@ -0,0 +1,17 @@
1
+ import { type AuthoringGraph } from '@cobol-ts/cel-graph-runtime';
2
+ import type { ProjectionAuthoring } from '@cobol-ts/cursor-loader-types';
3
+ import { type ErrorsOr } from '@cobol-ts/errors';
4
+ export type IdentificationGraphs = Readonly<{
5
+ evidence: AuthoringGraph;
6
+ identification: AuthoringGraph;
7
+ }>;
8
+ export type IdentificationFragment = IdentificationGraphs & Readonly<{
9
+ target: string;
10
+ }>;
11
+ /** Compose a complete set of independent experiments. Validate each fragment in
12
+ * isolation before namespacing, then compile the complete pair against every layout.
13
+ * Compilation is not evidence of joint empirical satisfaction. */
14
+ export declare function composeIdentificationGraphs(business: AuthoringGraph, fragments: readonly IdentificationFragment[], layouts: readonly {
15
+ name: string;
16
+ projection: ProjectionAuthoring;
17
+ }[], allowPartial?: boolean): ErrorsOr<IdentificationGraphs>;
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.composeIdentificationGraphs = composeIdentificationGraphs;
4
+ const cel_1 = require("@cobol-ts/cel");
5
+ const cel_graph_runtime_1 = require("@cobol-ts/cel-graph-runtime");
6
+ const errors_1 = require("@cobol-ts/errors");
7
+ const identification_1 = require("./identification");
8
+ /** Keep a deterministic, readable namespace; never allocate an existing name. */
9
+ function privateNames(graph, target, kind, reserved, keep) {
10
+ const names = new Map();
11
+ const safe = (name) => name.replace(/[^A-Za-z0-9_]/g, '_');
12
+ for (const name of Object.keys(graph).sort()) {
13
+ if (name === keep) {
14
+ names.set(name, name);
15
+ continue;
16
+ }
17
+ const base = `id_${safe(target)}_${kind}_${safe(name)}`;
18
+ let candidate = base, suffix = 1;
19
+ while (reserved.has(candidate))
20
+ candidate = `${base}_${suffix++}`;
21
+ reserved.add(candidate);
22
+ names.set(name, candidate);
23
+ }
24
+ return names;
25
+ }
26
+ function renamedGraph(graph, names, references) {
27
+ const nodes = [];
28
+ for (const [name, node] of Object.entries(graph)) {
29
+ if (node.type !== 'cel')
30
+ return (0, errors_1.errors)(`Identification composition: ${name} is not a CEL node`);
31
+ let cel = node.cel;
32
+ for (const [root, mapping] of references)
33
+ for (const [from, to] of mapping) {
34
+ if (from === to)
35
+ continue;
36
+ const rewritten = (0, cel_1.rewriteCelGraphReferences)(cel, from, to, [root]);
37
+ if ('errors' in rewritten)
38
+ return (0, errors_1.errors)(...rewritten.errors.map(error => `${name}: ${error}`));
39
+ cel = rewritten.value;
40
+ }
41
+ const dependsOn = node.dependsOn?.map(path => {
42
+ const [root, field, ...rest] = path.split('.');
43
+ const mapping = references.find(([candidate]) => candidate === root)?.[1];
44
+ return (mapping?.has(field) ? [root, mapping.get(field), ...rest].join('.') : path);
45
+ });
46
+ nodes.push([names.get(name), { ...node, cel, ...(dependsOn === undefined ? {} : { dependsOn }) }]);
47
+ }
48
+ return (0, errors_1.value)(Object.fromEntries(nodes));
49
+ }
50
+ /** Compose a complete set of independent experiments. Validate each fragment in
51
+ * isolation before namespacing, then compile the complete pair against every layout.
52
+ * Compilation is not evidence of joint empirical satisfaction. */
53
+ function composeIdentificationGraphs(business, fragments, layouts, allowPartial = false) {
54
+ const requirements = (0, identification_1.discoverIdentificationRequirements)(business);
55
+ if ('errors' in requirements)
56
+ return requirements;
57
+ const required = new Set(requirements.value.map(item => item.name));
58
+ const seen = new Set();
59
+ for (const fragment of fragments) {
60
+ if (!required.has(fragment.target))
61
+ return (0, errors_1.errors)(`Unknown identification target '${fragment.target}'`);
62
+ if (seen.has(fragment.target))
63
+ return (0, errors_1.errors)(`Duplicate identification target '${fragment.target}'`);
64
+ seen.add(fragment.target);
65
+ }
66
+ const missing = [...required].filter(name => !seen.has(name)).sort();
67
+ if (!allowPartial && missing.length)
68
+ return (0, errors_1.errors)(`Missing identification targets: ${missing.join(', ')}`);
69
+ if (!fragments.length)
70
+ return (0, errors_1.errors)('No identification fragments to compose');
71
+ // Fresh names cannot equal any old name, so sequential rewrites cannot cascade.
72
+ const reserved = new Set([...required, ...fragments.flatMap(fragment => [...Object.keys(fragment.evidence), ...Object.keys(fragment.identification)])]);
73
+ const evidenceSources = [], identificationSources = [];
74
+ for (const fragment of [...fragments].sort((a, b) => a.target < b.target ? -1 : a.target > b.target ? 1 : 0)) {
75
+ const { target, evidence, identification } = fragment;
76
+ const checked = (0, identification_1.prepareStreamingSystemIdentification)(business, evidence, identification, layouts, [target]);
77
+ if ('errors' in checked)
78
+ return (0, errors_1.errors)(...checked.errors.map(error => `${target}: ${error}`));
79
+ const evidenceNames = privateNames(evidence, target, 'evidence', reserved);
80
+ const calculationNames = privateNames(identification, target, 'calc', reserved, target);
81
+ const gathered = renamedGraph(evidence, evidenceNames, []);
82
+ if ('errors' in gathered)
83
+ return gathered;
84
+ const calculated = renamedGraph(identification, calculationNames, [['input', evidenceNames], ['now', calculationNames]]);
85
+ if ('errors' in calculated)
86
+ return calculated;
87
+ evidenceSources.push({ name: target, graph: gathered.value });
88
+ identificationSources.push({ name: target, graph: calculated.value });
89
+ }
90
+ const evidence = (0, cel_graph_runtime_1.composeAuthoringGraphs)(evidenceSources), identification = (0, cel_graph_runtime_1.composeAuthoringGraphs)(identificationSources);
91
+ const checked = (0, identification_1.prepareStreamingSystemIdentification)(business, evidence, identification, layouts, allowPartial ? [...seen] : undefined);
92
+ return 'errors' in checked ? checked : (0, errors_1.value)({ evidence, identification });
93
+ }
94
+ //# sourceMappingURL=identification.compose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identification.compose.js","sourceRoot":"","sources":["../../src/ident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,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAA,cAAK,EAAC,EAAC,QAAQ,EAAE,cAAc,EAAC,CAAC,CAAA;AAC5E,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const errors_1 = require("@cobol-ts/errors");
4
+ const cel_graph_runtime_1 = require("@cobol-ts/cel-graph-runtime");
5
+ const cel_access_1 = require("@cobol-ts/cel-access");
6
+ const cursor_loader_indexed_graph_state_1 = require("@cobol-ts/cursor-loader-indexed-graph-state");
7
+ const index_1 = require("../index");
8
+ const number = (cel, array = false) => ({ type: 'cel', cel, metadata: { type: 'number', ...(array ? { array: true } : {}) } });
9
+ const capture = (cel, size = 1, periodicity) => ({ ...number(cel), metadata: { type: 'number',
10
+ rollingWindow: { size, stopWhenFull: true, ...(periodicity ? { periodicity } : {}) } } });
11
+ const business = {
12
+ total: number('prev.total + input.amount'),
13
+ history: { ...number('input.amount'), metadata: { type: 'number', rollingWindow: { size: 3, periodicity: 'monthly' } } },
14
+ sum: { type: 'aggregate', operation: 'sum', window: 'history' }
15
+ };
16
+ const projection = { input: { type: 'object', fields: { amount: { type: 'integer' } } },
17
+ output: { type: 'object', fields: { total: { type: 'integer' }, sum: { type: 'integer' } } } };
18
+ const layouts = [{ name: 'one', projection }];
19
+ const total = { target: 'total', evidence: { amounts: capture('input.input.amount'), published: capture('input.output.total') },
20
+ identification: { remaining: number('input.published[0] - input.amounts[0]'), total: number('now.remaining') } };
21
+ const history = { target: 'history', evidence: { amounts: capture('input.input.amount', 2, 'monthly'), published: capture('input.output.sum', 2, 'monthly') },
22
+ identification: { expired: number('input.published[0] + input.amounts[1] - input.published[1]'),
23
+ remaining: number('input.published[0] - input.amounts[0] - now.expired'),
24
+ history: number('[0, now.expired, now.remaining]', true) } };
25
+ const observations = [{ date: '1', periodicity: 'daily', input: { amount: 8 }, output: { total: 108 } },
26
+ { date: '2', periodicity: 'monthly', input: { amount: 10 }, output: { total: 118, sum: 45 } },
27
+ { date: '3', periodicity: 'monthly', input: { amount: 20 }, output: { total: 138, sum: 50 } }];
28
+ it('composes independently authored fragments with colliding evidence and intermediate names and preserves the two seed names', () => {
29
+ const before = JSON.stringify([total, history]);
30
+ const pair = (0, errors_1.valueOrThrow)((0, index_1.composeIdentificationGraphs)(business, [total, history], layouts));
31
+ expect(Object.keys(pair.evidence).length).toEqual(4);
32
+ expect(Object.keys(pair.identification).length).toEqual(5);
33
+ const identify = (0, errors_1.valueOrThrow)((0, index_1.prepareSystemIdentification)(business, pair.evidence, pair.identification, projection));
34
+ expect((0, errors_1.valueOrThrow)(identify(observations))).toEqual({ total: 100, history: [0, 15, 20] });
35
+ expect((0, errors_1.valueOrThrow)((0, index_1.composeIdentificationGraphs)(business, [history, total], layouts))).toEqual(pair);
36
+ expect(JSON.stringify([total, history])).toEqual(before);
37
+ });
38
+ it('rejects incomplete, duplicate and unknown seed selections', () => {
39
+ expect((0, errors_1.errorsOrThrow)((0, index_1.composeIdentificationGraphs)(business, [total], layouts)).join()).toContain('Missing identification targets: history');
40
+ expect((0, errors_1.errorsOrThrow)((0, index_1.composeIdentificationGraphs)(business, [total, total, history], layouts)).join()).toContain('Duplicate identification target');
41
+ expect((0, errors_1.errorsOrThrow)((0, index_1.composeIdentificationGraphs)(business, [{ ...total, target: 'missing' }, history], layouts)).join()).toContain('Unknown identification target');
42
+ });
43
+ it('does not let a fragment accidentally resolve its missing references against a different experiment', () => {
44
+ const broken = { ...total, identification: { total: number('now.expired') } };
45
+ expect((0, errors_1.errorsOrThrow)((0, index_1.composeIdentificationGraphs)(business, [broken, history], layouts)).join()).toContain('total:');
46
+ });
47
+ it('keeps real observation fields and literal strings intact while rewriting private references', () => {
48
+ const modified = { ...total, identification: { ...total.identification,
49
+ total: number('"now.remaining" == "now.remaining" ? now.remaining : 0') } };
50
+ const pair = (0, errors_1.valueOrThrow)((0, index_1.composeIdentificationGraphs)(business, [modified, history], layouts));
51
+ expect(pair.identification.total.cel).toContain('"now.remaining"');
52
+ expect((0, errors_1.valueOrThrow)((0, errors_1.valueOrThrow)((0, index_1.prepareSystemIdentification)(business, pair.evidence, pair.identification, projection))(observations)))
53
+ .toEqual({ total: 100, history: [0, 15, 20] });
54
+ });
55
+ it('initialises the real business graph with the composed seed and replays both published outputs together', () => {
56
+ const pair = (0, errors_1.valueOrThrow)((0, index_1.composeIdentificationGraphs)(business, [total, history], layouts));
57
+ const identify = (0, errors_1.valueOrThrow)((0, index_1.prepareSystemIdentification)(business, pair.evidence, pair.identification, projection));
58
+ const seed = (0, errors_1.valueOrThrow)(identify(observations));
59
+ const initial = (0, errors_1.valueOrThrow)((0, cel_graph_runtime_1.validateInitialAccumulator)(seed, business, (0, errors_1.valueOrThrow)((0, cel_graph_runtime_1.canonicaliseCelGraph)(business))));
60
+ const input = { amount: { type: 'integer' } };
61
+ const prepared = (0, errors_1.valueOrThrow)((0, cel_graph_runtime_1.prepareCelGraph)(business, input, (0, cel_access_1.jsonAccessCompiler)(input)));
62
+ const state = (0, cursor_loader_indexed_graph_state_1.createIndexedGraphRecord)(prepared.schema.nodes.length);
63
+ prepared.schema.nodes.forEach((node, index) => { state.values[index] = initial[node.name]; });
64
+ const execute = prepared.createExecutor();
65
+ for (const observation of observations) {
66
+ execute(observation.input, state, { periodicity: observation.periodicity });
67
+ for (const [name, expected] of Object.entries(observation.output))
68
+ expect(state.values[prepared.schema.nodes.findIndex(node => node.name === name)]).toEqual(expected);
69
+ }
70
+ });
71
+ //# sourceMappingURL=identification.compose.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identification.compose.spec.js","sourceRoot":"","sources":["../../src/identification.compose.spec.ts"],"names":[],"mappings":";;AAAA,6CAA4D;AAC5D,mEAAkI;AAClI,qDAAuD;AACvD,mGAAoF;AAEpF,oCAA8G;AAE9G,MAAM,MAAM,GAAG,CAAC,GAAW,EAAE,KAAK,GAAG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edGraphRecord } from '@cobol-ts/cursor-loader-indexed-graph-state';
3
+ import type { ProjectionAuthoring } from '@cobol-ts/cursor-loader-types';
4
+ import { type RingBuffer } from '@cobol-ts/ring-buffer';
5
+ import { type ErrorsOr } from '@cobol-ts/errors';
6
+ import { type Observation } from './previous.values';
7
+ export type IdentificationRequirement = Readonly<{
8
+ name: string;
9
+ valueType: GraphNode['valueType'];
10
+ }>;
11
+ export declare function discoverIdentificationRequirements(business: AuthoringGraph): ErrorsOr<IdentificationRequirement[]>;
12
+ /** Evidence graph runs once per observation. Its state contains only bounded, scalar windows. */
13
+ export declare function prepareEvidenceGathering(graph: AuthoringGraph, projection: ProjectionAuthoring): import("@cobol-ts/errors").Errors | import("@cobol-ts/errors").Value<{
14
+ windows: Readonly<Record<string, Readonly<{
15
+ valueType: Readonly<{
16
+ kind: "rolling-window";
17
+ periodicity?: string;
18
+ stopWhenFull?: boolean;
19
+ size: number;
20
+ element: import("@cobol-ts/value-types").ScalarValueType;
21
+ }>;
22
+ read: (record: IndexedGraphRecord) => RingBuffer<import("@cobol-ts/cel-types").CelValue>;
23
+ }>>>;
24
+ schema: import("@cobol-ts/cursor-loader-indexed-graph-state").IndexedGraphSchema;
25
+ createState: () => IndexedGraphRecord;
26
+ observe: (state: IndexedGraphRecord, observation: Observation) => void;
27
+ gather(observations: Iterable<Observation>): ErrorsOr<IndexedGraphRecord>;
28
+ }>;
29
+ export type IdentifyEntity = (observations: Iterable<Observation>) => ErrorsOr<AccumulatorInitial>;
30
+ /** Three-graph workflow: gather, calculate candidate seed, then caller replays the business graph.
31
+ * Both authored preparation graphs are compiled once, and each call owns fresh state.
32
+ * Optional seedNames selects a partial seed fragment for an independent identification experiment. */
33
+ export declare function prepareSystemIdentification(business: AuthoringGraph, evidence: AuthoringGraph, identification: AuthoringGraph, observationProjection: ProjectionAuthoring, seedNames?: readonly string[]): ErrorsOr<IdentifyEntity>;
34
+ export interface IdentificationSession {
35
+ observe(layout: string, observation: Observation): void;
36
+ finish(): ErrorsOr<AccumulatorInitial>;
37
+ }
38
+ /** Inspection is opt-in; ordinary identification never copies evidence windows. */
39
+ type EvidenceSnapshot = Record<string, ReturnType<GraphInputWindows<IndexedGraphRecord>[string]['read']>>;
40
+ export interface InspectableIdentificationSession extends IdentificationSession {
41
+ evidenceValues(): ErrorsOr<EvidenceSnapshot>;
42
+ inspect(): {
43
+ values: ErrorsOr<AccumulatorInitial>;
44
+ seed: ErrorsOr<AccumulatorInitial>;
45
+ partialValues: AccumulatorInitial;
46
+ };
47
+ }
48
+ /** Compile each layout once; all layouts update one bounded evidence state per
49
+ * entity. Borrowed records can be projected, observed and released immediately. */
50
+ export declare function prepareStreamingSystemIdentification(business: AuthoringGraph, evidence: AuthoringGraph, identification: AuthoringGraph, layouts: readonly {
51
+ name: string;
52
+ projection: ProjectionAuthoring;
53
+ }[], seedNames?: readonly string[]): ErrorsOr<() => InspectableIdentificationSession>;
54
+ export {};