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

make position-invariance adoption structural instead of a documented convention

[._.]/ Adam Eivy2367c5cb654e
diff --git a/AGENTS.md b/AGENTS.md
index 24d37f5e59..c35c05f4f6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -180,7 +180,7 @@ Existing deep imports (`import { x } from '../lib/foo.js'`) keep working — the
A checked-in `*.generated.json` must change when — and *only* when — the thing it describes changes. A record pointing at `foo.js:412` breaks the *only*: any edit inserting a line above 412 rewrites it, so its drift test fires on commits that change nothing, each parallel branch regenerates it differently, and **every rebase conflicts on it**. Key each record by the declaring file plus the semantic identity of what it declares (`routeDeclarationKey` in `scripts/generate-api-route-catalog.js`), never by line/column.
-**A new generator proves this with `generateAcrossShiftedSources` (`scripts/lib/positionInvariance.js`)** — shift every line in its inputs, regenerate, assert byte-identical output. That tests the rule itself, so it catches a position under any key name. `server/lib/generatedManifests.test.js` is the tree-wide backstop for a manifest whose generator skipped it. This rule lives in root because the generators are in `scripts/`, which carries no nested file; rationale and the coverage-without-positions pattern are in `server/AGENTS.md`.
+**A new generator proves this with `generateAcrossShiftedSources` (`scripts/lib/positionInvariance.js`)** — shift every line in its inputs, regenerate, assert byte-identical output. That tests the rule itself, so it catches a position under any key name. `server/lib/generatedManifests.test.js` is the tree-wide backstop for a manifest whose generator skipped it, and it also **fails when a `scripts/generate-*.js` has no sibling test importing `positionInvariance.js`** — so adoption is structural, not a convention you have to remember. This rule lives in root because the generators are in `scripts/`, which carries no nested file; rationale and the coverage-without-positions pattern are in `server/AGENTS.md`.
## Scope Boundary
diff --git a/scripts/generate-api-route-catalog.js b/scripts/generate-api-route-catalog.js
index ac4fde6813..3e7629ec65 100644
--- a/scripts/generate-api-route-catalog.js
+++ b/scripts/generate-api-route-catalog.js
@@ -41,7 +41,7 @@ const HERE = dirname(fileURLToPath(import.meta.url));
export const REPO_ROOT = resolve(HERE, '..');
export const MANIFEST_RELATIVE_PATH = 'server/lib/apiRouteCatalog.generated.json';
export const REGENERATE_COMMAND = 'node scripts/generate-api-route-catalog.js';
-export const SCHEMA_VERSION = 2;
+const SCHEMA_VERSION = 2;
const INDEX_RELATIVE_PATH = 'server/index.js';
const ROUTE_METHODS = Object.freeze(['delete', 'get', 'head', 'options', 'patch', 'post', 'put']);
diff --git a/scripts/generate-api-route-catalog.test.js b/scripts/generate-api-route-catalog.test.js
index 816618bef7..3d9273b70e 100644
--- a/scripts/generate-api-route-catalog.test.js
+++ b/scripts/generate-api-route-catalog.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
@@ -15,7 +15,7 @@ import {
scanRouteGraph,
serializeApiRouteCatalog,
} from './generate-api-route-catalog.js';
-import { POSITION_INVARIANCE_FAILURE, generateAcrossShiftedSources } from './lib/positionInvariance.js';
+import { POSITION_INVARIANCE_FAILURE, generateAcrossShiftedSources, walkFiles } from './lib/positionInvariance.js';
const write = (root, path, source) => {
const target = join(root, path);
@@ -23,11 +23,6 @@ const write = (root, path, source) => {
writeFileSync(target, source, 'utf8');
};
-const walk = (dir) => readdirSync(dir).flatMap((name) => {
- const path = join(dir, name);
- return statSync(path).isDirectory() ? walk(path) : [path];
-});
-
describe('API route catalog scanner', () => {
it('resolves top-level mounts, imported child routers, local subrouters, and aliases', () => {
const root = mkdtempSync(join(tmpdir(), 'portos-api-catalog-'));
@@ -175,7 +170,7 @@ describe('API route catalog scanner', () => {
// Where each declaration sits, which is exactly what the manifest must NOT
// encode. Used only to prove the shift below is big enough to be noticed.
- const declarationLines = (repoRoot) => walk(join(repoRoot, 'server')).map((path) => readFileSync(path, 'utf8')
+ const declarationLines = (repoRoot) => walkFiles(join(repoRoot, 'server')).map((path) => readFileSync(path, 'utf8')
.split('\n')
.flatMap((line, index) => (/router\.(get|patch|post)\(/.test(line) ? [`${path}:${index + 1}`] : []))
.join(',')).join('|');
@@ -212,7 +207,7 @@ describe('generated API route catalog', () => {
// has to point back at the source it was derived from for the guard to work.
it('covers every HTTP declaration mounted below /api or /sdapi', () => {
const { declarationKeys } = routeGraph();
- const routeFiles = walk(join(REPO_ROOT, 'server', 'routes'))
+ const routeFiles = walkFiles(join(REPO_ROOT, 'server', 'routes'))
.filter((path) => path.endsWith('.js') && !path.endsWith('.test.js'));
const omitted = [];
for (const file of routeFiles) {
diff --git a/scripts/lib/positionInvariance.js b/scripts/lib/positionInvariance.js
index e115a9eef8..6d2c71d280 100644
--- a/scripts/lib/positionInvariance.js
+++ b/scripts/lib/positionInvariance.js
@@ -22,7 +22,7 @@
* generator proves it directly. Use both.
*/
-import { readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs';
+import { readFileSync, writeFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
/**
@@ -33,9 +33,10 @@ import { join } from 'node:path';
const SHIFT_HEADER = '// position-invariance probe: shifts every line and offset below it.\n'
+ '// Nothing a generated manifest describes lives in these two lines.\n';
-const walkFiles = (dir) => readdirSync(dir).flatMap((name) => {
- const path = join(dir, name);
- return statSync(path).isDirectory() ? walkFiles(path) : [path];
+/** Every file under `dir`, recursively. One `readdir` per directory, no `stat` per entry. */
+export const walkFiles = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(dir, entry.name);
+ return entry.isDirectory() ? walkFiles(path) : [path];
});
/** Shift the positions in one in-memory source string. */
diff --git a/server/AGENTS.md b/server/AGENTS.md
index 1737d06c8e..197580b25e 100644
--- a/server/AGENTS.md
+++ b/server/AGENTS.md
@@ -19,7 +19,7 @@ These apply to Express/service/model code. Universal constraints (no try/catch o
- **A checked-in generated manifest is addressed by CONTENT, never by POSITION.** `server/lib/*.generated.json` files are derived from source and kept honest by a drift test that regenerates and compares. That only works if the manifest changes when the thing it describes changes — and *only* then. A record that says "declared at `foo.js:412`" is rewritten by any edit that inserts a line above 412 (a rename, a comment, an unrelated handler), so the drift test fires on commits that change no route/stage/event at all, each parallel branch regenerates the file differently, and every rebase conflicts on it. `apiRouteCatalog.generated.json` shipped 30 changed lines per no-op refactor this way, and `main` still ended up carrying a stale `stats.declarations` whose route graph was byte-identical.
- **Key each record by the declaring file plus the semantic identity of what it declares** — `file#routerId METHOD /path` for a route (`routeDeclarationKey` in `scripts/generate-api-route-catalog.js`), the stage key plus file paths for `promptStageCallSites.generated.json`. Positional detail may stay **in memory**: a coverage guard compares two fresh in-memory scans (`scanRouteGraph()` vs `parseRouteModule()`), so the committed file never has to point back into the source it was derived from.
-- **Prove it with a property test, not a name list.** `generateAcrossShiftedSources` (`scripts/lib/positionInvariance.js`) prepends a comment header to every scanned source, regenerates, and demands byte-identical output — asserting the rule directly, so it catches a position recorded as `at`, `span`, `row`, a `loc: [412, 8]` tuple, or a `foo.js#L412` anchor. Both generators carry that test. `server/lib/generatedManifests.test.js` is the cheap tree-wide backstop: it scans every git-tracked `*.generated.json` for `line`/`column`/`offset`-style keys and `path/to/file.js:412` strings, catching a manifest whose generator never adopted the property test. It matches key names, so it is a net, not a proof — write both.
+- **Prove it with a property test, not a name list.** `generateAcrossShiftedSources` (`scripts/lib/positionInvariance.js`) prepends a comment header to every scanned source, regenerates, and demands byte-identical output — asserting the rule directly, so it catches a position recorded as `at`, `span`, `row`, a `loc: [412, 8]` tuple, or a `foo.js#L412` anchor. Both generators carry that test. `server/lib/generatedManifests.test.js` is the cheap tree-wide backstop: it scans every git-tracked `*.generated.json` for `line`/`column`/`offset`-style keys and `path/to/file.js:412` strings, catching a manifest whose generator never adopted the property test. It matches key names, so it is a net, not a proof — write both. That same file also enforces adoption structurally: it lists every git-tracked `scripts/generate-*.js` and fails when one has no sibling `.test.js` importing `positionInvariance.js`, so generator #3 cannot ship without the property test.
## Prompt templates
diff --git a/server/lib/generatedManifests.test.js b/server/lib/generatedManifests.test.js
index e91fb229d5..5777b0d1f9 100644
--- a/server/lib/generatedManifests.test.js
+++ b/server/lib/generatedManifests.test.js
@@ -61,7 +61,7 @@ const isPositionalValue = (value) => typeof value === 'number'
const SOURCE_POINTER_RE = /[\w./-]+\.(?:js|jsx|mjs|cjs|ts|tsx|json|md):\d+(?::\d+)?/;
/** Every positional reference in one parsed manifest, as `jsonPath — why`. */
-export const findPositionalReferences = (value, path = '$') => {
+const findPositionalReferences = (value, path = '$') => {
if (Array.isArray(value)) {
return value.flatMap((entry, index) => findPositionalReferences(entry, `${path}[${index}]`));
}
@@ -133,4 +133,38 @@ describe('checked-in generated manifests', () => {
.toEqual([]);
expect(findPositionalReferences({ column: 'user_id' })).toEqual([]);
});
+
+ // The two guards above only reach a generator that followed the naming
+ // convention and got its property test written. Neither is structural: a
+ // third generator can be added tomorrow with no position-invariance test at
+ // all, and nothing fails — the rule would live only in AGENTS.md prose,
+ // 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'], {
+ 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
+ // vacuously over an empty list.
+ expect(generators.length).toBeGreaterThanOrEqual(2);
+
+ 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');
+ });
+
+ expect(missing, [
+ 'A generator under scripts/ has no position-invariance property test.',
+ 'Import generateAcrossShiftedSources (or shiftSourceText, for a generator that',
+ 'takes in-memory sources) from scripts/lib/positionInvariance.js in its sibling',
+ '.test.js, regenerate across shifted sources, and assert byte-identical output.',
+ 'Without it, this generator can start recording line numbers and only the',
+ 'shallow key-name net above would notice — and only if it guessed the name.',
+ ].join(' ')).toEqual([]);
+ });
});