Skip to content

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

review: merge over stored config (not effective), narrow lastRunAt race, robust PLAN.md Next Up insert (#2262)

Adam Eivybf3a56875400
diff --git a/server/services/apps.js b/server/services/apps.js
index d129b02331..43ca31c84b 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -440,17 +440,23 @@ export async function getAppLayeredIntelligenceConfig(id) {
/**
* Update an app's Layered Intelligence config. Shallow-merges `updates` over the
- * stored config (with `sources` merged one level deep) so a partial PATCH
- * doesn't wipe untouched fields. Returns the updated app, or null if unknown.
+ * *stored* config only (with `sources` merged one level deep) so a partial PATCH
+ * doesn't wipe untouched fields. We deliberately merge over the raw stored value,
+ * NOT the effective (defaults-filled) config — persisting the full default set to
+ * disk would freeze this install against future default changes (the config
+ * accessor's "adopt baseline on read" forward-compat property). Untouched fields
+ * stay absent and keep resolving to the shipped default via getEffectiveConfig.
+ * Returns the updated app, or null if unknown.
*/
export async function updateAppLayeredIntelligence(id, updates = {}) {
const app = await getAppById(id);
if (!app) return null;
- const { getEffectiveConfig } = await import('./layeredIntelligence.js');
- const current = getEffectiveConfig({ ...app, isPortos: id === PORTOS_APP_ID });
- const merged = { ...current, ...updates };
+ const stored = (app.layeredIntelligence && typeof app.layeredIntelligence === 'object' && !Array.isArray(app.layeredIntelligence))
+ ? app.layeredIntelligence
+ : {};
+ const merged = { ...stored, ...updates };
if (updates.sources && typeof updates.sources === 'object') {
- merged.sources = { ...current.sources, ...updates.sources };
+ merged.sources = { ...(stored.sources && typeof stored.sources === 'object' ? stored.sources : {}), ...updates.sources };
}
return updateApp(id, { layeredIntelligence: merged });
}
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.js
index d8c7b09985..ba67335985 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHandler.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.js
@@ -13,7 +13,7 @@
* bad app never aborts the whole sweep. Off by default (AI-provider policy).
*/
-import { PORTOS_APP_ID, getActiveApps, updateApp } from '../apps.js'
+import { PORTOS_APP_ID, getActiveApps, updateAppLayeredIntelligence } from '../apps.js'
import {
getEffectiveConfig,
buildPrompt,
@@ -209,10 +209,15 @@ function safeParse(text) {
}
}
-/** Persist per-app run bookkeeping (lastRunAt) — run cadence, not issue memory. */
+/**
+ * Persist per-app run bookkeeping (lastRunAt) — run cadence, not issue memory.
+ * Routes through updateAppLayeredIntelligence so the write RE-READS the current
+ * stored config and merges ONLY `lastRunAt` over it, rather than writing back the
+ * (possibly seconds-stale) snapshot captured at sweep start — so a user config
+ * edit made mid-sweep isn't clobbered by the run-bookkeeping write.
+ */
async function recordRun(app, config, now) {
- const li = { ...(app.layeredIntelligence || {}), lastRunAt: new Date(now).toISOString() }
- await updateApp(app.id, { layeredIntelligence: li }).catch((err) => {
+ await updateAppLayeredIntelligence(app.id, { lastRunAt: new Date(now).toISOString() }).catch((err) => {
console.error(`❌ Layered Intelligence: failed to record run for ${app.id}: ${err.message}`)
})
}
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
index 10c514a96b..9be24d69cb 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
@@ -6,7 +6,8 @@ const updateAppMock = vi.fn().mockResolvedValue({});
vi.mock('../apps.js', () => ({
PORTOS_APP_ID: 'portos-default',
getActiveApps: vi.fn().mockResolvedValue([]),
- updateApp: (...args) => updateAppMock(...args)
+ // recordRun routes lastRunAt bookkeeping through updateAppLayeredIntelligence.
+ updateAppLayeredIntelligence: (...args) => updateAppMock(...args)
}));
// resolveAppWorkTracker is async + shells out to git; stub per-test.
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index 1ad4977c75..d314e59cf8 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -79,7 +79,9 @@ export function defaultLayeredIntelligenceConfig(isPortos = false) {
export function getEffectiveConfig(app) {
const isPortos = !!app?.isPortos;
const base = defaultLayeredIntelligenceConfig(isPortos);
- const stored = (app && typeof app.layeredIntelligence === 'object' && app.layeredIntelligence) || {};
+ const stored = (app?.layeredIntelligence && typeof app.layeredIntelligence === 'object' && !Array.isArray(app.layeredIntelligence))
+ ? app.layeredIntelligence
+ : {};
const merged = { ...base, ...stored };
merged.sources = {
...base.sources,
@@ -452,9 +454,12 @@ export async function appendProposalToPlan({ repoPath, appName, slug, title, bod
await writeFile(planPath, content);
return { success: true, duplicate: false };
}
- if (existing.includes('## Next Up')) {
- // Insert right after the "## Next Up" heading line.
- const updated = existing.replace(/(##\s+Next Up\s*\n)/, `$1${item}\n`);
+ const nextUpRe = /(##\s+Next Up[^\n]*)(\n?)/;
+ if (nextUpRe.test(existing)) {
+ // Insert right after the "## Next Up" heading line, normalizing the heading's
+ // line ending first so a file that ENDS at `## Next Up` (no trailing newline)
+ // gets the item on its own line rather than a second section appended below.
+ const updated = existing.replace(nextUpRe, `$1\n${item}\n`);
await writeFile(planPath, updated.endsWith('\n') ? updated : `${updated}\n`);
return { success: true, duplicate: false };
}
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index a9d1ff2471..1c57af8de2 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -1,4 +1,7 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, readFile, writeFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
import {
defaultLayeredIntelligenceConfig,
getEffectiveConfig,
@@ -16,6 +19,7 @@ import {
trackerSupportsPause,
buildPrompt,
extractPlanSlugs,
+ appendProposalToPlan,
listForgeIssues,
listBlockingIssues,
fileProposalToForge,
@@ -331,6 +335,45 @@ describe('extractPlanSlugs', () => {
});
});
+describe('appendProposalToPlan', () => {
+ let dir;
+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'lil-plan-')); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ it('creates PLAN.md with a Next Up section when absent', async () => {
+ const res = await appendProposalToPlan({ repoPath: dir, appName: 'App', slug: 'add-x', title: 'Add X', body: 'do it' });
+ expect(res).toEqual({ success: true, duplicate: false });
+ const content = await readFile(join(dir, 'PLAN.md'), 'utf-8');
+ expect(content).toContain('# App — Development Plan');
+ expect(content).toContain('## Next Up');
+ expect(content).toContain('[lil-add-x]');
+ });
+
+ it('is a no-op (duplicate) when the slug tag already exists', async () => {
+ await writeFile(join(dir, 'PLAN.md'), '## Next Up\n- [ ] [lil-add-x] existing\n');
+ const res = await appendProposalToPlan({ repoPath: dir, appName: 'App', slug: 'add-x', title: 'Add X', body: 'b' });
+ expect(res.duplicate).toBe(true);
+ });
+
+ it('inserts under an existing Next Up heading that has NO trailing newline (no duplicate section)', async () => {
+ await writeFile(join(dir, 'PLAN.md'), '# Plan\n\n## Next Up'); // ends at heading, no newline
+ const res = await appendProposalToPlan({ repoPath: dir, appName: 'App', slug: 'add-x', title: 'Add X', body: 'b' });
+ expect(res.duplicate).toBe(false);
+ const content = await readFile(join(dir, 'PLAN.md'), 'utf-8');
+ // Exactly one Next Up section, item on its own line.
+ expect(content.match(/## Next Up/g)).toHaveLength(1);
+ expect(content).toContain('\n- [ ] [lil-add-x]');
+ });
+
+ it('appends a Next Up section when the file exists without one', async () => {
+ await writeFile(join(dir, 'PLAN.md'), '# Plan\n\nSome notes.\n');
+ await appendProposalToPlan({ repoPath: dir, appName: 'App', slug: 'add-x', title: 'Add X', body: 'b' });
+ const content = await readFile(join(dir, 'PLAN.md'), 'utf-8');
+ expect(content).toContain('## Next Up');
+ expect(content).toContain('[lil-add-x]');
+ });
+});
+
describe('forge I/O (injected exec)', () => {
it('listForgeIssues parses gh JSON and extracts slugs', async () => {
const exec = vi.fn().mockResolvedValue({