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: derive perpetual park rollups in taskSchedule from one shared aggregate (#3574)
[._.]/ Adam Eivya2bf0e314913
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9c780aa623..d273ee5a2b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -200,3 +200,4 @@- **[issue-3590] Lengthening a perpetual task's recheck cadence no longer delays a recheck that was already due.** When the recheck cadence changes, the schedule re-derives the park timestamp of every currently-parked execution record from the new cadence, so the edit takes effect on the next slot instead of waiting out the old timestamp. The guard was "does this record carry a park at all" — but an elapsed park is never cleared when it expires (the task simply reports itself as due for a recheck, and the dispatch gate clears the park when it actually runs), so a record that was ready to run right now was matched by that guard too and stamped with a fresh future timestamp. Shortening the cadence was harmless, since the new timestamp was sooner; lengthening it pushed the pending recheck back out by the new interval, and the drain the user was waiting on silently went quiet again. Only parks still in the future are re-derived now — a record whose park has already elapsed is left exactly as it is, so it rechecks on the very next tick.- **[issue-3594] The drafting prompt now teaches how to write a scene, not just how much scene to write.** The craft doctrine injected into both drafting stages — the prose pipeline and Writers Room live continuation — was entirely negative: eleven "avoid X" rules plus the Stability Trap countermeasures. One of those rules carries a measurable target with no technique attached ("at least 70% in-scene, not summary"), and a model told to dramatize more with no construction recipe reaches for longer description, which is exactly the white-room, zero-interiority draft the editorial checks then have to catch. A new "Zoom into the moment" section — the first positive-instruction block in the partial, placed right after the rule it operationalizes — gives it the recipe in five elements: name the location with one concrete noun rather than an inventory, say what the character is doing in present-moment verbs, render thoughts raw in the character's own diction instead of essay register, show emotion on the body rather than naming the feeling, and quote dialogue that is worth quoting instead of narrating that someone spoke. Each element ships with the failure mode that makes it a rule rather than a suggestion. Because the partial is a file on disk that existing installs already have, and both `setup-data.js` and the original seed migration only ever copy it when it is *missing*, the section arrives through a hash-gated migration: an install still running the shipped version is upgraded in place, and a hand-edited partial is left exactly as it is and told what to merge.- **[issue-3591] Editorial checks now catch a pivotal moment that got narrated instead of played out.** The drafting prompts have long carried the rule that a draft should be at least 70% in-scene, not summary — but nothing on the review side ever checked it, so the most common structural failure in a draft went unflagged: a decision, confrontation or reveal delivered from helicopter altitude ("Over the next week they argued about it, and eventually she agreed to go") where the scene would have landed. The new **Narrated summary where a scene belongs** check reads your drafted manuscript and names four modes of it — a compressed-away turning point, reported action the reader never physically enters, habitual mode ("every night she would…") wrapped around what was really a single decisive event, and result-first narration that states the outcome and skips the scene. Each finding quotes a verbatim anchor and, rather than just saying "dramatize this", names the concrete moment to zoom into. It reads the reverse-outline scene segmentation as context so honest between-scene compression is left alone — the target is a beat that never became a scene at all, which is invisible to the existing scene checks precisely because they only judge scenes that exist. Deliberate montages, brief time-skips, backstory summary (that belongs to info-dumping) and beats too minor to be worth the words are explicitly out of scope. Enabled by default at medium severity under Create → Editorial Checks; the new `pipeline-editorial-summary-not-scene` stage prompt ships and migrates for existing installs. (#3591)+- **[issue-3574] A parked perpetual task now reports the same park state to the schedule UI and to the daemon's wake-up planner.** "Which scopes of a perpetual task are parked, and when does the soonest one recheck?" was answered by three separate walks of the same records: one for the Schedule page's parked/draining badge, one for the upcoming-tasks eligibility that decides when the daemon wakes, and a third inline read of a single record's `parkedUntil` in the due check. They had already drifted — the badge only ever folded the top-level execution record in when its park hadn't elapsed, while the wake-up planner folded in any top-level record carrying a park at all — so a global park that had just come due could read as "nothing parked" in one and "due now" in the other. All of it now projects from one aggregate whose global-record inclusion rule is written down in exactly one place: every per-app record is a tracked scope, and the top-level record is a tracked scope only when it carries its own park. Each caller's existing behavior is unchanged; the two are pinned to the same fixtures by tests so they can't diverge again.diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 34f1798171..7e43f7dff0 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -808,8 +808,7 @@ export async function updateTaskInterval(taskType, settings) {const nowMs = Date.now();const records = [exec, ...Object.values(exec.perApp || {})];for (const rec of records) {- const parkedUntilMs = rec?.parkedUntil ? new Date(rec.parkedUntil).getTime() : 0;- if (parkedUntilMs > nowMs) {+ if (parkedUntilMs(rec) > nowMs) {rec.parkedUntil = await computePerpetualRecheckAt(merged);}}@@ -900,6 +899,86 @@ export async function computePerpetualRecheckAt(interval, fromMs = Date.now()) {return new Date(fromMs + ms).toISOString();}+/**+ * Numeric ms of a record's perpetual park, or 0 when it carries none (or an+ * unparseable timestamp). The single reader of `parkedUntil` — every park+ * comparison in this file goes through it so "parked" can't mean two things.+ */+function parkedUntilMs(record) {+ if (!record?.parkedUntil) return 0;+ const ms = new Date(record.parkedUntil).getTime();+ return Number.isFinite(ms) ? ms : 0;+}++/**+ * Roll a perpetual task's park records up into ONE aggregate that every+ * per-app-park consumer projects from (getUpcomingTasks eligibility and the+ * getScheduleStatus UI block).+ *+ * GLOBAL-RECORD INCLUSION RULE (documented once, here, so the callers can't+ * diverge): every `perApp` record is a tracked scope; the top-level execution+ * record is a tracked scope ONLY when it carries its OWN `parkedUntil`.+ * Rationale — perpetual parks are recorded PER-APP (parkPerpetual is always+ * called with an appId for the shipped app-scoped drains: claim-issue,+ * claim-work, branch-/issue-reconcile), so for those the top-level record is+ * just a container and must not be mistaken for a scope that is "due now".+ * A future global-park perpetual (none ship today) stamps its own `parkedUntil`+ * and is then folded in like any other scope.+ *+ * Returns:+ * trackedAppCount per-app records (the UI's "N app(s)" denominator)+ * trackedCount tracked scopes total (per-app + an own-parked global)+ * parkedAppCount per-app records still parked in the future+ * globalParked the top-level record carries a park that hasn't elapsed+ * soonestParkAt ms of the earliest un-elapsed park, or null when none+ * anyDueNow some tracked scope is unparked or its park has elapsed+ * parkReason first parked app's reason, else the parked global's+ */+function aggregatePerpetualParks(execution, now) {+ const appRecords = Object.values(execution?.perApp || {});+ const globalUntil = parkedUntilMs(execution);+ const globalTracked = globalUntil > 0;+ const globalParked = globalUntil > now;++ let parkedAppCount = 0;+ let anyDueNow = false;+ let soonestParkAt = null;+ // The FIRST parked app in iteration order, not the first one that happens to+ // carry a reason — the UI names the app it counted first, so a reasonless park+ // must read as "no reason" rather than borrowing the next app's.+ let firstParkedApp = null;++ for (const rec of appRecords) {+ const until = parkedUntilMs(rec);+ // Unparked (mid-drain) or park already elapsed → this scope is due now.+ if (until <= now) {+ anyDueNow = true;+ continue;+ }+ parkedAppCount++;+ if (firstParkedApp === null) firstParkedApp = rec;+ if (soonestParkAt === null || until < soonestParkAt) soonestParkAt = until;+ }++ if (globalTracked) {+ if (globalParked) {+ if (soonestParkAt === null || globalUntil < soonestParkAt) soonestParkAt = globalUntil;+ } else {+ anyDueNow = true;+ }+ }++ return {+ trackedAppCount: appRecords.length,+ trackedCount: appRecords.length + (globalTracked ? 1 : 0),+ parkedAppCount,+ globalParked,+ soonestParkAt,+ anyDueNow,+ parkReason: firstParkedApp?.parkReason || (globalParked ? execution.parkReason : null) || null+ };+}+/*** The park record lives ALONGSIDE the execution record (global or per-app), so a* perpetual task's "parked until" survives restarts the same way `lastRun` does.@@ -1433,19 +1512,17 @@ export async function shouldRunTask(taskType, appId = null) {// I/O even though it's called several times per evaluation cycle. While// parked, the recheck cadence (parkedUntil) gates re-probing; once it// elapses the task becomes due again and the gate re-runs the detector.- const parkedUntilMs = appExecution.parkedUntil- ? new Date(appExecution.parkedUntil).getTime()- : 0;- if (parkedUntilMs && now < parkedUntilMs) {+ const parkUntil = parkedUntilMs(appExecution);+ if (parkUntil && now < parkUntil) {result = {shouldRun: false,reason: 'perpetual-parked',- nextRunAt: new Date(parkedUntilMs).toISOString(),+ nextRunAt: new Date(parkUntil).toISOString(),parkReason: appExecution.parkReason || null,parkActionableCount: appExecution.parkActionableCount ?? null};} else {- result = { shouldRun: true, reason: parkedUntilMs ? 'perpetual-recheck' : 'perpetual-drain' };+ result = { shouldRun: true, reason: parkUntil ? 'perpetual-recheck' : 'perpetual-drain' };}break;}@@ -1783,22 +1860,16 @@ export async function getScheduleStatus() {// 'perpetual-drain' for app-scoped tasks like claim-issue/claim-work even// when every app is parked. Aggregate the per-app (and global) park records// so the UI can show the true parked/draining state and the soonest recheck.+ // Projects the shared aggregatePerpetualParks rollup (same park semantics as+ // the getUpcomingTasks eligibility derivation below).if (interval.type === INTERVAL_TYPES.PERPETUAL) {- const nowMs = Date.now();- const isParked = (r) => !!(r?.parkedUntil && new Date(r.parkedUntil).getTime() > nowMs);- const perAppEntries = Object.values(execution.perApp || {});- const parkedApps = perAppEntries.filter(isParked);- const globalParked = isParked(execution);- const nextRecheckAt = [- ...parkedApps.map((r) => r.parkedUntil),- ...(globalParked ? [execution.parkedUntil] : [])- ].filter(Boolean).sort()[0] || null;+ const parks = aggregatePerpetualParks(execution, Date.now());taskStatus.perpetual = {- globalParked,- parkedAppCount: parkedApps.length,- trackedAppCount: perAppEntries.length,- nextRecheckAt,- parkReason: parkedApps[0]?.parkReason || (globalParked ? execution.parkReason : null) || null+ globalParked: parks.globalParked,+ parkedAppCount: parks.parkedAppCount,+ trackedAppCount: parks.trackedAppCount,+ nextRecheckAt: parks.soonestParkAt === null ? null : new Date(parks.soonestParkAt).toISOString(),+ parkReason: parks.parkReason};}@@ -1857,25 +1928,18 @@ export async function resetExecutionHistory(taskType, appId = null) {* drain only resumed on the ≤1h fallback poll, so a task configured for 9am ran* up to an hour late (or read as "didn't run").*- * Derive eligibility from the per-app records instead — plus the top-level record- * only when it carries its OWN park (a future global-park perpetual; none ship- * today, but keep it general). Returns:+ * Derive eligibility from the shared aggregatePerpetualParks rollup instead (see+ * its GLOBAL-RECORD INCLUSION RULE for which scopes count). Returns:* - null → no tracked scope yet (caller keeps its global 'ready' default)* - { status:'ready', eligibleAt:now } → some tracked scope is due now (unparked or park elapsed)* - { status:'scheduled', eligibleAt:<ms> } → every tracked scope parked; soonest recheck*/function perpetualUpcomingEligibility(execution, now) {- const scopes = Object.values(execution?.perApp || {});- if (execution?.parkedUntil) scopes.push(execution);- if (scopes.length === 0) return null;- let soonest = Infinity;- for (const rec of scopes) {- const until = rec?.parkedUntil ? new Date(rec.parkedUntil).getTime() : 0;- // Unparked (mid-drain) or park already elapsed → this scope is due now.- if (!until || until <= now) return { status: 'ready', eligibleAt: now };- if (until < soonest) soonest = until;- }- return { status: 'scheduled', eligibleAt: soonest };+ const parks = aggregatePerpetualParks(execution, now);+ if (parks.trackedCount === 0) return null;+ return parks.anyDueNow+ ? { status: 'ready', eligibleAt: now }+ : { status: 'scheduled', eligibleAt: parks.soonestParkAt };}export async function getUpcomingTasks(limit = 10) {diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex bd923e3a13..113ec3867a 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -1910,5 +1910,100 @@ describe('taskSchedule', () => {expect(p).toMatchObject({ parkedAppCount: 1, trackedAppCount: 2, globalParked: false, nextRecheckAt: future, parkReason: 'no-actionable-issues' })})})++ // getScheduleStatus (UI rollup) and getUpcomingTasks (daemon wake-up) both+ // project the shared aggregatePerpetualParks rollup. These fixtures pin them+ // to the SAME park semantics — including the global-record inclusion rule+ // the two used to disagree on (status only ever folded in a global park that+ // hadn't elapsed; eligibility folded in any global record carrying a park).+ describe('perpetual park aggregate — getScheduleStatus and getUpcomingTasks agree', () => {+ const perpetualOf = async (taskType = 'claim-issue') =>+ (await getScheduleStatus()).tasks[taskType].perpetual+ const upcomingOf = async (taskType = 'claim-issue') =>+ (await getUpcomingTasks(50)).find(t => t.taskType === taskType)++ it('every app parked: the status nextRecheckAt IS the upcoming eligibleAt', async () => {+ const soon = new Date(Date.now() + 30 * 60 * 1000).toISOString()+ const later = new Date(Date.now() + 6 * 60 * 60 * 1000).toISOString()+ mockSchedule({+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {+ 'app-1': { lastRun: null, count: 0, parkedUntil: later, parkReason: 'no-actionable-issues' },+ 'app-2': { lastRun: null, count: 0, parkedUntil: soon, parkReason: 'no-progress' }+ } } }+ })+ const p = await perpetualOf()+ const claim = await upcomingOf()+ expect(p).toMatchObject({ parkedAppCount: 2, trackedAppCount: 2, globalParked: false, nextRecheckAt: soon })+ expect(claim.status).toBe('scheduled')+ expect(new Date(claim.eligibleAt).toISOString()).toBe(p.nextRecheckAt)+ })++ it('an ELAPSED app park counts as due for both: ready upcoming, not parked in status', async () => {+ const past = new Date(Date.now() - 60 * 1000).toISOString()+ const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()+ mockSchedule({+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {+ 'app-1': { lastRun: null, count: 0, parkedUntil: past, parkReason: 'stale' },+ 'app-2': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-actionable-issues' }+ } } }+ })+ const p = await perpetualOf()+ const claim = await upcomingOf()+ expect(p).toMatchObject({ parkedAppCount: 1, trackedAppCount: 2, nextRecheckAt: future, parkReason: 'no-actionable-issues' })+ expect(claim.status).toBe('ready')+ })++ it('an own-parked GLOBAL record (no per-app) is a tracked scope for both', async () => {+ const future = new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()+ mockSchedule({+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future, parkReason: 'no-actionable-issues' } }+ })+ const p = await perpetualOf()+ const claim = await upcomingOf()+ expect(p).toMatchObject({ globalParked: true, parkedAppCount: 0, trackedAppCount: 0, nextRecheckAt: future, parkReason: 'no-actionable-issues' })+ expect(claim.status).toBe('scheduled')+ expect(new Date(claim.eligibleAt).toISOString()).toBe(p.nextRecheckAt)+ })++ it('an ELAPSED global park is due now for both (no lingering nextRecheckAt)', async () => {+ const past = new Date(Date.now() - 60 * 1000).toISOString()+ mockSchedule({+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: past, parkReason: 'no-actionable-issues' } }+ })+ const p = await perpetualOf()+ const claim = await upcomingOf()+ expect(p).toMatchObject({ globalParked: false, nextRecheckAt: null, parkReason: null })+ expect(claim.status).toBe('ready')+ })++ it('a global park is folded in alongside per-app parks when it is the soonest', async () => {+ const globalPark = new Date(Date.now() + 10 * 60 * 1000).toISOString()+ const appPark = new Date(Date.now() + 60 * 60 * 1000).toISOString()+ mockSchedule({+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },+ executions: { 'task:claim-issue': { lastRun: null, count: 0, parkedUntil: globalPark, parkReason: 'global-idle', perApp: {+ 'app-1': { lastRun: null, count: 0, parkedUntil: appPark, parkReason: 'no-actionable-issues' }+ } } }+ })+ const p = await perpetualOf()+ const claim = await upcomingOf()+ // parkReason still prefers the first parked APP over the global one.+ expect(p).toMatchObject({ globalParked: true, parkedAppCount: 1, trackedAppCount: 1, nextRecheckAt: globalPark, parkReason: 'no-actionable-issues' })+ expect(claim.status).toBe('scheduled')+ expect(new Date(claim.eligibleAt).toISOString()).toBe(p.nextRecheckAt)+ })++ it('no tracked scope at all: status reports nothing parked and upcoming stays ready', async () => {+ mockSchedule({ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } } })+ const p = await perpetualOf()+ const claim = await upcomingOf()+ expect(p).toMatchObject({ globalParked: false, parkedAppCount: 0, trackedAppCount: 0, nextRecheckAt: null, parkReason: null })+ expect(claim.status).toBe('ready')+ })+ })})})