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
fix(sharing): watch records/, dedupe backlog scans, emit on issue create
[._.]/ Adam Eivyfe66fd1bd572
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6f5439993b..c6c50d504e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -41,6 +41,41 @@## Fixed+- **Series shares now deliver issues, scripts, and renders to collaborators.**+ When the manifest reached a peer ahead of its 30+ issue record JSONs+ (Google Drive sync is order-non-deterministic), the importer silently+ dropped the missing records and advanced the cursor, orphaning the issues+ forever — the series and universe appeared on the collaborator but the+ issues panel was empty. Three fixes: `readReferencedRecords` now returns+ a `missing` list and `processManifest` defers cursoring whenever any+ record file (or asset blob) is still unsynced, mirroring the existing+ pending-assets path. The chokidar watcher now watches `records/` in+ addition to `manifests/` and `assets/`, so a late-arriving issue JSON+ re-fires `processBacklog`. `createIssue` now emits `recordUpdated`+ alongside every other issue mutation, so a freshly-created issue+ propagates to subscribers without waiting for a follow-up stage edit.+ `queueBacklog` collapses bursts of records/ events into at most one+ in-flight scan + one queued follow-up so a 32-file sync doesn't trigger+ 32 sequential rescans. Touches:+ `server/services/sharing/importer.js`,+ `server/services/sharing/watcher.js`,+ `server/services/pipeline/issues.js`,+ `server/services/sharing/integration.test.js`.++- **Codex TUI agents no longer hang waiting for tool approvals.** Spawning+ a sub-agent through the Codex TUI provider invoked `codex` without+ `--ask-for-approval never`, so every tool call paused waiting for a human+ at the keyboard — unattended runs (`agent-46d2e8ff` was the canary) sat+ idle until the idle-timeout fired. `buildTuiSpawnConfig` now injects+ `--ask-for-approval never` whenever the command is `codex` and the+ provider's saved args don't already pin the flag, so existing installs+ pick it up without a migration. The `codex-tui` entries in both sample+ provider JSONs also include the flag so new installs match. Touches:+ `server/services/agentTuiSpawning.js`,+ `server/services/agentTuiSpawning.test.js`,+ `data.sample/providers.json`,+ `server/lib/aiToolkit/defaults/providers.sample.json`.+- **Sharing inbox no longer prompts you to import your own shares.** When thelocal PortOS published a manifest into a share bucket (e.g. a Google Drivefolder it also reads from), the importer treated the round-tripped file asdiff --git a/data.sample/providers.json b/data.sample/providers.jsonindex 0be19c6fbe..2e4f94076d 100644--- a/data.sample/providers.json+++ b/data.sample/providers.json@@ -71,7 +71,7 @@"name": "Codex TUI","type": "tui","command": "codex",- "args": [],+ "args": ["--ask-for-approval", "never"],"models": ["codex-configured-default"],"defaultModel": "codex-configured-default","lightModel": "codex-configured-default",diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 86ad168396..fb16b4d35a 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -59,7 +59,7 @@"name": "Codex TUI","type": "tui","command": "codex",- "args": [],+ "args": ["--ask-for-approval", "never"],"models": ["codex-configured-default"],"defaultModel": "codex-configured-default","lightModel": "codex-configured-default",diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 56f2f1b5f1..a0b3d7b56a 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -116,9 +116,20 @@ function inferTuiCommand(id) {return 'claude';}+// Without `--ask-for-approval never`, codex TUI blocks on the user to approve+// every tool call — there's no human at the keyboard for sub-agent runs, so+// the session hangs until idle-timeout. Injected here (vs. requiring it in+// every saved provider config) so existing installs upgrade automatically.+function applyCommandDefaults(command, args) {+ if (command === 'codex' && !args.includes('--ask-for-approval')) {+ return ['--ask-for-approval', 'never', ...args];+ }+ return args;+}+export function buildTuiSpawnConfig(provider, model) {const command = provider?.command || inferTuiCommand(provider?.id);- const baseArgs = [...(provider?.args || [])];+ const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);const args = appendModelArgs(baseArgs, model);return {diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex d90d0b3521..928d82ee09 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -100,8 +100,38 @@ describe('agent TUI spawning', () => {}, 'codex-configured-default');expect(config.command).toBe('codex');- expect(config.args).toEqual([]);- expect(config.commandLine).toBe('codex');+ expect(config.args).toEqual(['--ask-for-approval', 'never']);+ expect(config.commandLine).toBe('codex --ask-for-approval never');+ });++ it('injects --ask-for-approval never for codex TUI when not already set', () => {+ const config = buildTuiSpawnConfig({+ id: 'codex-tui',+ command: 'codex',+ type: 'tui',+ args: ['--cd', '/tmp/work']+ }, null);+ expect(config.args).toEqual(['--ask-for-approval', 'never', '--cd', '/tmp/work']);+ });++ it('does not duplicate --ask-for-approval when the provider config already pins it', () => {+ const config = buildTuiSpawnConfig({+ id: 'codex-tui',+ command: 'codex',+ type: 'tui',+ args: ['--ask-for-approval', 'on-failure']+ }, null);+ expect(config.args).toEqual(['--ask-for-approval', 'on-failure']);+ });++ it('does not inject --ask-for-approval for non-codex TUI commands', () => {+ const config = buildTuiSpawnConfig({+ id: 'claude-code-tui',+ command: 'claude',+ type: 'tui',+ args: ['--dangerously-skip-permissions']+ }, null);+ expect(config.args).toEqual(['--dangerously-skip-permissions']);});it('quotes TUI arguments and carries idle timing config', () => {@@ -143,8 +173,8 @@ describe('agent TUI spawning', () => {it('omits the --model flag when model is null/empty', () => {const config = buildTuiSpawnConfig({ id: 'codex-tui', command: 'codex', type: 'tui', args: [] }, null);- expect(config.args).toEqual([]);- expect(config.commandLine).toBe('codex');+ expect(config.args).toEqual(['--ask-for-approval', 'never']);+ expect(config.commandLine).toBe('codex --ask-for-approval never');});});diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 1a1106c9f7..7632b9f8cc 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -433,6 +433,8 @@ export function createIssue(input = {}) {if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);state.issues.push(next);await writeState(state);+ // New issue = series-level change for any active share subscription.+ emitRecordUpdated('series', next.seriesId);return next;}); // end queueIssueWrite}diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 4cf2545b41..361c41eeb6 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -189,7 +189,9 @@ async function mergeMediaJobRecords(bucketPath, recordIds) {* Read the records referenced by a manifest. `missing` lists recordIds whose* JSON file hasn't synced into the bucket yet — the caller defers* markProcessed until that list is empty, otherwise a manifest delivered- * ahead of its records would be silently dropped forever.+ * ahead of its records would be silently dropped forever. Bible-prefixed ids+ * (chr-/set-/obj-) are sub-records of universes and never standalone, so they+ * are skipped without being tracked as missing.*/async function readReferencedRecords(bucketPath, manifest) {const records = { series: [], issues: [], universes: [], media: [] };@@ -425,9 +427,10 @@ export async function processManifest(bucketId, manifestFilename) {const { records, missing: missingRecords } = await readReferencedRecords(bucket.path, manifest);// Always copy assets + media-job records ahead of the merge so canon and- // pipeline records that reference them point at present files. Asset sync can- // lag behind manifest sync in Drive/Dropbox/etc.; copy what exists now and- // leave the manifest un-cursored until the rest arrives.+ // pipeline records that reference them point at present files. Asset and+ // record-bundle sync can both lag behind manifest sync in Drive/Dropbox/etc.;+ // apply what exists now and leave the manifest un-cursored until the rest+ // arrives (the watcher re-fires backlog on records/ + assets/ changes).const assetCopy = await copyAssetsLocally(bucket.path, manifestAssetRefs(manifest));const availableAssetKeys = new Set(assetCopy.available.map((ref) => `${ref.kind}:${ref.ref}`));await mergeMediaJobRecords(bucket.path, manifest.recordIds);diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 662c35dc45..039dd20f4d 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -358,6 +358,73 @@ describe('sharing round-trip', () => {expect(hasBeenProcessed(cursor, exp.filename, exp.manifestId)).toBe(true);});+ it('keeps series manifests retryable while issue record files are still syncing', async () => {+ const bucket = await buckets.createBucket({ name: 'SlowIssueSync', path: tempBucket, mode: 'auto-merge' });+ const { readCursor, hasBeenProcessed } = await import('./manifest.js');++ const s = await series.createSeries({ name: 'Drifts a Bit Late' });+ const issA = await issues.createIssue({ seriesId: s.id, title: 'Arrives on Time' });+ const issB = await issues.createIssue({ seriesId: s.id, title: 'Arrives Later' });++ const exp = await exporter.exportSeries(s.id, bucket.id);+ expect(exp.recordCount).toBe(3); // series + 2 issues++ // Simulate Drive having synced the manifest + series + issA but not yet issB.+ const fs = await import('fs');+ const issBPath = join(tempBucket, 'records', 'issues', `${issB.id}.json`);+ expect(fs.existsSync(issBPath)).toBe(true);+ fs.rmSync(issBPath, { force: true });++ // Drop local copies so the importer has to insert from the bucket.+ await issues.deleteIssue(issA.id);+ await issues.deleteIssue(issB.id);+ await series.deleteSeries(s.id);++ simulateRemoteSender(tempBucket, exp.filename);+ const first = await importer.processManifest(bucket.id, exp.filename);+ expect(first.pending).toBe(true);+ expect(first.outcome.pendingRecords).toEqual([issB.id]);+ expect(first.outcome.pendingAssets).toBeUndefined();++ // The records that DID arrive should be applied — the late one stays absent.+ const restoredA = await issues.getIssue(issA.id);+ expect(restoredA.title).toBe('Arrives on Time');+ await expect(issues.getIssue(issB.id)).rejects.toMatchObject({ code: 'PIPELINE_ISSUE_NOT_FOUND' });++ let cursor = await readCursor(bucket.id);+ expect(hasBeenProcessed(cursor, exp.filename, exp.manifestId)).toBe(false);++ // Late-arriving record file → backlog retry completes the import.+ fs.writeFileSync(issBPath, JSON.stringify({+ id: issB.id, seriesId: s.id, title: 'Arrives Later', number: 2,+ status: 'draft', stages: {},+ createdAt: issB.createdAt, updatedAt: issB.updatedAt,+ }));++ const retry = await importer.processBacklog(bucket.id);+ expect(retry.processed).toBe(1);++ const restoredB = await issues.getIssue(issB.id);+ expect(restoredB.title).toBe('Arrives Later');+ cursor = await readCursor(bucket.id);+ expect(hasBeenProcessed(cursor, exp.filename, exp.manifestId)).toBe(true);+ });++ it('createIssue emits recordUpdated so series subscriptions re-export', async () => {+ const { recordEvents } = await import('./recordEvents.js');+ const s = await series.createSeries({ name: 'Emits On Create' });+ const events = [];+ const onUpdated = (p) => events.push(p);+ recordEvents.on('updated', onUpdated);+ try {+ const iss = await issues.createIssue({ seriesId: s.id, title: 'First Issue' });+ expect(events).toContainEqual({ recordKind: 'series', recordId: s.id });+ expect(iss.seriesId).toBe(s.id);+ } finally {+ recordEvents.off('updated', onUpdated);+ }+ });+it('subscription round-trip: subscribe → mutate → re-export onto same filename → unsubscribe → unshared event', async () => {const { subscribe, unsubscribe, subscriptionFilename, __resetForTests } = await import('./subscriptions.js');const { sharingEvents } = await import('./importer.js');diff --git a/server/services/sharing/watcher.js b/server/services/sharing/watcher.jsindex cf3ca97e43..cf2255efee 100644--- a/server/services/sharing/watcher.js+++ b/server/services/sharing/watcher.js@@ -20,21 +20,35 @@ import { processManifest, processBacklog, handleUnshare, sharingEvents } from '.import { getBucket, listBuckets, ensureBucketLayout } from './buckets.js';const watchers = new Map(); // bucketId → chokidar instance-const backlogQueues = new Map(); // bucketId → promise chain+const backlogQueues = new Map(); // bucketId → { running: Promise, queued: Promise|null }+/**+ * Coalesce backlog-scan requests per bucket. A flood of records/ or assets/+ * events from cloud sync (e.g. 32 issue JSONs landing in quick succession)+ * should collapse to at most one in-flight scan + one queued follow-up, not+ * N sequential rescans. While a scan is running, any subsequent request+ * shares the same queued follow-up so all events get exactly one observation.+ */function queueBacklog(bucketId) {- const previous = backlogQueues.get(bucketId) || Promise.resolve();- const next = previous- .catch(() => {})- .then(() => processBacklog(bucketId))- .catch((err) => {- console.error(`❌ sharing.watcher: backlog process failed bucket=${bucketId}: ${err?.message || err}`);- })- .finally(() => {- if (backlogQueues.get(bucketId) === next) backlogQueues.delete(bucketId);+ const slot = backlogQueues.get(bucketId);+ if (slot?.queued) return slot.queued;+ const runScan = () => processBacklog(bucketId).catch((err) => {+ console.error(`❌ sharing.watcher: backlog process failed bucket=${bucketId}: ${err?.message || err}`);+ });+ if (!slot) {+ const running = runScan().finally(() => {+ const live = backlogQueues.get(bucketId);+ if (live && live.running === running) backlogQueues.delete(bucketId);});- backlogQueues.set(bucketId, next);- return next;+ backlogQueues.set(bucketId, { running, queued: null });+ return running;+ }+ const queued = slot.running.then(runScan).finally(() => {+ const live = backlogQueues.get(bucketId);+ if (live && live.queued === queued) backlogQueues.delete(bucketId);+ });+ slot.queued = queued;+ return queued;}export async function attachWatcher(bucketId) {@@ -46,21 +60,27 @@ export async function attachWatcher(bucketId) {await ensureBucketLayout(bucket);const manifestsDir = join(bucket.path, 'manifests');const assetsDir = join(bucket.path, 'assets');- const w = watch([manifestsDir, assetsDir], {+ // Records sync at the same lag as assets — Drive may deliver the small+ // manifest before the larger record JSONs. Watch the dir so a late-arriving+ // record file re-triggers backlog and the importer can retry the manifest.+ const recordsDir = join(bucket.path, 'records');+ const w = watch([manifestsDir, assetsDir, recordsDir], {persistent: true,ignoreInitial: true,awaitWriteFinish: { stabilityThreshold: 300, pollInterval: 100 },});+ // A path under assets/ or records/ is bundle-side sync we should retry on,+ // not a manifest to process. Manifests live in manifests/ (always *.json).+ const isBundleSync = (p) => p.includes(`${assetsDir}/`) || p.includes(`${recordsDir}/`);+// try/catch around async event handlers — see CLAUDE.md "PTY/child-process// /setTimeout/setInterval callbacks" rule (chokidar events fire outside the// request lifecycle, no Express middleware to bubble the throw to).w.on('add', async (path) => {+ if (isBundleSync(path)) { await queueBacklog(bucketId); return; }const file = basename(path);- if (!file.endsWith('.json')) {- if (path.includes(`${assetsDir}/`)) await queueBacklog(bucketId);- return;- }+ if (!file.endsWith('.json')) return;try {await processManifest(bucketId, file);} catch (err) {@@ -68,14 +88,12 @@ export async function attachWatcher(bucketId) {}});w.on('change', async (path) => {+ if (isBundleSync(path)) { await queueBacklog(bucketId); return; }// A manifest *changing* after first write is unusual (atomicWrite// produces a stable file), but it can happen if a peer's sync app// does a delete-then-write. Re-process — cursor will dedup.const file = basename(path);- if (!file.endsWith('.json')) {- if (path.includes(`${assetsDir}/`)) await queueBacklog(bucketId);- return;- }+ if (!file.endsWith('.json')) return;try {await processManifest(bucketId, file);} catch (err) {@@ -83,6 +101,9 @@ export async function attachWatcher(bucketId) {}});w.on('unlink', async (path) => {+ // Only manifest deletions are unshare signals. Record/asset unlinks are+ // expected during cloud-sync churn and not actionable here.+ if (!path.includes(`${manifestsDir}/`)) return;const file = basename(path);if (!file.endsWith('.json')) return;try {