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
refactor: address code review findings
[._.]/ Adam Eivy9dd6f7b59596
diff --git a/.claude/commands/claim.md b/.claude/commands/claim.mdindex 12c3132ce4..773e199fc8 100644--- a/.claude/commands/claim.md+++ b/.claude/commands/claim.md@@ -32,7 +32,7 @@ Claim the next unclaimed `- [ ]` item from PLAN.md via the slug-ID system, work## Phase 2: Claim (worktree) — REQUIRED, NOT OPTIONAL-> **This phase overrides CLAUDE.md's "don't spawn a worktree in TUI" rule.** That rule exists so single-session TUI work doesn't fragment into stray worktrees. `/claim` is the documented exception: the worktree is what lets the user fire off a *second* `/claim` in another tab without the two claims fighting over the main repo's working tree. **A `/claim` without a worktree is a broken claim — it blocks every subsequent claim until cleaned up.**+> `/claim` always uses a worktree so the user can fire off a *second* `/claim` in another tab without the two claims fighting over the main repo's working tree. **A `/claim` without a worktree is a broken claim — it blocks every subsequent claim until cleaned up.**>> **Hard rules:**> - ❌ NEVER run `git checkout -b claim/<slug>` in the main repo. That's the failure mode this phase exists to prevent.diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsxindex 4eb579d808..d444f5fb2c 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -39,7 +39,7 @@ import {generatePipelineArcOverview, generatePipelineSeasonEpisodes, verifyPipelineArc,verifyPipelineVolume,resolvePipelineArcIssues,- listPipelineIssues, updatePipelineSeries,+ listPipelineIssues, updatePipelineSeries, setPipelineArcFieldLock,startPipelineVolumeBeats, cancelPipelineVolumeBeats,generatePipelineVolumeCover, generatePipelineVolumeBackCover,generatePipelineVolumeCoverConcepts,@@ -210,7 +210,7 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {setLockBusy(true);const updated = await updatePipelineSeries(series.id, {locked: { ...(series.locked || {}), arc: next },- }).catch((err) => {+ }, { silent: true }).catch((err) => {toast.error(err.message || 'Failed to update lock');return null;});@@ -570,15 +570,12 @@ function FieldLockToggle({ series, field, label, onSeriesUpdate }) {const [saving, setSaving] = useState(false);const toggle = async () => {if (saving) return;- const nextFields = { ...lockedFields };- if (locked) delete nextFields[field];- else nextFields[field] = true;setSaving(true);- // `updatePipelineSeries` toasts the error itself on rejection — silent: false- // by default in apiCore.request. No custom catch needed; just short-circuit.- const updated = await updatePipelineSeries(series.id, {- locked: { ...(series.locked || {}), arcFields: nextFields },- }).catch(() => null);+ const updated = await setPipelineArcFieldLock(series.id, field, !locked, { silent: true })+ .catch((err) => {+ toast.error(err.message || `${label} lock update failed`);+ return null;+ });setSaving(false);if (!updated) return;onSeriesUpdate(updated);diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsxindex c639364841..f7e728bd6f 100644--- a/client/src/pages/PipelineIssue.jsx+++ b/client/src/pages/PipelineIssue.jsx@@ -74,6 +74,12 @@ const STATUS_DOT = {error: 'bg-port-error',};+const lockStageIdsForTab = (id) => {+ if (id === 'nouns') return [];+ if (id === 'comicScript') return ['comicScript', 'comicPages'];+ return [id];+};+export default function PipelineIssue() {const { issueId, stage: stageParam } = useParams();const navigate = useNavigate();@@ -156,7 +162,7 @@ export default function PipelineIssue() {// routes lengthProfile / pageTarget / minutesTarget straight onto the record.const handleLengthChange = async (patch) => {setLengthProfileSaving(true);- updatePipelineIssue(issueId, patch)+ updatePipelineIssue(issueId, patch, { silent: true }).then((updated) => { if (updated) setIssue(updated); }).catch((err) => { toast.error(err.message || 'Save failed'); }).finally(() => setLengthProfileSaving(false));@@ -169,26 +175,34 @@ export default function PipelineIssue() {setGenConfigSaving(true);const updated = await updatePipelineIssue(issueId, {stages: { [stageId]: { genConfig: next } },- }).catch((err) => {+ }, { silent: true }).catch((err) => {toast.error(err.message || 'Save failed');return null;}).finally(() => setGenConfigSaving(false));if (updated) setIssue(updated);};+ const activeLockStageIds = useMemo(() => lockStageIdsForTab(stageId), [stageId]);+ const activeStageLocked = activeLockStageIds.some((id) => issue?.stages?.[id]?.locked === true);+ const canLockActiveStage = activeLockStageIds.length > 0;+// Toggle the per-stage lock for the currently-active tab. Routes through// the generic issue PATCH path so the issue sanitizer + write queue handle// the merge; the server enforces the lock semantics at the regenerate// boundary (textStages.generateStage, visualStages.enqueueXxx, etc.).+ // The merged Comic tab owns both text (`comicScript`) and render/page+ // artifacts (`comicPages`), so it toggles both persisted stages together.const handleStageLockToggle = async () => {- if (stageLockSaving || !issue) return;- const next = !(issue.stages?.[stageId]?.locked === true);+ if (stageLockSaving || !issue || !canLockActiveStage) return;+ const next = !activeStageLocked;setStageLockSaving(true);- // updatePipelineIssue toasts on rejection via apiCore.request — short-circuit- // on null and skip a second toast.+ const stages = Object.fromEntries(activeLockStageIds.map((id) => [id, { locked: next }]));const updated = await updatePipelineIssue(issueId, {- stages: { [stageId]: { locked: next } },- }).catch(() => null);+ stages,+ }, { silent: true }).catch((err) => {+ toast.error(err.message || `${PIPELINE_STAGE_LABELS[stageId]} lock update failed`);+ return null;+ });setStageLockSaving(false);if (!updated) return;setIssue(updated);@@ -237,7 +251,8 @@ export default function PipelineIssue() {.filter((id) => id !== 'audio' || series?.targetFormat !== 'comic').map((id) => {const status = issue?.stages?.[id]?.status || 'empty';- const stageLocked = issue?.stages?.[id]?.locked === true;+ const tabLockStageIds = lockStageIdsForTab(id);+ const stageLocked = tabLockStageIds.some((lockId) => issue?.stages?.[lockId]?.locked === true);const tabLockHint = stageLocked? `${PIPELINE_STAGE_LABELS[id]} stage is locked — unlock it to regenerate`: ambientLockHint;@@ -254,7 +269,6 @@ export default function PipelineIssue() {// Active-tab specific banner: prefer per-stage lock when the current tab is// locked, fall back to the arc/season-wide message otherwise.- const activeStageLocked = issue?.stages?.[stageId]?.locked === true;const lockHint = activeStageLocked? `${PIPELINE_STAGE_LABELS[stageId]} stage is locked — unlock it to regenerate`: ambientLockHint;@@ -340,25 +354,27 @@ export default function PipelineIssue() {<Settings size={16} /></button>)}- <button- type="button"- onClick={handleStageLockToggle}- disabled={stageLockSaving || autoRunStarting || autoRunActive}- aria-pressed={activeStageLocked}- title={activeStageLocked- ? `Unlock ${PIPELINE_STAGE_LABELS[stageId]} — allows regeneration again`- : `Lock ${PIPELINE_STAGE_LABELS[stageId]} — blocks regeneration of this stage; siblings stay runnable`}- aria-label={activeStageLocked ? `Unlock ${PIPELINE_STAGE_LABELS[stageId]}` : `Lock ${PIPELINE_STAGE_LABELS[stageId]}`}- className={`inline-flex items-center justify-center p-2 rounded-lg border text-sm transition-colors disabled:opacity-40 ${- activeStageLocked- ? 'bg-port-warning/10 text-port-warning border-port-warning/40 hover:bg-port-warning/20'- : 'bg-port-card text-gray-300 border-port-border hover:text-white hover:border-port-accent/40'- }`}- >- {stageLockSaving- ? <Loader2 size={16} className="animate-spin" />- : (activeStageLocked ? <Lock size={16} /> : <Unlock size={16} />)}- </button>+ {canLockActiveStage ? (+ <button+ type="button"+ onClick={handleStageLockToggle}+ disabled={stageLockSaving || autoRunStarting || autoRunActive}+ aria-pressed={activeStageLocked}+ title={activeStageLocked+ ? `Unlock ${PIPELINE_STAGE_LABELS[stageId]} — allows regeneration again`+ : `Lock ${PIPELINE_STAGE_LABELS[stageId]} — blocks regeneration of this stage; siblings stay runnable`}+ aria-label={activeStageLocked ? `Unlock ${PIPELINE_STAGE_LABELS[stageId]}` : `Lock ${PIPELINE_STAGE_LABELS[stageId]}`}+ className={`inline-flex items-center justify-center p-2 rounded-lg border text-sm transition-colors disabled:opacity-40 ${+ activeStageLocked+ ? 'bg-port-warning/10 text-port-warning border-port-warning/40 hover:bg-port-warning/20'+ : 'bg-port-card text-gray-300 border-port-border hover:text-white hover:border-port-accent/40'+ }`}+ >+ {stageLockSaving+ ? <Loader2 size={16} className="animate-spin" />+ : (activeStageLocked ? <Lock size={16} /> : <Unlock size={16} />)}+ </button>+ ) : null}</div></div>diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 31b62cfdae..eb8fd53595 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -84,10 +84,18 @@ export const createPipelineSeries = (data) => request('/pipeline/series', {method: 'POST',body: JSON.stringify(data),});-export const updatePipelineSeries = (id, patch) => request(`/pipeline/series/${encodeURIComponent(id)}`, {+export const updatePipelineSeries = (id, patch, requestOptions = {}) => request(`/pipeline/series/${encodeURIComponent(id)}`, {method: 'PATCH',body: JSON.stringify(patch),+ ...requestOptions,});++export const setPipelineArcFieldLock = (id, field, locked, requestOptions = {}) =>+ request(`/pipeline/series/${encodeURIComponent(id)}/arc-fields/${encodeURIComponent(field)}/lock`, {+ method: 'PATCH',+ body: JSON.stringify({ locked }),+ ...requestOptions,+ });export const deletePipelineSeries = (id) => request(`/pipeline/series/${encodeURIComponent(id)}`, {method: 'DELETE',});@@ -117,10 +125,11 @@ export const createPipelineIssue = (seriesId, data) =>export const getPipelineIssue = (id) => request(`/pipeline/issues/${encodeURIComponent(id)}`);-export const updatePipelineIssue = (id, patch) =>+export const updatePipelineIssue = (id, patch, requestOptions = {}) =>request(`/pipeline/issues/${encodeURIComponent(id)}`, {method: 'PATCH',body: JSON.stringify(patch),+ ...requestOptions,});export const deletePipelineIssue = (id) =>diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 775135c8c1..d6d27d4c7b 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -223,6 +223,7 @@ const seriesPatchSchema = z.object({issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),llm: llmSchema,}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });+const arcFieldLockSchema = z.object({ locked: z.boolean() });// Season-resource schemas: dedicated CRUD on a sibling resource so the// client can edit one season without resending the whole series patch.@@ -256,6 +257,7 @@ const stageInputSchema = z.object({input: z.string().max(issuesSvc.STAGE_INPUT_MAX).optional(),output: z.string().max(issuesSvc.STAGE_OUTPUT_MAX).optional(),errorMessage: z.string().max(issuesSvc.STAGE_NOTES_MAX).optional(),+ locked: z.boolean().optional(),});// Visual stage records also accept pages/scenes/cdProjectId/videoPath — those@@ -842,6 +844,13 @@ router.patch('/series/:id', asyncHandler(async (req, res) => {res.json(s);}));+router.patch('/series/:id/arc-fields/:field/lock', asyncHandler(async (req, res) => {+ const body = validateRequest(arcFieldLockSchema, req.body ?? {});+ const s = await seriesSvc.setArcFieldLock(req.params.id, req.params.field, body.locked)+ .catch((err) => { throw mapServiceError(err); });+ res.json(s);+}));+router.delete('/series/:id', asyncHandler(async (req, res) => {const r = await seriesSvc.deleteSeries(req.params.id).catch((err) => { throw mapServiceError(err); });res.json(r);diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex ff06ba3e2e..1f703603d0 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -1208,6 +1208,17 @@ describe('pipeline routes', () => {expect(r.body.arcPosition).toBe(3);});+ it('PATCH /issues/:id preserves per-stage locked flags through validation', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });+ const r = await request(app).patch(`/api/pipeline/issues/${iss.body.id}`)+ .send({ stages: { idea: { locked: true } } });+ expect(r.status).toBe(200);+ expect(r.body.stages.idea.locked).toBe(true);+ expect(r.body.stages.idea.status).toBe('empty');+ });+it('PATCH /series/:id accepts arc payload', async () => {const app = makeApp();const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });@@ -1222,6 +1233,19 @@ describe('pipeline routes', () => {});});+ it('PATCH /series/:id/arc-fields/:field/lock merges a single arc field lock', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({+ name: 'S',+ locked: { arcFields: { logline: true } },+ });+ const r = await request(app)+ .patch(`/api/pipeline/series/${ser.body.id}/arc-fields/themes/lock`)+ .send({ locked: true });+ expect(r.status).toBe(200);+ expect(r.body.locked.arcFields).toEqual({ logline: true, themes: true });+ });+// -----------------------// Arc planning routes (Phase 3 of Story Arc Planning)// -----------------------diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex ceef5a27d6..66cfbb9943 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -870,7 +870,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {// Verify (read-only) stays enabled — the user can act on findings manually.if (series.locked?.arc === true) {throw new ServerError(- 'Arc is locked — unlock it before auto-resolving findings',+ 'Arc is locked — unlock it before rewriting the arc',{ status: 400, code: ERR_VALIDATION },);}@@ -996,15 +996,23 @@ export function mergeArcWithLocks(currentArc, nextArc, lockedFields) {* are restored from `currentSeries.arc` before the persist, so an auto-resolve* that proposes a new logline can preserve the user-frozen themes verbatim.*- * `currentSeries` is the pre-write snapshot; pass the result of `getSeries(id)`- * so we know which ids existed before the write.+ * `currentSeries` identifies the target series. The helper refreshes the+ * latest snapshot before writing so locks toggled while an LLM run is in+ * flight are honored at commit time.*/export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }) {const seriesId = currentSeries.id;- const mergedArc = mergeArcWithLocks(currentSeries.arc, arc, currentSeries.locked?.arcFields);+ const latestSeries = await getSeries(seriesId);+ if (latestSeries.locked?.arc === true) {+ throw new ServerError(+ 'Arc is locked — unlock it before rewriting the arc',+ { status: 400, code: ERR_VALIDATION },+ );+ }+ const mergedArc = mergeArcWithLocks(latestSeries.arc, arc, latestSeries.locked?.arcFields);const newIds = new Set((seasons || []).map((s) => s.id));- const droppedOldSeasons = (currentSeries.seasons || []).filter((s) => !newIds.has(s.id));- const oldIds = new Set((currentSeries.seasons || []).map((s) => s.id));+ const droppedOldSeasons = (latestSeries.seasons || []).filter((s) => !newIds.has(s.id));+ const oldIds = new Set((latestSeries.seasons || []).map((s) => s.id));const newlyMintedSeasons = (seasons || []).filter((s) => !oldIds.has(s.id));const remap = buildSeasonRemap(droppedOldSeasons, newlyMintedSeasons);const droppedIdSet = new Set(droppedOldSeasons.map((s) => s.id));diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 5f893e2280..cf832e45ef 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -826,6 +826,34 @@ describe('arcPlanner — commitSeasonsWithRemap', () => {expect(out.series.arc.protagonistArc).toBe('a fresh pa');expect(out.series.arc.shape).toBe('icarus');});++ it('honors arc field locks toggled after the caller snapshot was read', async () => {+ const s = await setupSeries({+ arc: {+ logline: 'original logline',+ summary: 'original summary',+ themes: [],+ protagonistArc: '',+ shape: null,+ status: 'draft',+ },+ });+ const stale = await seriesSvc.getSeries(s.id);+ await seriesSvc.updateSeries(s.id, {+ arc: { ...stale.arc, logline: 'latest locked logline' },+ locked: { arcFields: { logline: true } },+ });+ const out = await planner.commitSeasonsWithRemap(stale, {+ arc: {+ ...stale.arc,+ logline: 'incoming overwrite',+ summary: 'incoming summary',+ },+ seasons: [],+ });+ expect(out.series.arc.logline).toBe('latest locked logline');+ expect(out.series.arc.summary).toBe('incoming summary');+ });});describe('arcPlanner — mergeArcWithLocks', () => {diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 6ca0a5ff45..2bfb572de2 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -273,6 +273,34 @@ export async function updateSeries(id, patch = {}) {return merged;}+export async function setArcFieldLock(id, field, locked) {+ if (!ARC_LOCKABLE_FIELDS.includes(field)) {+ throw makeErr(`Unknown arc lock field: ${field}`, ERR_VALIDATION);+ }+ return queueSeriesWrite(async () => {+ const state = await readState();+ const idx = state.series.findIndex((s) => s.id === id);+ if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.series[idx];+ const arcFields = { ...(cur.locked?.arcFields || {}) };+ if (locked === true) arcFields[field] = true;+ else delete arcFields[field];+ const nextLocked = { ...(cur.locked || {}) };+ if (Object.keys(arcFields).length > 0) nextLocked.arcFields = arcFields;+ else delete nextLocked.arcFields;+ const next = sanitizeSeries({+ ...cur,+ locked: nextLocked,+ updatedAt: new Date().toISOString(),+ });+ if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);+ state.series[idx] = next;+ await writeState(state);+ emitRecordUpdated('series', next.id);+ return next;+ });+}+/*** Apply a structured patch to one season inside a series. Routes through the* shared series write tail so a season-cover render PATCH, the season-coverdiff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.jsindex 33f594684c..abe68a9d2c 100644--- a/server/services/pipeline/series.test.js+++ b/server/services/pipeline/series.test.js@@ -211,5 +211,19 @@ describe('pipeline series service', () => {expect(updated.locked).toEqual({ arc: true });expect(updated.logline).toBe('new logline');});++ it('setArcFieldLock merges against latest arcFields without clobbering siblings', async () => {+ const s = await svc.createSeries({ name: 'X', locked: { arcFields: { logline: true } } });+ const updated = await svc.setArcFieldLock(s.id, 'themes', true);+ expect(updated.locked.arcFields).toEqual({ logline: true, themes: true });+ const cleared = await svc.setArcFieldLock(s.id, 'logline', false);+ expect(cleared.locked.arcFields).toEqual({ themes: true });+ });++ it('setArcFieldLock rejects unknown arc fields', async () => {+ const s = await svc.createSeries({ name: 'X' });+ await expect(svc.setArcFieldLock(s.id, 'bogus', true))+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ });});});diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 63831e91b6..25873fa1c7 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -31,12 +31,11 @@ const updateStageMock = vi.fn(async (issueId, stageId, patch) => ({issue: { ...mockIssue, stages: { ...mockIssue.stages, [stageId]: { ...mockIssue.stages[stageId], ...patch } } },stage: { ...mockIssue.stages[stageId], ...patch },}));+const assertStageUnlockedMock = vi.fn(() => undefined);vi.mock('./issues.js', () => ({getIssue: (...a) => getIssueMock(...a),updateStage: (...a) => updateStageMock(...a),- // Default to "not locked" so existing tests keep their semantics; per-stage- // lock enforcement is covered in its own describe block.- assertStageUnlocked: vi.fn(() => undefined),+ assertStageUnlocked: (...a) => assertStageUnlockedMock(...a),VISUAL_STAGE_IDS: ['comicPages', 'storyboards', 'episodeVideo'],STAGE_IDS: ['idea', 'prose', 'comicScript', 'teleplay', 'comicPages', 'storyboards', 'episodeVideo'],}));@@ -86,6 +85,7 @@ const {beforeEach(() => {getIssueMock.mockClear();updateStageMock.mockClear();+ assertStageUnlockedMock.mockClear();enqueueJobMock.mockClear();runStagedLLMMock.mockClear();});@@ -374,6 +374,18 @@ describe('visual style resolution threads into image prompts', () => {});});+describe('per-stage lock enforcement', () => {+ it('checks the comicPages lock before queueing a cover render', async () => {+ await enqueueComicCover('iss-test', {});+ expect(assertStageUnlockedMock).toHaveBeenCalledWith(expect.objectContaining({ id: 'iss-test' }), 'comicPages');+ });++ it('checks the storyboards lock before queueing a scene video', async () => {+ await enqueueStoryboardSceneVideo('iss-test', 0, { aspectRatio: '16:9' });+ expect(assertStageUnlockedMock).toHaveBeenCalledWith(expect.objectContaining({ id: 'iss-test' }), 'storyboards');+ });+});+describe('enqueueStoryboardSceneVideo', () => {it('rejects a non-integer sceneIndex', async () => {await expect(enqueueStoryboardSceneVideo('iss-test', 'nope')).rejects.toThrow(/non-negative integer/);