Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

close the gaps an agy review found in the two position guards

[._.]/ Adam Eivycb990e240763
diff --git a/scripts/generate-api-route-catalog.js b/scripts/generate-api-route-catalog.js
index 3e7629ec65..3e5f772e4c 100644
--- a/scripts/generate-api-route-catalog.js
+++ b/scripts/generate-api-route-catalog.js
@@ -102,10 +102,16 @@ export function parseImports(source, filePath) {
/**
* Position-independent identity for one `router.<method>('<path>')` call.
*
- * Two declarations collide only when the same file registers the same method
- * and path on the same router variable — which is a duplicate registration,
- * not two distinct bindings. Unlike a line number, this key survives every
- * edit that does not change the declaration itself.
+ * Two declarations collide when the same file registers the same method and
+ * path on the same router *name* — normally a duplicate registration rather
+ * than two distinct bindings. The exception is shadowing: a module-level
+ * `const router = Router()` and a second one inside a factory share the id
+ * `router`, so distinct bindings could collide and silently undercount. That
+ * is why `scanRouteGraph` reports `duplicateDeclarationKeys` instead of just
+ * folding them into a Set — see the collision assertion in the test.
+ *
+ * Unlike a line number, this key survives every edit that does not change the
+ * declaration itself.
*/
export const routeDeclarationKey = ({ source, routerId, method, path }) =>
`${source}#${routerId} ${method.toUpperCase()} ${path || '/'}`;
@@ -275,10 +281,27 @@ export function scanRouteGraph({ repoRoot = REPO_ROOT, indexSource } = {}) {
.map((operation) => ({ ...operation, sources: [...new Set(operation.sources)].sort() }))
.sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method));
+ // Collisions are counted PER MODULE, from the parsed declarations rather than
+ // from `record`: one router mounted at two prefixes reaches `record` twice
+ // with the same declaration, which is the same binding seen twice, not two
+ // bindings sharing a key. Within a single file, a repeated key is the real
+ // thing — a duplicate registration, or two shadowed routers sharing a name.
+ const duplicateDeclarationKeys = [...moduleCache.values()].flatMap((module) => {
+ const seen = new Set();
+ return module.routes
+ .map((declaration) => routeDeclarationKey(declaration))
+ .filter((key) => {
+ if (seen.has(key)) return true;
+ seen.add(key);
+ return false;
+ });
+ }).sort();
+
return {
mounts: [...new Set(topLevelMounts.map((mount) => mount.mountPath))].sort(),
routes,
declarationKeys,
+ duplicateDeclarationKeys,
sourceFileCount: moduleCache.size,
};
}
diff --git a/scripts/generate-api-route-catalog.test.js b/scripts/generate-api-route-catalog.test.js
index 3d9273b70e..bf39635b9b 100644
--- a/scripts/generate-api-route-catalog.test.js
+++ b/scripts/generate-api-route-catalog.test.js
@@ -202,6 +202,18 @@ describe('generated API route catalog', () => {
.toBe(serializeApiRouteCatalog(fresh));
});
+ // Content keying trades a line number's uniqueness for a name's, so the one
+ // way it can lose a route is two declarations sharing a key. Left alone the
+ // Set would just swallow the second one and undercount; this makes it loud.
+ it('gives every declaration in a file a distinct key', () => {
+ expect(routeGraph().duplicateDeclarationKeys, [
+ 'Two route declarations in one file produced the same catalog key, so the',
+ 'second is invisible to the coverage guard and to stats.declarations. Either',
+ 'it is a genuine duplicate registration (delete one), or two routers in that',
+ 'file share a variable name through shadowing (rename one).',
+ ].join(' ')).toEqual([]);
+ });
+
// Both sides of this comparison are fresh in-memory scans, which is what
// lets the committed manifest stay free of line numbers: the manifest never
// has to point back at the source it was derived from for the guard to work.
diff --git a/server/lib/generatedManifests.test.js b/server/lib/generatedManifests.test.js
index 5777b0d1f9..b2b2e01ce3 100644
--- a/server/lib/generatedManifests.test.js
+++ b/server/lib/generatedManifests.test.js
@@ -47,14 +47,23 @@ const POSITIONAL_KEYS = new Set([
'line', 'lineNumber', 'lineNo', 'startLine', 'endLine',
'column', 'columnNumber', 'col', 'startColumn', 'endColumn',
'offset', 'startOffset', 'endOffset', 'charIndex', 'byteOffset',
+ // Names for a position that carries its own pair or range. They only fire on
+ // a numeric value (or an all-numeric array), so a `span` counting items or a
+ // `loc` naming a place is left alone.
+ 'loc', 'span', 'pos', 'position', 'range',
]);
// A position is always a number. Several of these key names have perfectly
// good non-positional uses with a non-numeric value — a `column` naming a
// Postgres column — and rejecting those would make this guard block manifests
// it has no quarrel with.
+// A range or coordinate pair is still a position — `loc: [412, 8]` and
+// `line: [412, 420]` are exactly the shapes a generator reaches for once a
+// scalar line number feels too coarse, and checking only scalars would recurse
+// into the array and find nothing but bare numbers with no key to judge them by.
const isPositionalValue = (value) => typeof value === 'number'
- || (typeof value === 'string' && /^\d+$/.test(value.trim()));
+ || (typeof value === 'string' && /^\d+$/.test(value.trim()))
+ || (Array.isArray(value) && value.length > 0 && value.every(isPositionalValue));
// A `path/to/file.js:412` (optionally `:8` for a column) pointer smuggled into
// a string, which is how a positional reference survives dropping the key.
@@ -126,6 +135,14 @@ describe('checked-in generated manifests', () => {
// A numeric string is still a position — dropping the type doesn't help.
expect(findPositionalReferences({ loc: { line: '412' } }))
.toEqual(['$.loc.line — positional key "line"']);
+ // Nor does wrapping it in an array: a range and a coordinate pair are the
+ // shapes a generator reaches for when one number stops being enough.
+ expect(findPositionalReferences({ loc: [412, 8] }))
+ .toEqual(['$.loc — positional key "loc"']);
+ expect(findPositionalReferences({ line: [412, 420] }))
+ .toEqual(['$.line — positional key "line"']);
+ // An empty array names no position, and a list of paths is not one either.
+ expect(findPositionalReferences({ line: [] })).toEqual([]);
// Plain file paths and ordinary counts are what a manifest SHOULD contain,
// and a positional-sounding key holding a non-numeric value is not a
// position at all — a Postgres column name.
@@ -141,21 +158,39 @@ describe('checked-in generated manifests', () => {
// which is the same "someone has to remember" problem this whole change set
// exists to delete. This makes adoption structural instead.
it('requires every generator to carry the position-invariance property test', () => {
- const listed = execFileSync('git', ['ls-files', 'scripts/generate-*.js'], {
+ const listed = execFileSync('git', ['ls-files', 'scripts/*.js'], {
cwd: REPO_ROOT,
encoding: 'utf8',
}).split('\n').filter(Boolean);
const tests = new Set(listed.filter((path) => path.endsWith('.test.js')));
- const generators = listed.filter((path) => !path.endsWith('.test.js'));
- // Guard the guard: if the glob stops matching, the assertion below passes
+ // Scope by what a script PRODUCES, not by what it is named. Keying off
+ // `generate-*.js` fails a future generate-types.js or generate-fixtures.js
+ // that writes no manifest and has nothing to hold invariant, while missing
+ // a manifest generator named build-*.js. Writing a checked-in
+ // `*.generated.json` is the property that actually incurs the obligation.
+ // `scripts/*.js` as a git pathspec also matches nested paths, and the
+ // helper library itself names `.generated.json` in its own docstring —
+ // so require a runnable script directly under scripts/, not a module it
+ // imports.
+ const generators = listed.filter((path) => !path.endsWith('.test.js')
+ && path.split('/').length === 2
+ && readFileSync(join(REPO_ROOT, path), 'utf8').includes('.generated.json'));
+
+ // Guard the guard: if the filter stops matching, the assertion below passes
// vacuously over an empty list.
- expect(generators.length).toBeGreaterThanOrEqual(2);
+ expect(generators).toEqual(expect.arrayContaining([
+ 'scripts/generate-api-route-catalog.js',
+ 'scripts/generate-prompt-stage-call-sites.js',
+ ]));
+ // Require a real import, not a passing mention: a comment naming the module
+ // would satisfy a bare substring check while asserting nothing.
+ const IMPORTS_HELPER = /^\s*import\s[^;]*from\s+['"][^'"]*positionInvariance\.js['"]/m;
const missing = generators.filter((path) => {
const testPath = path.replace(/\.js$/, '.test.js');
if (!tests.has(testPath)) return true;
- return !readFileSync(join(REPO_ROOT, testPath), 'utf8').includes('positionInvariance.js');
+ return !IMPORTS_HELPER.test(readFileSync(join(REPO_ROOT, testPath), 'utf8'));
});
expect(missing, [