Skip to content

Commit 2a76758

Browse files
committed
wip: facade gate registers the scoped classes (#30052)
Claude-Session: https://claude.ai/code/session_01Utp6Cbo4rDxRL3yugqM5c7 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1631624 commit 2a76758

3 files changed

Lines changed: 243 additions & 14 deletions

File tree

‎scripts/check-facade-delegation-only.mjs‎

Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,16 @@
3131
* facades { file, class, card } a file that has LANDED in facade form,
3232
* the class in it that is the facade, and
3333
* the card that landed it.
34-
* exceptions { file, member, card, reason? }
34+
* exceptions { file, class?, member, card, reason? }
3535
* a member of a registered facade that may
3636
* keep a body for now, and the card that
3737
* will move it (ruling 6624345766 item 3).
3838
*
39+
* A file may register more than one class: `engine.ts` holds `ObjectQL` and,
40+
* since #30052, its two scoped classes `ObjectRepository` and `ScopedContext`.
41+
* Each is its own `facades` row, and an exception row in such a file names its
42+
* `class` (in a file with one facade the `class` may be left out).
43+
*
3944
* The next split adds one `facades` row. ⛔ A file joins only once it is in
4045
* facade form on `main`, so the gate never reds `main` ahead of a landing: the
4146
* PR that lands the facade (or the first PR after it) adds the row.
@@ -164,7 +169,7 @@ export const REGISTRY_FILE = 'scripts/facade-delegation-registry.json';
164169

165170
const CARD_REF = /^#[1-9][0-9]*$/;
166171
const FACADE_KEYS = Object.freeze(['file', 'class', 'card']);
167-
const EXCEPTION_KEYS = Object.freeze(['file', 'member', 'card', 'reason']);
172+
const EXCEPTION_KEYS = Object.freeze(['file', 'class', 'member', 'card', 'reason']);
168173

169174
/** One level of nested call in an argument: `protocolHost(this)`. Two is logic. */
170175
const MAX_NESTED_CALL_DEPTH = 1;
@@ -663,7 +668,9 @@ export function checkRegistry(registry, readFile) {
663668
const extraTop = unknownKeys(registry, ['facades', 'exceptions']);
664669
if (extraTop.length) problem(REGISTRY_FILE, `unknown top-level key(s) ${extraTop.join(', ')}`);
665670

666-
const byFile = new Map();
671+
const facadeKey = (file, cls) => `${file}\u0000${cls}`;
672+
const byFacade = new Map();
673+
const classesOfFile = new Map();
667674
registry.facades.forEach((row, i) => {
668675
const where = `${REGISTRY_FILE} facades[${i}]`;
669676
if (!row || typeof row !== 'object') return problem(where, 'a row must be an object');
@@ -674,11 +681,15 @@ export function checkRegistry(registry, readFile) {
674681
if (typeof row.card !== 'string' || !CARD_REF.test(row.card)) {
675682
problem(where, `${row.file}: a row must name the card that landed the facade as \`#<number>\`, got ${JSON.stringify(row.card)}`);
676683
}
677-
if (byFile.has(row.file)) return problem(where, `${row.file} is registered twice`);
678-
byFile.set(row.file, { row, judged: null });
684+
if (byFacade.has(facadeKey(row.file, row.class))) return problem(where, `${row.file} \`${row.class}\` is registered twice`);
685+
const entry = { row, judged: null };
686+
byFacade.set(facadeKey(row.file, row.class), entry);
687+
if (!classesOfFile.has(row.file)) classesOfFile.set(row.file, []);
688+
classesOfFile.get(row.file).push(entry);
679689
});
680690

681-
for (const [file, entry] of byFile) {
691+
for (const entry of byFacade.values()) {
692+
const file = entry.row.file;
682693
const text = readFile(file);
683694
if (text === null) {
684695
problem(file, `registered as a facade, but the file does not exist — a gate over a missing file judges nothing. Restore the file or remove its row.`);
@@ -713,18 +724,30 @@ export function checkRegistry(registry, readFile) {
713724
if (typeof row.file !== 'string' || typeof row.member !== 'string' || !row.member) {
714725
return problem(where, 'a row must name its `file` and `member`');
715726
}
716-
const label = `${row.file} \`${row.member}\``;
727+
if (row.class !== undefined && (typeof row.class !== 'string' || !row.class)) {
728+
return problem(where, `${row.file} \`${row.member}\`: \`class\`, when present, is a non-empty string`);
729+
}
730+
const label = `${row.file} \`${row.class ? `${row.class}.` : ''}${row.member}\``;
717731
if (typeof row.card !== 'string' || !CARD_REF.test(row.card)) {
718732
problem(where, `${label}: an exception must name the card that will move the member, as \`#<number>\`; got ${JSON.stringify(row.card)}. An exception nobody owns is a permanent hole.`);
719733
}
720734
if (row.reason !== undefined && (typeof row.reason !== 'string' || !row.reason)) {
721735
problem(where, `${label}: \`reason\`, when present, is a non-empty string`);
722736
}
723-
const id = `${row.file}\u0000${row.member}`;
737+
const ofFile = classesOfFile.get(row.file);
738+
if (!ofFile) return problem(where, `${label}: ${row.file} is not a registered facade`);
739+
let entry;
740+
if (row.class) {
741+
entry = byFacade.get(facadeKey(row.file, row.class));
742+
if (!entry) return problem(where, `${label}: \`${row.class}\` is not a registered facade class of ${row.file} (registered: ${ofFile.map((e) => `\`${e.row.class}\``).join(', ')})`);
743+
} else if (ofFile.length > 1) {
744+
return problem(where, `${label}: ${row.file} registers ${ofFile.length} facade classes (${ofFile.map((e) => `\`${e.row.class}\``).join(', ')}), so the row must name its \`class\``);
745+
} else {
746+
entry = ofFile[0];
747+
}
748+
const id = `${row.file}\u0000${entry.row.class}\u0000${row.member}`;
724749
if (seen.has(id)) return problem(where, `${label} has two exception rows`);
725750
seen.add(id);
726-
const entry = byFile.get(row.file);
727-
if (!entry) return problem(where, `${label}: ${row.file} is not a registered facade`);
728751
if (!entry.judged) return; // the facade itself was refused above
729752
const member = entry.judged.find((m) => m.key === row.member && m.verdict !== 'signature');
730753
if (!member) {
@@ -738,7 +761,7 @@ export function checkRegistry(registry, readFile) {
738761
return problem(where, `${label}: the member is already a ${member.verdict === 'field' ? 'field' : 'delegation'} — its card ${row.card} has moved it. Delete the row; the member must stay a delegation.`);
739762
}
740763
member.exception = row;
741-
excepted.push({ file: row.file, member: row.member, card: row.card, line: member.line });
764+
excepted.push({ file: row.file, class: entry.row.class, member: row.member, card: row.card, line: member.line });
742765
});
743766

744767
for (const f of facades) {
@@ -791,14 +814,15 @@ const SELF_TEST_BATTERIES = Object.freeze({
791814
'E7 two exception rows for one member → RED': 1,
792815
'E8 an unknown key in a row → RED': 1,
793816
'E9 a row missing its static/get/set prefix → RED naming the nearest member key': 1,
817+
'E10 two facades in one file: each judged; an exception row there names its class, or → RED': 1,
794818
'N1 a registered facade file that is missing → RED': 1,
795819
'N2 a registered class that is absent from its file → RED': 1,
796820
'N3 a registered facade with zero delegations → RED': 1,
797821
'N4 a facade row without its card → RED': 1,
798822
'N5 an empty registry → GREEN with nothing guarded, never a crash': 1,
799823
'N6 the committed registry is well-formed against this checkout': 1,
800824
});
801-
const SELF_TEST_BATTERY_FLOOR = 36;
825+
const SELF_TEST_BATTERY_FLOOR = 37;
802826

803827
function selfTest() {
804828
const FILE = 'pkg/src/facade.ts';
@@ -963,6 +987,20 @@ function selfTest() {
963987
]);
964988
return all(red(r, /no member spelled `table`; did you mean `static table`\?/), red(r, /no member spelled `size`; did you mean `get size`\?/));
965989
} },
990+
{ label: 'E10 two facades in one file: each judged; an exception row there names its class, or → RED', run: () => {
991+
const text = `${facadeOf(' update(x: number) { let y = x; return y; }')}export class Second {\n m(a: string) { return F.m(host(this), a); }\n update(x: number) { let y = x; return y; }\n}\n`;
992+
const rows = [row, { file: FILE, class: 'Second', card: '#2' }];
993+
const both = [{ file: FILE, class: 'Facade', member: 'update', card: '#30020' }, { file: FILE, class: 'Second', member: 'update', card: '#30020' }];
994+
const ok = run(text, both, rows);
995+
return all(
996+
green(ok),
997+
ok.facades.length === 2 && ok.excepted.length === 2 ? null : `facades ${ok.facades.length}, excepted ${ok.excepted.length}`,
998+
red(run(text, [both[0]], rows), /Second\.update holds a body/),
999+
red(run(text, [{ file: FILE, member: 'update', card: '#30020' }, both[1]], rows), /registers 2 facade classes .* must name its `class`/),
1000+
red(run(text, [{ ...both[0], class: 'Third' }, both[1]], rows), /`Third` is not a registered facade class/),
1001+
red(run(text, both, [row, row]), /`Facade` is registered twice/),
1002+
);
1003+
} },
9661004
{ label: 'N1 a registered facade file that is missing → RED', run: () =>
9671005
red(checkRegistry(reg([row]), () => null), /pkg\/src\/facade\.ts registered as a facade, but the file does not exist/) },
9681006
{ label: 'N2 a registered class that is absent from its file → RED', run: () =>
@@ -1110,7 +1148,7 @@ function main() {
11101148
if (m.verdict === 'field') fields += 1;
11111149
if (m.verdict === 'delegation') shapes.set(m.shape, (shapes.get(m.shape) ?? 0) + 1);
11121150
}
1113-
const own = excepted.filter((x) => x.file === f.file);
1151+
const own = excepted.filter((x) => x.file === f.file && x.class === f.class);
11141152
const cards = [...new Set(own.map((x) => x.card))].join(', ');
11151153
console.log(
11161154
`✓ ${f.file} \`${f.class}\`: ${f.members.length} members — ` +
@@ -1119,7 +1157,8 @@ function main() {
11191157
);
11201158
for (const [shape, n] of [...shapes].sort((a, b) => b[1] - a[1])) console.log(` ${String(n).padStart(4)} ${shape}`);
11211159
}
1122-
console.log(`✓ check-facade-delegation-only: ${facades.length} facade file(s) hold delegations only, ${excepted.length} named exception(s).`);
1160+
const files = new Set(facades.map((f) => f.file)).size;
1161+
console.log(`✓ check-facade-delegation-only: ${facades.length} facade class(es) in ${files} file(s) hold delegations only, ${excepted.length} named exception(s).`);
11231162
}
11241163

11251164
if (isEntrypoint(import.meta.url)) {

‎scripts/codemod-split-engine.mjs‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2760,6 +2760,7 @@ const SELF_TEST_BATTERIES = Object.freeze({
27602760
'byte-identity proof': 10,
27612761
'import prune': 4,
27622762
'refusals': 6,
2763+
'scoped classes (second pass)': 16,
27632764
});
27642765
const SELF_TEST_BATTERY_FLOOR = 5;
27652766

@@ -2937,6 +2938,80 @@ function needleInMethod(n: number): number {
29372938
`;
29382939
}
29392940

2941+
const FIXTURE_SCOPED_CLASSES = Object.freeze([
2942+
['ObjectRepository', 'engine-object-repository.ts', 'Repository'],
2943+
['ScopedContext', 'engine-scoped-context.ts', 'Context'],
2944+
]);
2945+
2946+
/** An `engine.ts` whose `ObjectQL` the first pass already split, ahead of two unsplit scoped classes. */
2947+
function scopedFixtureSource() {
2948+
return `import { helperImported } from './other.js';
2949+
import { onlyScopedReads } from './scoped-only.js';
2950+
import { count } from './engine-count-aggregate.js';
2951+
import { LifecycleFacet } from './engine-lifecycle.js';
2952+
2953+
export class ObjectQL {
2954+
run(n: number): number {
2955+
// ${MARK} The body moved to \`engine-lifecycle.ts\`.
2956+
return LifecycleFacet.run(n);
2957+
}
2958+
}
2959+
2960+
export class ObjectRepository {
2961+
constructor(
2962+
private objectName: string,
2963+
private engine: { find(o: string): Promise<any[]>; count(o: string): Promise<number> },
2964+
) {}
2965+
2966+
/** A public docblock: it stays on the class. */
2967+
async find(query: any = {}): Promise<any[]> {
2968+
return this.engine.find(this.objectName + String(query));
2969+
}
2970+
2971+
async count(): Promise<number> {
2972+
return this.engine.count(this.objectName);
2973+
}
2974+
2975+
inferred() {
2976+
return 1;
2977+
}
2978+
}
2979+
2980+
export class ScopedContext {
2981+
constructor(private ctx: { user?: string }, private engine: any) {}
2982+
2983+
private flag = false;
2984+
2985+
private derive(ctx: { user?: string }): ScopedContext {
2986+
const child = new ScopedContext(ctx, this.engine);
2987+
child.flag = this.flag;
2988+
return child;
2989+
}
2990+
2991+
/** A private docblock: it moves with the body. */
2992+
private readFlag(): boolean {
2993+
return this.flag && Boolean(helperImported());
2994+
}
2995+
2996+
object(name: string): ObjectRepository {
2997+
return new ObjectRepository(name, this.engine);
2998+
}
2999+
3000+
sudo(): ScopedContext {
3001+
this.flag = this.readFlag() || Boolean(onlyScopedReads());
3002+
return this.derive({ ...this.ctx });
3003+
}
3004+
3005+
handsSelf(): ScopedContext {
3006+
void count;
3007+
return this;
3008+
}
3009+
3010+
get user() { return this.ctx.user; }
3011+
}
3012+
`;
3013+
}
3014+
29403015
async function selfTest() {
29413016
const tm = await loadTsMorph();
29423017
const batterySeen = new Map();
@@ -3117,6 +3192,53 @@ async function selfTest() {
31173192
check('--help is answered, never refused, whatever engine.ts holds', (await main(['--help']).catch(() => 2)) === 0);
31183193
}
31193194

3195+
open('scoped classes (second pass)');
3196+
{
3197+
const input = scopedFixtureSource();
3198+
const planned = planScoped(tm, input, { classes: FIXTURE_SCOPED_CLASSES });
3199+
const record = (cls, name) => planned.targets.find((t) => t.className === cls)?.records.find((r) => r.name === name);
3200+
const why = (cls, name) => (record(cls, name)?.reasons ?? ['<absent>']).join('; ');
3201+
check('a forwarding method, an assigning one and one constructing a sibling class move',
3202+
['find', 'count'].every((n) => why('ObjectRepository', n) === '') && ['object', 'sudo', 'readFlag'].every((n) => why('ScopedContext', n) === ''),
3203+
['find', 'count'].map((n) => why('ObjectRepository', n)).concat(['object', 'sudo', 'readFlag'].map((n) => why('ScopedContext', n))).join(' | '));
3204+
check('a method that only shares a hand-series import\'s name is not a hand-series stub', why('ObjectRepository', 'count') === '', why('ObjectRepository', 'count'));
3205+
check('a body writing a private member of another instance stays (foreign-private)', why('ScopedContext', 'derive').startsWith('foreign-private'), why('ScopedContext', 'derive'));
3206+
check('a body handing the instance on stays (bare-this)', why('ScopedContext', 'handsSelf').startsWith('bare-this'), why('ScopedContext', 'handsSelf'));
3207+
check('a public method with an inferred return type stays (inferred-return-type)', why('ObjectRepository', 'inferred').startsWith('inferred-return-type'), why('ObjectRepository', 'inferred'));
3208+
const out = generateScoped(tm, input, planned);
3209+
const again = generateScoped(tm, input, planScoped(tm, input, { classes: FIXTURE_SCOPED_CLASSES }));
3210+
const v = verifyScoped(tm, input, out.host, out.modules, { classes: FIXTURE_SCOPED_CLASSES });
3211+
check('the generated scoped split proves against its base', v.failures.length === 0 && v.moved.length === 5,
3212+
[...v.failures, `moved: ${v.moved.map((m) => m.name).join()}`].join(' | '));
3213+
check('two runs on one input write byte-identical trees',
3214+
treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules])));
3215+
const ctxMod = out.modules.get('engine-scoped-context.ts') ?? '';
3216+
const hostsMod = out.modules.get(SCOPED_HOSTS_MODULE) ?? '';
3217+
check('each stub hands its body the one host of its own instance',
3218+
out.host.includes('return ScopedContextFacet.sudo.call(scopedContextHost.of(this));') &&
3219+
out.host.includes('return ObjectRepositoryFacet.find.call(objectRepositoryHost.of(this), query);'),
3220+
out.host.slice(out.host.indexOf('sudo(')));
3221+
check('the host module keeps one InstanceHost per class and imports types only',
3222+
hostsMod.includes("export const scopedContextHost = new InstanceHost<ScopedContext, ScopedContextHost>('ScopedContextFacet', 'ScopedContext');") &&
3223+
!/^import (?!type )/m.test(hostsMod));
3224+
check('a private docblock moves with its body; a public one stays on the class',
3225+
ctxMod.includes(' /** A private docblock: it moves with the body. */\n static readFlag(') && !out.host.includes('A private docblock') &&
3226+
out.host.includes(' /** A public docblock: it stays on the class. */\n find(query: any = {}): Promise<any[]> {'));
3227+
check('a field a body assigns gets a setter in its class\'s install block',
3228+
out.host.includes(' get flag() { return instance.flag; },\n set flag(v) { instance.flag = v; },'));
3229+
check('the first pass\'s class is not touched', out.host.includes(` run(n: number): number {\n // ${MARK} The body moved to \`engine-lifecycle.ts\`.\n return LifecycleFacet.run(n);\n }`) &&
3230+
!out.host.slice(out.host.indexOf('export class ObjectQL'), out.host.indexOf('export class ObjectRepository')).includes(SCOPED_MARK));
3231+
const verifyWith = (host, mods) => verifyScoped(tm, input, host, mods, { classes: FIXTURE_SCOPED_CLASSES }).failures.length > 0;
3232+
check('one edited character in a moved body fails', verifyWith(out.host,
3233+
new Map([...out.modules, ['engine-scoped-context.ts', ctxMod.replace('{ ...this.ctx }', '{ ...this.ctx, x: 1 }')]])));
3234+
check('a stub handing the other class\'s host fails', verifyWith(out.host.replace('ScopedContextFacet.sudo.call(scopedContextHost.of(this))', 'ScopedContextFacet.sudo.call(objectRepositoryHost.of(this))'), out.modules));
3235+
check('a written field\'s setter left out of the install block fails', verifyWith(out.host.replace(' set flag(v) { instance.flag = v; },\n', ''), out.modules));
3236+
check('an edited host module fails', verifyWith(out.host, new Map([...out.modules, [SCOPED_HOSTS_MODULE, hostsMod.replace('this.hosts.set(instance, host);', '')]])));
3237+
check('an import only a moved body read is pruned, and the proof names it', out.pruned.includes('onlyScopedReads') && v.pruned.includes('onlyScopedReads'), out.pruned.join());
3238+
check('a scoped class the file does not declare refuses',
3239+
refused(() => planScoped(tm, input, { classes: [['Gone', 'engine-gone.ts', 'Gone']] })));
3240+
}
3241+
31203242
const declared = Object.keys(SELF_TEST_BATTERIES);
31213243
if (declared.length < SELF_TEST_BATTERY_FLOOR) {
31223244
failed += 1;

0 commit comments

Comments
 (0)