Repository navigation
Expand file tree
/
Copy pathcheck-engine-double-contract.mjs
More file actions
5677 lines (5350 loc) · 295 KB
/
Copy pathcheck-engine-double-contract.mjs
File metadata and controls
5677 lines (5350 loc) · 295 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// check-engine-double-contract -- a fake ObjectQL engine's WRITE VERBS must be
// pinned to the real engine's dispatch contract, not a looser hand-written
// approximation of it (objectstack#4550, from objectstack#4434; the `update`
// slice added by objectstack#5480).
//
// node scripts/check-engine-double-contract.mjs
// node scripts/check-engine-double-contract.mjs --self-test
//
// ## The failure mode this exists for
//
// `DELETE /api/v1/sharing/rules/:idOrName` answered **500 for every rule and
// both address forms** from the day it was written. It was not untested:
// plugin-sharing's `deleteRule drops rule + all its grants` asserted success on
// it the whole time -- against a FAKE ENGINE whose `delete` accepted a call the
// real engine refuses. `deleteRule` purged `sys_record_share` with a
// predicate-shaped delete carrying neither a scalar `where.id` nor
// `options.multi`, which is precisely the one shape `ObjectQL.delete` throws
// on. The fake deleted by predicate happily, so the suite was green, the gate
// was green, and the route was dead. That is #4434.
//
// The general shape, and the reason this is a gate rather than a fixed test:
// **a test double looser than the implementation it replaces converts a green
// suite into no suite at all**, silently, on exactly the paths a double was
// introduced for -- which are the paths that were hard to test, which are
// usually the paths where the contract is densest.
//
// ## Slices: the WRITE-VERB dispatches, and only on ENGINE doubles
//
// #4550 lists four instances of the family. This gate takes the ones whose
// criterion is mechanically decidable with no judgment call: a write verb's
// dispatch is a total function from a call to one of three verdicts, so "is
// this double looser?" has a yes/no answer that does not depend on reading the
// test's intent.
//
// - `delete` -- `assertEngineDeleteDispatch` / `resolveEngineDeleteDispatch`
// (#4550, from #4434).
// - `update` -- `assertEngineUpdateDispatch` / `resolveEngineUpdateDispatch`
// (#5480). Same three-way dispatch, same destructiveness: a predicate
// update rewrites every matching row's fields. It sat in the "not covered"
// list below until #5480 extracted the producer-side predicate it needed,
// which is the ONLY thing that was ever missing -- the criterion, the
// scanner and the ledger are shared verbatim.
//
// A slice is exactly two facts: which member of the double to look at, and
// which producer-side predicate that member must reach. Everything else --
// the shape attribution below, the one-helper-deep indirection, the ledger,
// the both-directions reconciliation -- is one implementation serving both.
//
// ## Three data-access shapes, not two (#6327, from #5945)
//
// A discovered literal is attributed to one of THREE contracts, because the
// repo has three. The write verbs side by side are the whole taxonomy:
//
// IDataEngine update(objectName, data, options?) object name FIRST
// IDataDriver update(objectName, id, data, …) primary key SECOND
// IScopedObjectRepository update(data, options?) NO object name
//
// Only the first is this gate's subject. The driver is vetoed by
// DRIVER_ONLY_MEMBERS and the primary-key parameter test; the scoped repository
// -- added by #5945 as `packages/spec/src/contracts/scoped-context.ts`, and
// implemented by objectql's `ObjectRepository` -- is vetoed by
// REPOSITORY_ONLY_MEMBERS. Both vetoes put their shape OUT OF SCAN SCOPE rather
// than into the ledger, because neither is a looser copy of `ObjectQL.<verb>`:
// it is a different function with a different arity, so there is no dispatch
// contract for it to be looser THAN.
//
// Why the third arm had to be built rather than baselined: a scoped repository
// binds to one object, so its literal reads as engine-shaped to a scan that can
// only see member names (`find`/`findOne`/`count`/`insert`, and `insert` is in
// ENGINE_ONLY_MEMBERS). Accurate for what the scan can see, wrong about what the
// object is. `@objectstack/spec` -- where the contract and both of its
// conformance witnesses live -- cannot import `assertEngineUpdateDispatch` even
// in principle, since the predicate's two homes both DEPEND ON spec, so every
// witness of this interface could only ever leave the gate through a
// hand-written EXEMPT. A gate that reddens correct code and can only be digested
// through its ledger grows the ledger into noise, and the ledger's readability
// is this gate's whole value (see the baseline's `$comment`: shrink-only, hand
// reviewed).
//
// A fourth shape sits one layer BELOW the driver (#29859): MongoDB's native
// `Collection`, faked by driver-mongodb tests to record what the driver sends.
// `findOne(filter, options)` takes no object name, and `find`/`insertMany`
// read as engine siblings, so it is vetoed by NATIVE_COLLECTION_ONLY_MEMBERS
// under the same object-name guard -- out of scan scope, for the same reason.
//
// Deliberately NOT covered, and why (each wants its own slice, not a vaguer
// version of these -- a gate whose scope is fuzzy is indistinguishable from
// no gate to everyone downstream of it):
//
// - fixtures that disable a platform constraint in prose (`// FK enforcement
// is off in this harness`, #4441). The criterion is a comment, so it is
// both evadable by deleting the comment and unable to find the silent
// cases. That one wants a declared debt ledger, not a scanner.
// - stubbing the very thing under assertion (objectui#3129) and missing
// counterparts (objectui#3134). Both live in the `objectui` repo, which
// this script cannot see, and #3134 names no double at all.
// - the option surface (unknown-option rejection). Same family, but it needs
// its own producer-side predicate extracted first -- the two write verbs
// have one because #4434 and #5480 paid for them.
// - the READ side (`find` filter semantics) is no longer uncovered:
// `scripts/check-where-matcher-conformance.mjs` (#8494) holds it. It could
// not follow this gate's pattern, because extracting the producer-side
// predicate a read slice would need -- a shared `matchesWhere` -- was ruled
// NO on #7620 for these doubles specifically. So it asks each independent
// double a behavioural question instead of handing it an implementation.
// - a scoped repository that declares NO repository-only member. Measured on
// the corpus this landed against:
// `packages/runtime/src/action-body-identity.test.ts` (line 71 as measured)
// is a real scoped facade (`createContext().object(name)`)
// spelling only `find`/`count`/`insert`/`update`/`delete`, and it stays in
// the ledger. Seeing it would mean reading its parameter NAMES, and `o` is
// ambiguous in exactly this repo: `o: string` is the object name in twelve
// discovered doubles and `o?: any` is the options bag in that facade. A
// criterion that guessed would trade a ledger row for the risk of putting a
// genuine engine double out of scan scope, which is the one error this gate
// cannot report. One ledger row is the cheaper half.
//
// ## Two admission routes: sibling INFERENCE, and a DECLARED contract (#11626)
//
// Everything above describes discovery inferring "is this an engine?" from the
// members a literal declares, which needs the verb plus two engine siblings to
// separate a fake engine from every cache and router in the repo. That
// threshold is right for inference and it had one structural consequence,
// measured rather than argued: a double declaring ONLY the verb under test was
// never discovered, so it could never be pinned, and this script's headline
// number excluded the whole minimal class without saying so.
//
// The half that made it a defect rather than a coverage gap is what it asked
// of an author. The only way into the ratchet was to give the double
// `find`/`insert` siblings that exist to be COUNTED and that the test never
// calls -- so the gate's own admission criterion rewarded padding a double with
// ceremony, and a reader of a padded double cannot tell which verbs are
// load-bearing. That is the property a test double exists to have.
//
// So there is a second route, and it is a different KIND of evidence rather
// than a looser guess: the construct DECLARES the contract it implements
// (`const engine: IDataEngine = …`, `… as unknown as IDataEngine`, a factory's
// return type, `class F implements IDataEngine`). Declared means enforced. The
// criterion, the measurement behind it and the import test that keeps it from
// being a spelling match all live at ENGINE_CONTRACT_NAME below.
//
// What the second route deliberately does NOT do is relax the first. Measured
// on the corpus this landed against: dropping the sibling threshold to zero
// admits 74 constructs, of which 32 are HTTP routers and servers whose
// `delete` is the HTTP verb (7 of them saying so with an explicit
// `IHttpServer`), and most of the remaining 40 are stores and persistence
// facades declared as some other contract entirely -- `EmailPersistence`,
// `SettingsSecretStore` -- or as `any`. Exactly 2 declare `IDataEngine`, both single-verb
// doubles already calling `assertEngineUpdateDispatch` and getting nothing for
// it. Reddening correct code is the one cost this gate's ledger cannot absorb.
//
// ⛔ THE RESIDUAL GAP, stated because a closed-sounding section is worse than
// an open one: a single-verb double that declares NOTHING -- `const engine =
// { async update(o, data, opts) { … } }`, no annotation, no assertion -- is
// still outside discovery, and this route does not reach it. Nothing in the
// output will say so, which is the same shape as the defect this section
// closes, one step narrower. It is left open deliberately: the only evidence
// available for such a construct is its member names, and that is the
// inference route, at a threshold already measured to sweep in routers by the
// dozen. The remedy an author has is now cheap and honest -- annotate the
// double with the contract it stands in for -- where before it was to pad it.
//
// ## Invariants
//
// Each holds PER SLICE -- a green `delete` slice says nothing about `update`,
// and the ledger is keyed on (file, verb) for the same reason.
//
// DISCOVERED the scan found engine doubles at all. Zero is not "a clean
// repo", it is a broken scan: PINNED iterates the discovered set,
// so a discovery that silently stops matching makes this script
// print OK while checking nothing -- the #4868 family, where a
// check runs, is green, and structurally cannot reach its subject.
// PINNED every discovered engine double's verb routes through that
// slice's `assert…Dispatch` / `resolve…Dispatch` -- the predicate
// the real `ObjectQL.<verb>` itself uses, importable from
// `@objectstack/metadata-core` (where it lives since #5619) or
// from `@objectstack/objectql` (which re-exports it from the
// original path) -- or its file carries a measured baseline entry
// for that verb.
// RECONCILED one-sided (#26586). A baseline entry for a file with no
// unguarded doubles left, for a file that no longer exists, or
// whose count is now lower, PASSES and is reported with the edit
// that ratchets it down -- deleting or fixing a test file must not
// red a PR that never touched this gate. Until that edit lands
// the old count stays the file's ceiling, and the report says so.
// Growth is PINNED's, and still fails.
// UNREAD the dead-scan half RECONCILED going one-sided needs. An entry
// whose file is still on disk but was not among the test files
// the walk read is an error, not a decrease: a walk that lost part
// of the tree used to red through RECONCILED, and would otherwise
// pass as a list of shrunken entries.
// DECLARED every baseline entry names a `verb` this script actually
// scans. Without it a typo'd or retired verb makes an entry
// unreachable -- it would reconcile against nothing, forever,
// and read as a live exemption.
// RETAINED a double that WAS pinned still is. The pinned population is
// enumerated in `engine-double-contract.pinned.json`, so a pin
// that leaves names itself instead of decrementing a printed
// integer nobody compares (#9680). See the block below.
//
// ## RETAINED, and why the pinned set is enumerated rather than counted (#9680)
//
// When #9680 landed, the invariants above ratcheted the LEDGERED population in
// both directions -- measured on that branch, deleting a DEBT-ledgered double's
// member reddened (`RECONCILED: baseline entry for … declares no engine double
// with a delete any more`), and so did dropping one of the five doubles behind
// the EXEMPT entry (`down to 4 … from the baseline's 5`). Since #26586 both are
// passing reports instead: the DEBT ledger records looseness, so its shrinking
// is the goal, and RETAINED below is what still reds on a PINNED loss. Before
// #9680 the PINNED population had no ratchet at all, and that asymmetry is the
// whole of #9680: DISCOVERED fires at zero, never at one-fewer-than-yesterday,
// and PINNED iterates the discovered set, so a pinned double that stops
// declaring the member simply LEAVES.
//
// Discovery requires the member to exist, so absence is invisible by
// construction. Measured, two directions, on `packages/core/src/utils/
// migration-journal.test.ts`:
//
// delete the whole `async delete(…)` member OK -- 318 pinned (was 319), exit 0
// delete only the `assertEngineDeleteDispatch` call x PINNED …, exit 1
//
// The control going red is what makes the first line a blind spot rather than a
// broken harness: the gate pins the dispatch behaviour of a member that EXISTS.
//
// ## Why an identity ledger and not a count, priced rather than assumed
//
// A count-delta ("319, shrink-fails") is the cheaper artifact and was rejected
// on two measurements, not on taste:
//
// - It cannot see a SWAP. One double loses `delete` while another gains one
// and the total is unchanged, so the instrument reads clean while coverage
// moved. An enumeration compares membership, so the swap is two rows.
// - Its remedy carries no information. A legitimate removal and this card's
// defect produce the SAME one-character diff (`319` -> `318`), so review
// cannot tell them apart and the only available habit is "bump the number"
// -- the failure mode a ratchet exists to prevent, re-created by the
// ratchet itself.
//
// The maintenance objection to an enumeration is real but was measured and is
// small. Measured over the FULL population: 3,103 first-parent commits on
// `main` in the month to 2026-08-18 (`git log --first-parent
// --since=2026-07-18 --until=2026-08-18 origin/main`). Membership of the pinned
// set changed in 111 of them for `delete` (3.6%) and 103 for `update` (3.3%);
// 162 and 160 files ENTERED, and exactly ONE left per verb.
//
// ⛔ An earlier revision of this comment read "the 269 commits ... changed in 7
// commits (2.6%) ... zero left". 269 was the depth of the shallow clone the
// measuring agent ran in, not the month's traffic, and the 7 and the "zero"
// were themselves computed over only those 269 commits -- so every number in
// the sentence, numerator included, described a ~9% sample. It is re-measured
// here rather than rescaled: the true rate is HIGHER than the sample reported,
// which is the direction that swapping only the denominator would have hidden.
//
// The single departure per verb is the case worth stating precisely, because it
// is the nuisance an identity ledger is accused of and it did not behave like
// one: f16e54e1d deleted `protocol-delete-object-package-binding-guard.test.ts`
// and added a replacement carrying both pins in the SAME commit, so repo-wide
// coverage never dropped. It lands in the "file gone from disk" world below,
// whose remedy is mechanical and carries no judgement call. Across the whole
// month there were ZERO instances of the shape this ratchet exists to catch --
// file present, verb gone -- and zero per-file counts that shrank without
// reaching zero.
//
// Method, stated so this can be redone rather than trusted: membership is
// proxied by `assertEngine…Dispatch(` call sites in test files under the scan
// roots, calibrated on 2026-08-19 against this gate's own ledger as it then
// stood -- 0 false negatives on the file sets, and every (file, verb) row but
// ONE agreeing on the exact count. That calibration is a dated measurement, not
// a standing property; anyone re-running it must first prove their clone covers
// the window; a shallow one silently answers for its own depth, which is the
// whole reason this paragraph had to be rewritten.
//
// So the additions the ratchet does redden on are already in conversation with
// this gate (they are new fakes that had to write `assert…Dispatch` because
// PINNED demanded it). Set against the DEBT ledger this gate already carries,
// the pinned ledger is the same file format, the same order of magnitude and
// the same reconciliation shape -- so it is the maintenance cost already being
// paid for the other ledger, not a new one. Both sizes are printed by a run and
// countable in the artifacts; they are deliberately not copied into this prose,
// because `--write` moves one of them and nothing here would notice.
//
// ## How a LEGITIMATE decrease is expressed (the anti-nuisance half)
//
// `node scripts/check-engine-double-contract.mjs --write`, then commit. That is
// the whole remedy, it is the repo's existing ratchet idiom (see
// check-slot-lookup-ratchet.mjs's `--update`), and it is mechanical -- there is
// no number to choose, so there is no number to fudge.
//
// What keeps that from degenerating into "regenerate on red" is that the gate
// CLASSIFIES the loss before asking for anything, and says which of three
// worlds it is in:
//
// file gone from disk a deleted test. Legitimate; regenerate.
// file present, verb gone THE #9680 DEFECT. The member was dropped while
// the fake and its file live on. Loud, and named.
// fewer doubles than pinned the same defect at a finer grain: the file pins
// several and one member was deleted. Nothing else
// in this gate reacts, because a fake is still there.
// all doubles present, the double went UNGUARDED -- already an error
// fewer pinned under PINNED above, and cross-named here so one
// output explains the whole picture.
//
// A count can reach none of those three, because by the time it has been
// decremented the identity is gone. And `--write` prints every loss it is about
// to record, so the author reads what left at the moment they regenerate rather
// than discovering it in review.
//
// ## Why "routes through the shared predicate" and not "mirrors the guard"
//
// The #4434 fix mirrored the engine's guard into that one fake by hand. That
// closes one fake and opens a second copy of the contract -- and the scalar
// test is the half a hand-written copy drops: `where: { id: { $in: [...] } }`
// LOOKS like an id and is a multi-row predicate, so the real engine rejects it
// without `multi` and a mirrored `if (!opts?.where?.id && !opts?.multi)` accepts
// it. Requiring the producer's own function removes the class: a double that
// imports the decision cannot be looser than the decision. Same reasoning as
// objectstack#4455 -- the scan and the validator must answer with ONE predicate.
//
// `update` adds a second way a copy goes wrong, in the opposite direction: its
// id also comes from the PAYLOAD (`data.id`, taken verbatim when truthy, ahead
// of `where` and ahead of `multi`), so a copyist who "improves" the rule by
// scalar-testing `data.id` writes a double STRICTER than the producer, which
// fails calls a running server accepts. Looser hides bugs, stricter invents
// them; importing the decision is the only spelling that does neither.
//
// ## What this deliberately does NOT claim
//
// It checks that the shared predicate is CALLED, not that the double's by-id
// and multi branches then behave like the driver would. A gate cannot judge
// that, and one that pretended to would be the verifier that reports success
// while degrading. What it can do is make the rejection surface impossible to
// drift, which is the half that shipped #4434.
import { readFileSync, readdirSync, existsSync, writeFileSync } from 'node:fs';
import { join, dirname, relative, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { requireDefaultExport } from './import-prerequisite.mjs';
const ts = await requireDefaultExport('typescript', () => import('typescript'), import.meta.url);
import { parseSourceFile } from './ts-parse.mjs';
import { definePopulationFloor } from './population-floor.mjs';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const BASELINE_PATH = join(ROOT, 'scripts', 'engine-double-contract.baseline.json');
const PINNED_LEDGER_PATH = join(ROOT, 'scripts', 'engine-double-contract.pinned.json');
const SEAM_LEDGER_PATH = join(ROOT, 'scripts', 'engine-double-contract.seams.json');
const SCAN_ROOTS = ['packages', 'examples'];
/**
* The exit code for a POPULATION REFUSAL (#13014), distinct from a finding's 1.
*
* A refusal and a finding are different verdicts and must not share a code: 1
* says "this tree has problems, here they are", 2 says "this run read too
* little of the tree to say anything about it". Both fail CI, so the split
* costs nothing there and buys a reader the difference.
*/
const EXIT_POPULATION_REFUSED = 2;
/**
* The slices. Each names ONE member of an engine double and the producer-side
* predicate that member must reach; everything else in this file is shared.
*
* `symbols` is the pair the producer exports (`assert…` throws, `resolve…`
* classifies -- a double may legitimately use either), and `modules` is where
* they may come from.
*
* ## Why `modules` names TWO packages and not one (#5619)
*
* The predicates were written in `packages/objectql/src/` and MOVED to
* `@objectstack/metadata-core` by #5619 -- the implementation lives there now,
* and `@objectstack/objectql` re-exports every symbol from the original paths.
* Both spellings therefore reach the SAME function, which is the only property
* this list has ever been about: a double that imports the producer's decision
* cannot be looser than the producer, whichever door it came through.
*
* The move was not cosmetic. `@objectstack/objectql` DEPENDS ON
* `@objectstack/metadata-protocol`, so that package's thirteen fake engines
* could not import from `@objectstack/objectql` at all -- turbo 2.10.7 rejects
* the resulting task graph outright ("Circular package dependency detected") --
* and all 26 of their (file, verb) pairs sat in the ledger for that one
* structural reason. Sinking the predicate into a package both sides already
* depend on is the route the EXEMPT entry for
* `packages/spec/src/contracts/data-engine.test.ts` names, and #5619 took it.
*
* Note what this does NOT relax: `@objectstack/spec` stays unpinnable in
* principle, because `metadata-core` depends on `spec` -- the import would
* invert that edge exactly as it inverted `objectql -> spec`. That entry's
* EXEMPT reasoning survives the move unchanged.
*/
const SLICES = [
{
verb: 'delete',
producer: 'ObjectQL.delete',
symbols: new Set(['assertEngineDeleteDispatch', 'resolveEngineDeleteDispatch']),
modules: [
/^@objectstack\/objectql$/,
/^@objectstack\/metadata-core$/,
/engine-delete-dispatch(\.js)?$/,
],
pinCall: 'assertEngineDeleteDispatch(options)',
origin: '#4434',
},
{
verb: 'update',
producer: 'ObjectQL.update',
symbols: new Set(['assertEngineUpdateDispatch', 'resolveEngineUpdateDispatch']),
modules: [
/^@objectstack\/objectql$/,
/^@objectstack\/metadata-core$/,
/engine-update-dispatch(\.js)?$/,
],
pinCall: 'assertEngineUpdateDispatch(data, options)',
origin: '#5480',
},
{
verb: 'findOne',
producer: 'ObjectQL.findOne',
symbols: new Set(['assertEngineFindOnePredicate', 'resolveEngineFindOnePredicate']),
modules: [
/^@objectstack\/objectql$/,
/^@objectstack\/metadata-core$/,
/engine-findone-predicate(\.js)?$/,
],
pinCall: 'assertEngineFindOnePredicate(object, query)',
origin: '#4419',
},
];
/** The verbs the ledger may name -- see the DECLARED invariant. */
const SCANNED_VERBS = new Set(SLICES.map((s) => s.verb));
/**
* Members that mark an object literal as standing in for the ENGINE.
*
* The engine and the driver share every name here, so the sibling set is what
* separates them alongside the parameter test below: drivers speak
* `create`/`bulkCreate`/`checkHealth`, the engine speaks `insert`/`findOne`.
*
* A slice never counts its OWN verb as a sibling (`scanSource` filters it),
* which is why `delete` can sit in this set without changing the delete
* slice's discovery by one file: it is evidence for the `update` slice --
* `{ find, update, delete }` is an engine-shaped trio -- and self-excluded
* for its own.
*/
const ENGINE_SIBLINGS = new Set([
'find', 'findOne', 'insert', 'update', 'delete', 'count', 'aggregate', 'getSchema', 'registry',
'insertMany',
]);
/**
* Parameter names that mean "this is the DRIVER's signature": the primary key
* sits in the second position for both write verbs -- `delete(object, id,
* options)` and `update(object, id, data, options)` -- where the engine takes
* an options bag and a payload respectively.
*/
const ID_PARAM = /^_*(id|recordId|ids|pk)$/i;
/**
* Members present on `IDataDriver` and on NEITHER `IDataEngine` nor the ObjectQL
* class — so declaring one is positive evidence of the DRIVER contract.
*
* Consulted only when the parameter test cannot answer (see `isEngineDeleteShape`).
* Deliberately excludes every name both contracts share — `find`, `findOne`,
* `update`, `count`, `delete` and `execute` (the engine declares `execute?` too,
* `data-engine.ts`) — because a name on both sides separates nothing.
*/
const DRIVER_ONLY_MEMBERS = new Set([
'connect', 'disconnect', 'checkHealth', 'getPoolStats', 'create', 'upsert',
'bulkCreate', 'bulkUpdate', 'bulkDelete', 'updateMany', 'deleteMany',
'beginTransaction', 'commit', 'rollback', 'syncSchema', 'syncSchemasBatch',
'registerExternalObject', 'getSchemaSyncStats', 'dropTable', 'reclaimSpace',
'explain', 'temporalFilterValue', 'temporalFilterColumnSql',
]);
/**
* The engine-side half of the same evidence: on `IDataEngine` (`insert`,
* `aggregate`) or on the ObjectQL class itself (`getSchema`, `registry`,
* `insertMany`), and absent from `IDataDriver`.
*
* A subset of ENGINE_SIBLINGS, and the distinction is the whole point: `find` /
* `findOne` / `update` / `count` are engine siblings for DISCOVERY (they mark a
* data-access object) while being useless for ATTRIBUTION (drivers speak all
* four). Only the names here answer "engine, not driver".
*/
const ENGINE_ONLY_MEMBERS = new Set(['insert', 'insertMany', 'aggregate', 'getSchema', 'registry']);
/**
* The third arm of the same evidence architecture (#6327, from #5945): members
* present on the SCOPED REPOSITORY — `IScopedObjectRepository`
* (`packages/spec/src/contracts/scoped-context.ts`) and the `ObjectRepository`
* class that declares `implements` it — and on NEITHER `IDataEngine` NOR
* `IDataDriver` NOR the ObjectQL class. Declaring one is positive evidence of
* an object-BOUND repository, which is not this gate's subject.
*
* Verified member by member rather than assumed, on the tree this landed
* against: `IDataEngine` declares find/findOne/insert/update/delete/count/
* aggregate/vectorFind/execute and no by-id form; `IDataDriver` reaches for
* records by `id` in a PARAMETER (`update(object, id, data)`) and spells its
* bulk forms `bulkUpdate`/`updateMany`/`bulkDelete`/`deleteMany`; and inside
* `packages/objectql/src/engine.ts` the only declarations of these two names
* are on `class ObjectRepository implements IScopedObjectRepository`.
*
* Kept to the names that answer, exactly as DRIVER_ONLY_MEMBERS is. The
* repository's `create` / `upsert` / `delete` / `aggregate` / `execute` are
* real members and are deliberately absent: every one of them is also on the
* driver or the engine, so it separates nothing. (`create` already sits in
* DRIVER_ONLY_MEMBERS, so a repository double spelling it leaves scan scope
* through that veto instead — the right outcome by the wrong name, recorded
* here so the next reader does not read it as a gap.)
*/
const REPOSITORY_ONLY_MEMBERS = new Set(['updateById', 'deleteById']);
/**
* The fourth shape (#29859): MongoDB's native `Collection`, which a driver-
* mongodb test fakes to record what the DRIVER sends (`(driver as any).db =
* { collection: () => collection }`). Its read and batch-write names collide
* with the engine's -- `find`, `findOne`, `insertMany`, `aggregate` -- so a
* fake declaring `insertOne`/`insertMany`/`updateOne`/`findOne`/`find` holds
* two engine siblings and reads as an engine `findOne` double whose
* `findOne(filter, options)` takes no object name at all. It is not a looser
* copy of `ObjectQL.findOne`; it is the driver's DEPENDENCY, one layer below
* the driver, and has no dispatch contract to be looser than.
*
* `insertMany` stays engine evidence: `ObjectQL.insertMany(object, rows)` is a
* real member of the engine class, and an engine double spelling it must keep
* reading as one. The fix is positive evidence of the OTHER shape, not less
* evidence of this one.
*
* Verified member by member on the tree this landed against: none of these
* names is declared in `packages/objectql/src/engine.ts`, nor on `IDataEngine`,
* `IDataDriver` or `IScopedObjectRepository` (`packages/spec/src/contracts/`).
* Kept to the names only the native Collection speaks -- its single-document
* writes, its atomic find-and-modify forms, its counts and `bulkWrite`. Its
* `updateMany`/`deleteMany` are absent because DRIVER_ONLY_MEMBERS already
* vetoes them at any arity; `distinct`/`createIndex`/`watch` are absent because
* those names are too generic to answer "Mongo" in a repo with caches and
* routers. Consulted under the same object-name guard as the repository veto,
* so `findOne(objectName, query)` beside an `insertOne` helper stays in scope.
*/
const NATIVE_COLLECTION_ONLY_MEMBERS = new Set([
'insertOne', 'updateOne', 'deleteOne', 'replaceOne', 'bulkWrite',
'countDocuments', 'estimatedDocumentCount',
'findOneAndUpdate', 'findOneAndDelete', 'findOneAndReplace',
]);
/**
* Parameter names that mean "this position holds an OBJECT NAME" — the
* complement of ID_PARAM, and the first position rather than the second.
*
* Both contracts this gate DOES judge take the object name first, so positive
* evidence of one is positive evidence that the literal is NOT an object-bound
* repository. `t` and `table` are here because this repo's fakes use them
* (`_t: string` is the commonest spelling in the discovered corpus after
* `object: string`).
*/
const OBJECT_NAME_PARAM = /^_*(o|obj|object|objectName|objectname|name|table|tableName|t)$/i;
/**
* The DECLARED engine contract: the interface a construct can name to say what
* it IS, rather than leaving the gate to infer it from member names (#11626).
*
* ## Why a second admission route exists at all
*
* Discovery's sibling test asks "does this literal LOOK like an engine?" and it
* needs two engine siblings to answer, because `{ update }` alone is also every
* cache, every store mock and every router in the repo. That threshold is
* correct for inference and it has one structural consequence: a double that
* declares ONLY the verb under test can never be discovered, so it can never be
* pinned, and the headline "N pinned" silently excludes the whole minimal class.
*
* The half that makes it a defect rather than a coverage gap is what it asks of
* an author. The only way into the ratchet was to give the double verbs its
* test never calls -- `find`/`insert` siblings that exist to be counted -- so
* the gate's admission criterion actively rewarded padding a double with
* ceremony. A reader then cannot tell which verbs are load-bearing, which is
* the property a double exists to have.
*
* ## Why a DECLARATION and not a looser inference
*
* Relaxing the sibling threshold was measured and is not available: on the tree
* this landed against, dropping it to zero admits 74 constructs, of which 32
* are HTTP routers and servers whose `delete` is the HTTP verb
* (`{ delete, get, post, routes }`, `{ close, delete, get, listen, patch, post,
* put, use }`). Reddening correct code is the one thing this gate's ledger
* cannot absorb -- its readability is its whole value -- so inference stays
* where it is.
*
* What a declaration adds is not a better guess, it is a different KIND of
* evidence: the author has written down which contract the object implements.
* `const engine: IDataEngine = { … }`, `… as unknown as IDataEngine`,
* `function make(): IDataEngine`, `class F implements IDataEngine`. That is
* decidable with no heuristic and no member-name guessing, and it is the repo's
* standing rule that declared means enforced: an object that declares itself
* the engine is held to the engine's dispatch contract at any sibling count.
*
* Measured on the same corpus: exactly 2 of those 74 declare `IDataEngine` --
* `metadata/src/loaders/database-loader-update-id-fold-wins.test.ts` and
* `services/service-settings/src/settings-engine-id-fold-wins.test.ts`, both
* single-verb doubles that were ALREADY calling `assertEngineUpdateDispatch`
* and getting no protection for it. The other 72 declare `IHttpServer` (7),
* `EmailPersistence`, `SettingsSecretStore`, `any`, or nothing at all. So this
* route reddens nothing on the tree it landed against and never could: it only
* admits constructs, and every construct it admits was already pinned.
*
* ## The import test, and why it is not optional
*
* The name alone is not the evidence -- a file-local interface that happens to
* be called `IDataEngine` is not this contract. So the local name must be BOUND
* by an import from where the contract lives, exactly as `pinnedImportsOf` does
* for the predicates and for the same reason: one name, one meaning, or the
* criterion is a spelling match wearing a criterion's costume.
*
* The module list is measured rather than guessed -- every spelling of this
* import in the scanned corpus on 2026-08-24: `@objectstack/spec/contracts`
* (36 files), `@objectstack/core` (5), and the relative `./data-engine` inside
* `packages/spec` itself (2). Re-derive with
* `grep -rhn --include=*.test.ts IDataEngine packages examples | grep -o "from '[^']*'"`
* before adding one.
*/
const ENGINE_CONTRACT_NAME = 'IDataEngine';
/** Where {@link ENGINE_CONTRACT_NAME} may legitimately be imported from. */
const ENGINE_CONTRACT_MODULES = [
/^@objectstack\/spec(\/contracts)?$/,
/^@objectstack\/core$/,
/(^|\/)data-engine(\.js)?$/,
];
// ── Discovery ───────────────────────────────────────────────────────────────
function walk(dir, out = []) {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const e of entries) {
if (e.name === 'node_modules' || e.name === 'dist' || e.name === '.git' || e.name === '.cache') continue;
const p = join(dir, e.name);
if (e.isDirectory()) walk(p, out);
else if (/\.(test|spec)\.(ts|tsx|mts)$/.test(e.name)) out.push(p);
}
return out;
}
function testFiles() {
const out = [];
for (const r of SCAN_ROOTS) walk(join(ROOT, r), out);
return out.sort();
}
/**
* The cheap pre-filter EVERY walk in this file shares: could this text declare
* a member named `verb` at all? If not, there is nothing to parse.
*
* ⛔ It is one function because it was FOUR copies and two of them were
* narrower than the others (#10175). `scanSlice` and the `--census` veto
* ablation tested `\b<verb>\s*[(:]`, which admits `delete(` and `delete:` and
* nothing else; the two census walks tested `[(:,}]`, which also admits the
* SHORTHAND spellings `update,` and `update }`. While `implOf` could not read a
* shorthand that difference was invisible -- discovery would have found nothing
* in those files anyway. The moment it can (below), the narrow copies become a
* silent skip: a file whose ONLY spelling of the verb is a shorthand member is
* never parsed by discovery while the census parses it and reports it, so the
* two walks disagree for a reason that is nowhere near the code that decides.
*
* That is #9747's self-test failure with a pre-filter wearing the costume, and
* it is the same class as the widening hazard #10175's structural note names --
* one step further upstream, where a reader looking at `implOf` cannot see it.
* So the class is closed rather than the instance: there is one spelling now,
* and a fifth walk gets it by calling this.
*/
function mentionsVerb(text, verb) {
return new RegExp(`\\b${verb}\\s*[(:,}]`).test(text);
}
/**
* The implementation a MOCK CONSTRUCTOR wraps, or null (#8639).
*
* `delete: vi.fn(async (o, opts) => …)` is a CallExpression, so the two
* initializer branches of `implOf` below used to answer `null` for it —
* `consider()` then returned before the sibling and shape tests ever ran, and
* the double was discovered by NEITHER side of a ledger that then reconciled in
* both directions. Not "declared out of scope": absent. That is the DISCOVERED
* invariant's blind half, one layer down — `DISCOVERED != 0` catches a scan
* that breaks entirely and cannot catch a scan that quietly skips one spelling,
* and `vi.fn` is the spelling a test reaches for precisely when it wants to
* assert call counts on the double it just wrote.
*
* ## How wide to unwrap, measured rather than assumed
*
* The criterion is STRUCTURAL and callee-agnostic: a call carrying EXACTLY ONE
* argument which is a function expression / arrow function. That admits every
* spelling holding an implementation (`vi.fn(fn)` and, for free and correctly,
* the chained `.mockImplementation(fn)` — the arrow there IS what the double
* runs) and rejects the ones that hold a VALUE or nothing at all, without an
* allowlist of callee names that would go silently blind the day someone writes
* `vitest.fn` or a local wrapper.
*
* Deliberately NOT widened, both measured at ZERO occurrences on this corpus:
*
* - a function among SEVERAL arguments (`traced('delete', fn)`). The card's
* phrasing is "sole function argument" and the narrow reading is the one
* that cannot mistake a lifecycle callback for the verb's implementation.
* - a function in the chained receiver (`vi.fn(fn).mockResolvedValue(v)`),
* which would need this to recurse into `init.expression`.
*
* ## ⛔ The per-spelling counts are NOT written here any more (#9943)
*
* This header used to carry the census as CONSTANTS — `310` CallExpression
* members, a callee table summing to it, `93` admitted and `217` rejected.
* Nothing regenerated them, so nothing could catch them drifting, and by
* 2026-08-19 they had. Writing fresher constants in their place would reproduce
* the defect with newer values (#9803 / PR #9909), so they are gone and
* `--census` prints the same table from THIS FILE'S OWN `implOf` walk instead.
* `#9943` had to hand-copy the criterion to re-scan and got 341 against the
* recorded 310 with no way to say which was wrong; that question no longer
* exists. The two ZERO readings above are printed by `--census` too, and were
* still ZERO on 2026-08-20 — re-run it rather than trusting this sentence.
*
* ## What the old census could not have told you, and #9877 is the proof
*
* Its population was "every member whose initializer is a CallExpression" —
* the shape this function already reads. A census of what the matcher already
* matches cannot report the matcher's blind spots however carefully it is
* re-run, and both spellings it listed as ZERO are CallExpression spellings for
* that reason. #9877's defaulted initializer (`overrides.delete ?? vi.fn(fn)`)
* is a BinaryExpression and was never in the population at all, while hiding a
* live unguarded engine `delete` double. `--census` buckets by initializer KIND
* first for exactly this reason: a spelling the gate cannot read shows up as a
* row with a low read-rate, not as silence.
*
* Both remain measurements, not opinions — run `--census` before widening,
* exactly as the REPOSITORY_ONLY_MEMBERS note above asks.
*
* Note which way the remaining error leans. A `vi.fn()` with no argument stays
* `null` and stays undiscovered, and that is correct rather than a residual
* gap: there is no implementation to read, so there is no function for
* `isEngineVerbShape` to judge and nothing that could be looser than
* `ObjectQL.<verb>` — the double's behaviour is `undefined`, not a lax guard.
*/
function unwrapCallImpl(init) {
if (!ts.isCallExpression(init)) return null;
const args = init.arguments ?? [];
if (args.length !== 1) return null;
const only = args[0];
if (ts.isFunctionExpression(only) || ts.isArrowFunction(only)) return only;
return null;
}
/**
* The implementation behind a DEFAULTED initializer, or null (#9877).
*
* `delete: overrides.delete ?? vi.fn(async (o, arg) => …)` is a
* BinaryExpression, which is neither of the two shapes `fnInitializer` knew, so
* `implOf` answered null, `consider()` returned before `isEngineVerbShape` was
* ever asked, and the double left the population with no verdict recorded --
* not baselined, not exempt, not pinned. Absent. `rest-batch-endpoint.test.ts`
* held a live unguarded engine `delete` double behind exactly this spelling and
* the gate reddens on it the moment it can read it, so this is not cosmetic.
*
* ## Why the census above could not have found this, which is the real lesson
*
* That census enumerates "every delete/update member whose initializer is a
* CallExpression". A defaulted initializer is a BinaryExpression, so it was
* never in the census POPULATION -- the census is scoped to the shape the
* recognizer already reads, and a census of what the matcher already matches
* cannot report the matcher's blind spots however carefully it is re-run. The
* two spellings it lists as "measured at ZERO" are both CallExpression
* spellings for the same reason. `--census` fixes the population, not the
* arithmetic: it now buckets EVERY initializer by kind first, so a spelling
* outside the recognizer shows up as its own row rather than as silence.
*
* ## Which side, and why both are read
*
* `a ?? b` and `a || b` reach the subject as `a` when `a` is present and as `b`
* otherwise, so BOTH sides are implementations the double may run. The default
* is read first because it is the one this file itself authored and the only
* one that is statically knowable -- the left side of a `??` default is by
* construction the maybe-absent, caller-supplied one, and where it IS statically
* a function (`f ?? g`, both literals) reading the left as a fallback keeps the
* spelling from going dark again.
*
* Deliberately NOT widened, and this one is a judgement rather than a count:
* `cond ? a : b`. A conditional's arms are selected by a test this gate cannot
* evaluate, so "the implementation" is not a property of the initializer at all
* -- unlike `??`/`||`, where the fallback is unconditionally reachable. Measured
* at ZERO occurrences on this corpus (`--census`, ConditionalExpression row);
* re-run that before widening it, not the number in this sentence.
*/
function unwrapDefaultedImpl(init, seen) {
if (!ts.isBinaryExpression(init)) return null;
const op = init.operatorToken.kind;
if (op !== ts.SyntaxKind.QuestionQuestionToken && op !== ts.SyntaxKind.BarBarToken) return null;
return fnInitializer(init.right, seen) ?? fnInitializer(init.left, seen);
}
/**
* The NEAREST declaration of `name` visible from `node`, or null (#10175).
*
* Resolution is by SCOPE CHAIN -- walk out through the enclosing statement
* lists and take the first one that declares the name -- and not by a
* file-wide `name -> node` map, which is the cheaper shape and the one the
* card proposed. The reason is measured on this corpus rather than argued:
*
* packages/metadata-protocol/src/protocol.dropped-fields.bulk.test.ts
* declares `const update` TWICE (two fakes, two `describe` blocks)
* packages/plugins/plugin-auth/src/admin-user-endpoints.test.ts
* declares `const engineUpdate` TWICE (module scope and a nested block)
*
* A file-wide map has to pick one of each pair for every use site, so on three
* of the constructs this card is about it would be reading a DIFFERENT
* function than the one that runs. Today the two spellings happen to agree --
* each pair's members carry the same shape, so the verdict is the same either
* way -- and "they agree today" is exactly the kind of property that is true
* until someone edits one half of a pair. Getting it right costs a parent
* walk, which `setParentNodes: true` (fixed in `ts-parse.mjs`) already pays
* for.
*
* What it deliberately does NOT reach, both for the same reason -- the
* implementation is not statically knowable, so refusing keeps the construct
* in the UNRECOGNISED census instead of guessing at it:
*
* - PARAMETERS (`function make(del) { return { delete: del }; }`). The
* implementation is whatever the caller passed.
* - imported bindings. The function is in another file, and one file is all
* any walk here has.
*
* Note which way the error leans, the same way `takesObjectNameFirst` states
* it: answering null leaves a construct UNRECOGNISED -- printed, counted, and
* visible -- while answering with the wrong function would put a verdict on a
* double this gate never read. The first is a row in a census; the second is
* the failure mode this gate exists to prevent, wearing the gate's own badge.
*/
function resolveBinding(node, name) {
for (let scope = node.parent; scope; scope = scope.parent) {
let statements = null;
if (ts.isSourceFile(scope) || ts.isBlock(scope) || ts.isModuleBlock(scope)) statements = scope.statements;
else if (ts.isCaseClause(scope) || ts.isDefaultClause(scope)) statements = scope.statements;
if (!statements) continue;
let found = null;
for (const st of statements) {
if (ts.isFunctionDeclaration(st) && st.name?.text === name) found = st;
else if (ts.isVariableStatement(st)) {
for (const d of st.declarationList.declarations) {
if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer) found = d.initializer;
}
}
}
if (found) return found;
}
return null;
}
/**
* The implementation behind a BARE LOCAL BINDING, or null (#10175).
*
* `delete: del` (with `const del = vi.fn(async (o, opts) => …)` above it) and
* the shorthand `{ registry, insert, findOne, update }` are the two remaining
* spellings #9877 named and narrowed away from. Both are the same shape: the
* initializer is an IDENTIFIER, so `fnInitializer` had nothing to unwrap,
* `implOf` answered null, and the double left the population with no verdict
* recorded -- not pinned, not baselined, not exempt. Absent. Measured on the
* tree this landed against, they were the WHOLE of the UNRECOGNISED census:
* 21 constructs, 7 rooting at a named binding and 14 shorthand.
*
* ## Why it recurses through `fnInitializer` rather than reading the binding
*
* The binding is not usually a bare arrow -- every one of the 21 is
* `vi.fn(async (…) => …)`, which is the CallExpression spelling `unwrapCallImpl`
* already reads. Handing the resolved initializer back to `fnInitializer` means
* this spelling composes with every other one for free (`const del =
* overrides.delete ?? vi.fn(fn)` reads, and so does a binding that is itself
* another binding) instead of re-implementing a second, narrower unwrap that
* would drift from the first -- the drift `fnInitializer` was extracted to
* remove (#8639's sibling half).
*
* `seen` is keyed on the resolved DECLARATION NODE rather than on the name,
* because `const a = b` in one scope and `const b = a` in another are two
* different bindings that share a spelling. A cycle answers null, which leaves
* the construct in the census where it belongs.
*
* A `FunctionDeclaration` is returned as itself: everything downstream reads
* `.parameters` and walks the body (`isEngineVerbShape`, `calleesIn`), and both
* work on a declaration exactly as they do on the expression forms. One without
* a body is an overload signature -- no implementation, so null.
*/
function unwrapBoundImpl(init, seen) {
if (!ts.isIdentifier(init)) return null;
const decl = resolveBinding(init, init.text);
if (!decl || seen.has(decl)) return null;
seen.add(decl);
if (ts.isFunctionDeclaration(decl)) return decl.body ? decl : null;
return fnInitializer(decl, seen);
}
/**
* One initializer reading, shared by BOTH initializer spellings below.
*
* Shared on purpose: the object-literal (`PropertyAssignment`) and class-field
* (`PropertyDeclaration`) branches carried the same three lines twice and drifted
* apart in exactly the way that produced #8639's sibling half — a fix applied to
* one spelling and not the other reproduces this card at the next reading. With
* one function there is no second copy to forget.
*/
function fnInitializer(init, seen = new Set()) {
if (!init) return null;
if (ts.isFunctionExpression(init) || ts.isArrowFunction(init)) return init;
const defaulted = unwrapDefaultedImpl(init, seen);
if (defaulted) return defaulted;
const called = unwrapCallImpl(init);
if (called) return called;
return unwrapBoundImpl(init, seen);
}
/**
* A member's function-ish implementation, or null.
*
* ⛔ It takes no binding map and no `SourceFile`, and that is deliberate rather
* than an omission: `resolveBinding` walks `node.parent`, so the ONE function
* every walk in this file already calls gained the local-binding spellings
* without a second parameter to thread -- and therefore without a call site
* that could be missed. #10175's structural note is about exactly that hazard:
* a widening applied to `scanSource` alone leaves `censusSource` reporting the
* same constructs as UNRECOGNISED, the two walks disagree, and #9747's
* self-test reddens. Here there is no second place to apply it.
*/
function implOf(member) {
if (ts.isMethodDeclaration(member) || ts.isMethodSignature(member)) return member;
if (ts.isPropertyAssignment(member)) return fnInitializer(member.initializer);
if (ts.isPropertyDeclaration(member)) return fnInitializer(member.initializer);
// `{ registry, insert, findOne, update }` -- the member's NAME is the binding.
if (ts.isShorthandPropertyAssignment(member)) return unwrapBoundImpl(member.name, new Set());
return null;
}
function memberName(member) {
const n = member.name;
if (!n) return null;
if (ts.isIdentifier(n) || ts.isStringLiteral(n)) return n.text;
return null;
}
/**
* Is this `<verb>(a, b, …)` the ENGINE's shape rather than the DRIVER's?
* (Named `isEngineDeleteShape` until #5480 made it serve both write verbs; the
* body never was delete-specific.)
*
* engine `delete(object, options)` `update(object, data, options)`
* driver `delete(object, id, options)` `update(object, id, data, options)`
*
* The second parameter is the whole question for both: the engine takes an
* options bag / a payload there, the driver takes a primary key. Judged on the
* name first (the repo writes `id` when it means one) and on a scalar type
* annotation second.
*
* ## When there IS no second parameter (#5629)
*
* A fake omits the parameters it ignores — `async delete() { return false; }` —
* and this function used to open with `if (params.length < 2) return false`,
* which discarded the double before any other test ran. Not "declared out of
* scope": unreachable. Those deletes reached neither PINNED nor the ledger and
* produced no output at all, which is the #4868 shape this script's own
* DISCOVERED invariant is written against. Measured on this branch: 92 such
* deletes behind that one line, 0 of them pinned.
*
* So when arity cannot answer, the SIBLING SET answers instead — and it has to
* be a real test, not a waved-through `return true`. #5629's premise for a
* blanket admit ("a zero-parameter delete cannot be the driver's, since the
* driver's signature has a primary-key position") does not survive measurement:
* fake DRIVERS drop their unused parameters exactly like fake engines do, so 43
* of those 92 are driver doubles — `spec/src/contracts/data-driver.test.ts`
* itself, and `objectql/src/engine-aggregate-having.test.ts`'s self-described
* "driver WITH native aggregate()". Admitting them unconditionally would have
* pointed this gate at the wrong contract 43 times.
*
* The evidence that does separate them is which members the object declares
* ALONGSIDE delete: it must show a member only the engine has, and none that
* only the driver has. Both halves are load-bearing — `aggregate` alone admits
* the native-aggregate driver above, and "no driver members" alone admits any
* `{ find, findOne, update, delete }` store mock that is neither contract.
*/
/**
* Does this verb take an OBJECT NAME in first position? Positive evidence only
* — an unreadable or absent first parameter answers `false`, never `true`.
*
* The asymmetry is deliberate and is the whole safety property of the scoped-
* repository veto below: this function's `true` KEEPS a literal in scan scope,
* so being generous with it can only cost a ledger row, while being generous
* with `false` would put a genuine engine double out of scan scope — the one
* error a gate cannot report about itself.
*/
function takesObjectNameFirst(fn) {
const first = (fn.parameters ?? [])[0];
if (!first) return false;
const name = ts.isIdentifier(first.name) ? first.name.text : '';
if (OBJECT_NAME_PARAM.test(name)) return true;