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

prove generated manifests are position-independent instead of denying key names

[._.]/ Adam Eivy71e5df5ebf0c
diff --git a/AGENTS.md b/AGENTS.md
index ef9fa52d0f..24d37f5e59 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -178,7 +178,9 @@ Existing deep imports (`import { x } from '../lib/foo.js'`) keep working — the
### Generated manifests are addressed by content, never by position
-A checked-in `*.generated.json` is derived from source and kept honest by a drift test that regenerates and compares. That only works if the file changes when the thing it describes changes — and *only* then. A record pointing at `foo.js:412` is rewritten by any edit that inserts a line above 412, so the drift test fires on commits that change nothing it describes, 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`); keep line/column detail in memory, where a fresh scan can still use it to verify coverage. `server/lib/generatedManifests.test.js` enforces this across every tracked `*.generated.json`. This lives in root rather than `server/AGENTS.md` because the generators it governs are in `scripts/`, which carries no nested file of its own; the longer rationale is in `server/AGENTS.md`.
+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`.
## Scope Boundary
diff --git a/scripts/generate-api-route-catalog.test.js b/scripts/generate-api-route-catalog.test.js
index a2c2d30d60..816618bef7 100644
--- a/scripts/generate-api-route-catalog.test.js
+++ b/scripts/generate-api-route-catalog.test.js
@@ -7,7 +7,6 @@ import {
MANIFEST_RELATIVE_PATH,
REGENERATE_COMMAND,
REPO_ROOT,
- SCHEMA_VERSION,
buildApiRouteCatalog,
generateApiRouteCatalog,
parseRouteModule,
@@ -16,6 +15,7 @@ import {
scanRouteGraph,
serializeApiRouteCatalog,
} from './generate-api-route-catalog.js';
+import { POSITION_INVARIANCE_FAILURE, generateAcrossShiftedSources } from './lib/positionInvariance.js';
const write = (root, path, source) => {
const target = join(root, path);
@@ -145,6 +145,52 @@ describe('API route catalog scanner', () => {
'POST /api/runs/:id/stop',
]);
});
+
+ // The property that keeps this manifest out of every rebase, tested directly:
+ // shifting every line in every scanned source must not move one byte of the
+ // output. Because it asserts the rule rather than the vocabulary that breaks
+ // it, this catches a position recorded under ANY key — `at`, `span`, `row`, a
+ // `loc: [412, 8]` tuple, a `foo.js#L412` anchor — where the tree-wide net in
+ // `server/lib/generatedManifests.test.js` can only deny-list names it knows.
+ it('generates a byte-identical catalog after every source line shifts', () => {
+ const root = mkdtempSync(join(tmpdir(), 'portos-api-catalog-'));
+ write(root, 'server/index.js', `
+ import widgetsRoutes from './routes/widgets.js';
+ app.use('/api/widgets', widgetsRoutes);
+ `);
+ write(root, 'server/routes/widgets.js', `
+ import { Router } from 'express';
+ import childRoutes from './widgets-child.js';
+ const router = Router();
+ router.get('/', handler);
+ router.use('/child', childRoutes);
+ export default router;
+ `);
+ write(root, 'server/routes/widgets-child.js', `
+ import { Router } from 'express';
+ const router = Router();
+ router.patch('/:id', handler);
+ export default router;
+ `);
+
+ // 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')
+ .split('\n')
+ .flatMap((line, index) => (/router\.(get|patch|post)\(/.test(line) ? [`${path}:${index + 1}`] : []))
+ .join(',')).join('|');
+
+ const { before, after, shiftedFiles } = generateAcrossShiftedSources(root, () => ({
+ catalog: serializeApiRouteCatalog(buildApiRouteCatalog({ repoRoot: root })),
+ declarationLines: declarationLines(root),
+ }));
+
+ expect(shiftedFiles).toHaveLength(3);
+ expect(after.catalog, POSITION_INVARIANCE_FAILURE).toBe(before.catalog);
+ // Bypass probe: a generator that DID record positions would have churned
+ // here, so the assertion above is not just observing a stable fixture.
+ expect(after.declarationLines).not.toBe(before.declarationLines);
+ });
});
describe('generated API route catalog', () => {
@@ -183,7 +229,6 @@ describe('generated API route catalog', () => {
it('is a unique, stable, complete inventory with source pointers', () => {
const catalog = readApiRouteCatalog();
- expect(catalog.schemaVersion).toBe(SCHEMA_VERSION);
expect(catalog.stats.mounts).toBeGreaterThan(140);
expect(catalog.stats.operations).toBeGreaterThan(2_000);
expect(catalog.routes).toHaveLength(catalog.stats.operations);
diff --git a/scripts/generate-prompt-stage-call-sites.test.js b/scripts/generate-prompt-stage-call-sites.test.js
index 3c98d4e2cc..b69c42fbb7 100644
--- a/scripts/generate-prompt-stage-call-sites.test.js
+++ b/scripts/generate-prompt-stage-call-sites.test.js
@@ -13,6 +13,7 @@ import {
readStageCallSitesManifest,
serializeManifest,
} from './generate-prompt-stage-call-sites.js';
+import { POSITION_INVARIANCE_FAILURE, shiftSourceText } from './lib/positionInvariance.js';
// Fixture sources exercise the scanner's contract without depending on the
// real tree, so a legitimate refactor of `server/` can't turn these into
@@ -152,6 +153,24 @@ describe('prompt stage call-site scanner', () => {
expect(Object.keys(index)).toEqual(['demo-alpha', 'demo-beta']);
expect(index['demo-beta']).toEqual(['server/services/a.js', 'server/services/z.js']);
});
+
+ // This manifest already keys by stage and lists paths only, so it passes
+ // today. The test is here to keep it that way: it states the rule as a
+ // property, so a future scanner that starts recording where a call site sits
+ // fails here rather than in someone's rebase. Same guard as the route
+ // catalog's, which is why both call the one helper.
+ it('builds a byte-identical index after every source line shifts', () => {
+ const sources = [
+ src('server/services/a.js', "await getStage('demo-alpha');"),
+ src('server/services/b.js', 'await buildPrompt("demo-beta", {});'),
+ ];
+ const build = (scanned) => serializeManifest(buildStageCallSites({ shippedStageKeys, sources: scanned }));
+
+ expect(
+ build(sources.map(({ path, source }) => src(path, shiftSourceText(source)))),
+ POSITION_INVARIANCE_FAILURE,
+ ).toBe(build(sources));
+ });
});
// The guard the whole generated-manifest posture exists for: adding a
diff --git a/scripts/lib/positionInvariance.js b/scripts/lib/positionInvariance.js
new file mode 100644
index 0000000000..e115a9eef8
--- /dev/null
+++ b/scripts/lib/positionInvariance.js
@@ -0,0 +1,77 @@
+/**
+ * Position invariance — the property every checked-in generated manifest owes
+ * the people who rebase onto it.
+ *
+ * A `*.generated.json` is kept honest by a drift test that regenerates and
+ * compares, which only works if the file changes when the thing it describes
+ * changes — and *only* then. The "only" is the half that rots. A manifest
+ * recording `foo.js:412` is rewritten by any edit that inserts a line above
+ * 412: a comment, a rename, an unrelated handler. The drift test then fires on
+ * commits that change nothing it describes, every parallel branch regenerates
+ * it differently, and every rebase conflicts on it.
+ *
+ * The direct way to prove a generator is clean is to test the property rather
+ * than guess at the vocabulary that violates it. Shift every position in the
+ * inputs — without touching anything a manifest is supposed to describe — and
+ * demand byte-identical output. That catches a `line`, and equally an `at`, a
+ * `span`, a `row`, a `loc: [412, 8]` tuple, or a `foo.js#L412` anchor: every
+ * spelling of a position, including the ones nobody thought to deny-list.
+ *
+ * `server/lib/generatedManifests.test.js` is the cheap tree-wide net that
+ * catches a manifest whose generator never adopted this; this module is how a
+ * generator proves it directly. Use both.
+ */
+
+import { readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+
+/**
+ * Two comment lines. Prepending them shifts every line number, byte offset,
+ * and character index in the file below without altering one token of the
+ * code a manifest actually describes.
+ */
+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];
+});
+
+/** Shift the positions in one in-memory source string. */
+export const shiftSourceText = (source) => `${SHIFT_HEADER}${source}`;
+
+/**
+ * Shift the positions in every matching file under `root`, in place.
+ *
+ * Returns the files it rewrote so a caller can assert it actually shifted
+ * something — a probe that silently matched no files proves nothing.
+ */
+export const shiftSourcePositions = (root, { extensions = ['.js'] } = {}) => {
+ const targets = walkFiles(root).filter((path) => extensions.some((ext) => path.endsWith(ext)));
+ for (const path of targets) writeFileSync(path, shiftSourceText(readFileSync(path, 'utf8')), 'utf8');
+ return targets;
+};
+
+/**
+ * Run `generate` against a fixture tree, shift every position in that tree,
+ * and run it again — so a caller only has to compare the two results.
+ *
+ * Taking the generator as a thunk keeps the order right: it is the second
+ * result that has to match the first, and building them in the wrong order
+ * would quietly pass.
+ */
+export const generateAcrossShiftedSources = (root, generate, options) => {
+ const before = generate();
+ const shiftedFiles = shiftSourcePositions(root, options);
+ return { before, after: generate(), shiftedFiles };
+};
+
+/** Explains a position-invariance failure in terms of what it costs. */
+export const POSITION_INVARIANCE_FAILURE = [
+ 'Regenerating after an edit that changed no described content produced a different manifest,',
+ 'so this generator is recording a position (a line, offset, or file:line pointer) rather than',
+ 'content. Every rebase will conflict on the committed file and the drift test will fire on',
+ 'commits that change nothing. Key each record by the declaring file plus the semantic identity',
+ 'of what it declares, and keep positional detail in memory for the generator\'s own verification.',
+].join(' ');
diff --git a/server/AGENTS.md b/server/AGENTS.md
index 007490c97e..1737d06c8e 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.
-- `server/lib/generatedManifests.test.js` enforces this across every git-tracked `*.generated.json` — it fails on `line`/`column`/`offset`-style keys and on `path/to/file.js:412` strings anywhere in the tree, so a new generator inherits the rule rather than rediscovering it.
+- **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.
## Prompt templates
diff --git a/server/lib/generatedManifests.test.js b/server/lib/generatedManifests.test.js
index 878dc7a1cd..e91fb229d5 100644
--- a/server/lib/generatedManifests.test.js
+++ b/server/lib/generatedManifests.test.js
@@ -23,26 +23,36 @@ import { execFileSync } from './childProcess.js';
* keys declarations as `file#routerId METHOD /path`; `promptStageCallSites`
* keys them by stage key and lists file paths only.
*
- * This guard exists so the next generator does not have to rediscover that.
+ * This guard is the cheap tree-wide net, and it is deliberately shallow: it
+ * matches key NAMES, so it can only catch spellings someone anticipated. A
+ * generator proves itself clean with the property test in
+ * `scripts/lib/positionInvariance.js` instead — shift every line in its inputs
+ * and demand byte-identical output. Both generators here do that; this file
+ * catches the manifest whose generator never did.
*/
const HERE = resolve(fileURLToPath(import.meta.url), '..');
const REPO_ROOT = resolve(HERE, '..', '..');
// Keys whose numeric value points into a file rather than describing content.
-// `index` and `offset` are here for the same reason a line number is: they
-// name a position in something that moves.
+// Offsets are here for the same reason a line number is: they name a position
+// in something that moves.
+//
+// A name list is a cheap tree-wide net, not a proof: it only catches the
+// spellings someone thought of. What actually proves a generator clean is the
+// property test in `scripts/lib/positionInvariance.js` — shift every line in
+// the inputs and demand byte-identical output — which catches `at`, `span`,
+// `row`, and every other name this list will never have. Use both.
const POSITIONAL_KEYS = new Set([
'line', 'lineNumber', 'lineNo', 'startLine', 'endLine',
'column', 'columnNumber', 'col', 'startColumn', 'endColumn',
'offset', 'startOffset', 'endOffset', 'charIndex', 'byteOffset',
- 'loc', 'position',
]);
// 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, a `position` holding `"left"` — and rejecting those would
-// make this guard block manifests it has no quarrel with.
+// Postgres column — and rejecting those would make this guard block manifests
+// it has no quarrel with.
const isPositionalValue = (value) => typeof value === 'number'
|| (typeof value === 'string' && /^\d+$/.test(value.trim()));
@@ -118,10 +128,9 @@ describe('checked-in generated manifests', () => {
.toEqual(['$.loc.line — positional key "line"']);
// 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, a layout side.
+ // position at all — a Postgres column name.
expect(findPositionalReferences({ sources: ['server/routes/a.js'], stats: { operations: 2153 } }))
.toEqual([]);
- expect(findPositionalReferences({ column: 'user_id', position: 'left' }))
- .toEqual([]);
+ expect(findPositionalReferences({ column: 'user_id' })).toEqual([]);
});
});