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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
docs([issue-726]): establish the collectionStore config-slot convention
[._.]/ Adam Eivy03d8ccecd48b
diff --git a/server/lib/README.md b/server/lib/README.mdindex b4981ea01d..c5613b069b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -95,7 +95,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|-| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. |+| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. || `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.jsindex 12a0b34987..e02b0194a1 100644--- a/server/lib/collectionStore.js+++ b/server/lib/collectionStore.js@@ -5,7 +5,7 @@* Layout on disk:** {dir}/- * ├── index.json // { schemaVersion, type, updatedAt, config: {} }+ * ├── index.json // { schemaVersion, type, updatedAt, config: {…} }* ├── <id-1>/* │ └── index.json // the record itself* └── <id-2>/@@ -16,6 +16,48 @@* collection has outgrown it. See `data/runs/` for the proven prior-art shape* this generalizes.*+ * The `config` slot — type-level shared state (convention):+ * The type index's `config` object holds cross-record state that belongs to+ * the collection as a whole rather than to any single record — the things+ * that would otherwise need their own sidecar file. The convention is+ * grounded in the first real consumer (universeBuilder, see migration 034),+ * which keeps a capped `config.runs[]` history log alongside its per-universe+ * records. The agreed shape (see the `TypeIndexConfig` typedef below):+ *+ * config: {+ * runs?: [], // append-mostly cross-record history/audit log,+ * // capped by the consumer (universeBuilder caps+ * // at the last 200) — the established slot+ * featureFlags?: {}, // reserved: per-collection toggles+ * lockPolicies?: {}, // reserved: per-collection lock rules+ * … // consumers MAY add their own keys; document the+ * // shape next to the consumer that owns it+ * }+ *+ * `runs` is the only slot with a shipped consumer; `featureFlags` /+ * `lockPolicies` are reserved names so the next consumer reuses them instead+ * of inventing a synonym. Treat the slot as open-but-conventional: prefer a+ * reserved name when one fits, and keep each key's value an object or array+ * so the shallow-merge semantics below stay predictable.+ *+ * Merge semantics: `saveTypeIndex({ config })` shallow-merges at the TOP+ * level of `config` — `{ ...current.config, ...patch.config }`. A patch that+ * sets `runs` REPLACES the whole `runs` array; it does NOT deep-merge into+ * it. So a read-modify-write of an array (or nested-object) slot must load+ * the current value, mutate a copy, and write the full replacement (see+ * `recordRun` in universeBuilder). The merge is one level deep only.+ *+ * Write-fence: `config`-slot writes all share ONE file (`index.json`) across+ * every record in the type, so a read→modify→write cycle on a slot must run+ * inside `queueTypeIndexWrite(fn)` to avoid clobbering a concurrent edit.+ * `recordRun` is the canonical example: it loads the index, appends to+ * `runs`, caps, and writes — all inside the type-index queue. Use+ * `saveTypeIndex` for a simple patch (it queues internally); reach for+ * `queueTypeIndexWrite` directly only when the read and the write must be+ * fenced together. `defaultTypeIndexConfig` seeds the slot on a fresh type+ * index (and on any read where `config` is missing or not a plain object);+ * it is NOT re-applied on later writes.+ ** Two versioning concerns coexist:* - The TYPE-LEVEL `schemaVersion` (this file): describes the on-disk* storage layout. Bumped by a migration that changes layout (e.g. a split@@ -49,6 +91,25 @@ import { atomicWrite, readJSONFile, ensureDir } from './fileUtils.js';const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);+/**+ * The type-index `config` slot — cross-record state owned by the collection as+ * a whole. See the header doc block for the convention. All keys are optional;+ * a consumer that needs a slot not listed here MAY add its own (document it+ * next to the consumer), but should prefer a reserved name when one fits. Each+ * value should be an array or plain object so the top-level shallow-merge in+ * `saveTypeIndex` stays predictable.+ *+ * @typedef {object} TypeIndexConfig+ * @property {Array<object>} [runs]+ * Append-mostly cross-record history/audit log. The consumer is responsible+ * for capping growth (universeBuilder keeps the last 200) and for sanitizing+ * each entry on read/write. The only slot with a shipped consumer today.+ * @property {Object<string, boolean>} [featureFlags]+ * Reserved: per-collection on/off toggles.+ * @property {Object<string, object>} [lockPolicies]+ * Reserved: per-collection lock rules.+ */+/*** Create a per-type collection store.*@@ -64,9 +125,12 @@ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArr* @param {(record: any) => any} [opts.sanitizeRecord]* Optional record-level normalizer. Called on every `loadOne` result. Return* `null` to treat the on-disk record as invalid (loadOne returns `null`).- * @param {object} [opts.defaultTypeIndexConfig]- * Initial value for the `config` slot of a freshly-minted type index.- * Defaults to `{}`.+ * @param {TypeIndexConfig} [opts.defaultTypeIndexConfig]+ * Initial value for the `config` slot of a freshly-minted type index (and the+ * fallback when an on-disk index is missing/has a non-object `config`).+ * Defaults to `{}`. Seeds the slot on first read only — it is NOT re-applied+ * on later `saveTypeIndex` writes, which shallow-merge over the current value.+ * See the `TypeIndexConfig` typedef and the header `config`-slot convention.* @param {RegExp} [opts.idPattern]* Allowlist for record-directory names. Defaults to a permissive pattern* (`/^[A-Za-z0-9_-]{1,128}$/`) — services with stricter id rules should pass@@ -160,10 +224,18 @@ export function createCollectionStore({}/**- * Persist a patch into the type-level index. Top-level fields (schemaVersion,- * type, config) are shallow-merged; `updatedAt` is restamped automatically.- * Serialized through `queueTypeIndexWrite` so concurrent callers can't- * stomp each other's config-slot edits.+ * Persist a patch into the type-level index. `schemaVersion` / `type` are+ * replaced only when the patch supplies a valid value (else preserved);+ * `config` is SHALLOW-merged one level deep (`{ ...current, ...patch.config }`,+ * so a patched slot like `runs` replaces the whole array — see the header+ * `config`-slot convention); `updatedAt` is restamped automatically.+ * Serialized through `queueTypeIndexWrite` so concurrent callers can't stomp+ * each other's config-slot edits. For a read-modify-write that must read the+ * current slot value before writing (e.g. appending to `runs`), do the load+ * and the write together inside one `queueTypeIndexWrite(fn)` rather than+ * leaning on this patch form.+ *+ * @param {{ schemaVersion?: number, type?: string, config?: TypeIndexConfig }} [patch]*/function saveTypeIndex(patch = {}) {return queueTypeIndexWrite(async () => {diff --git a/server/lib/collectionStore.test.js b/server/lib/collectionStore.test.jsindex d3d25ac835..4f879324dd 100644--- a/server/lib/collectionStore.test.js+++ b/server/lib/collectionStore.test.js@@ -4,6 +4,7 @@ import { readFile } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';import { createCollectionStore, verifyCollectionVersions } from './collectionStore.js';+import { atomicWrite } from './fileUtils.js';// Defer one tick so we can interleave per-id queue assertions.const tick = () => new Promise((r) => setImmediate(r));@@ -82,6 +83,59 @@ describe('loadTypeIndex / saveTypeIndex', () => {});});+// Pins the documented `config`-slot convention (see the collectionStore header+// + the TypeIndexConfig typedef). These guarantees are load-bearing for the+// universeBuilder `config.runs` history-log pattern.+describe('config slot convention', () => {+ it('shallow-merge REPLACES an array slot (does not concat) — runs RMW must write the full array', async () => {+ const store = createCollectionStore({ dir, type: 'universes', schemaVersion: 1 });+ await store.saveTypeIndex({ config: { runs: [{ id: 'r1' }] } });+ // A naive patch with only the new entry replaces the whole array — proving+ // a consumer MUST load → append → write the full array (recordRun pattern).+ await store.saveTypeIndex({ config: { runs: [{ id: 'r2' }] } });+ const idx = await store.loadTypeIndex();+ expect(idx.config.runs).toEqual([{ id: 'r2' }]);+ });++ it('correct append pattern: load the slot, mutate a copy, write the full replacement (fenced)', async () => {+ const store = createCollectionStore({ dir, type: 'universes', schemaVersion: 1 });+ // Mirrors universeBuilder.recordRun: the load→append→write runs inside a+ // single queueTypeIndexWrite fence (writing the index directly, NOT via the+ // re-entrant saveTypeIndex) so concurrent appends don't clobber each other.+ const append = (run) => store.queueTypeIndexWrite(async () => {+ const current = await store.loadTypeIndex();+ const runs = Array.isArray(current.config?.runs) ? [...current.config.runs] : [];+ runs.push(run);+ await atomicWrite(store.typeIndexPath(), {+ schemaVersion: current.schemaVersion,+ type: current.type,+ config: { ...(current.config || {}), runs },+ updatedAt: new Date().toISOString(),+ });+ });+ await Promise.all([append({ id: 'r1' }), append({ id: 'r2' }), append({ id: 'r3' })]);+ const idx = await store.loadTypeIndex();+ expect(idx.config.runs.map((r) => r.id).sort()).toEqual(['r1', 'r2', 'r3']);+ });++ it('defaultTypeIndexConfig seeds the slot once but is NOT re-applied on later writes', async () => {+ const store = createCollectionStore({+ dir, type: 'universes', schemaVersion: 1,+ defaultTypeIndexConfig: { runs: [], featureFlags: { beta: false } },+ });+ // First write only touches runs; the seeded featureFlags is NOT re-merged+ // because saveTypeIndex shallow-merges over the CURRENT on-disk config.+ await store.saveTypeIndex({ config: { runs: [{ id: 'r1' }] } });+ const seeded = await store.loadTypeIndex();+ expect(seeded.config).toEqual({ runs: [{ id: 'r1' }], featureFlags: { beta: false } });+ // Overwriting featureFlags replaces it wholesale (one-level shallow merge).+ await store.saveTypeIndex({ config: { featureFlags: { beta: true } } });+ const idx = await store.loadTypeIndex();+ expect(idx.config.featureFlags).toEqual({ beta: true });+ expect(idx.config.runs).toEqual([{ id: 'r1' }]);+ });+});+describe('saveOne / loadOne / deleteOne', () => {it('persists a record under {dir}/{id}/index.json', async () => {const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });