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

feat: index cached CoS tasks for targeted lookups

[._.]/ Adam Eivye85ce7a2a53b
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsx
index 8200c38338..4190324c29 100644
--- a/client/src/components/cos/tabs/ConfigTab.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.jsx
@@ -528,6 +528,7 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r
</div>
<div className="rounded-lg border border-port-border bg-port-card p-4">
<h5 className="text-sm font-medium text-port-text">Task files</h5>
+ <p className="mt-1 text-xs text-port-text-muted">Editable Markdown queues. Changes made in these files are picked up automatically.</p>
<div className="mt-3 space-y-2 text-xs">
<div className="flex items-center gap-2 rounded-md bg-port-bg px-3 py-2">
<FileText size={14} className="text-port-text-muted" />
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 5e720c7c85..02956ae22e 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -54,6 +54,8 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
**When to use.** The payload is long externally-editable prose; the domain syncs through iCloud/file-sync outside PortOS; or forcing the record through the app DB would break an existing sync boundary.
+**CoS task queues** (`data/TASKS.md`, `data/COS-TASKS.md`, or configured paths) remain file-primary because direct Markdown editing and watcher-driven updates are supported inputs. `cosTaskStore.js` caches parsed snapshots by file stamp and lazily indexes task IDs; single-task reads clone only the matching record, without grouping or copying either backlog. Store writes invalidate the snapshot and index together; external changes are detected on the next read. This optimization changes no persisted format, config key, or peer payload, so existing installs upgrade without an import or migration. PostgreSQL would permit per-row writes, but a future migration must explicitly replace the direct-edit/watch contract, import both configured sources without losing task metadata/order, and retain recovery copies before switching authority. Merely storing the complete Markdown blob in PostgreSQL would retain whole-queue parsing and rewriting.
+
**Where it lives.** Filesystem under `./data/` (or an OS-managed sync container). DB may hold metadata/index rows (hashes, word counts, segment indexes) but **not** the body.
**Examples.**
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 666492d61b..35cecd4009 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -135,7 +135,7 @@ function isContentEdit(updates, existingMetadata = {}) {
// 2. Every write through `writeTaskFile` DROPS the entry outright. mtime can
// be as coarse as one second on some filesystems, so a write-then-read in
// the same tick must not depend on the stamp having moved.
-const parsedTaskCache = new Map(); // filePath -> { stamp, tasks }
+const parsedTaskCache = new Map(); // filePath -> { stamp, tasks, byId? }
// `null` = could not stat (missing/unreadable) → do not cache, distinct from a
// legitimately empty file, which stamps normally and caches its empty parse.
@@ -144,24 +144,35 @@ const taskFileStamp = async (filePath) => {
return stats ? `${stats.mtimeMs}:${stats.size}` : null;
};
-/**
- * Read + parse a task markdown file, serving the cached parse when the file is
- * unchanged on disk.
- *
- * Always returns a DEEP COPY. Callers (`addTask`, `updateTask`, `reorderTasks`,
- * the sweeps) mutate both the array and the task objects in place; handing out
- * the cached originals would let one caller's in-flight edits leak into every
- * later reader — including edits that were never persisted.
- */
-async function readTaskFile(filePath) {
+// Private snapshots never leave this module: list readers clone the array,
+// while ID lookups clone only the matching task. Both share invalidation.
+async function readTaskSnapshot(filePath) {
const stamp = await taskFileStamp(filePath);
const cached = parsedTaskCache.get(filePath);
- if (stamp && cached?.stamp === stamp) return structuredClone(cached.tasks);
+ if (stamp && cached?.stamp === stamp) return cached;
- const tasks = parseTasksMarkdown(await readFile(filePath, 'utf-8'));
- if (stamp) parsedTaskCache.set(filePath, { stamp, tasks });
+ const snapshot = { stamp, tasks: parseTasksMarkdown(await readFile(filePath, 'utf-8')) };
+ if (stamp) parsedTaskCache.set(filePath, snapshot);
else parsedTaskCache.delete(filePath);
- return structuredClone(tasks);
+ return snapshot;
+}
+
+async function readTaskFile(filePath) {
+ return structuredClone((await readTaskSnapshot(filePath)).tasks);
+}
+
+async function findTaskInFile(filePath, taskId) {
+ if (!existsSync(filePath)) return null;
+ const snapshot = await readTaskSnapshot(filePath);
+ if (!snapshot.byId) {
+ snapshot.byId = new Map();
+ for (const task of snapshot.tasks) {
+ // Preserve Array.find's first-match behavior for hand-edited duplicate IDs.
+ if (!snapshot.byId.has(task.id)) snapshot.byId.set(task.id, task);
+ }
+ }
+ const task = snapshot.byId.get(taskId);
+ return task ? structuredClone(task) : null;
}
/**
@@ -231,19 +242,14 @@ export const getTasks = getUserTasks;
* Get a specific task by ID from any task source
*/
export async function getTaskById(taskId) {
- const { user: userTasks, cos: cosTasks } = await getAllTasks();
-
- // Search user tasks
- const userTask = userTasks.tasks?.find(t => t.id === taskId);
- if (userTask) {
- return { ...userTask, taskType: 'user' };
- }
-
- // Search CoS internal tasks
- const cosTask = cosTasks.tasks?.find(t => t.id === taskId);
- if (cosTask) {
- return { ...cosTask, taskType: 'internal' };
- }
+ const { config } = await loadState();
+ // Keep user-first precedence, including legacy/custom IDs. Do not infer the
+ // source from a prefix or prepare grouped copies of both queues for one ID.
+ const userTask = await findTaskInFile(join(ROOT_DIR, config.userTasksFile), taskId);
+ if (userTask) return { ...userTask, taskType: 'user' };
+
+ const cosTask = await findTaskInFile(join(ROOT_DIR, config.cosTasksFile), taskId);
+ if (cosTask) return { ...cosTask, taskType: 'internal' };
return null;
}
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 3f7a0a5a95..2ce6ac9922 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -308,6 +308,45 @@ describe('cosTaskStore.getAllTasks / getTasks / getTaskById', () => {
expect(found.taskType).toBe('internal');
});
+ it('looks up one task without cloning either backlog, and isolates returned metadata', async () => {
+ const { generateTasksMarkdown } = await import('../lib/taskParser.js');
+ const tasks = Array.from({ length: 1000 }, (_, index) => ({
+ id: `task-${index}`, description: `Example task ${index}`, status: 'pending',
+ priority: 'MEDIUM', metadata: { prompt: 'Example prompt', reviewers: ['codex'] }
+ }));
+ mock.files.set(USER_FILE, generateTasksMarkdown(tasks));
+ const clone = vi.spyOn(globalThis, 'structuredClone');
+ const found = await getTaskById('task-999');
+ expect(clone.mock.calls.map(([value]) => value.id)).toEqual(['task-999']);
+ clone.mockRestore();
+ found.metadata.reviewers.push('changed');
+ expect((await getTaskById('task-999')).metadata.reviewers).toEqual(['codex']);
+ expect(mock.parseCalls).toBe(1);
+ });
+
+ it('preserves user-first and first-duplicate precedence with custom paths and IDs', async () => {
+ mock.state.config = { userTasksFile: 'custom/user.md', cosTasksFile: 'custom/system.md' };
+ const { generateTasksMarkdown } = await import('../lib/taskParser.js');
+ const task = { id: 'sys-legacy', description: 'first', status: 'pending', priority: 'HIGH', metadata: {} };
+ mock.files.set(join('/root', 'custom/user.md'), generateTasksMarkdown([task, { ...task, description: 'duplicate' }]));
+ mock.files.set(join('/root', 'custom/system.md'), generateTasksMarkdown([{ ...task, description: 'internal' }]));
+ expect(await getTaskById(task.id)).toMatchObject({ description: 'first', taskType: 'user' });
+ mock.files.delete(join('/root', 'custom/user.md'));
+ expect(await getTaskById(task.id)).toMatchObject({ description: 'internal', taskType: 'internal' });
+ });
+
+ it('invalidates the ID index after store mutations, external edits, and deletion', async () => {
+ await addTask({ id: 'task-index', description: 'before' }, 'user');
+ expect((await getTaskById('task-index')).description).toBe('before');
+ await updateTask('task-index', { description: 'after' }, 'user');
+ expect((await getTaskById('task-index')).description).toBe('after');
+ mock.files.set(USER_FILE, mock.files.get(USER_FILE).replace('after', 'external'));
+ mock.mtimes.set(USER_FILE, mock.mtimes.get(USER_FILE) + 5000);
+ expect((await getTaskById('task-index')).description).toBe('external');
+ await deleteTask('task-index', 'user');
+ expect(await getTaskById('task-index')).toBeNull();
+ });
+
it('getTaskById returns null when no source has the id', async () => {
expect(await getTaskById('nope')).toBeNull();
});
@@ -1444,9 +1483,9 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const STORE_SRC = realReadFileSync(join(__dirname, 'cosTaskStore.js'), 'utf-8');
describe('parsed-task cache — no bypass (source guards, #3497)', () => {
- // Everything outside the two cache accessors. Any fs call the rest of the
+ // Everything outside the cache accessors. Any fs call the rest of the
// module makes to the task files is a bypass by definition.
- const ACCESSOR_START = 'async function readTaskFile';
+ const ACCESSOR_START = 'async function readTaskSnapshot';
const ACCESSOR_END = '/** Test hook: forget every cached parse. */';
const outsideAccessors = (() => {
const start = STORE_SRC.indexOf(ACCESSOR_START);
@@ -1462,7 +1501,7 @@ describe('parsed-task cache — no bypass (source guards, #3497)', () => {
expect(outsideAccessors, `anchors "${ACCESSOR_START}" / "${ACCESSOR_END}" not found in order`).not.toBeNull();
});
- it('every task-file read goes through readTaskFile', () => {
+ it('every task-file read goes through the snapshot cache', () => {
// A read path calling readFile + parseTasksMarkdown directly still works,
// but pays the full parse the cache exists to avoid and skips the
// copy-on-read that keeps a caller's in-place mutations out of the cache.