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
test: prevent unclassified JSON fallback write-back stores (#6977)
[._.]/ Adam Eivycc4cc19283bc
diff --git a/server/jsonWritebackConventions.test.js b/server/jsonWritebackConventions.test.jsnew file mode 100644index 0000000000..0f54354aaa--- /dev/null+++ b/server/jsonWritebackConventions.test.js@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest';+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { join } from 'node:path';+import { scanJsonWriteback, reconcileJsonWriteback } from './test/jsonWritebackScan.js';+import { JSON_WRITEBACK_EXCEPTIONS } from './test/jsonWritebackExceptions.js';++function sourceFiles(directory, prefix = '') {+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {+ const relative = `${prefix}${entry.name}`;+ if (entry.isDirectory()) return sourceFiles(join(directory, entry.name), `${relative}/`);+ return entry.name.endsWith('.js') && !entry.name.endsWith('.test.js') ? [relative] : [];+ });+}++// Regression: a newly introduced fallback cannot silently become a write-back+// base. Existing exceptions must disappear when their source pair disappears.+it('classifies every same-path non-strict service read/write pair with no stale exceptions', () => {+ const root = fileURLToPath(new URL('./services/', import.meta.url));+ const candidates = sourceFiles(root).flatMap(file =>+ scanJsonWriteback(readFileSync(join(root, file), 'utf8')).candidates.map(path => `${file} :: ${path}`));+ const result = reconcileJsonWriteback(candidates, JSON_WRITEBACK_EXCEPTIONS);+ expect(result, 'Use strict reads or document the actual lifecycle in test/jsonWritebackExceptions.js; remove stale entries.').toEqual({ unclassified: [], stale: [] });+ expect(new Set(JSON_WRITEBACK_EXCEPTIONS.map(entry => entry.key)).size).toBe(JSON_WRITEBACK_EXCEPTIONS.length);+ expect(JSON_WRITEBACK_EXCEPTIONS.every(entry => entry.reason.trim().length > 0)).toBe(true);+});++describe('syntax scanner regression contracts', () => {+ it('finds new pairs with nested arguments, comments and quote/whitespace differences', () => {+ const source = `+ import { readJSONFile as read, atomicWrite as write } from './fileUtils.js';+ const value = await read(join(root, nameFor(id, { suffix: '.json' })),+ defaults({ nested: [1, 2] }), { logError: false });+ await write(join( root, nameFor( id, { suffix: ".json" } )), value);+ // readJSONFile(FAKE, {}); atomicWrite(FAKE, {});+ const text = 'readJSONFile(FAKE, {}); atomicWrite(FAKE, {})';+ readJSONFile(OTHER, {}); atomicWrite(DIFFERENT, {});+ `;+ const { candidates } = scanJsonWriteback(source);+ expect(candidates).toEqual(['join ( root , nameFor ( id , { suffix : ".json" } ) )']);+ expect(scanJsonWriteback(`// shifted source\n\n${source}`).candidates).toEqual(candidates);+ expect(reconcileJsonWriteback(candidates, [])).toEqual({ unclassified: candidates, stale: [] });+ expect(reconcileJsonWriteback([], [{ key: candidates[0], reason: 'Removed cache' }])).toEqual({ unclassified: [], stale: candidates });+ });++ it('only exempts strict reads whose actual options prove strictness', () => {+ const { candidates, strict } = scanJsonWriteback(`+ readJSONFile(A, { strict: true }); atomicWrite(A, {});+ readJSONFile(B, {}, { strict: true }); atomicWrite(B, {});+ readJSONFileStrict(C, {}); atomicWrite(C, {});+ readJSONFile(D, {}, { strict: true, ...options }); atomicWrite(D, {});+ readJSONFile(E, {}, { ...options, strict: true }); atomicWrite(E, {});+ readJSONFile(F, {}, { strict: true, strict: false }); atomicWrite(F, {});+ readJSONFile(G, {}, { strict }); atomicWrite(G, {});+ readJSONFile(H, {}, { strict: true, [key]: false }); atomicWrite(H, {});+ readJSONFile(I, {}, { strict: false, 'strict': true }); atomicWrite(I, {});+ readJSONFile(J, {}, { nested: { strict: true } }); atomicWrite(J, {});+ readJSONFile(K, {}, { strict: true }); readJSONFile(K, {}); atomicWrite(K, {});+ `);+ expect(candidates).toEqual(['A', 'D', 'F', 'G', 'H', 'J', 'K']);+ expect(strict).toEqual(['B', 'C', 'E', 'I', 'K']);+ });++ it('keeps literal contents and dynamic template expressions distinct and fails on invalid syntax', () => {+ expect(scanJsonWriteback('readJSONFile("a b", {}); atomicWrite("ab", {});').candidates).toEqual([]);+ expect(scanJsonWriteback('readJSONFile(`row-${id}`, {}); atomicWrite(`row-${other}`, {});').candidates).toEqual([]);+ expect(() => scanJsonWriteback('readJSONFile(')).toThrow();+ });+});diff --git a/server/test/JSON_WRITEBACK.md b/server/test/JSON_WRITEBACK.mdnew file mode 100644index 0000000000..db952b85a0--- /dev/null+++ b/server/test/JSON_WRITEBACK.md@@ -0,0 +1,161 @@+# JSON write-back prevention guard++Run from `server/`: `node_modules/.bin/vitest run jsonWritebackConventions.test.js`.+The guard parses service source only; it never imports services, reads runtime+records, connects to a database, or requires git history to run.++A direct `readJSONFile` call and `atomicWrite` call with the same normalized+first argument in the same service module require either statically strict reads+or an explicit lifecycle exception in `jsonWritebackExceptions.js`. New pairs+fail as unclassified; removed/strict-converted pairs fail as stale exceptions.+Every exception records why a fallback cannot overwrite durable records. Review+that reason against the caller whenever the lifecycle changes. This is a review+inventory guard, not a proof that all exceptional control flow remains safe.++## Syntax and limits++Babel parses real call expressions, including nested arguments, options and+calls inside template interpolations. Comments and strings describing calls do+not count. Path tokens ignore formatting and comments, normalize string quotes,+and preserve literal contents. Keys contain no positions. Literal `strict: true`+in the third argument and `readJSONFileStrict` are strict. A subsequent spread,+computed key, or false/unknown strict property invalidates that proof; an earlier+spread followed by literal strict:true is safe. Mixed strict/non-strict reads of+one path still require classification. Dynamic strict options require manual+caller review, including the strict defaults in Ask and POST run storage.++This is deliberately same-expression, same-module syntax matching, not+whole-program dataflow. It recognizes direct names and named import aliases;+it does not resolve scopes/shadowing, namespace calls, wrapper functions,+aliased path variables, equivalent path-building expressions, or different+parameter names across functions. Same-name locals in unrelated functions can+be false positives. A changed expression can therefore leave this scanner's+coverage; the stale-entry failure calls attention to existing exceptions that+move. There is no blanket module exemption and no assertion that 79 modules+represent every JSON lifecycle in PortOS.++The sibling audits explicitly checked paths outside exact-expression matching:++- Alcohol/Nicotine daily logs go through `loadDailyLog` and `readLocalDailyLog`;+ all mutation callers pass strict:true. MortalLoom response summaries are+ read-only, and its imported destination aliases are preflighted strictly.+- Ask's `pathFor(conversationId)` mutation and `pathFor(id)` listing share a+ strict-by-default loader; only aggregation opts out and skips null records.+- Daily review history uses `reviewDate`, while confirmation uses `date` and a+ strict loader. These expressions deliberately do not compare equal.+- Sprite generation, candidate listing, approval, runtime pointers and run+ records use different local aliases. The media audit made mutable provenance,+ geometry and approval reads strict; source/projection-only fallbacks stay+ documented beside their calls. Candidate sidecars use new generated names.+- Sharing import/export reads include transport input and local merge-target+ aliases; the sync audit hardened the destination reads and annotation sources.+- MeatSpace's goals birth-date mirror gained a same-expression pair during the+ personal audit. It is an additional registry entry beyond the original 94:+ migration skips unreadable input, and mirror mutation preflights strictly.++## Baseline reconciliation++Historical audit at `d7e2fb47d`: **79 modules, 94 path pairs**. All seven sibling+PR classifications were reconciled with their merged source. **73 original+pairs now read strictly; 21 remain explicitly classified**, plus the additional+MeatSpace goals pair above (22 current exceptions). The registry gives the+concrete cache, authoritative-rebuild, or no-unsafe-write-back reason for each.+The table is a historical audit record, not a generated manifest or a fixed+allowlist of modules. Future service pairs are discovered directly at test time.++| Service module | Normalized path expression | Disposition after audits | Classification PR |+| --- | --- | --- | --- |+| agentRunReconciler.js | <code>path</code> | Reviewed exception (see registry) | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| agentRunTracking.js | <code>metaPath</code> | Reviewed exception (see registry) | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| albums/file.js | <code>ALBUMS_FILE</code> | Strict read | [#6984](https://github.com/atomantic/PortOS/pull/6984) |+| appleHealthIngest.js | <code>filePath</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| artists/file.js | <code>ARTISTS_FILE</code> | Strict read | [#6984](https://github.com/atomantic/PortOS/pull/6984) |+| askConversations.js | <code>pathFor ( id )</code> | Reviewed exception (see registry) | [#6983](https://github.com/atomantic/PortOS/pull/6983) |+| authors/file.js | <code>AUTHORS_FILE</code> | Strict read | [#6984](https://github.com/atomantic/PortOS/pull/6984) |+| autobiography.js | <code>CONFIG_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| autobiography.js | <code>STORIES_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| autonomousJobs/store.js | <code>JOBS_FILE</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| backup.js | <code>STATE_PATH</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| backup.js | <code>manifestPath</code> | Reviewed exception (see registry) | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| bibleStore.js | <code>filePath ( workId )</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |+| brainJournal.js | <code>OBSIDIAN_LOCATIONS_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| brainParity.js | <code>REPORTS_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| calendarAccounts.js | <code>ACCOUNTS_FILE</code> | Strict read | [#6978](https://github.com/atomantic/PortOS/pull/6978) |+| character.js | <code>CHARACTER_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| claudeChangelog.js | <code>STATE_FILE</code> | Reviewed exception (see registry) | [#6978](https://github.com/atomantic/PortOS/pull/6978) |+| creative/creativeRunLedger.js | <code>file</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |+| dailyDriver.js | <code>FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| dailyReview.js | <code>join ( REVIEW_DIR , ` ${ date } .json ` )</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| dataSync.js | <code>CHARACTER_FILE</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| dataSync.js | <code>GOALS_FILE</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| dataSync.js | <code>filePath</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| datadog.js | <code>DATADOG_CONFIG_FILE</code> | Strict read | [#6978](https://github.com/atomantic/PortOS/pull/6978) |+| digital-twin-sync.js | <code>TASTE_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| digital-twin-sync.js | <code>path</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| featureAgents.js | <code>FA_FILE</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| github.js | <code>REPOS_FILE</code> | Strict read | [#6978](https://github.com/atomantic/PortOS/pull/6978) |+| goalCalendarScheduler.js | <code>GOALS_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| imageTo3d/sourceKeying.js | <code>preparedCacheMetadataPath ( targetPath )</code> | Reviewed exception (see registry) | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| insightsService.js | <code>NARRATIVE_FILE</code> | Reviewed exception (see registry) | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| insightsService.js | <code>THEMES_FILE</code> | Reviewed exception (see registry) | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| maintenanceRun.js | <code>runsFile ( )</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| meatspace.js | <code>CONFIG_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| meatspaceAlcohol.js | <code>CUSTOM_DRINKS_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| meatspaceCalendar.js | <code>ACTIVITIES_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| meatspaceCalendar.js | <code>EVENTS_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| meatspaceNicotine.js | <code>CUSTOM_PRODUCTS_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| meatspacePost.js | <code>CONFIG_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| meatspacePostMemory.js | <code>MEMORY_ITEMS_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| meatspacePostMorse.js | <code>MORSE_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| meatspacePostReview.js | <code>REVIEW_SCHEDULE_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| mediaAnnotations.js | <code>STATE_PATH</code> | Strict read | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| mediaSketches.js | <code>jsonPathFor ( key )</code> | Reviewed exception (see registry) | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| modelPersonality.js | <code>resultsFile ( )</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| mortalLoomStore.js | <code>goalsPath</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| mortalLoomStore.js | <code>localPath</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| obsidian.js | <code>VAULTS_FILE</code> | Strict read | [#6978](https://github.com/atomantic/PortOS/pull/6978) |+| peerUsage.js | <code>PEER_USAGE_FILE</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| pipeline/continuityBible.js | <code>ledgerPath ( seriesId )</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |+| pipeline/editorialScore.js | <code>ledgerPath ( seriesId )</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |+| pipeline/manuscriptComments.js | <code>reviewPath ( seriesId )</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |+| pipeline/reverseOutline.js | <code>outlinePath ( seriesId )</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |+| postRunStore.js | <code>SESSIONS_FILE</code> | Reviewed exception (see registry) | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| postRunStore.js | <code>TRAINING_FILE</code> | Reviewed exception (see registry) | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| productivity.js | <code>PRODUCTIVITY_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| projectFileStore.js | <code>file</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |+| providerQuotaShare.js | <code>PROVIDER_QUOTAS_FILE</code> | Reviewed exception (see registry) | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| rounds.js | <code>STATE_PATH</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| sharing/annotationsSync.js | <code>recordPath</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sharing/buckets.js | <code>REGISTRY_PATH ( )</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sharing/buckets.js | <code>bucketJsonPath</code> | Reviewed exception (see registry) | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sharing/exporter.js | <code>bucketBlobIndexPath ( bucketPath )</code> | Reviewed exception (see registry) | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sharing/importer.js | <code>inboxPath ( bucketId )</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sharing/importer.js | <code>persistedPath</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sharing/manifest.js | <code>cursorPath ( bucketId )</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sharing/manifest.js | <code>join ( bucketPath , "manifests" , filename )</code> | Reviewed exception (see registry) | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sharing/subscriptions.js | <code>STATE_PATH ( )</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| sprites/atlas.js | <code>join ( dir , RUNTIME_POINTER_REL )</code> | Strict read | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| sprites/localAnimationJobHook.js | <code>recordPath</code> | Strict read | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| sprites/publish.js | <code>join ( dir , RUNTIME_PUBLICATIONS_REL )</code> | Strict read | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| sprites/recordsFile.js | <code>RECORDS_FILE</code> | Strict read | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| sprites/reference.js | <code>join ( candidatesDir , ` ${ name . replace ( /\.png$/ , "" ) } .generation.json ` )</code> | Reviewed exception (see registry) | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| sprites/walk.js | <code>join ( spriteDir ( recordId ) , selectionRelPath ( recordId ) )</code> | Strict read | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| sprites/walk.js | <code>join ( spriteDir ( recordId ) , walkSetRelPath ( recordId ) )</code> | Strict read | [#6979](https://github.com/atomantic/PortOS/pull/6979) |+| syncOrchestrator.js | <code>CURSORS_FILE</code> | Strict read | [#6982](https://github.com/atomantic/PortOS/pull/6982) |+| taskScheduleStore.js | <code>SCHEDULE_FILE</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| taskTemplates.js | <code>TEMPLATES_FILE</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| tools.js | <code>toolPath ( id )</code> | Reviewed exception (see registry) | [#6978](https://github.com/atomantic/PortOS/pull/6978) |+| tracks/file.js | <code>TRACKS_FILE</code> | Strict read | [#6984](https://github.com/atomantic/PortOS/pull/6984) |+| twinEnrichment.js | <code>CHRONOTYPE_OBSERVED_FILE</code> | Reviewed exception (see registry) | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| twinEnrichment.js | <code>TASTE_OBSERVED_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| updateChecker.js | <code>UPDATE_FILE</code> | Strict read | [#6978](https://github.com/atomantic/PortOS/pull/6978) |+| usageBackfill.js | <code>correction . metadataPath</code> | Reviewed exception (see registry) | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| usageReconciler.js | <code>metadataPath</code> | Reviewed exception (see registry) | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| userActions.js | <code>eventsFile ( )</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| videoTimeline/local.js | <code>PROJECTS_FILE</code> | Strict read | [#6984](https://github.com/atomantic/PortOS/pull/6984) |+| voice/timers.js | <code>STORE_PATH</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| weeklyDigest.js | <code>path</code> | Reviewed exception (see registry) | [#6981](https://github.com/atomantic/PortOS/pull/6981) |+| workspaceContext.js | <code>CONTEXTS_FILE</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |+| writersRoom/store.js | <code>wrExercisesFile ( )</code> | Strict read | [#6984](https://github.com/atomantic/PortOS/pull/6984) |+| writersRoom/store.js | <code>wrFoldersFile ( )</code> | Strict read | [#6984](https://github.com/atomantic/PortOS/pull/6984) |+| youtubeIngest.js | <code>INDEX_FILE</code> | Strict read | [#6979](https://github.com/atomantic/PortOS/pull/6979) |diff --git a/server/test/jsonWritebackExceptions.js b/server/test/jsonWritebackExceptions.jsnew file mode 100644index 0000000000..d60d6bb79f--- /dev/null+++ b/server/test/jsonWritebackExceptions.js@@ -0,0 +1,92 @@+// Reviewed lifecycle exceptions from #6970–#6976. Keys are service-relative+// module + normalized first argument, never source positions. See JSON_WRITEBACK.md.+export const JSON_WRITEBACK_EXCEPTIONS = [+ {+ "key": "agentRunReconciler.js :: path",+ "reason": "No failed-read write-back: repair planning and its final re-read skip null run metadata."+ },+ {+ "key": "agentRunTracking.js :: metaPath",+ "reason": "No failed-read write-back: completion returns on null before metadata or output writes."+ },+ {+ "key": "askConversations.js :: pathFor ( id )",+ "reason": "No non-strict write-back: mutations use the strict default; only the listing sweep passes strict:false and skips unreadable members."+ },+ {+ "key": "backup.js :: manifestPath",+ "reason": "No write-back cycle: snapshot generation builds manifests from snapshot files; listing and restore only consume them."+ },+ {+ "key": "claudeChangelog.js :: STATE_FILE",+ "reason": "Cache-only: feed polling replaces the feed cache and its polling/seen cursors; there is no user-edit writer."+ },+ {+ "key": "imageTo3d/sourceKeying.js :: preparedCacheMetadataPath ( targetPath )",+ "reason": "Cache-only: source bytes and the explicit keying/framing request rebuild the prepared image metadata."+ },+ {+ "key": "insightsService.js :: NARRATIVE_FILE",+ "reason": "No non-strict write-back: display getter is tolerant; narrative refresh reads strictly before retaining prior text and timestamp."+ },+ {+ "key": "insightsService.js :: THEMES_FILE",+ "reason": "Authoritative rebuild: theme extraction replaces the cache from source evidence without retaining prior fields."+ },+ {+ "key": "meatspace.js :: GOALS_FILE",+ "reason": "No failed-read write-back: legacy birth-date migration skips unreadable input; birth-date mirror mutations preflight with a strict read."+ },+ {+ "key": "mediaSketches.js :: jsonPathFor ( key )",+ "reason": "No write-back cycle: the read projects the canvas; explicit save replaces the complete canvas supplied by the user."+ },+ {+ "key": "postRunStore.js :: SESSIONS_FILE",+ "reason": "No non-strict write-back: loadFileSessions defaults strict=true and all mutation callers retain that default; tolerant reads cannot feed persistence."+ },+ {+ "key": "postRunStore.js :: TRAINING_FILE",+ "reason": "No non-strict write-back: loadFileTraining defaults strict=true and all mutation callers retain that default; tolerant reads cannot feed persistence."+ },+ {+ "key": "providerQuotaShare.js :: PROVIDER_QUOTAS_FILE",+ "reason": "No non-strict write-back: readLocalQuotaCards only projects UI cards; the quota merge writer reads strictly."+ },+ {+ "key": "sharing/buckets.js :: bucketJsonPath",+ "reason": "No non-strict write-back: the UI identity projection is tolerant; registration checks identity strictly before publishing."+ },+ {+ "key": "sharing/exporter.js :: bucketBlobIndexPath ( bucketPath )",+ "reason": "Cache-only: source path, mtime and size map to hashes rebuilt from authoritative source bytes, without records or tombstones."+ },+ {+ "key": "sharing/manifest.js :: join ( bucketPath , \"manifests\" , filename )",+ "reason": "No write-back cycle: transport manifests are input-only; exports build new manifests from authoritative records."+ },+ {+ "key": "sprites/reference.js :: join ( candidatesDir , ` ${ name . replace ( /\\.png$/ , \"\" ) } .generation.json ` )",+ "reason": "No same-record write-back cycle: listing reads generation sidecars, generation writes new candidate names; approval reads provenance strictly."+ },+ {+ "key": "tools.js :: toolPath ( id )",+ "reason": "No failed-read write-back: updateTool returns on null; registerTool is an explicit complete replacement."+ },+ {+ "key": "twinEnrichment.js :: CHRONOTYPE_OBSERVED_FILE",+ "reason": "Authoritative rebuild: activity rows rebuild the complete chronotype histogram without retaining previous fields."+ },+ {+ "key": "usageBackfill.js :: correction . metadataPath",+ "reason": "No failed-read write-back: null metadata skips this correction, preserving bytes for repair and retry."+ },+ {+ "key": "usageReconciler.js :: metadataPath",+ "reason": "No failed-read write-back: null metadata skips marker persistence; accounting is owned by the usage ledger."+ },+ {+ "key": "weeklyDigest.js :: path",+ "reason": "Authoritative rebuild: generation replaces the target week from agent records; reads display or compare a previous week, not a write-back base."+ }+];diff --git a/server/test/jsonWritebackScan.js b/server/test/jsonWritebackScan.jsnew file mode 100644index 0000000000..97498a4140--- /dev/null+++ b/server/test/jsonWritebackScan.js@@ -0,0 +1,73 @@+import { parse } from '@babel/parser';++// Test-only syntax scan, never imports a service or reads runtime data.+// Matches direct helper names (including imported aliases), not arbitrary+// wrappers, namespace calls, variable aliases, or cross-module dataflow.+function walk(node, visit) {+ if (!node || typeof node !== 'object') return;+ if (Array.isArray(node)) { node.forEach(child => walk(child, visit)); return; }+ if (node.type) visit(node);+ for (const [key, child] of Object.entries(node)) {+ if (!['loc', 'extra', 'tokens', 'comments'].includes(key)) walk(child, visit);+ }+}++// Only a final, statically true strict property proves strictness. A later+// spread/computed key might override it, so unknown options remain candidates.+function isStrict(options) {+ if (options?.type !== 'ObjectExpression') return false;+ let strict = false;+ for (const property of options.properties) {+ if (property.type === 'SpreadElement' || property.computed) strict = false;+ else if ((property.key.name ?? property.key.value) === 'strict') {+ strict = property.value?.type === 'BooleanLiteral' && property.value.value;+ }+ }+ return strict;+}++function expressionKey(node, tokens, source) {+ return tokens.filter(token => token.start >= node.start && token.end <= node.end+ && token.type.label && token.type.label !== 'eof')+ .map(token => token.type.label === 'string' ? JSON.stringify(token.value)+ : source.slice(token.start, token.end)).join(' ');+}++/** Same-module first-argument syntax equality; no control-flow proof implied. */+export function scanJsonWriteback(source) {+ const ast = parse(source, { sourceType: 'module', tokens: true });+ const names = new Map(['readJSONFile', 'readJSONFileStrict', 'atomicWrite'].map(name => [name, name]));+ for (const statement of ast.program.body) {+ if (statement.type !== 'ImportDeclaration') continue;+ for (const specifier of statement.specifiers) {+ if (specifier.type === 'ImportSpecifier' && names.has(specifier.imported.name)) {+ names.set(specifier.local.name, specifier.imported.name);+ }+ }+ }+ const reads = new Set();+ const strictReads = new Set();+ const writes = new Set();+ walk(ast.program, node => {+ if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier' || !node.arguments[0]) return;+ const name = names.get(node.callee.name);+ if (!name) return;+ const key = expressionKey(node.arguments[0], ast.tokens, source);+ if (name === 'atomicWrite') writes.add(key);+ else if (name === 'readJSONFileStrict' || isStrict(node.arguments[2])) strictReads.add(key);+ else reads.add(key);+ });+ return {+ candidates: [...reads].filter(key => writes.has(key)).sort(),+ strict: [...strictReads].filter(key => writes.has(key)).sort(),+ };+}++export function reconcileJsonWriteback(candidates, exceptions) {+ const keys = new Set(candidates);+ const allowed = new Set(exceptions.map(entry => entry.key));+ return {+ unclassified: [...keys].filter(key => !allowed.has(key)).sort(),+ stale: [...allowed].filter(key => !keys.has(key)).sort(),+ };+}