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: fix stale symbol pointers in instruction docs and add pointer guard (#11852)
Adam Eivy9b2fc913fac1
diff --git a/AGENTS.md b/AGENTS.mdindex a6c6469943..88cc7058b9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -144,7 +144,7 @@ Read the applicable nested instruction files before editing those trees (each an- `server/AGENTS.md` — schema parity, write serialization, peer fan-out in tests, generated manifests, prompt-template migrations- `server/lib/aiToolkit/AGENTS.md` — the override-consistency contract for the vendored provider/runner/prompt toolkit (self-contained: no imports out to other PortOS modules). Read it before editing the runner or provider config.-**Nested files reach API-provider agents too — but the walk is bounded.** `getAgentInstructionsContext()` in `server/services/agentPromptBuilder.js` splices `~/.claude/CLAUDE.md`, the workspace-root file, then every nested one (`AGENTS.md` preferred, one entry per directory, bridge `CLAUDE.md`s skipped) into the prompts PortOS builds for its API-provider agents. The walk is capped at depth 5 / 10 files and skips dot-dirs, `node_modules/`, `data/`, build output, and any subdirectory with its own `.git`. Consequences: **a rule that must reach every agent has to sit inside that budget** (raise the cap in the same change if the repo exceeds 10 nested files), and **the root file is the only guaranteed-first slot** — a rule guarding data loss, a destructive action, privacy, or spend belongs here when it must outrank a subtree convention.+**Nested files reach API-provider agents too — but the walk is bounded.** `getAgentInstructionsContext()` in `server/services/promptSections/instructions.js` splices `~/.claude/CLAUDE.md`, the workspace-root file, then every nested one (`AGENTS.md` preferred, one entry per directory, bridge `CLAUDE.md`s skipped) into the prompts PortOS builds for its API-provider agents. The walk is capped at depth 5 / 10 files and skips dot-dirs, `node_modules/`, `data/`, build output, and any subdirectory with its own `.git`. Consequences: **a rule that must reach every agent has to sit inside that budget** (raise the cap in the same change if the repo exceeds 10 nested files), and **the root file is the only guaranteed-first slot** — a rule guarding data loss, a destructive action, privacy, or spend belongs here when it must outrank a subtree convention.### Command Palette & Voice Nav — shared backbonediff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsxindex c4143b4e25..8cb1829712 100644--- a/client/src/components/pipeline/stages/AudioStage.jsx+++ b/client/src/components/pipeline/stages/AudioStage.jsx@@ -148,7 +148,7 @@ export default function AudioStage({ issue, onStageUpdate }) {// second clobber the first. The tail awaits the prior save, then rebuilds the// patch from the FRESHEST cues (`latestCuesRef`, updated every render from the// lifted issue) so each edit merges against the latest persisted list.- // Mirrors the server-side `issueWriteTail` "collapse to one tail per shared+ // Mirrors the server-side `queueSeriesIssuesWrite` "collapse to one tail per shared// file" rule. `savingCueIdxs` is reactive state (not a ref) so the per-row// Render gate updates live and recovers if a save fails.const cueSaveTailRef = useRef(Promise.resolve());diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex f95878adf1..7d9f700dcf 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -262,7 +262,7 @@ grep -i "what you want to do" client/src/lib/README.md| `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. || `estimationTolerance.js` | `estimationToleranceText(tolerancePct)` → the one line an estimation drill shows to say how precise to be, e.g. "Within 10% counts — 2 significant figures is close enough". Converts the grading band into significant figures (scale-free: rounding to `n` of them is worst-case `0.5 x 10^(1-n)` off, so the smallest `n` that fits the band IS the precision required), because a percentage of an answer you have not worked out yet is not actionable mid-drill. Reads the band through `resolveEstimationTolerancePct` (`server/lib/postScoring.js`), the same resolver both graders use, so the copy can never claim a band the ✓/✗ did not apply. Rendered by `components/meatspace/post/EstimationPrecision.jsx`. Pure, DOM-free. || `powersBreakdown.js` | Pure, DOM-free Powers mental-math lessons — maps supported base/exponent pairs to named techniques and deterministic worked steps for drill misses and historical review. |-| `promptStageGroups.js` | Search + grouping for the Prompt Manager's Stages pane (#3284). `buildStageGroups(stages, { query, systemOnly, systemStageKeys })` → `{ groups, matchCount, totalCount }`, filtering the `{ key: config }` stage map on title + description + key (AND-token, reusing `mediaSearch.js`'s `tokenizeQuery`/`matchHaystack`) and bucketing survivors into ordered `[{ key, label, stages: [[key, config], …] }]` groups (`Other` pinned last). `stageGroupLabel(name)` derives the family from the `Family — Specific` dash convention (em dash, en dash, or a spaced ASCII hyphen — a user typing their own stage name reaches for the last), falling back to the `STAGE_WORD_PREFIXES` word list (`CoS Agent Briefing`) and then `Other`; `stageGroupKey(label)` case-folds it into the group's identity, so `Pipeline — X` and `pipeline — y` are one group rather than twin headers that render alike under `uppercase`; `stageGroupLabelFor(key, config)` / `stageGroupKeyFor(key, config)` are the name-or-key forms both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. `stageHaystack(key, config)` is the searchable string. The system-stage list is NOT mirrored here — `GET /api/prompts` ships it as `systemStages` from `server/lib/promptSystemStages.js` and the page threads it in as `systemStageKeys` (#3314). Pure — no React, no I/O. |+| `promptStageGroups.js` | Search + grouping for the Prompt Manager's Stages pane (#3284). `buildStageGroups(stages, { query, systemOnly, systemStageKeys })` → `{ groups, matchCount, totalCount }`, filtering the `{ key: config }` stage map on title + description + key (AND-token, reusing `mediaSearch.js`'s `tokenizeQuery`/`matchHaystack`) and bucketing survivors into ordered `[{ key, label, stages: [[key, config], …] }]` groups (`Other` pinned last). `stageGroupLabel(name)` derives the family from the `Family — Specific` dash convention (em dash, en dash, or a spaced ASCII hyphen — a user typing their own stage name reaches for the last), falling back to the `STAGE_WORD_PREFIXES` word list (`CoS Agent Briefing`) and then `Other`; `stageGroupKey(label)` case-folds it into the group's identity, so `Pipeline — X` and `pipeline — y` are one group rather than twin headers that render alike under `uppercase`; `stageGroupLabelFor(key, config)` / `stageGroupKeyFor(key, config)` are the name-or-key forms both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. `stageHaystack(key, config)` is the searchable string. The system-stage list is NOT mirrored here — `GET /api/prompts` ships it as `systemStages` (the `SYSTEM_STAGE_KEYS` list in `server/lib/promptSystemStages.js`) and the page threads it in as `systemStageKeys` (#3314). Pure — no React, no I/O. || `stageModelTiers.js` | Re-export of `server/lib/stageModelTiers.js` — the prompt-stage tier vocabulary (`STAGE_MODEL_TIER_OPTIONS` rows for every stage model select, `canonicalStageModelTier` so a legacy stored `quick`/`coding` still selects Light/Medium, `isStageModelTier`). || `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Each actionable regenerate also names the `correctionKey` (#3134) the card binds its inline correction note to — `walk:<dir>` for a walk output, the bare direction for an anchor — so the card can never write a still-image note into a video re-roll. Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js` and the key vocabulary from `spriteCorrections.js`. || `spriteCorrections.js` | The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned `corrections` map (`Sprites.jsx`); this module owns its keys so the pure gating layer (`spriteCollectionActions.js`) and the React surfaces (`CorrectionNote.jsx` + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — `anchorCorrectionKey(dir)` keeps the bare direction (pre-#3134 state untouched) while `walkCorrectionKey(dir)` / `MAIN_CORRECTION_KEY` / `AMBIENT_REFERENCE_CORRECTION_KEY` prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. `trackCorrectionKey(trackId, dir)` (#3136) replaces the per-track keys the scanner/ambient surfaces each spelled by hand, so a user-defined animation track gets a namespaced key with nothing to add here. `correctionPromptPayload(corrections, key)` → `{ correctionPrompt }` only when the note is non-empty after trimming, else `{}` — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O. |diff --git a/docs/features/video-speed-profiles.md b/docs/features/video-speed-profiles.mdindex ce5b4c795a..2ce2b53528 100644--- a/docs/features/video-speed-profiles.md+++ b/docs/features/video-speed-profiles.md@@ -92,7 +92,7 @@ shows `Speed profile: fast — reduced: teacache unavailable`).| Attached to registry entries at load | `applyVideoSpeedProfiles` in `server/lib/mediaModels.js` || Durable on disk for existing installs | `scripts/migrations/295-video-speed-profiles.js` || Request field | `speedProfileId` in `LOCAL_ONLY_VIDEO_PARAMS` (`server/routes/videoGen.js`) |-| Applied to the render | `resolveVideoSpeedProfile` + `resolveVideoSampler` in `server/services/videoGen/local.js` |+| Applied to the render | `resolveVideoSpeedProfile` + `resolveVideoSampler` defined in `server/lib/videoSpeedProfiles.js`, applied in `server/services/videoGen/generateVideo.js` (and `chainedVideo.js`) || Runner levers + capability probe | `--speed-profile` / `--teacache` / `--require-adapter` in `scripts/generate_ltx2.py` || Outcome parsed back | `SPEEDPROFILE:` in `server/services/videoGen/generateVideoHelpers.js` || Picker | `client/src/components/videoGen/AdvancedParamsPanel.jsx` |diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 8c963992f8..152dd7dc3a 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -280,6 +280,7 @@ export const ALWAYS_RUN_TESTS = ['docs/deps-doc.test.js','docs/features/product-surfaces.test.js','scripts/agent-instructions-files.test.js',+ 'scripts/doc-code-pointers.test.js',// Whole-tree scanner: a new browser suite can adopt the gate with no import// edge back to the registry it must join (#10312).'scripts/browser-suite-registry.test.js',diff --git a/scripts/doc-code-pointers.test.js b/scripts/doc-code-pointers.test.jsnew file mode 100644index 0000000000..f3804c1021--- /dev/null+++ b/scripts/doc-code-pointers.test.js@@ -0,0 +1,62 @@+import { describe, it, expect } from 'vitest';+import { existsSync, readFileSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++// Guards "`symbol` in `path`" pointers in the instruction and catalog docs+// agents load before editing (#11852). A rename or extraction leaves the+// pointer naming a symbol that no longer lives at the cited path, and nothing+// else notices. Prose docs stay out of scope: they use relative shorthand that+// would false-positive.++const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++const DOC_FILES = [+ 'AGENTS.md',+ 'server/AGENTS.md',+ 'client/src/AGENTS.md',+ 'client/src/components/dashboard/AGENTS.md',+ 'server/lib/aiToolkit/AGENTS.md',+ 'server/lib/README.md',+ 'client/src/lib/README.md',+ 'client/src/hooks/README.md',+ 'server/services/README.md',+];++const POINTER = /`([A-Za-z_$][\w$]*)(?:\([^`)]*\))?`\s+(?:in|from|at)\s+`([^`\s]+\.jsx?)`/g;++// Root, the doc's own directory, then the two source roots for shorthand paths.+const resolvePointerPath = (docFile, pointerPath) => {+ const bases = ['', dirname(docFile), 'server', 'client/src'];+ return bases.map((b) => join(REPO_ROOT, b, pointerPath)).find((p) => existsSync(p)) ?? null;+};++export const findBrokenPointers = (docFile, text) => {+ const broken = [];+ text.split('\n').forEach((line, i) => {+ for (const m of line.matchAll(POINTER)) {+ const [, ident, path] = m;+ const resolved = resolvePointerPath(docFile, path);+ if (!resolved) broken.push(`${docFile}:${i + 1} \`${ident}\` -> ${path} (file not found)`);+ else if (!new RegExp(`(?<![\\w$])${ident.replace(/\$/g, '\\$')}(?![\\w$])`).test(readFileSync(resolved, 'utf8'))) {+ broken.push(`${docFile}:${i + 1} \`${ident}\` not found in ${path}`);+ }+ }+ });+ return broken;+};++describe('doc code pointers', () => {+ it('every "`symbol` in `path`" pointer resolves', () => {+ const broken = DOC_FILES.filter((f) => existsSync(join(REPO_ROOT, f)))+ .flatMap((f) => findBrokenPointers(f, readFileSync(join(REPO_ROOT, f), 'utf8')));+ expect(broken).toEqual([]);+ });++ it('reports a stale pointer with file:line', () => {+ const stale = 'See `issueWriteTail` in `server/services/pipeline/issues.js`.';+ expect(findBrokenPointers('server/AGENTS.md', `x\n${stale}`)).toEqual([+ 'server/AGENTS.md:2 `issueWriteTail` not found in server/services/pipeline/issues.js',+ ]);+ });+});diff --git a/server/AGENTS.md b/server/AGENTS.mdindex 98c8f94ccc..3d71359df0 100644--- a/server/AGENTS.md+++ b/server/AGENTS.md@@ -16,8 +16,8 @@ These apply to Express/service/model code. Universal constraints (no try/catch o## Write serialization and throughput-- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.-- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgentLifecycle.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.+- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `queueSeriesIssuesWrite` in `server/services/pipeline/issuesShared.js` (built on `createKeyCachedQueue` in `server/lib/createKeyCachedQueue.js`). A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.+- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `server/services/cosAgentLifecycle.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.## Timers@@ -37,7 +37,7 @@ These apply to Express/service/model code. Universal constraints (no try/catch o## Import scoping-- **A widely-reached module must not drag a subtree it only needs a constant from.** The Linux CI server suite spends more wall time importing modules than running assertions, because import cost multiplies: every test file that transitively reaches module `X` re-instantiates all of `X`'s closure in its own worker. So one convenient barrel import inside a module 400 suites reach is worth thousands of module instantiations. `server/lib/importScoping.test.js` pins the narrowings made in #6009 (which cut the suite from ~115.5k static module instantiations to ~94.5k) as negative reachability assertions over `staticImportClosure`; add a row there when you narrow another one. The two shapes worth looking for: a constant re-exported through a heavy barrel (import it from the module that *declares* it — `CHECK_SCOPES` from `editorial/checkInfra/taxonomy.js`, not from `editorial/checkRegistry.js` and its 13 check-definition modules), and a dependency only a boot/rare path uses (`await import()` it inside that path — `ensureSchemaImpl()` composes the DDL that way, keeping `lib/db/schema/**` out of the ~400 suites that reach `lib/db.js` through `pgFileFacade.js`).+- **A widely-reached module must not drag a subtree it only needs a constant from.** The Linux CI server suite spends more wall time importing modules than running assertions, because import cost multiplies: every test file that transitively reaches module `X` re-instantiates all of `X`'s closure in its own worker. So one convenient barrel import inside a module 400 suites reach is worth thousands of module instantiations. `server/lib/importScoping.test.js` pins the narrowings made in #6009 (which cut the suite from ~115.5k static module instantiations to ~94.5k) as negative reachability assertions over `staticImportClosure`; add a row there when you narrow another one. The two shapes worth looking for: a constant re-exported through a heavy barrel (import it from the module that *declares* it — `CHECK_SCOPES` from `server/lib/editorial/checkInfra/taxonomy.js`, not from `editorial/checkRegistry.js` and its 13 check-definition modules), and a dependency only a boot/rare path uses (`await import()` it inside that path — `ensureSchemaImpl()` composes the DDL that way, keeping `lib/db/schema/**` out of the ~400 suites that reach `lib/db.js` through `pgFileFacade.js`).- **In a non-async scope, defer with `.then()` rather than giving up.** The lazy shape is not limited to `async` functions: a `new Promise` executor or a fire-and-forget branch takes `import('./x.js').then(({ fn }) => fn(…)).catch(handler)`, which also routes an import failure into the error path the call already had. That is how the TUI branch in `services/promptRunner.js` defers `tuiPromptRunner.js` (and with it `node-pty`). Prefer putting the `import()` INSIDE an existing predicate gate when there is one — `runner.js` defers `ollamaAgentContext.js` inside the `isOllamaBackedProvider` ternary, so a cloud-provider run pays neither the hop nor the subtree.- **The tree-wide backstop is a base-relative growth guard, not an absolute ceiling.** `importScoping.test.js` compares every server `*.test.js` file's static import closure against the merge base, using one analyzer for both sides (`scripts/lib/importGrowth.js`). The count is a **proxy**: closure size summed across suites, shared modules counted once per suite that reaches them, not a count of runtime instantiations or a wall-clock. New test files are reported as new-suite contribution and do not spend the allowance, so ordinary additions cannot fail the guard just because the repository total grew. The gated number is the sum, over suites that exist on both sides, of how much each closure grew (shrinkage elsewhere does not cancel it). The limit is 2,500, above the old ceiling's ~1,500 ordinary-growth note and below half of the smaller heavy regression this file already records: #6009 removed 19,286 (115,519 → 96,233) and #6156 removed 12,794 (96,233 → 83,439). A failure names the largest suite increases and the largest newly reached dependency closures. Narrow the import, or defer it with `await import()` on the path that uses it. Raising `EXISTING_SUITE_GROWTH_LIMIT` is the intentional-regression path: do it in the same change, name the module that cannot be deferred, and keep the limit under that #6156 band — the pin test rejects a limit high enough to admit those edges. A missing or unreadable base fails the guard; it is not treated as zero growth. `benchmarkProxySplit` reports synthetic collection time and execution time separately and neither is a per-PR threshold. CI and `npm run pregate` run this comparison: the test is on `ALWAYS_RUN_TESTS`, and pregate forwards the same `CI_BASE_SHA` the planner used.- **Narrowing an import must not step around a barrel a suite mocks.** `vi.mock('./cos.js')` intercepts the specifier, not the function — so re-pointing a caller from `./cos.js` to the `./cosTaskStore.js` that declares `addTask` makes production code reach the REAL implementation while the suite still believes it is doubled. The failure lands in an unrelated test file with no obvious link to the import you changed. Before narrowing, grep the tree for `vi.mock` against the module you are leaving; if any suite that reaches the caller mocks it, leave the import on the barrel. A lazy `await import()` has no such hazard — vitest's mock registry covers dynamic imports too.diff --git a/server/lib/README.md b/server/lib/README.mdindex 1f2cc2a629..a0b5b14de4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -630,7 +630,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `postPowersLadder.js` | Pure technique-anchored Powers ladder — cumulative named-method pools, full supported-pair registry, and speed+accuracy mastery progression built on `postProgression.js`. || `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from exact-level sample, accuracy, completion, and optional speed evidence with an anti-demotion floor. Also defines meaningful cognitive-drill ladders (including task switching, Go/No-Go, and Flanker) and their level→generator-config mapping. || `spacedRepetition.js` | The shared SM-2-inspired review scheduler, extracted from `services/meatspacePostMemory.js` when SongBook practice became its second consumer (#4102). One four-field schedule shape (`{ ease, intervalDays, nextReview, lastReviewed }`, no `repetitions` counter — the 0 → 1 → 6 → `round(prev * ease)` ladder derives from the previous interval, so a schedule round-trips through import/export/federation on those four fields alone). `advanceSchedule(schedule, ratio, now)` is the core (ease clamped to `MIN_EASE`..`MAX_EASE`, interval capped at `MAX_INTERVAL_DAYS` so `new Date(now + interval*DAY)` can't overflow into an Invalid Date; quality < 3 zeroes the interval to resurface the record but still applies the ease penalty). `mergeScheduleAdvance(prev, advanced, now)` gates interval GROWTH to once per review day (a shrink always applies) for UIs that submit per chunk/section; `isSameReviewDay` is that gate's own predicate, reusable by callers gating their own once-a-day progression. `scheduleOrDefault(record, schedule?)` is the read-path fallback — a record with no schedule derives one anchored to its `updatedAt`/`createdAt` (stable and in the past → due now), so "due" can't flap between two reads a millisecond apart. `ratioToQuality` / `qualityToRatio` are exact inverses over the integers, so a self-graded 0..5 review lands on the quality the user picked. `isScheduleDue` treats an absent/unparseable `nextReview` as due — a record we can't schedule is one to surface, never one to hide forever. Pure. |-| `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `songDueAt` in `client/src/components/songbook/constants.js`. Pure. |+| `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `isSongDue` in `client/src/components/songbook/constants.js`. Pure. || `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. A pure leaf: the client's post `constants.js` re-exports it and layers the UI-only `TOPIC_UI` on top. || `postScoring.js` | Scoring and accuracy helpers for post-training drill types shared between server (`services/meatspacePost.js`) and client (`components/meatspace/post/constants.js`) — `nBackBalancedAccuracy` (balanced signal-detection accuracy for n-back questions), plus `DEFAULT_ESTIMATION_TOLERANCE_PCT` / `resolveEstimationTolerancePct(pct)` — the single estimation band that server grading, the client's optimistic check, and the on-screen "within N%" copy all read, so the number shown and the number graded cannot drift. || `postRotation.js` | Pure deterministic day-based rotation for POST practice selection — `shuffleForDay` supplies a stable pseudorandom daily mix; `orderByRecencyRotation` sorts candidates fresh-before-recently-practiced, then by priority, and rotates equivalent ones by local day so a tier never pins to one drill. Mirrored at `client/src/lib/postRotation.js`. |diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex ef3bb23659..84e4b3c53e 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -484,7 +484,7 @@ export async function spawnDirectly({// listener before the enqueue, so a blocked earlier write can never delay// killing the provider on a usage-limit signal. The close/error handlers// `await drainTranscriptWrites()` before finalize so the tail lands first.- // Mirrors shell.js `hookQueue` and pipeline/issues.js `issueWriteTail`.+ // Mirrors shell.js `hookQueue` and pipeline/issuesShared.js `queueSeriesIssuesWrite`.let transcriptWriteTail = Promise.resolve();const enqueueTranscriptWrite = (fn) => {transcriptWriteTail = transcriptWriteTail.then(fn).catch((err) => {diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.jsindex 984b280bf9..ff6d4c25f3 100644--- a/server/services/appQualitySnapshotFile.js+++ b/server/services/appQualitySnapshotFile.js@@ -110,7 +110,7 @@ function skipped(app, reason) {// together, and read-modify-write against `.quality.json` plus `.git/index` is// not re-entrant — the second run must see the first run's bytes (and answer// `no-changes`) rather than race it. Keyed by repo path, not app id: two app-// records can point at one checkout. Same shape as `issueWriteTail`.+// records can point at one checkout. Same shape as `queueSeriesIssuesWrite`.const publishTails = new Map();// Bytes the in-process publisher last landed (or confirmed on origin) for a// checkout. Origin/default still holds the previous file until the PR merges,diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 028357f354..119f5b715f 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -442,7 +442,7 @@ export async function getState() {// concurrent writers (e.g. an auto-window-activate PUT + a manual layout// save firing from the same browser, or palette + dashboard tabs) can't// interleave load → modify → write and lose each other's changes. Mirrors-// the `issueWriteTail` / `cacheWriteTails` pattern documented in AGENTS.md+// the `createKeyCachedQueue` / `cacheWriteTails` pattern documented in AGENTS.md// ("Async PATCH races on shared records — serialize writes server-side").let layoutsWriteTail = Promise.resolve();const queueLayoutsWrite = (fn) => {diff --git a/server/services/loraTraining/db.js b/server/services/loraTraining/db.jsindex a8bcee20c1..fa3cfaa194 100644--- a/server/services/loraTraining/db.js+++ b/server/services/loraTraining/db.js@@ -11,7 +11,7 @@* status/startedAt/completedAt writes. A bare read-modify-write would let a* stale read clobber a concurrent append, so `updateRun` chains every* mutation for the same id onto a per-id tail promise (the same discipline- * as `issueWriteTail` in pipeline/issues.js). Writes to DIFFERENT runs stay+ * as `queueSeriesIssuesWrite` in pipeline/issuesShared.js). Writes to DIFFERENT runs stay* parallel; the map entry is pruned once its chain settles.*/diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 2b8af4ed68..a43341df93 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -24,7 +24,7 @@ const syncLocks = new Map();// `updateMessageEvaluations` all share the one `${accountId}.json` cache file, so// two that interleave their load/save would clobber each other's writes. The tail// makes each one await the previous and re-read the freshest persisted state-// inside its serialized region — mirroring `issueWriteTail` in pipeline/issues.js.+// inside its serialized region — mirroring `queueSeriesIssuesWrite` in pipeline/issuesShared.js.const accountWriteQueue = createKeyCachedQueue();const summarySnapshots = createBoundedStateMap({ maxSize: 8 });const summaryReads = new Map();diff --git a/server/services/videoGen/history.js b/server/services/videoGen/history.jsindex 81747b7490..9a097938e6 100644--- a/server/services/videoGen/history.js+++ b/server/services/videoGen/history.js@@ -99,7 +99,7 @@ export async function getHistoryItem(id) {// same stale array and the later save clobbers the earlier's new entry, leaving// an orphaned file that's absent from the list/media-index and undeletable. A// module-level promise tail collapses concurrent mutations to a single writer-// per file (the `issueWriteTail` pattern in AGENTS.md). `mutator(list)` receives+// per file (the `createKeyCachedQueue` pattern in AGENTS.md). `mutator(list)` receives// the freshest persisted array and returns the array to persist (return the// same reference after mutating it in place, or a new array). Any writer that// can race another on this file should route through here.diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex b0584bc089..830ca92bf7 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -209,7 +209,7 @@ export function addWorktreeWithRetry(args, repo, attempt = 1, firstError = null)}// Per-source-repo serialization tail for worktree-creating git operations —-// the issueWriteTail pattern (see server/services/pipeline/issues.js). Git+// the createKeyCachedQueue pattern (see server/services/pipeline/issuesShared.js). Git// serializes its own worktree bookkeeping behind a per-repo lock, so two// `git worktree add` calls in the same evaluation tick race and the loser is// blocked with `blockedCategory: worktree-failed` (#2193). A single promise