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

feat([issue-2728]): add loadAllResult to surface corrupt records in collectionStore

[._.]/ Adam Eivye7db8ee22de1
diff --git a/server/lib/README.md b/server/lib/README.md
index f7af38c904..adb9b2978b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -122,7 +122,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. **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)`. |
+| `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` / `loadAllResult` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. `loadAll` silently drops corrupt records; `loadAllResult()` → `{ records, failedIds }` keeps the "which ids failed to load" signal so a caller can tell a partial set from a complete one. 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. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.js
index ebfd68c511..d5ba15405b 100644
--- a/server/lib/collectionStore.js
+++ b/server/lib/collectionStore.js
@@ -298,16 +298,44 @@ export function createCollectionStore({
return isPlainObject(parsed) ? parsed : null;
}
+ /**
+ * Load every record in parallel, keeping the "which ids failed to load" signal
+ * that `loadAll` throws away. A record `id` returned by `listIds()` whose
+ * `loadOne(id)` resolves to `null` means the on-disk file is
+ * missing/unreadable/unparseable or was rejected by `sanitizeRecord` — i.e. a
+ * corrupt record in an otherwise-readable collection. Callers that reason over
+ * the whole set (merge-rate stats, adoption reports) need to distinguish
+ * "N records" from "N-of-M records, K corrupt" so a silent undercount can't
+ * masquerade as complete truth — the same sentinel-vs-empty rule the CLAUDE.md
+ * conventions call out. Mirrors the `loadAll`/`listOutcomesResult` precedent.
+ *
+ * @returns {Promise<{ records: any[], failedIds: string[] }>}
+ * `records` — the successfully-loaded, sanitized records (nulls dropped).
+ * `failedIds` — the ids `listIds()` surfaced that failed to load (empty when
+ * every record loaded cleanly).
+ */
+ async function loadAllResult() {
+ const ids = await listIds();
+ const loaded = await Promise.all(ids.map((id) => loadOne(id)));
+ const records = [];
+ const failedIds = [];
+ ids.forEach((id, i) => {
+ if (loaded[i] != null) records.push(loaded[i]);
+ else failedIds.push(id);
+ });
+ return { records, failedIds };
+ }
+
/**
* Load every record in parallel. O(N) cost — acceptable while record counts
* are bounded (typical PortOS collections sit in the tens-to-hundreds), but
* callers iterating very large collections should prefer `listIds` +
- * targeted `loadOne` rather than slurping the whole set.
+ * targeted `loadOne` rather than slurping the whole set. Back-compat flattening
+ * wrapper over `loadAllResult` — silently drops corrupt records; reach for
+ * `loadAllResult` when the caller must be able to tell a partial set apart.
*/
async function loadAll() {
- const ids = await listIds();
- const records = await Promise.all(ids.map((id) => loadOne(id)));
- return records.filter((r) => r != null);
+ return (await loadAllResult()).records;
}
/**
@@ -434,6 +462,7 @@ export function createCollectionStore({
loadOne,
loadOneRaw,
loadAll,
+ loadAllResult,
saveOneNow,
saveOne,
deleteOneNow,
diff --git a/server/lib/collectionStore.test.js b/server/lib/collectionStore.test.js
index ac5f6b1d29..cd4601d9ad 100644
--- a/server/lib/collectionStore.test.js
+++ b/server/lib/collectionStore.test.js
@@ -296,6 +296,51 @@ describe('loadAll', () => {
});
});
+describe('loadAllResult (#2728)', () => {
+ it('returns every record with an empty failedIds when all load cleanly', async () => {
+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });
+ await store.saveOne('a', { id: 'a', n: 1 });
+ await store.saveOne('b', { id: 'b', n: 2 });
+ const { records, failedIds } = await store.loadAllResult();
+ expect(records.map((r) => r.id).sort()).toEqual(['a', 'b']);
+ expect(failedIds).toEqual([]);
+ });
+
+ it('surfaces a corrupt record in failedIds while still returning the readable ones', async () => {
+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });
+ await store.saveOne('good', { id: 'good' });
+ // A record dir whose index.json is unparseable — loadOne(id) → null.
+ mkdirSync(join(dir, 'broken'), { recursive: true });
+ writeFileSync(join(dir, 'broken', 'index.json'), '{not valid json');
+ const { records, failedIds } = await store.loadAllResult();
+ expect(records.map((r) => r.id)).toEqual(['good']);
+ expect(failedIds).toEqual(['broken']);
+ });
+
+ it('reports sanitizer-rejected records as failedIds (distinct from absent ones)', async () => {
+ const store = createCollectionStore({
+ dir, type: 'widgets', schemaVersion: 1,
+ sanitizeRecord: (r) => r.n > 1 ? r : null,
+ });
+ await store.saveOne('a', { id: 'a', n: 1 });
+ await store.saveOne('b', { id: 'b', n: 2 });
+ const { records, failedIds } = await store.loadAllResult();
+ expect(records.map((r) => r.id)).toEqual(['b']);
+ expect(failedIds).toEqual(['a']);
+ });
+
+ it('loadAll stays a back-compat flatten of loadAllResult.records', async () => {
+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });
+ await store.saveOne('good', { id: 'good' });
+ mkdirSync(join(dir, 'broken'), { recursive: true });
+ writeFileSync(join(dir, 'broken', 'index.json'), 'nope');
+ const all = await store.loadAll();
+ const { records } = await store.loadAllResult();
+ expect(all.map((r) => r.id)).toEqual(['good']);
+ expect(all).toEqual(records);
+ });
+});
+
describe('per-id write queue', () => {
it('two saves to the same id serialize in submission order', async () => {
const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });
diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.js
index 7bb23eebab..46ed27c868 100644
--- a/server/services/layeredIntelligenceOutcomes.js
+++ b/server/services/layeredIntelligenceOutcomes.js
@@ -266,23 +266,34 @@ export async function listOutcomes(args = {}, store = outcomesStore()) {
}
/**
- * `listOutcomes` with a discriminated read status (#2700):
- * `{ read: true, outcomes: [...] }` — the store was read; the list is the truth
- * (an empty one means nothing was ever filed).
- * `{ read: false, outcomes: [] }` — the store could NOT be read.
+ * `listOutcomes` with a discriminated read status (#2700, #2728):
+ * `{ read: true, outcomes: [...] }` — the store was read
+ * cleanly; the list is the truth (an empty one means nothing was ever filed).
+ * `{ read: false, outcomes: [] }` — the store could NOT
+ * be read at all (a total failure).
+ * `{ read: false, partial: true, outcomes: [...], failedIds: [...] }` — the store
+ * was read but ONE OR MORE records failed to load (corrupt/unparseable/
+ * sanitizer-rejected). The `outcomes` we DID load are returned for the
+ * best-effort flatten path, but `read` is false because the list is an
+ * untrustworthy undercount.
*
* The distinction is load-bearing for selfEval, which reports LI's merge rate to the
- * reasoner: a corrupt/unreadable store flattened to `[]` would tell the loop "you
- * have never filed a proposal" and invite it to re-file work it already filed, on
- * evidence that doesn't exist. Same sentinel rule as readLiTaskMetrics.
+ * reasoner: a corrupt/unreadable store flattened to `[]` (or silently short) would
+ * tell the loop "you have never filed a proposal" (or fewer than you did) and invite
+ * it to re-file work it already filed, on evidence that doesn't exist. Same sentinel
+ * rule as readLiTaskMetrics — a partial read is NOT a clean `read: true`, so a
+ * single corrupt record taints the whole read (we can't know which app's history it
+ * belonged to). Built on `collectionStore.loadAllResult` (#2728), which surfaces the
+ * `failedIds` `loadAll` throws away.
*/
export async function listOutcomesResult({ appId, now = Date.now() } = {}, store = outcomesStore()) {
// No appId is a caller bug, not a store failure: nothing was asked for, so the
// honest answer is an empty (successful) read, not "the store is broken".
if (!appId) return { read: true, outcomes: [] };
- const all = await store.loadAll().catch(() => null);
- if (!Array.isArray(all)) return { read: false, outcomes: [] };
- const mine = all.filter(r => r && r.appId === appId);
+ const result = await store.loadAllResult().catch(() => null);
+ if (!result || !Array.isArray(result.records)) return { read: false, outcomes: [] };
+ const failedIds = Array.isArray(result.failedIds) ? result.failedIds : [];
+ const mine = result.records.filter(r => r && r.appId === appId);
const kept = [];
for (const r of mine) {
if (r.outcome) {
@@ -294,7 +305,12 @@ export async function listOutcomesResult({ appId, now = Date.now() } = {}, store
}
kept.push(r);
}
- return { read: true, outcomes: kept.sort((a, b) => (Date.parse(b.filedAt) || 0) - (Date.parse(a.filedAt) || 0)) };
+ const outcomes = kept.sort((a, b) => (Date.parse(b.filedAt) || 0) - (Date.parse(a.filedAt) || 0));
+ // A corrupt record makes the surviving list an untrustworthy undercount — signal
+ // partial (read:false) so callers reasoning over the whole history don't treat a
+ // short list as "these are all the proposals ever filed".
+ if (failedIds.length > 0) return { read: false, partial: true, outcomes, failedIds };
+ return { read: true, outcomes };
}
/**
diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.js
index 45e59a76f7..a95b23f784 100644
--- a/server/services/layeredIntelligenceOutcomes.test.js
+++ b/server/services/layeredIntelligenceOutcomes.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtemp, rm } from 'fs/promises';
+import { mkdtemp, rm, mkdir, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { createCollectionStore } from '../lib/collectionStore.js';
@@ -465,15 +465,29 @@ describe('listOutcomesResult read sentinel (#2700)', () => {
});
it('reports read:false when the store read throws — never a fabricated empty history', async () => {
- const broken = { loadAll: () => Promise.reject(new Error('disk on fire')), deleteOne: () => Promise.resolve() };
+ const broken = { loadAllResult: () => Promise.reject(new Error('disk on fire')), deleteOne: () => Promise.resolve() };
expect(await listOutcomesResult({ appId: 'app-1' }, broken)).toEqual({ read: false, outcomes: [] });
});
it('reports read:false when the store returns a non-array', async () => {
- const broken = { loadAll: () => Promise.resolve(null), deleteOne: () => Promise.resolve() };
+ const broken = { loadAllResult: () => Promise.resolve(null), deleteOne: () => Promise.resolve() };
expect(await listOutcomesResult({ appId: 'app-1' }, broken)).toEqual({ read: false, outcomes: [] });
});
+ it('reports read:false + partial + failedIds when a record fails to load (#2728)', async () => {
+ // One clean record for this app plus a corrupt record dir the store can't parse —
+ // the surviving list is an undercount, so the read must NOT report as clean.
+ await recordFiledProposal({ appId: 'app-1', slug: 'add-metrics', tracker: 'github', issueRef: '#42' }, store);
+ await mkdir(join(dir, 'app-1--broken-slug'), { recursive: true });
+ await writeFile(join(dir, 'app-1--broken-slug', 'index.json'), '{not valid json');
+ const res = await listOutcomesResult({ appId: 'app-1' }, store);
+ expect(res.read).toBe(false);
+ expect(res.partial).toBe(true);
+ expect(res.failedIds).toEqual(['app-1--broken-slug']);
+ // The record that DID load is still returned for the best-effort flatten path.
+ expect(res.outcomes.map(r => r.slug)).toEqual(['add-metrics']);
+ });
+
it('treats a missing appId as an empty successful read, not a store failure', async () => {
expect(await listOutcomesResult({}, store)).toEqual({ read: true, outcomes: [] });
});
@@ -481,7 +495,7 @@ describe('listOutcomesResult read sentinel (#2700)', () => {
it('listOutcomes still flattens to the bare array for back-compat', async () => {
await recordFiledProposal({ appId: 'app-1', slug: 'add-metrics', tracker: 'github', issueRef: '#42' }, store);
expect(await listOutcomes({ appId: 'app-1' }, store)).toHaveLength(1);
- const broken = { loadAll: () => Promise.reject(new Error('nope')), deleteOne: () => Promise.resolve() };
+ const broken = { loadAllResult: () => Promise.reject(new Error('nope')), deleteOne: () => Promise.resolve() };
expect(await listOutcomes({ appId: 'app-1' }, broken)).toEqual([]);
});
});