@agimon-ai/doompi-task 0.0.1-alpha.21 → 0.0.1-alpha.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,26 +1,21 @@
1
1
  # @agimon-ai/doompi-task
2
2
 
3
- **A task list that survives the conversation.**
3
+ A persistent, dependency-aware task graph for Pi, with an optional delegation bridge to DoomPi Team.
4
4
 
5
- This is a file-backed task graph, not a checklist copied into chat. Tasks have statuses and
6
- dependencies, can be handed to subagents, and remain authoritative after compaction rewrites
7
- the transcript. The agent can forget the prose; it does not get to forget the work.
5
+ Part of the [DoomPi distribution](https://www.npmjs.com/package/@agimon-ai/doompi).
8
6
 
9
- This is part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi). Most users get
10
- it with the distribution; install it directly when embedding the task graph in another Pi
11
- setup.
7
+ Task owns task records and `tasks.json`. Team owns agents and runs. Loading both lets Task delegate pending work through Team's protocol; it does not merge their persistence.
12
8
 
13
- ## Install
9
+ > **Alpha:** task and delegation contracts may change between releases.
14
10
 
15
- ```bash
16
- npm install @agimon-ai/doompi-task
17
- ```
11
+ ## Requirements
18
12
 
19
- ## How it loads
13
+ - Node.js 22.19.0 or newer
14
+ - Pi 0.84.2 and Pi TUI 0.84.2
20
15
 
21
- Task is a major-mode capability selected through `.doom/modes.yaml`. Fresh Doompi
22
- configuration enables it in both `minimal` and `copilot` so existing sessions keep the
23
- persistent task graph, while a custom major mode can omit the tool entirely:
16
+ ## Install
17
+
18
+ Add Task to a DoomPi layer:
24
19
 
25
20
  ```yaml
26
21
  layers:
@@ -33,29 +28,91 @@ majorMode:
33
28
  layers: [task]
34
29
  ```
35
30
 
36
- The bare package name follows its Pi manifest and selects the Doom adapter. That adapter
37
- connects the graph to the Doom TUI and team runtime.
31
+ For standalone Pi:
32
+
33
+ ```bash
34
+ pi install npm:@agimon-ai/doompi-task
35
+ ```
36
+
37
+ Task works without Team for local graph management. Add `@agimon-ai/doompi-team` to the same selected mode when `assign` and `cancel` should launch or control subagents.
38
+
39
+ ## Use the `task` tool
40
+
41
+ Supported actions are:
42
+
43
+ | Action | Purpose |
44
+ | ------------- | ------------------------------------------------------------------ |
45
+ | `upsert` | Create tasks or update status, metadata, dependencies, and details |
46
+ | `list`, `get` | Read the graph or one task |
47
+ | `delete` | Tombstone a task |
48
+ | `clear` | Close and reset a completed graph |
49
+ | `assign` | Delegate a pending, unblocked task through Team |
50
+ | `cancel` | Stop a delegated run and return its task to pending |
51
+
52
+ ```json
53
+ {
54
+ "action": "upsert",
55
+ "tasks": [
56
+ { "ref": "design", "subject": "Design the API" },
57
+ {
58
+ "subject": "Implement the API",
59
+ "blockedBy": ["design"]
60
+ }
61
+ ]
62
+ }
63
+ ```
64
+
65
+ The reducer enforces lifecycle transitions and rejects dependency cycles. A graph allows 15 non-deleted tasks by default; updates still apply when full, but new tasks are rejected until space is freed.
66
+
67
+ ## TUI
38
68
 
39
- ## What it does
69
+ Use `/tasks` or `SPC t t` to open the interactive task view. These surfaces require a TUI. The `task` tool remains available in headless sessions.
40
70
 
41
- - Stores tasks on disk instead of relying on transcript memory.
42
- - Enforces dependency and lifecycle transitions.
43
- - Shares one board with Doompi subagents.
44
- - Keeps delegation visible to the parent session.
45
- - Gives compaction an authoritative task snapshot to carry forward.
71
+ ## Storage and cleanup
46
72
 
47
- ## Leader
73
+ The default session-tree store is:
48
74
 
49
- `SPC t t` opens the task board.
75
+ ```text
76
+ ~/.pi/agent/doom-task/<session>/tasks.json
77
+ ```
78
+
79
+ Task is authoritative across transcript compaction because the graph is file-backed. This does not mean Task persists Team membership, intercom, or child-process state.
80
+
81
+ Defaults and overrides:
50
82
 
51
- ## Task limit
83
+ | Setting | Default |
84
+ | --------------------------------- | ----------------------------------- |
85
+ | `DOOM_TASK_MAX_TASKS` | 15 non-deleted tasks |
86
+ | `DOOM_TASK_STORE_TTL_MS` | 30 days |
87
+ | `DOOM_TASK_DELEGATION_TIMEOUT_MS` | 20 minutes |
88
+ | `DOOM_TASK_STORE` | Override the store root |
89
+ | `DOOM_TASK_COLLAPSE_KEY` | Override the task-view collapse key |
52
90
 
53
- A board allows 15 non-deleted tasks by default. Set `DOOM_TASK_MAX_TASKS` to a positive integer to change the limit. When the board is full, updates still apply, but new tasks are rejected until completed tasks are deleted.
91
+ Startup/reconciliation sweeps expired stores and repairs delegation records whose owning process is no longer live.
92
+
93
+ ## Task and Team together
94
+
95
+ Task sends a delegation request and records the resulting lifecycle on the task. Team discovers the selected agent, applies model/tool policy, owns the run, and returns completion or failure. Intercom and Team membership remain Team state; `tasks.json` remains Task state.
54
96
 
55
97
  ## Public API
56
98
 
57
- The package exports its task model, storage, tools, TUI, and Pi/Doom adapters through
58
- supported subpaths. See `package.json` for the complete list.
99
+ ```ts
100
+ import { detectCycle, isBlocked, TaskStore, taskExtension } from '@agimon-ai/doompi-task';
101
+ import type { Task, TaskStatus } from '@agimon-ai/doompi-task';
102
+ ```
103
+
104
+ Focused exports cover schemas, reducers, storage, invariants, delegation management, tool responses, and TUI selectors.
105
+
106
+ ## Development
107
+
108
+ ```bash
109
+ pnpm build
110
+ pnpm typecheck
111
+ pnpm test
112
+ pnpm lint
113
+ ```
114
+
115
+ Maintained by [Agimon](https://agimon.ai/about).
59
116
 
60
117
  ## License
61
118
 
@@ -1,2 +1,2 @@
1
- const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../telemetry/logSinkTelemetry.cjs"),n=require("../../services/store/processLiveness.cjs"),r=require("../../services/store/types.cjs"),i=require("./paths.cjs");let a=require("node:path");a=e.__toESM(a,1);let o=require("node:fs");o=e.__toESM(o,1);const s=`utf8`,c=`ENOENT`,l=`store.path`;function u(e){return new Promise(t=>setTimeout(t,e))}function d(e){if(!e||typeof e!=`object`)return r.emptyDocument();let t=e;if(!Array.isArray(t.tasks))return r.emptyDocument();let n=t.tasks.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`number`),i=n.reduce((e,t)=>Math.max(e,t.id),0);return{version:typeof t.version==`number`?t.version:1,rev:typeof t.rev==`number`?t.rev:0,nextId:typeof t.nextId==`number`&&t.nextId>i?t.nextId:i+1,tasks:n}}var f=class{storePath;cwd;env;cached=r.emptyDocument();lastKnownRev=-1;watcher;pollTimer;debounceTimer;checkInFlight;checkQueued=!1;watchGeneration=0;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;onCommitted;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.env=e.env??process.env,this.storePath=e.storePath??i.resolveStorePath(this.cwd,this.env),this.pollIntervalMs=e.pollIntervalMs??2e3,this.lockTimeoutMs=e.lockTimeoutMs??2e3,this.report=e.report,this.onCommitted=e.onCommitted}configureSession(e){this.env.DOOM_TASK_STORE?.trim()||(this.stopWatching(),this.storePath=i.resolveStorePath(this.cwd,this.env,e),this.cached=r.emptyDocument(),this.lastKnownRev=-1)}get snapshot(){return this.cached}read(){try{let e=o.default.readFileSync(this.storePath,s);this.cached=d(JSON.parse(e))}catch(e){e.code!==c&&this.report?.error(t.TASK_EVENT.storeReadFailed,e,{[l]:this.storePath}),this.cached=r.emptyDocument()}return this.lastKnownRev=this.cached.rev,this.cached}async readAsync(){return this.cached=await this.readDocumentAsync(),this.lastKnownRev=this.cached.rev,this.cached}async readDocumentAsync(){try{let e=await o.default.promises.readFile(this.storePath,s);return d(JSON.parse(e))}catch(e){return e.code!==c&&this.report?.error(t.TASK_EVENT.storeReadFailed,e,{[l]:this.storePath}),r.emptyDocument()}}async mutate(e){let t=await this.acquireLock(),n=(()=>{try{let t=this.read(),n=e(t);if(!n.document)return{result:{document:t,value:n.value}};let r=this.write(n.document);return{result:{document:r,value:n.value},notification:{previous:t,committed:r}}}finally{t()}})();return n.notification&&this.notifyCommitted(n.notification.previous,n.notification.committed),n.result}notifyCommitted(e,n){try{this.onCommitted?.(e,n)}catch(e){this.report?.error(t.TASK_EVENT.storeCommitListenerFailed,e,{[l]:this.storePath})}}write(e){let t={...e,version:1,rev:e.rev+1};o.default.mkdirSync(a.default.dirname(this.storePath),{recursive:!0});let n=i.tempPathFor(this.storePath);return o.default.writeFileSync(n,`${JSON.stringify(t,void 0,2)}\n`,s),o.default.renameSync(n,this.storePath),this.cached=t,this.lastKnownRev=t.rev,t}async acquireLock(){let e=i.lockPathFor(this.storePath);o.default.mkdirSync(a.default.dirname(this.storePath),{recursive:!0});let n=Date.now()+this.lockTimeoutMs;for(;;)try{let t=o.default.openSync(e,`wx`);return o.default.writeSync(t,JSON.stringify({pid:process.pid,time:Date.now()})),o.default.closeSync(t),()=>o.default.rmSync(e,{force:!0})}catch(r){if(r.code!==`EEXIST`)throw r;if(Date.now()>=n)return this.report?.warn(t.TASK_EVENT.storeLockTimeout,Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),{[l]:this.storePath}),()=>{};this.breakStaleLock(e),await u(10+Math.random()*60)}}breakStaleLock(e){try{let t=JSON.parse(o.default.readFileSync(e,s)),r=typeof t.time==`number`&&Date.now()-t.time>1e4,i=typeof t.pid==`number`&&!n.isProcessAlive(t.pid);return!r&&!i?!1:(o.default.unlinkSync(e),!0)}catch(n){return n.code!==c&&this.report?.warn(t.TASK_EVENT.storeLockBreakFailed,n,{[l]:e}),!1}}onExternalChange(e){return this.listeners.add(e),this.startWatching(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.stopWatching()}}startWatching(){if(this.watcher||this.pollTimer)return;this.watchGeneration+=1;let e=a.default.dirname(this.storePath),n=a.default.basename(this.storePath);try{o.default.mkdirSync(e,{recursive:!0}),this.watcher=o.default.watch(e,(e,t)=>{t&&t!==n||this.scheduleCheck()})}catch(e){this.report?.warn(t.TASK_EVENT.storeWatchFailed,e,{[l]:this.storePath})}this.pollTimer=setInterval(()=>this.queueChangeCheck(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.queueChangeCheck(),150),this.debounceTimer.unref?.()}queueChangeCheck(){if(this.checkInFlight){this.checkQueued=!0;return}let e=this.watchGeneration,t=(async()=>{do this.checkQueued=!1,await this.checkForChange(e);while(this.checkQueued&&e===this.watchGeneration)})().finally(()=>{this.checkInFlight===t&&(this.checkInFlight=void 0)});this.checkInFlight=t}async checkForChange(e){let n=this.lastKnownRev,r=await this.readDocumentAsync();if(e===this.watchGeneration){if(this.lastKnownRev!==n){this.checkQueued=!0;return}if(this.cached=r,this.lastKnownRev=r.rev,r.rev!==n)for(let e of this.listeners)try{e(r)}catch(e){this.report?.error(t.TASK_EVENT.storeListenerFailed,e,{[l]:this.storePath})}}}stopWatching(){this.watchGeneration+=1,this.checkQueued=!1,this.watcher?.close(),this.watcher=void 0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=void 0,clearTimeout(this.debounceTimer),this.debounceTimer=void 0}dispose(){this.listeners.clear(),this.stopWatching()}};exports.TaskStore=f;
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../telemetry/logSinkTelemetry.cjs"),n=require("../../services/store/processLiveness.cjs"),r=require("../../services/store/types.cjs"),i=require("../../services/store/invariants.cjs"),a=require("./paths.cjs");let o=require("node:path");o=e.__toESM(o,1);let s=require("node:fs");s=e.__toESM(s,1);const c=`utf8`,l=`ENOENT`,u=`store.path`;function d(e){return new Promise(t=>setTimeout(t,e))}function f(e){if(!e||typeof e!=`object`)return r.emptyDocument();let t=e;if(!Array.isArray(t.tasks))return r.emptyDocument();let n=i.canonicalizeTasks(t.tasks.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`number`)),a=n.reduce((e,t)=>Math.max(e,t.id),0);return{version:typeof t.version==`number`?t.version:1,rev:typeof t.rev==`number`?t.rev:0,nextId:typeof t.nextId==`number`&&t.nextId>a?t.nextId:a+1,tasks:n}}var p=class{storePath;cwd;env;cached=r.emptyDocument();lastKnownRev=-1;watcher;pollTimer;debounceTimer;checkInFlight;checkQueued=!1;watchGeneration=0;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;onCommitted;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.env=e.env??process.env,this.storePath=e.storePath??a.resolveStorePath(this.cwd,this.env),this.pollIntervalMs=e.pollIntervalMs??2e3,this.lockTimeoutMs=e.lockTimeoutMs??2e3,this.report=e.report,this.onCommitted=e.onCommitted}configureSession(e){this.env.DOOM_TASK_STORE?.trim()||(this.stopWatching(),this.storePath=a.resolveStorePath(this.cwd,this.env,e),this.cached=r.emptyDocument(),this.lastKnownRev=-1)}get snapshot(){return this.cached}read(){try{let e=s.default.readFileSync(this.storePath,c);this.cached=f(JSON.parse(e))}catch(e){e.code!==l&&this.report?.error(t.TASK_EVENT.storeReadFailed,e,{[u]:this.storePath}),this.cached=r.emptyDocument()}return this.lastKnownRev=this.cached.rev,this.cached}async readAsync(){return this.cached=await this.readDocumentAsync(),this.lastKnownRev=this.cached.rev,this.cached}async readDocumentAsync(){try{let e=await s.default.promises.readFile(this.storePath,c);return f(JSON.parse(e))}catch(e){return e.code!==l&&this.report?.error(t.TASK_EVENT.storeReadFailed,e,{[u]:this.storePath}),r.emptyDocument()}}async mutate(e){let t=await this.acquireLock(),n=(()=>{try{let t=this.read(),n=e(t);if(!n.document)return{result:{document:t,value:n.value}};let r=this.write(n.document);return{result:{document:r,value:n.value},notification:{previous:t,committed:r}}}finally{t()}})();return n.notification&&this.notifyCommitted(n.notification.previous,n.notification.committed),n.result}notifyCommitted(e,n){try{this.onCommitted?.(e,n)}catch(e){this.report?.error(t.TASK_EVENT.storeCommitListenerFailed,e,{[u]:this.storePath})}}write(e){let t={...e,version:1,rev:e.rev+1};s.default.mkdirSync(o.default.dirname(this.storePath),{recursive:!0});let n=a.tempPathFor(this.storePath);return s.default.writeFileSync(n,`${JSON.stringify(t,void 0,2)}\n`,c),s.default.renameSync(n,this.storePath),this.cached=t,this.lastKnownRev=t.rev,t}async acquireLock(){let e=a.lockPathFor(this.storePath);s.default.mkdirSync(o.default.dirname(this.storePath),{recursive:!0});let n=Date.now()+this.lockTimeoutMs;for(;;)try{let t=s.default.openSync(e,`wx`);return s.default.writeSync(t,JSON.stringify({pid:process.pid,time:Date.now()})),s.default.closeSync(t),()=>s.default.rmSync(e,{force:!0})}catch(r){if(r.code!==`EEXIST`)throw r;if(Date.now()>=n)return this.report?.warn(t.TASK_EVENT.storeLockTimeout,Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),{[u]:this.storePath}),()=>{};this.breakStaleLock(e),await d(10+Math.random()*60)}}breakStaleLock(e){try{let t=JSON.parse(s.default.readFileSync(e,c)),r=typeof t.time==`number`&&Date.now()-t.time>1e4,i=typeof t.pid==`number`&&!n.isProcessAlive(t.pid);return!r&&!i?!1:(s.default.unlinkSync(e),!0)}catch(n){return n.code!==l&&this.report?.warn(t.TASK_EVENT.storeLockBreakFailed,n,{[u]:e}),!1}}onExternalChange(e){return this.listeners.add(e),this.startWatching(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.stopWatching()}}startWatching(){if(this.watcher||this.pollTimer)return;this.watchGeneration+=1;let e=o.default.dirname(this.storePath),n=o.default.basename(this.storePath);try{s.default.mkdirSync(e,{recursive:!0}),this.watcher=s.default.watch(e,(e,t)=>{t&&t!==n||this.scheduleCheck()})}catch(e){this.report?.warn(t.TASK_EVENT.storeWatchFailed,e,{[u]:this.storePath})}this.pollTimer=setInterval(()=>this.queueChangeCheck(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.queueChangeCheck(),150),this.debounceTimer.unref?.()}queueChangeCheck(){if(this.checkInFlight){this.checkQueued=!0;return}let e=this.watchGeneration,t=(async()=>{do this.checkQueued=!1,await this.checkForChange(e);while(this.checkQueued&&e===this.watchGeneration)})().finally(()=>{this.checkInFlight===t&&(this.checkInFlight=void 0)});this.checkInFlight=t}async checkForChange(e){let n=this.lastKnownRev,r=await this.readDocumentAsync();if(e===this.watchGeneration){if(this.lastKnownRev!==n){this.checkQueued=!0;return}if(this.cached=r,this.lastKnownRev=r.rev,r.rev!==n)for(let e of this.listeners)try{e(r)}catch(e){this.report?.error(t.TASK_EVENT.storeListenerFailed,e,{[u]:this.storePath})}}}stopWatching(){this.watchGeneration+=1,this.checkQueued=!1,this.watcher?.close(),this.watcher=void 0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=void 0,clearTimeout(this.debounceTimer),this.debounceTimer=void 0}dispose(){this.listeners.clear(),this.stopWatching()}};exports.TaskStore=p;
2
2
  //# sourceMappingURL=taskStore.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"taskStore.cjs","names":["emptyDocument","resolveStorePath","fs","TASK_EVENT","path","tempPathFor","lockPathFor","isProcessAlive"],"sources":["../../../src/adapters/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { isProcessAlive } from '../../services/store/processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../services/store/types.ts';\nimport { TASK_EVENT, type TaskFailureReporter } from '../telemetry/logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.ts';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst WATCH_DEBOUNCE_MS = 150;\nconst POLL_INTERVAL_MS = 2000;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport type TaskStoreCommitListener = (previous: TaskDocument, committed: TaskDocument) => void;\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n onCommitted?: TaskStoreCommitListener;\n /** Backstop poll cadence for change detection. Lowered in tests so they do\n * not depend on `fs.watch`, whose delivery timing is platform-dependent. */\n pollIntervalMs?: number;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: NodeJS.ProcessEnv;\n private cached: TaskDocument = emptyDocument();\n private lastKnownRev = -1;\n private watcher?: fs.FSWatcher;\n private pollTimer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private checkInFlight?: Promise<void>;\n private checkQueued = false;\n private watchGeneration = 0;\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly pollIntervalMs: number;\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n private readonly onCommitted?: TaskStoreCommitListener;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n this.onCommitted = options.onCommitted;\n }\n\n /** Bind a default store to the current session tree before reading or watching it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.stopWatching();\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n this.lastKnownRev = -1;\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n async readAsync(): Promise<TaskDocument> {\n this.cached = await this.readDocumentAsync();\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n private async readDocumentAsync(): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(this.storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n return emptyDocument();\n }\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: { previous: current, committed },\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification.previous, outcome.notification.committed);\n }\n return outcome.result;\n }\n\n private notifyCommitted(previous: TaskDocument, committed: TaskDocument): void {\n try {\n this.onCommitted?.(previous, committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeCommitListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n this.lastKnownRev = next.rev;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Notify when another process changes the store.\n *\n * `fs.watch` alone is unreliable across the rename-based write (and on some\n * network filesystems), so a slow poll backs it up. Writes made by this\n * process are filtered out by revision so the UI does not redraw twice.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n this.startWatching();\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) this.stopWatching();\n };\n }\n\n private startWatching(): void {\n if (this.watcher || this.pollTimer) return;\n this.watchGeneration += 1;\n const directory = path.dirname(this.storePath);\n const fileName = path.basename(this.storePath);\n\n try {\n fs.mkdirSync(directory, { recursive: true });\n this.watcher = fs.watch(directory, (_event, changed) => {\n if (changed && changed !== fileName) return;\n this.scheduleCheck();\n });\n } catch (error) {\n // Polling still covers change detection, just more slowly.\n this.report?.warn(TASK_EVENT.storeWatchFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n\n this.pollTimer = setInterval(() => this.queueChangeCheck(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.queueChangeCheck(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private queueChangeCheck(): void {\n if (this.checkInFlight) {\n this.checkQueued = true;\n return;\n }\n const generation = this.watchGeneration;\n const execution = (async () => {\n do {\n this.checkQueued = false;\n await this.checkForChange(generation);\n } while (this.checkQueued && generation === this.watchGeneration);\n })().finally(() => {\n if (this.checkInFlight === execution) this.checkInFlight = undefined;\n });\n this.checkInFlight = execution;\n }\n\n private async checkForChange(generation: number): Promise<void> {\n const previousRev = this.lastKnownRev;\n const document = await this.readDocumentAsync();\n if (generation !== this.watchGeneration) return;\n if (this.lastKnownRev !== previousRev) {\n this.checkQueued = true;\n return;\n }\n this.cached = document;\n this.lastKnownRev = document.rev;\n if (document.rev === previousRev) return;\n for (const listener of this.listeners) {\n try {\n listener(document);\n } catch (error) {\n // This runs from a timer and from the fs.watch callback, so an\n // unguarded listener throw is an uncaught exception that takes the\n // harness down rather than a handled render failure.\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private stopWatching(): void {\n this.watchGeneration += 1;\n this.checkQueued = false;\n this.watcher?.close();\n this.watcher = undefined;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n dispose(): void {\n this.listeners.clear();\n this.stopWatching();\n }\n}\n"],"mappings":"wTAOA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAkB7B,SAAS,EAAM,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ChD,KAAK,UAAY,IAAA,GACjB,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,IAAA,EACvB,CAEA,SAAgB,CACd,KAAK,UAAU,MAAM,EACrB,KAAK,aAAa,CACpB,CACF"}
1
+ {"version":3,"file":"taskStore.cjs","names":["emptyDocument","canonicalizeTasks","resolveStorePath","fs","TASK_EVENT","path","tempPathFor","lockPathFor","isProcessAlive"],"sources":["../../../src/adapters/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { canonicalizeTasks } from '../../services/store/invariants.ts';\nimport { isProcessAlive } from '../../services/store/processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../services/store/types.ts';\nimport { TASK_EVENT, type TaskFailureReporter } from '../telemetry/logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.ts';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst WATCH_DEBOUNCE_MS = 150;\nconst POLL_INTERVAL_MS = 2000;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport type TaskStoreCommitListener = (previous: TaskDocument, committed: TaskDocument) => void;\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n onCommitted?: TaskStoreCommitListener;\n /** Backstop poll cadence for change detection. Lowered in tests so they do\n * not depend on `fs.watch`, whose delivery timing is platform-dependent. */\n pollIntervalMs?: number;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = canonicalizeTasks(\n candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n ),\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: NodeJS.ProcessEnv;\n private cached: TaskDocument = emptyDocument();\n private lastKnownRev = -1;\n private watcher?: fs.FSWatcher;\n private pollTimer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private checkInFlight?: Promise<void>;\n private checkQueued = false;\n private watchGeneration = 0;\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly pollIntervalMs: number;\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n private readonly onCommitted?: TaskStoreCommitListener;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n this.onCommitted = options.onCommitted;\n }\n\n /** Bind a default store to the current session tree before reading or watching it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.stopWatching();\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n this.lastKnownRev = -1;\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n async readAsync(): Promise<TaskDocument> {\n this.cached = await this.readDocumentAsync();\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n private async readDocumentAsync(): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(this.storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n return emptyDocument();\n }\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: { previous: current, committed },\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification.previous, outcome.notification.committed);\n }\n return outcome.result;\n }\n\n private notifyCommitted(previous: TaskDocument, committed: TaskDocument): void {\n try {\n this.onCommitted?.(previous, committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeCommitListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n this.lastKnownRev = next.rev;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Notify when another process changes the store.\n *\n * `fs.watch` alone is unreliable across the rename-based write (and on some\n * network filesystems), so a slow poll backs it up. Writes made by this\n * process are filtered out by revision so the UI does not redraw twice.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n this.startWatching();\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) this.stopWatching();\n };\n }\n\n private startWatching(): void {\n if (this.watcher || this.pollTimer) return;\n this.watchGeneration += 1;\n const directory = path.dirname(this.storePath);\n const fileName = path.basename(this.storePath);\n\n try {\n fs.mkdirSync(directory, { recursive: true });\n this.watcher = fs.watch(directory, (_event, changed) => {\n if (changed && changed !== fileName) return;\n this.scheduleCheck();\n });\n } catch (error) {\n // Polling still covers change detection, just more slowly.\n this.report?.warn(TASK_EVENT.storeWatchFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n\n this.pollTimer = setInterval(() => this.queueChangeCheck(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.queueChangeCheck(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private queueChangeCheck(): void {\n if (this.checkInFlight) {\n this.checkQueued = true;\n return;\n }\n const generation = this.watchGeneration;\n const execution = (async () => {\n do {\n this.checkQueued = false;\n await this.checkForChange(generation);\n } while (this.checkQueued && generation === this.watchGeneration);\n })().finally(() => {\n if (this.checkInFlight === execution) this.checkInFlight = undefined;\n });\n this.checkInFlight = execution;\n }\n\n private async checkForChange(generation: number): Promise<void> {\n const previousRev = this.lastKnownRev;\n const document = await this.readDocumentAsync();\n if (generation !== this.watchGeneration) return;\n if (this.lastKnownRev !== previousRev) {\n this.checkQueued = true;\n return;\n }\n this.cached = document;\n this.lastKnownRev = document.rev;\n if (document.rev === previousRev) return;\n for (const listener of this.listeners) {\n try {\n listener(document);\n } catch (error) {\n // This runs from a timer and from the fs.watch callback, so an\n // unguarded listener throw is an uncaught exception that takes the\n // harness down rather than a handled render failure.\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private stopWatching(): void {\n this.watchGeneration += 1;\n this.checkQueued = false;\n this.watcher?.close();\n this.watcher = undefined;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n dispose(): void {\n this.listeners.clear();\n this.stopWatching();\n }\n}\n"],"mappings":"yWAQA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAkB7B,SAAS,EAAM,EAA2B,CACxC,OAAO,IAAI,QAAS,GAAY,WAAW,EAAS,CAAE,CAAC,CACzD,CAQA,SAAS,EAAkB,EAA+B,CACxD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,CAEA,SAAgB,CACd,KAAK,UAAU,MAAM,EACrB,KAAK,aAAa,CACpB,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"taskStore.d.cts","names":[],"sources":["../../../src/adapters/store/taskStore.ts"],"mappings":";;;KAkBY,2BAA2B,UAAU,cAAc,WAAW;UAEzD;EACf;EACA,MAAM,OAAO;EACb;EACA,cAAc;;;EAGd;;EAEA;;EAEA,SAAS;;;;;;;;;;cAsCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAWrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;EAiBF,aAAa,QAAQ;UAMb;;;;;;;;EAmBR,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAwBpC;UAQA;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAqBA;UAMA;UAiBM;UAuBN;EAWR"}
1
+ {"version":3,"file":"taskStore.d.cts","names":[],"sources":["../../../src/adapters/store/taskStore.ts"],"mappings":";;;KAmBY,2BAA2B,UAAU,cAAc,WAAW;UAEzD;EACf;EACA,MAAM,OAAO;EACb;EACA,cAAc;;;EAGd;;EAEA;;EAEA,SAAS;;;;;;;;;;cAwCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAWrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;EAiBF,aAAa,QAAQ;UAMb;;;;;;;;EAmBR,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAwBpC;UAQA;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAqBA;UAMA;UAiBM;UAuBN;EAWR"}
@@ -1 +1 @@
1
- {"version":3,"file":"taskStore.d.mts","names":[],"sources":["../../../src/adapters/store/taskStore.ts"],"mappings":";;;KAkBY,2BAA2B,UAAU,cAAc,WAAW;UAEzD;EACf;EACA,MAAM,OAAO;EACb;EACA,cAAc;;;EAGd;;EAEA;;EAEA,SAAS;;;;;;;;;;cAsCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAWrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;EAiBF,aAAa,QAAQ;UAMb;;;;;;;;EAmBR,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAwBpC;UAQA;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAqBA;UAMA;UAiBM;UAuBN;EAWR"}
1
+ {"version":3,"file":"taskStore.d.mts","names":[],"sources":["../../../src/adapters/store/taskStore.ts"],"mappings":";;;KAmBY,2BAA2B,UAAU,cAAc,WAAW;UAEzD;EACf;EACA,MAAM,OAAO;EACb;EACA,cAAc;;;EAGd;;EAEA;;EAEA,SAAS;;;;;;;;;;cAwCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAWrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;EAiBF,aAAa,QAAQ;UAMb;;;;;;;;EAmBR,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAwBpC;UAQA;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAqBA;UAMA;UAiBM;UAuBN;EAWR"}
@@ -1,2 +1,2 @@
1
- import{TASK_EVENT as e}from"../telemetry/logSinkTelemetry.mjs";import{isProcessAlive as t}from"../../services/store/processLiveness.mjs";import{emptyDocument as n}from"../../services/store/types.mjs";import{lockPathFor as r,resolveStorePath as i,tempPathFor as a}from"./paths.mjs";import o from"node:path";import s from"node:fs";const c=`utf8`,l=`ENOENT`,u=`store.path`;function d(e){return new Promise(t=>setTimeout(t,e))}function f(e){if(!e||typeof e!=`object`)return n();let t=e;if(!Array.isArray(t.tasks))return n();let r=t.tasks.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`number`),i=r.reduce((e,t)=>Math.max(e,t.id),0);return{version:typeof t.version==`number`?t.version:1,rev:typeof t.rev==`number`?t.rev:0,nextId:typeof t.nextId==`number`&&t.nextId>i?t.nextId:i+1,tasks:r}}var p=class{storePath;cwd;env;cached=n();lastKnownRev=-1;watcher;pollTimer;debounceTimer;checkInFlight;checkQueued=!1;watchGeneration=0;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;onCommitted;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.env=e.env??process.env,this.storePath=e.storePath??i(this.cwd,this.env),this.pollIntervalMs=e.pollIntervalMs??2e3,this.lockTimeoutMs=e.lockTimeoutMs??2e3,this.report=e.report,this.onCommitted=e.onCommitted}configureSession(e){this.env.DOOM_TASK_STORE?.trim()||(this.stopWatching(),this.storePath=i(this.cwd,this.env,e),this.cached=n(),this.lastKnownRev=-1)}get snapshot(){return this.cached}read(){try{let e=s.readFileSync(this.storePath,c);this.cached=f(JSON.parse(e))}catch(t){t.code!==l&&this.report?.error(e.storeReadFailed,t,{[u]:this.storePath}),this.cached=n()}return this.lastKnownRev=this.cached.rev,this.cached}async readAsync(){return this.cached=await this.readDocumentAsync(),this.lastKnownRev=this.cached.rev,this.cached}async readDocumentAsync(){try{let e=await s.promises.readFile(this.storePath,c);return f(JSON.parse(e))}catch(t){return t.code!==l&&this.report?.error(e.storeReadFailed,t,{[u]:this.storePath}),n()}}async mutate(e){let t=await this.acquireLock(),n=(()=>{try{let t=this.read(),n=e(t);if(!n.document)return{result:{document:t,value:n.value}};let r=this.write(n.document);return{result:{document:r,value:n.value},notification:{previous:t,committed:r}}}finally{t()}})();return n.notification&&this.notifyCommitted(n.notification.previous,n.notification.committed),n.result}notifyCommitted(t,n){try{this.onCommitted?.(t,n)}catch(t){this.report?.error(e.storeCommitListenerFailed,t,{[u]:this.storePath})}}write(e){let t={...e,version:1,rev:e.rev+1};s.mkdirSync(o.dirname(this.storePath),{recursive:!0});let n=a(this.storePath);return s.writeFileSync(n,`${JSON.stringify(t,void 0,2)}\n`,c),s.renameSync(n,this.storePath),this.cached=t,this.lastKnownRev=t.rev,t}async acquireLock(){let t=r(this.storePath);s.mkdirSync(o.dirname(this.storePath),{recursive:!0});let n=Date.now()+this.lockTimeoutMs;for(;;)try{let e=s.openSync(t,`wx`);return s.writeSync(e,JSON.stringify({pid:process.pid,time:Date.now()})),s.closeSync(e),()=>s.rmSync(t,{force:!0})}catch(r){if(r.code!==`EEXIST`)throw r;if(Date.now()>=n)return this.report?.warn(e.storeLockTimeout,Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),{[u]:this.storePath}),()=>{};this.breakStaleLock(t),await d(10+Math.random()*60)}}breakStaleLock(n){try{let e=JSON.parse(s.readFileSync(n,c)),r=typeof e.time==`number`&&Date.now()-e.time>1e4,i=typeof e.pid==`number`&&!t(e.pid);return!r&&!i?!1:(s.unlinkSync(n),!0)}catch(t){return t.code!==l&&this.report?.warn(e.storeLockBreakFailed,t,{[u]:n}),!1}}onExternalChange(e){return this.listeners.add(e),this.startWatching(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.stopWatching()}}startWatching(){if(this.watcher||this.pollTimer)return;this.watchGeneration+=1;let t=o.dirname(this.storePath),n=o.basename(this.storePath);try{s.mkdirSync(t,{recursive:!0}),this.watcher=s.watch(t,(e,t)=>{t&&t!==n||this.scheduleCheck()})}catch(t){this.report?.warn(e.storeWatchFailed,t,{[u]:this.storePath})}this.pollTimer=setInterval(()=>this.queueChangeCheck(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.queueChangeCheck(),150),this.debounceTimer.unref?.()}queueChangeCheck(){if(this.checkInFlight){this.checkQueued=!0;return}let e=this.watchGeneration,t=(async()=>{do this.checkQueued=!1,await this.checkForChange(e);while(this.checkQueued&&e===this.watchGeneration)})().finally(()=>{this.checkInFlight===t&&(this.checkInFlight=void 0)});this.checkInFlight=t}async checkForChange(t){let n=this.lastKnownRev,r=await this.readDocumentAsync();if(t===this.watchGeneration){if(this.lastKnownRev!==n){this.checkQueued=!0;return}if(this.cached=r,this.lastKnownRev=r.rev,r.rev!==n)for(let t of this.listeners)try{t(r)}catch(t){this.report?.error(e.storeListenerFailed,t,{[u]:this.storePath})}}}stopWatching(){this.watchGeneration+=1,this.checkQueued=!1,this.watcher?.close(),this.watcher=void 0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=void 0,clearTimeout(this.debounceTimer),this.debounceTimer=void 0}dispose(){this.listeners.clear(),this.stopWatching()}};export{p as TaskStore};
1
+ import{TASK_EVENT as e}from"../telemetry/logSinkTelemetry.mjs";import{isProcessAlive as t}from"../../services/store/processLiveness.mjs";import{emptyDocument as n}from"../../services/store/types.mjs";import{canonicalizeTasks as r}from"../../services/store/invariants.mjs";import{lockPathFor as i,resolveStorePath as a,tempPathFor as o}from"./paths.mjs";import s from"node:path";import c from"node:fs";const l=`utf8`,u=`ENOENT`,d=`store.path`;function f(e){return new Promise(t=>setTimeout(t,e))}function p(e){if(!e||typeof e!=`object`)return n();let t=e;if(!Array.isArray(t.tasks))return n();let i=r(t.tasks.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`number`)),a=i.reduce((e,t)=>Math.max(e,t.id),0);return{version:typeof t.version==`number`?t.version:1,rev:typeof t.rev==`number`?t.rev:0,nextId:typeof t.nextId==`number`&&t.nextId>a?t.nextId:a+1,tasks:i}}var m=class{storePath;cwd;env;cached=n();lastKnownRev=-1;watcher;pollTimer;debounceTimer;checkInFlight;checkQueued=!1;watchGeneration=0;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;onCommitted;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.env=e.env??process.env,this.storePath=e.storePath??a(this.cwd,this.env),this.pollIntervalMs=e.pollIntervalMs??2e3,this.lockTimeoutMs=e.lockTimeoutMs??2e3,this.report=e.report,this.onCommitted=e.onCommitted}configureSession(e){this.env.DOOM_TASK_STORE?.trim()||(this.stopWatching(),this.storePath=a(this.cwd,this.env,e),this.cached=n(),this.lastKnownRev=-1)}get snapshot(){return this.cached}read(){try{let e=c.readFileSync(this.storePath,l);this.cached=p(JSON.parse(e))}catch(t){t.code!==u&&this.report?.error(e.storeReadFailed,t,{[d]:this.storePath}),this.cached=n()}return this.lastKnownRev=this.cached.rev,this.cached}async readAsync(){return this.cached=await this.readDocumentAsync(),this.lastKnownRev=this.cached.rev,this.cached}async readDocumentAsync(){try{let e=await c.promises.readFile(this.storePath,l);return p(JSON.parse(e))}catch(t){return t.code!==u&&this.report?.error(e.storeReadFailed,t,{[d]:this.storePath}),n()}}async mutate(e){let t=await this.acquireLock(),n=(()=>{try{let t=this.read(),n=e(t);if(!n.document)return{result:{document:t,value:n.value}};let r=this.write(n.document);return{result:{document:r,value:n.value},notification:{previous:t,committed:r}}}finally{t()}})();return n.notification&&this.notifyCommitted(n.notification.previous,n.notification.committed),n.result}notifyCommitted(t,n){try{this.onCommitted?.(t,n)}catch(t){this.report?.error(e.storeCommitListenerFailed,t,{[d]:this.storePath})}}write(e){let t={...e,version:1,rev:e.rev+1};c.mkdirSync(s.dirname(this.storePath),{recursive:!0});let n=o(this.storePath);return c.writeFileSync(n,`${JSON.stringify(t,void 0,2)}\n`,l),c.renameSync(n,this.storePath),this.cached=t,this.lastKnownRev=t.rev,t}async acquireLock(){let t=i(this.storePath);c.mkdirSync(s.dirname(this.storePath),{recursive:!0});let n=Date.now()+this.lockTimeoutMs;for(;;)try{let e=c.openSync(t,`wx`);return c.writeSync(e,JSON.stringify({pid:process.pid,time:Date.now()})),c.closeSync(e),()=>c.rmSync(t,{force:!0})}catch(r){if(r.code!==`EEXIST`)throw r;if(Date.now()>=n)return this.report?.warn(e.storeLockTimeout,Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),{[d]:this.storePath}),()=>{};this.breakStaleLock(t),await f(10+Math.random()*60)}}breakStaleLock(n){try{let e=JSON.parse(c.readFileSync(n,l)),r=typeof e.time==`number`&&Date.now()-e.time>1e4,i=typeof e.pid==`number`&&!t(e.pid);return!r&&!i?!1:(c.unlinkSync(n),!0)}catch(t){return t.code!==u&&this.report?.warn(e.storeLockBreakFailed,t,{[d]:n}),!1}}onExternalChange(e){return this.listeners.add(e),this.startWatching(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.stopWatching()}}startWatching(){if(this.watcher||this.pollTimer)return;this.watchGeneration+=1;let t=s.dirname(this.storePath),n=s.basename(this.storePath);try{c.mkdirSync(t,{recursive:!0}),this.watcher=c.watch(t,(e,t)=>{t&&t!==n||this.scheduleCheck()})}catch(t){this.report?.warn(e.storeWatchFailed,t,{[d]:this.storePath})}this.pollTimer=setInterval(()=>this.queueChangeCheck(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.queueChangeCheck(),150),this.debounceTimer.unref?.()}queueChangeCheck(){if(this.checkInFlight){this.checkQueued=!0;return}let e=this.watchGeneration,t=(async()=>{do this.checkQueued=!1,await this.checkForChange(e);while(this.checkQueued&&e===this.watchGeneration)})().finally(()=>{this.checkInFlight===t&&(this.checkInFlight=void 0)});this.checkInFlight=t}async checkForChange(t){let n=this.lastKnownRev,r=await this.readDocumentAsync();if(t===this.watchGeneration){if(this.lastKnownRev!==n){this.checkQueued=!0;return}if(this.cached=r,this.lastKnownRev=r.rev,r.rev!==n)for(let t of this.listeners)try{t(r)}catch(t){this.report?.error(e.storeListenerFailed,t,{[d]:this.storePath})}}}stopWatching(){this.watchGeneration+=1,this.checkQueued=!1,this.watcher?.close(),this.watcher=void 0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=void 0,clearTimeout(this.debounceTimer),this.debounceTimer=void 0}dispose(){this.listeners.clear(),this.stopWatching()}};export{m as TaskStore};
2
2
  //# sourceMappingURL=taskStore.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"taskStore.mjs","names":[],"sources":["../../../src/adapters/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { isProcessAlive } from '../../services/store/processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../services/store/types.ts';\nimport { TASK_EVENT, type TaskFailureReporter } from '../telemetry/logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.ts';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst WATCH_DEBOUNCE_MS = 150;\nconst POLL_INTERVAL_MS = 2000;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport type TaskStoreCommitListener = (previous: TaskDocument, committed: TaskDocument) => void;\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n onCommitted?: TaskStoreCommitListener;\n /** Backstop poll cadence for change detection. Lowered in tests so they do\n * not depend on `fs.watch`, whose delivery timing is platform-dependent. */\n pollIntervalMs?: number;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: NodeJS.ProcessEnv;\n private cached: TaskDocument = emptyDocument();\n private lastKnownRev = -1;\n private watcher?: fs.FSWatcher;\n private pollTimer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private checkInFlight?: Promise<void>;\n private checkQueued = false;\n private watchGeneration = 0;\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly pollIntervalMs: number;\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n private readonly onCommitted?: TaskStoreCommitListener;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n this.onCommitted = options.onCommitted;\n }\n\n /** Bind a default store to the current session tree before reading or watching it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.stopWatching();\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n this.lastKnownRev = -1;\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n async readAsync(): Promise<TaskDocument> {\n this.cached = await this.readDocumentAsync();\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n private async readDocumentAsync(): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(this.storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n return emptyDocument();\n }\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: { previous: current, committed },\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification.previous, outcome.notification.committed);\n }\n return outcome.result;\n }\n\n private notifyCommitted(previous: TaskDocument, committed: TaskDocument): void {\n try {\n this.onCommitted?.(previous, committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeCommitListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n this.lastKnownRev = next.rev;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Notify when another process changes the store.\n *\n * `fs.watch` alone is unreliable across the rename-based write (and on some\n * network filesystems), so a slow poll backs it up. Writes made by this\n * process are filtered out by revision so the UI does not redraw twice.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n this.startWatching();\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) this.stopWatching();\n };\n }\n\n private startWatching(): void {\n if (this.watcher || this.pollTimer) return;\n this.watchGeneration += 1;\n const directory = path.dirname(this.storePath);\n const fileName = path.basename(this.storePath);\n\n try {\n fs.mkdirSync(directory, { recursive: true });\n this.watcher = fs.watch(directory, (_event, changed) => {\n if (changed && changed !== fileName) return;\n this.scheduleCheck();\n });\n } catch (error) {\n // Polling still covers change detection, just more slowly.\n this.report?.warn(TASK_EVENT.storeWatchFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n\n this.pollTimer = setInterval(() => this.queueChangeCheck(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.queueChangeCheck(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private queueChangeCheck(): void {\n if (this.checkInFlight) {\n this.checkQueued = true;\n return;\n }\n const generation = this.watchGeneration;\n const execution = (async () => {\n do {\n this.checkQueued = false;\n await this.checkForChange(generation);\n } while (this.checkQueued && generation === this.watchGeneration);\n })().finally(() => {\n if (this.checkInFlight === execution) this.checkInFlight = undefined;\n });\n this.checkInFlight = execution;\n }\n\n private async checkForChange(generation: number): Promise<void> {\n const previousRev = this.lastKnownRev;\n const document = await this.readDocumentAsync();\n if (generation !== this.watchGeneration) return;\n if (this.lastKnownRev !== previousRev) {\n this.checkQueued = true;\n return;\n }\n this.cached = document;\n this.lastKnownRev = document.rev;\n if (document.rev === previousRev) return;\n for (const listener of this.listeners) {\n try {\n listener(document);\n } catch (error) {\n // This runs from a timer and from the fs.watch callback, so an\n // unguarded listener throw is an uncaught exception that takes the\n // harness down rather than a handled render failure.\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private stopWatching(): void {\n this.watchGeneration += 1;\n this.checkQueued = false;\n this.watcher?.close();\n this.watcher = undefined;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n dispose(): void {\n this.listeners.clear();\n this.stopWatching();\n }\n}\n"],"mappings":"yUAOA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAkB7B,SAAS,EAAM,EAA2B,CACxC,OAAO,IAAI,QAAS,GAAY,WAAW,EAAS,CAAE,CAAC,CACzD,CAQA,SAAS,EAAkB,EAA+B,CACxD,GAAI,CAAC,GAAU,OAAO,GAAW,SAA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K,cAAe,CACtB,KAAK,YAAc,GACnB,MACF,CACA,IAAM,EAAa,KAAK,gBAClB,GAAa,SAAY,CAC7B,EACE,MAAK,YAAc,GACnB,MAAM,KAAK,eAAe,CAAU,QAC7B,KAAK,aAAe,IAAe,KAAK,gBACnD,EAAA,CAAG,CAAC,CAAC,YAAc,CACb,KAAK,gBAAkB,IAAW,KAAK,cAAgB,IAAA,GAC7D,CAAC,EACD,KAAK,cAAgB,CACvB,CAEA,MAAc,eAAe,EAAmC,CAC9D,IAAM,EAAc,KAAK,aACnB,EAAW,MAAM,KAAK,kBAAkB,EAC1C,OAAe,KAAK,gBACxB,IAAI,KAAK,eAAiB,EAAa,CACrC,KAAK,YAAc,GACnB,MACF,CACA,QAAK,OAAS,EACd,KAAK,aAAe,EAAS,IACzB,EAAS,MAAQ,EACrB,IAAK,IAAM,KAAY,KAAK,UAC1B,GAAI,CACF,EAAS,CAAQ,CACnB,OAAS,EAAO,CAId,KAAK,QAAQ,MAAM,EAAW,oBAAqB,EAAO,EAAG,GAAuB,KAAK,SAAU,CAAC,CACtG,CAZF,CAcF,CAEA,cAA6B,CAC3B,KAAK,iBAAmB,EACxB,KAAK,YAAc,GACnB,KAAK,SAAS,MAAM,EACpB,KAAK,QAAU,IAAA,GACX,KAAK,WAAW,cAAc,KAAK,SAAS,EAChD,KAAK,UAAY,IAAA,GACjB,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,IAAA,EACvB,CAEA,SAAgB,CACd,KAAK,UAAU,MAAM,EACrB,KAAK,aAAa,CACpB,CACF"}
1
+ {"version":3,"file":"taskStore.mjs","names":[],"sources":["../../../src/adapters/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { canonicalizeTasks } from '../../services/store/invariants.ts';\nimport { isProcessAlive } from '../../services/store/processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../services/store/types.ts';\nimport { TASK_EVENT, type TaskFailureReporter } from '../telemetry/logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.ts';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst WATCH_DEBOUNCE_MS = 150;\nconst POLL_INTERVAL_MS = 2000;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport type TaskStoreCommitListener = (previous: TaskDocument, committed: TaskDocument) => void;\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n onCommitted?: TaskStoreCommitListener;\n /** Backstop poll cadence for change detection. Lowered in tests so they do\n * not depend on `fs.watch`, whose delivery timing is platform-dependent. */\n pollIntervalMs?: number;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = canonicalizeTasks(\n candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n ),\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: NodeJS.ProcessEnv;\n private cached: TaskDocument = emptyDocument();\n private lastKnownRev = -1;\n private watcher?: fs.FSWatcher;\n private pollTimer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private checkInFlight?: Promise<void>;\n private checkQueued = false;\n private watchGeneration = 0;\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly pollIntervalMs: number;\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n private readonly onCommitted?: TaskStoreCommitListener;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n this.onCommitted = options.onCommitted;\n }\n\n /** Bind a default store to the current session tree before reading or watching it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.stopWatching();\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n this.lastKnownRev = -1;\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n async readAsync(): Promise<TaskDocument> {\n this.cached = await this.readDocumentAsync();\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n private async readDocumentAsync(): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(this.storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n return emptyDocument();\n }\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: { previous: current, committed },\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification.previous, outcome.notification.committed);\n }\n return outcome.result;\n }\n\n private notifyCommitted(previous: TaskDocument, committed: TaskDocument): void {\n try {\n this.onCommitted?.(previous, committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeCommitListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n this.lastKnownRev = next.rev;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Notify when another process changes the store.\n *\n * `fs.watch` alone is unreliable across the rename-based write (and on some\n * network filesystems), so a slow poll backs it up. Writes made by this\n * process are filtered out by revision so the UI does not redraw twice.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n this.startWatching();\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) this.stopWatching();\n };\n }\n\n private startWatching(): void {\n if (this.watcher || this.pollTimer) return;\n this.watchGeneration += 1;\n const directory = path.dirname(this.storePath);\n const fileName = path.basename(this.storePath);\n\n try {\n fs.mkdirSync(directory, { recursive: true });\n this.watcher = fs.watch(directory, (_event, changed) => {\n if (changed && changed !== fileName) return;\n this.scheduleCheck();\n });\n } catch (error) {\n // Polling still covers change detection, just more slowly.\n this.report?.warn(TASK_EVENT.storeWatchFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n\n this.pollTimer = setInterval(() => this.queueChangeCheck(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.queueChangeCheck(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private queueChangeCheck(): void {\n if (this.checkInFlight) {\n this.checkQueued = true;\n return;\n }\n const generation = this.watchGeneration;\n const execution = (async () => {\n do {\n this.checkQueued = false;\n await this.checkForChange(generation);\n } while (this.checkQueued && generation === this.watchGeneration);\n })().finally(() => {\n if (this.checkInFlight === execution) this.checkInFlight = undefined;\n });\n this.checkInFlight = execution;\n }\n\n private async checkForChange(generation: number): Promise<void> {\n const previousRev = this.lastKnownRev;\n const document = await this.readDocumentAsync();\n if (generation !== this.watchGeneration) return;\n if (this.lastKnownRev !== previousRev) {\n this.checkQueued = true;\n return;\n }\n this.cached = document;\n this.lastKnownRev = document.rev;\n if (document.rev === previousRev) return;\n for (const listener of this.listeners) {\n try {\n listener(document);\n } catch (error) {\n // This runs from a timer and from the fs.watch callback, so an\n // unguarded listener throw is an uncaught exception that takes the\n // harness down rather than a handled render failure.\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private stopWatching(): void {\n this.watchGeneration += 1;\n this.checkQueued = false;\n this.watcher?.close();\n this.watcher = undefined;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n dispose(): void {\n this.listeners.clear();\n this.stopWatching();\n }\n}\n"],"mappings":"iZAQA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAkB7B,SAAS,EAAM,EAA2B,CACxC,OAAO,IAAI,QAAS,GAAY,WAAW,EAAS,CAAE,CAAC,CACzD,CAQA,SAAS,EAAkB,EAA+B,CACxD,GAAI,CAAC,GAAU,OAAO,GAAW,SAAU,OAAO,EAAc,EAChE,IAAM,EAAY,EAClB,GAAI,CAAC,MAAM,QAAQ,EAAU,KAAK,EAAG,OAAO,EAAc,EAE1D,IAAM,EAAQ,EACZ,EAAU,MAAM,OACb,GAAuB,EAAQ,GAAS,OAAO,GAAS,UAAY,OAAQ,EAAc,IAAO,QACpG,CACF,EACM,EAAQ,EAAM,QAAQ,EAAK,IAAS,KAAK,IAAI,EAAK,EAAK,EAAE,EAAG,CAAC,EACnE,MAAO,CACL,QAAS,OAAO,EAAU,SAAY,SAAW,EAAU,QAAA,EAC3D,IAAK,OAAO,EAAU,KAAQ,SAAW,EAAU,IAAM,EACzD,OAAQ,OAAO,EAAU,QAAW,UAAY,EAAU,OAAS,EAAQ,E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ACF,CACA,QAAK,OAAS,EACd,KAAK,aAAe,EAAS,IACzB,EAAS,MAAQ,EACrB,IAAK,IAAM,KAAY,KAAK,UAC1B,GAAI,CACF,EAAS,CAAQ,CACnB,OAAS,EAAO,CAId,KAAK,QAAQ,MAAM,EAAW,oBAAqB,EAAO,EAAG,GAAuB,KAAK,SAAU,CAAC,CACtG,CAZF,CAcF,CAEA,cAA6B,CAC3B,KAAK,iBAAmB,EACxB,KAAK,YAAc,GACnB,KAAK,SAAS,MAAM,EACpB,KAAK,QAAU,IAAA,GACX,KAAK,WAAW,cAAc,KAAK,SAAS,EAChD,KAAK,UAAY,IAAA,GACjB,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,IAAA,EACvB,CAEA,SAAgB,CACd,KAAK,UAAU,MAAM,EACrB,KAAK,aAAa,CACpB,CACF"}
@@ -1,2 +1,2 @@
1
- const e={pending:new Set([`in_progress`,`completed`,`failed`,`deleted`]),in_progress:new Set([`pending`,`completed`,`failed`,`deleted`]),failed:new Set([`pending`,`in_progress`,`completed`,`deleted`]),completed:new Set([`deleted`]),deleted:new Set};function t(t,n){return t===n||e[t].has(n)}exports.VALID_TRANSITIONS=e,exports.isTransitionValid=t;
1
+ function e(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.id);if(e===void 0){n.set(r.id,t.length),t.push(r);continue}let i=t[e];(!i.updatedAt||!r.updatedAt||r.updatedAt>=i.updatedAt)&&(t[e]=r)}return t}const t={pending:new Set([`in_progress`,`completed`,`failed`,`deleted`]),in_progress:new Set([`pending`,`completed`,`failed`,`deleted`]),failed:new Set([`pending`,`in_progress`,`completed`,`deleted`]),completed:new Set([`deleted`]),deleted:new Set};function n(e,n){return e===n||t[e].has(n)}exports.VALID_TRANSITIONS=t,exports.canonicalizeTasks=e,exports.isTransitionValid=n;
2
2
  //# sourceMappingURL=invariants.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"invariants.cjs","names":[],"sources":["../../../src/services/store/invariants.ts"],"sourcesContent":["import type { TaskStatus } from './types.ts';\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n completed: new Set<TaskStatus>(['deleted']),\n deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n if (from === to) return true;\n return VALID_TRANSITIONS[from].has(to);\n}\n"],"mappings":"AASA,MAAa,EAAiE,CAC5E,QAAS,IAAI,IAAgB,CAAC,cAAe,YAAa,SAAU,SAAS,CAAC,EAC9E,YAAa,IAAI,IAAgB,CAAC,UAAW,YAAa,SAAU,SAAS,CAAC,EAC9E,OAAQ,IAAI,IAAgB,CAAC,UAAW,cAAe,YAAa,SAAS,CAAC,EAC9E,UAAW,IAAI,IAAgB,CAAC,SAAS,CAAC,EAC1C,QAAS,IAAI,GACf,EAEA,SAAgB,EAAkB,EAAkB,EAAyB,CAE3E,OADI,IAAS,GACN,EAAkB,EAAK,CAAC,IAAI,CAAE,CACvC"}
1
+ {"version":3,"file":"invariants.cjs","names":[],"sources":["../../../src/services/store/invariants.ts"],"sourcesContent":["import type { Task, TaskStatus } from './types.ts';\n\n/**\n * Collapse a malformed snapshot to one row per task id.\n *\n * Normal writes replace tasks in place, but older or externally edited stores\n * can contain both a stale and a current copy. Prefer the copy with the newest\n * ISO update timestamp; equal or missing timestamps use the later array entry.\n * The winning row keeps the id's original position so repair does not reorder\n * an otherwise stable task list.\n */\nexport function canonicalizeTasks(tasks: readonly Task[]): Task[] {\n const canonical: Task[] = [];\n const indexById = new Map<number, number>();\n\n for (const task of tasks) {\n const existingIndex = indexById.get(task.id);\n if (existingIndex === undefined) {\n indexById.set(task.id, canonical.length);\n canonical.push(task);\n continue;\n }\n\n const existing = canonical[existingIndex];\n if (!existing.updatedAt || !task.updatedAt || task.updatedAt >= existing.updatedAt) {\n canonical[existingIndex] = task;\n }\n }\n\n return canonical;\n}\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n completed: new Set<TaskStatus>(['deleted']),\n deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n if (from === to) return true;\n return VALID_TRANSITIONS[from].has(to);\n}\n"],"mappings":"AAWA,SAAgB,EAAkB,EAAgC,CAChE,IAAM,EAAoB,CAAC,EACrB,EAAY,IAAI,IAEtB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAgB,EAAU,IAAI,EAAK,EAAE,EAC3C,GAAI,IAAkB,IAAA,GAAW,CAC/B,EAAU,IAAI,EAAK,GAAI,EAAU,MAAM,EACvC,EAAU,KAAK,CAAI,EACnB,QACF,CAEA,IAAM,EAAW,EAAU,IACvB,CAAC,EAAS,WAAa,CAAC,EAAK,WAAa,EAAK,WAAa,EAAS,aACvE,EAAU,GAAiB,EAE/B,CAEA,OAAO,CACT,CASA,MAAa,EAAiE,CAC5E,QAAS,IAAI,IAAgB,CAAC,cAAe,YAAa,SAAU,SAAS,CAAC,EAC9E,YAAa,IAAI,IAAgB,CAAC,UAAW,YAAa,SAAU,SAAS,CAAC,EAC9E,OAAQ,IAAI,IAAgB,CAAC,UAAW,cAAe,YAAa,SAAS,CAAC,EAC9E,UAAW,IAAI,IAAgB,CAAC,SAAS,CAAC,EAC1C,QAAS,IAAI,GACf,EAEA,SAAgB,EAAkB,EAAkB,EAAyB,CAE3E,OADI,IAAS,GACN,EAAkB,EAAK,CAAC,IAAI,CAAE,CACvC"}
@@ -1,5 +1,15 @@
1
- import { TaskStatus } from "./types.cjs";
1
+ import { Task, TaskStatus } from "./types.cjs";
2
2
  //#region src/services/store/invariants.d.ts
3
+ /**
4
+ * Collapse a malformed snapshot to one row per task id.
5
+ *
6
+ * Normal writes replace tasks in place, but older or externally edited stores
7
+ * can contain both a stale and a current copy. Prefer the copy with the newest
8
+ * ISO update timestamp; equal or missing timestamps use the later array entry.
9
+ * The winning row keeps the id's original position so repair does not reorder
10
+ * an otherwise stable task list.
11
+ */
12
+ declare function canonicalizeTasks(tasks: readonly Task[]): Task[];
3
13
  /**
4
14
  * Allowed forward transitions per source status.
5
15
  *
@@ -10,5 +20,5 @@ import { TaskStatus } from "./types.cjs";
10
20
  declare const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>>;
11
21
  declare function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean;
12
22
  //#endregion
13
- export { VALID_TRANSITIONS, isTransitionValid };
23
+ export { VALID_TRANSITIONS, canonicalizeTasks, isTransitionValid };
14
24
  //# sourceMappingURL=invariants.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"invariants.d.cts","names":[],"sources":["../../../src/services/store/invariants.ts"],"mappings":";;;;;;;;;cASa,mBAAmB,OAAO,YAAY,YAAY;iBAQ/C,kBAAkB,MAAM,YAAY,IAAI"}
1
+ {"version":3,"file":"invariants.d.cts","names":[],"sources":["../../../src/services/store/invariants.ts"],"mappings":";;;;;;;;;;;iBAWgB,kBAAkB,gBAAgB,SAAS;;;;;;;;cA4B9C,mBAAmB,OAAO,YAAY,YAAY;iBAQ/C,kBAAkB,MAAM,YAAY,IAAI"}
@@ -1,5 +1,15 @@
1
- import { TaskStatus } from "./types.mjs";
1
+ import { Task, TaskStatus } from "./types.mjs";
2
2
  //#region src/services/store/invariants.d.ts
3
+ /**
4
+ * Collapse a malformed snapshot to one row per task id.
5
+ *
6
+ * Normal writes replace tasks in place, but older or externally edited stores
7
+ * can contain both a stale and a current copy. Prefer the copy with the newest
8
+ * ISO update timestamp; equal or missing timestamps use the later array entry.
9
+ * The winning row keeps the id's original position so repair does not reorder
10
+ * an otherwise stable task list.
11
+ */
12
+ declare function canonicalizeTasks(tasks: readonly Task[]): Task[];
3
13
  /**
4
14
  * Allowed forward transitions per source status.
5
15
  *
@@ -10,5 +20,5 @@ import { TaskStatus } from "./types.mjs";
10
20
  declare const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>>;
11
21
  declare function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean;
12
22
  //#endregion
13
- export { VALID_TRANSITIONS, isTransitionValid };
23
+ export { VALID_TRANSITIONS, canonicalizeTasks, isTransitionValid };
14
24
  //# sourceMappingURL=invariants.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"invariants.d.mts","names":[],"sources":["../../../src/services/store/invariants.ts"],"mappings":";;;;;;;;;cASa,mBAAmB,OAAO,YAAY,YAAY;iBAQ/C,kBAAkB,MAAM,YAAY,IAAI"}
1
+ {"version":3,"file":"invariants.d.mts","names":[],"sources":["../../../src/services/store/invariants.ts"],"mappings":";;;;;;;;;;;iBAWgB,kBAAkB,gBAAgB,SAAS;;;;;;;;cA4B9C,mBAAmB,OAAO,YAAY,YAAY;iBAQ/C,kBAAkB,MAAM,YAAY,IAAI"}
@@ -1,2 +1,2 @@
1
- const e={pending:new Set([`in_progress`,`completed`,`failed`,`deleted`]),in_progress:new Set([`pending`,`completed`,`failed`,`deleted`]),failed:new Set([`pending`,`in_progress`,`completed`,`deleted`]),completed:new Set([`deleted`]),deleted:new Set};function t(t,n){return t===n||e[t].has(n)}export{e as VALID_TRANSITIONS,t as isTransitionValid};
1
+ function e(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.id);if(e===void 0){n.set(r.id,t.length),t.push(r);continue}let i=t[e];(!i.updatedAt||!r.updatedAt||r.updatedAt>=i.updatedAt)&&(t[e]=r)}return t}const t={pending:new Set([`in_progress`,`completed`,`failed`,`deleted`]),in_progress:new Set([`pending`,`completed`,`failed`,`deleted`]),failed:new Set([`pending`,`in_progress`,`completed`,`deleted`]),completed:new Set([`deleted`]),deleted:new Set};function n(e,n){return e===n||t[e].has(n)}export{t as VALID_TRANSITIONS,e as canonicalizeTasks,n as isTransitionValid};
2
2
  //# sourceMappingURL=invariants.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"invariants.mjs","names":[],"sources":["../../../src/services/store/invariants.ts"],"sourcesContent":["import type { TaskStatus } from './types.ts';\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n completed: new Set<TaskStatus>(['deleted']),\n deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n if (from === to) return true;\n return VALID_TRANSITIONS[from].has(to);\n}\n"],"mappings":"AASA,MAAa,EAAiE,CAC5E,QAAS,IAAI,IAAgB,CAAC,cAAe,YAAa,SAAU,SAAS,CAAC,EAC9E,YAAa,IAAI,IAAgB,CAAC,UAAW,YAAa,SAAU,SAAS,CAAC,EAC9E,OAAQ,IAAI,IAAgB,CAAC,UAAW,cAAe,YAAa,SAAS,CAAC,EAC9E,UAAW,IAAI,IAAgB,CAAC,SAAS,CAAC,EAC1C,QAAS,IAAI,GACf,EAEA,SAAgB,EAAkB,EAAkB,EAAyB,CAE3E,OADI,IAAS,GACN,EAAkB,EAAK,CAAC,IAAI,CAAE,CACvC"}
1
+ {"version":3,"file":"invariants.mjs","names":[],"sources":["../../../src/services/store/invariants.ts"],"sourcesContent":["import type { Task, TaskStatus } from './types.ts';\n\n/**\n * Collapse a malformed snapshot to one row per task id.\n *\n * Normal writes replace tasks in place, but older or externally edited stores\n * can contain both a stale and a current copy. Prefer the copy with the newest\n * ISO update timestamp; equal or missing timestamps use the later array entry.\n * The winning row keeps the id's original position so repair does not reorder\n * an otherwise stable task list.\n */\nexport function canonicalizeTasks(tasks: readonly Task[]): Task[] {\n const canonical: Task[] = [];\n const indexById = new Map<number, number>();\n\n for (const task of tasks) {\n const existingIndex = indexById.get(task.id);\n if (existingIndex === undefined) {\n indexById.set(task.id, canonical.length);\n canonical.push(task);\n continue;\n }\n\n const existing = canonical[existingIndex];\n if (!existing.updatedAt || !task.updatedAt || task.updatedAt >= existing.updatedAt) {\n canonical[existingIndex] = task;\n }\n }\n\n return canonical;\n}\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n completed: new Set<TaskStatus>(['deleted']),\n deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n if (from === to) return true;\n return VALID_TRANSITIONS[from].has(to);\n}\n"],"mappings":"AAWA,SAAgB,EAAkB,EAAgC,CAChE,IAAM,EAAoB,CAAC,EACrB,EAAY,IAAI,IAEtB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAgB,EAAU,IAAI,EAAK,EAAE,EAC3C,GAAI,IAAkB,IAAA,GAAW,CAC/B,EAAU,IAAI,EAAK,GAAI,EAAU,MAAM,EACvC,EAAU,KAAK,CAAI,EACnB,QACF,CAEA,IAAM,EAAW,EAAU,IACvB,CAAC,EAAS,WAAa,CAAC,EAAK,WAAa,EAAK,WAAa,EAAS,aACvE,EAAU,GAAiB,EAE/B,CAEA,OAAO,CACT,CASA,MAAa,EAAiE,CAC5E,QAAS,IAAI,IAAgB,CAAC,cAAe,YAAa,SAAU,SAAS,CAAC,EAC9E,YAAa,IAAI,IAAgB,CAAC,UAAW,YAAa,SAAU,SAAS,CAAC,EAC9E,OAAQ,IAAI,IAAgB,CAAC,UAAW,cAAe,YAAa,SAAS,CAAC,EAC9E,UAAW,IAAI,IAAgB,CAAC,SAAS,CAAC,EAC1C,QAAS,IAAI,GACf,EAEA,SAAgB,EAAkB,EAAkB,EAAyB,CAE3E,OADI,IAAS,GACN,EAAkB,EAAK,CAAC,IAAI,CAAE,CACvC"}
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../services/store/invariants.cjs");exports.VALID_TRANSITIONS=e.VALID_TRANSITIONS,exports.isTransitionValid=e.isTransitionValid;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../services/store/invariants.cjs");exports.VALID_TRANSITIONS=e.VALID_TRANSITIONS,exports.canonicalizeTasks=e.canonicalizeTasks,exports.isTransitionValid=e.isTransitionValid;
@@ -1,2 +1,2 @@
1
- import { VALID_TRANSITIONS, isTransitionValid } from "../services/store/invariants.cjs";
2
- export { VALID_TRANSITIONS, isTransitionValid };
1
+ import { VALID_TRANSITIONS, canonicalizeTasks, isTransitionValid } from "../services/store/invariants.cjs";
2
+ export { VALID_TRANSITIONS, canonicalizeTasks, isTransitionValid };
@@ -1,2 +1,2 @@
1
- import { VALID_TRANSITIONS, isTransitionValid } from "../services/store/invariants.mjs";
2
- export { VALID_TRANSITIONS, isTransitionValid };
1
+ import { VALID_TRANSITIONS, canonicalizeTasks, isTransitionValid } from "../services/store/invariants.mjs";
2
+ export { VALID_TRANSITIONS, canonicalizeTasks, isTransitionValid };
@@ -1 +1 @@
1
- import{VALID_TRANSITIONS as e,isTransitionValid as t}from"../services/store/invariants.mjs";export{e as VALID_TRANSITIONS,t as isTransitionValid};
1
+ import{VALID_TRANSITIONS as e,canonicalizeTasks as t,isTransitionValid as n}from"../services/store/invariants.mjs";export{e as VALID_TRANSITIONS,t as canonicalizeTasks,n as isTransitionValid};
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e){return e.filter(e=>e.status!==`deleted`)}function t(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,n.status);return t}function n(e,t){return e.blockedBy?.some(e=>{let n=t.get(e);return n!==void 0&&n!==`completed`&&n!==`deleted`})??!1}function r(e){let r=t(e),i=[],a={total:0,completed:0,inProgress:0,pending:0,failed:0,blocked:0},o={inProgress:[],blocked:[],pending:[],completed:[],failed:[]},s=!1;for(let t of e)if(t.status!==`deleted`)switch(i.push(t),a.total+=1,s||=!!t.blockedBy?.length,t.status){case`in_progress`:a.inProgress+=1,o.inProgress.push(t);break;case`pending`:a.pending+=1,n(t,r)?(a.blocked+=1,o.blocked.push(t)):o.pending.push(t);break;case`failed`:a.failed+=1,o.failed.push(t);break;case`completed`:a.completed+=1,o.completed.push(t)}return{visible:i,counts:a,groups:o,showIds:s,hasActiveWork:a.inProgress>0}}function i(e){return r(e).counts}function a(e){return r(e).groups}function o(e){return e.some(e=>e.status!==`deleted`&&!!e.blockedBy?.length)}function s(e){return e.some(e=>e.status===`in_progress`)}function c(e,t){let{groups:n,visible:r}=e,i=[...n.inProgress,...n.failed,...n.blocked,...n.pending];if(t<=0)return{visible:[],hiddenCompleted:n.completed.length,truncatedTail:i.length};if(r.length<=t)return{visible:r,hiddenCompleted:0,truncatedTail:0};if(i.length<=t){let e=t-i.length,a=n.completed.slice(0,e),o=new Set([...i,...a]);return{visible:r.filter(e=>o.has(e)),hiddenCompleted:n.completed.length-a.length,truncatedTail:0}}let a=new Set(i.slice(0,t));return{visible:r.filter(e=>a.has(e)),hiddenCompleted:n.completed.length,truncatedTail:i.length-t}}function l(e,t){return c(r(e),t)}exports.countTasks=i,exports.deriveTaskProjection=r,exports.groupTasks=a,exports.hasActiveWork=s,exports.selectOverlayLayout=l,exports.selectOverlayLayoutFromProjection=c,exports.shouldShowIds=o,exports.visibleTasks=e;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../services/store/invariants.cjs");function t(t){return e.canonicalizeTasks(t).filter(e=>e.status!==`deleted`)}function n(e){return new Map(e.map(e=>[e.id,e.status]))}function r(e,t){return e.blockedBy?.some(e=>{let n=t.get(e);return n!==void 0&&n!==`completed`&&n!==`deleted`})??!1}function i(t){let i=e.canonicalizeTasks(t),a=n(i),o=[],s={total:0,completed:0,inProgress:0,pending:0,failed:0,blocked:0},c={inProgress:[],blocked:[],pending:[],completed:[],failed:[]},l=!1;for(let e of i)if(e.status!==`deleted`)switch(o.push(e),s.total+=1,l||=!!e.blockedBy?.length,e.status){case`in_progress`:s.inProgress+=1,c.inProgress.push(e);break;case`pending`:s.pending+=1,r(e,a)?(s.blocked+=1,c.blocked.push(e)):c.pending.push(e);break;case`failed`:s.failed+=1,c.failed.push(e);break;case`completed`:s.completed+=1,c.completed.push(e)}return{visible:o,counts:s,groups:c,showIds:l,hasActiveWork:s.inProgress>0}}function a(e){return i(e).counts}function o(e){return i(e).groups}function s(e){return e.some(e=>e.status!==`deleted`&&!!e.blockedBy?.length)}function c(e){return e.some(e=>e.status===`in_progress`)}function l(e,t){let{groups:n,visible:r}=e,i=[...n.inProgress,...n.failed,...n.blocked,...n.pending];if(t<=0)return{visible:[],hiddenCompleted:n.completed.length,truncatedTail:i.length};if(r.length<=t)return{visible:r,hiddenCompleted:0,truncatedTail:0};if(i.length<=t){let e=t-i.length,a=n.completed.slice(0,e),o=new Set([...i,...a]);return{visible:r.filter(e=>o.has(e)),hiddenCompleted:n.completed.length-a.length,truncatedTail:0}}let a=new Set(i.slice(0,t));return{visible:r.filter(e=>a.has(e)),hiddenCompleted:n.completed.length,truncatedTail:i.length-t}}function u(e,t){return l(i(e),t)}exports.countTasks=a,exports.deriveTaskProjection=i,exports.groupTasks=o,exports.hasActiveWork=c,exports.selectOverlayLayout=u,exports.selectOverlayLayoutFromProjection=l,exports.shouldShowIds=s,exports.visibleTasks=t;
2
2
  //# sourceMappingURL=selectors.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"selectors.cjs","names":[],"sources":["../../src/tui/selectors.ts"],"sourcesContent":["import type { Task } from '../services/store/types.ts';\n\nexport interface TaskCounts {\n total: number;\n completed: number;\n inProgress: number;\n pending: number;\n failed: number;\n blocked: number;\n}\n\nexport interface TaskGroups {\n inProgress: Task[];\n blocked: Task[];\n pending: Task[];\n completed: Task[];\n failed: Task[];\n}\n\nexport interface TaskProjection {\n visible: Task[];\n counts: TaskCounts;\n groups: TaskGroups;\n showIds: boolean;\n hasActiveWork: boolean;\n}\n\nexport function visibleTasks(tasks: readonly Task[]): Task[] {\n return tasks.filter((task) => task.status !== 'deleted');\n}\n\nfunction indexStatuses(tasks: readonly Task[]): Map<number, Task['status']> {\n const statuses = new Map<number, Task['status']>();\n for (const task of tasks) {\n // Valid stores have unique ids. Keeping the first entry also preserves the\n // former `Array.find` behavior if a corrupt document contains duplicates.\n if (!statuses.has(task.id)) statuses.set(task.id, task.status);\n }\n return statuses;\n}\n\nfunction hasUnresolvedBlocker(task: Task, statuses: ReadonlyMap<number, Task['status']>): boolean {\n return (\n task.blockedBy?.some((id) => {\n const status = statuses.get(id);\n return status !== undefined && status !== 'completed' && status !== 'deleted';\n }) ?? false\n );\n}\n\n/**\n * Derive all overlay-facing state in O(tasks + dependency edges).\n *\n * The id index replaces one full task-list scan per dependency, while the\n * ordered pass keeps group ordering identical to the source document.\n */\nexport function deriveTaskProjection(tasks: readonly Task[]): TaskProjection {\n const statuses = indexStatuses(tasks);\n const visible: Task[] = [];\n const counts: TaskCounts = { total: 0, completed: 0, inProgress: 0, pending: 0, failed: 0, blocked: 0 };\n const groups: TaskGroups = { inProgress: [], blocked: [], pending: [], completed: [], failed: [] };\n let showIds = false;\n\n for (const task of tasks) {\n if (task.status === 'deleted') continue;\n\n visible.push(task);\n counts.total += 1;\n showIds ||= Boolean(task.blockedBy?.length);\n\n switch (task.status) {\n case 'in_progress':\n counts.inProgress += 1;\n groups.inProgress.push(task);\n break;\n case 'pending': {\n counts.pending += 1;\n if (hasUnresolvedBlocker(task, statuses)) {\n counts.blocked += 1;\n groups.blocked.push(task);\n } else {\n groups.pending.push(task);\n }\n break;\n }\n case 'failed':\n counts.failed += 1;\n groups.failed.push(task);\n break;\n case 'completed':\n counts.completed += 1;\n groups.completed.push(task);\n break;\n }\n }\n\n return { visible, counts, groups, showIds, hasActiveWork: counts.inProgress > 0 };\n}\n\nexport function countTasks(tasks: readonly Task[]): TaskCounts {\n return deriveTaskProjection(tasks).counts;\n}\n\n/**\n * Group tasks for display.\n *\n * Blocked tasks split out of `pending` because a reader scanning the overlay\n * needs to know at a glance what is actually actionable right now.\n */\nexport function groupTasks(tasks: readonly Task[]): TaskGroups {\n return deriveTaskProjection(tasks).groups;\n}\n\n/** Ids are only worth the visual noise once dependencies are in play. */\nexport function shouldShowIds(tasks: readonly Task[]): boolean {\n return tasks.some((task) => task.status !== 'deleted' && Boolean(task.blockedBy?.length));\n}\n\nexport function hasActiveWork(tasks: readonly Task[]): boolean {\n return tasks.some((task) => task.status === 'in_progress');\n}\n\nexport interface OverlayLayout {\n visible: Task[];\n hiddenCompleted: number;\n truncatedTail: number;\n}\n\n/**\n * Choose which rows fit the overlay budget.\n *\n * Active work wins limited space: in-progress first, then failed, blocked, and\n * pending. Selected rows are always returned in source order, however, so a\n * status update does not reshuffle an otherwise unchanged overlay.\n */\nexport function selectOverlayLayoutFromProjection(projection: TaskProjection, budget: number): OverlayLayout {\n const { groups, visible: sourceOrder } = projection;\n const active = [...groups.inProgress, ...groups.failed, ...groups.blocked, ...groups.pending];\n if (budget <= 0) {\n return {\n visible: [],\n hiddenCompleted: groups.completed.length,\n truncatedTail: active.length,\n };\n }\n if (sourceOrder.length <= budget) {\n return { visible: sourceOrder, hiddenCompleted: 0, truncatedTail: 0 };\n }\n\n if (active.length <= budget) {\n const remaining = budget - active.length;\n const shownCompleted = groups.completed.slice(0, remaining);\n const selected = new Set([...active, ...shownCompleted]);\n return {\n visible: sourceOrder.filter((task) => selected.has(task)),\n hiddenCompleted: groups.completed.length - shownCompleted.length,\n truncatedTail: 0,\n };\n }\n\n const selected = new Set(active.slice(0, budget));\n return {\n visible: sourceOrder.filter((task) => selected.has(task)),\n hiddenCompleted: groups.completed.length,\n truncatedTail: active.length - budget,\n };\n}\n\nexport function selectOverlayLayout(tasks: readonly Task[], budget: number): OverlayLayout {\n return selectOverlayLayoutFromProjection(deriveTaskProjection(tasks), budget);\n}\n"],"mappings":"mEA2BA,SAAgB,EAAa,EAAgC,CAC3D,OAAO,EAAM,OAAQ,GAAS,EAAK,SAAW,SAAS,CACzD,CAEA,SAAS,EAAc,EAAqD,CAC1E,IAAM,EAAW,IAAI,IACrB,IAAK,IAAM,KAAQ,EAGZ,EAAS,IAAI,EAAK,EAAE,GAAG,EAAS,IAAI,EAAK,GAAI,EAAK,MAAM,EAE/D,OAAO,CACT,CAEA,SAAS,EAAqB,EAAY,EAAwD,CAChG,OACE,EAAK,WAAW,KAAM,GAAO,CAC3B,IAAM,EAAS,EAAS,IAAI,CAAE,EAC9B,OAAO,IAAW,IAAA,IAAa,IAAW,aAAe,IAAW,SACtE,CAAC,GAAK,EAEV,CAQA,SAAgB,EAAqB,EAAwC,CAC3E,IAAM,EAAW,EAAc,CAAK,EAC9B,EAAkB,CAAC,EACnB,EAAqB,CAAE,MAAO,EAAG,UAAW,EAAG,WA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AAI,GAAU,EACZ,MAAO,CACL,QAAS,CAAC,EACV,gBAAiB,EAAO,UAAU,OAClC,cAAe,EAAO,MACxB,EAEF,GAAI,EAAY,QAAU,EACxB,MAAO,CAAE,QAAS,EAAa,gBAAiB,EAAG,cAAe,CAAE,EAGtE,GAAI,EAAO,QAAU,EAAQ,CAC3B,IAAM,EAAY,EAAS,EAAO,OAC5B,EAAiB,EAAO,UAAU,MAAM,EAAG,CAAS,EACpD,EAAW,IAAI,IAAI,CAAC,GAAG,EAAQ,GAAG,CAAc,CAAC,EACvD,MAAO,CACL,QAAS,EAAY,OAAQ,GAAS,EAAS,IAAI,CAAI,CAAC,EACxD,gBAAiB,EAAO,UAAU,OAAS,EAAe,OAC1D,cAAe,CACjB,CACF,CAEA,IAAM,EAAW,IAAI,IAAI,EAAO,MAAM,EAAG,CAAM,CAAC,EAChD,MAAO,CACL,QAAS,EAAY,OAAQ,GAAS,EAAS,IAAI,CAAI,CAAC,EACxD,gBAAiB,EAAO,UAAU,OAClC,cAAe,EAAO,OAAS,CACjC,CACF,CAEA,SAAgB,EAAoB,EAAwB,EAA+B,CACzF,OAAO,EAAkC,EAAqB,CAAK,EAAG,CAAM,CAC9E"}
1
+ {"version":3,"file":"selectors.cjs","names":["canonicalizeTasks"],"sources":["../../src/tui/selectors.ts"],"sourcesContent":["import { canonicalizeTasks } from '../services/store/invariants.ts';\nimport type { Task } from '../services/store/types.ts';\n\nexport interface TaskCounts {\n total: number;\n completed: number;\n inProgress: number;\n pending: number;\n failed: number;\n blocked: number;\n}\n\nexport interface TaskGroups {\n inProgress: Task[];\n blocked: Task[];\n pending: Task[];\n completed: Task[];\n failed: Task[];\n}\n\nexport interface TaskProjection {\n visible: Task[];\n counts: TaskCounts;\n groups: TaskGroups;\n showIds: boolean;\n hasActiveWork: boolean;\n}\n\nexport function visibleTasks(tasks: readonly Task[]): Task[] {\n return canonicalizeTasks(tasks).filter((task) => task.status !== 'deleted');\n}\n\nfunction indexStatuses(tasks: readonly Task[]): Map<number, Task['status']> {\n return new Map(tasks.map((task) => [task.id, task.status]));\n}\n\nfunction hasUnresolvedBlocker(task: Task, statuses: ReadonlyMap<number, Task['status']>): boolean {\n return (\n task.blockedBy?.some((id) => {\n const status = statuses.get(id);\n return status !== undefined && status !== 'completed' && status !== 'deleted';\n }) ?? false\n );\n}\n\n/**\n * Derive all overlay-facing state in O(tasks + dependency edges).\n *\n * The id index replaces one full task-list scan per dependency, while the\n * ordered pass keeps group ordering identical to the source document.\n */\nexport function deriveTaskProjection(tasks: readonly Task[]): TaskProjection {\n const canonical = canonicalizeTasks(tasks);\n const statuses = indexStatuses(canonical);\n const visible: Task[] = [];\n const counts: TaskCounts = { total: 0, completed: 0, inProgress: 0, pending: 0, failed: 0, blocked: 0 };\n const groups: TaskGroups = { inProgress: [], blocked: [], pending: [], completed: [], failed: [] };\n let showIds = false;\n\n for (const task of canonical) {\n if (task.status === 'deleted') continue;\n\n visible.push(task);\n counts.total += 1;\n showIds ||= Boolean(task.blockedBy?.length);\n\n switch (task.status) {\n case 'in_progress':\n counts.inProgress += 1;\n groups.inProgress.push(task);\n break;\n case 'pending': {\n counts.pending += 1;\n if (hasUnresolvedBlocker(task, statuses)) {\n counts.blocked += 1;\n groups.blocked.push(task);\n } else {\n groups.pending.push(task);\n }\n break;\n }\n case 'failed':\n counts.failed += 1;\n groups.failed.push(task);\n break;\n case 'completed':\n counts.completed += 1;\n groups.completed.push(task);\n break;\n }\n }\n\n return { visible, counts, groups, showIds, hasActiveWork: counts.inProgress > 0 };\n}\n\nexport function countTasks(tasks: readonly Task[]): TaskCounts {\n return deriveTaskProjection(tasks).counts;\n}\n\n/**\n * Group tasks for display.\n *\n * Blocked tasks split out of `pending` because a reader scanning the overlay\n * needs to know at a glance what is actually actionable right now.\n */\nexport function groupTasks(tasks: readonly Task[]): TaskGroups {\n return deriveTaskProjection(tasks).groups;\n}\n\n/** Ids are only worth the visual noise once dependencies are in play. */\nexport function shouldShowIds(tasks: readonly Task[]): boolean {\n return tasks.some((task) => task.status !== 'deleted' && Boolean(task.blockedBy?.length));\n}\n\nexport function hasActiveWork(tasks: readonly Task[]): boolean {\n return tasks.some((task) => task.status === 'in_progress');\n}\n\nexport interface OverlayLayout {\n visible: Task[];\n hiddenCompleted: number;\n truncatedTail: number;\n}\n\n/**\n * Choose which rows fit the overlay budget.\n *\n * Active work wins limited space: in-progress first, then failed, blocked, and\n * pending. Selected rows are always returned in source order, however, so a\n * status update does not reshuffle an otherwise unchanged overlay.\n */\nexport function selectOverlayLayoutFromProjection(projection: TaskProjection, budget: number): OverlayLayout {\n const { groups, visible: sourceOrder } = projection;\n const active = [...groups.inProgress, ...groups.failed, ...groups.blocked, ...groups.pending];\n if (budget <= 0) {\n return {\n visible: [],\n hiddenCompleted: groups.completed.length,\n truncatedTail: active.length,\n };\n }\n if (sourceOrder.length <= budget) {\n return { visible: sourceOrder, hiddenCompleted: 0, truncatedTail: 0 };\n }\n\n if (active.length <= budget) {\n const remaining = budget - active.length;\n const shownCompleted = groups.completed.slice(0, remaining);\n const selected = new Set([...active, ...shownCompleted]);\n return {\n visible: sourceOrder.filter((task) => selected.has(task)),\n hiddenCompleted: groups.completed.length - shownCompleted.length,\n truncatedTail: 0,\n };\n }\n\n const selected = new Set(active.slice(0, budget));\n return {\n visible: sourceOrder.filter((task) => selected.has(task)),\n hiddenCompleted: groups.completed.length,\n truncatedTail: active.length - budget,\n };\n}\n\nexport function selectOverlayLayout(tasks: readonly Task[], budget: number): OverlayLayout {\n return selectOverlayLayoutFromProjection(deriveTaskProjection(tasks), budget);\n}\n"],"mappings":"uHA4BA,SAAgB,EAAa,EAAgC,CAC3D,OAAOA,EAAAA,kBAAkB,CAAK,CAAC,CAAC,OAAQ,GAAS,EAAK,SAAW,SAAS,CAC5E,CAEA,SAAS,EAAc,EAAqD,CAC1E,OAAO,IAAI,IAAI,EAAM,IAAK,GAAS,CAAC,EAAK,GAAI,EAAK,MAAM,CAAC,CAAC,CAC5D,CAEA,SAAS,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AW;EACX,QAAQ;;UAGO;EACf,SAAS;EACT,QAAQ;EACR,QAAQ;EACR;EACA;;iBAGc,aAAa,gBAAgB,SAAS;;;;;;;iBA6BtC,qBAAqB,gBAAgB,SAAS;iBA2C9C,WAAW,gBAAgB,SAAS;;;;;;;iBAUpC,WAAW,gBAAgB,SAAS;;iBAKpC,cAAc,gBAAgB;iBAI9B,cAAc,gBAAgB;UAI7B;EACf,SAAS;EACT;EACA;;;;;;;;;iBAUc,kCAAkC,YAAY,gBAAgB,iBAAiB;iBAiC/E,oBAAoB,gBAAgB,QAAQ,iBAAiB"}
1
+ {"version":3,"file":"selectors.d.cts","names":[],"sources":["../../src/tui/selectors.ts"],"mappings":";;UAGiB;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,YAAY;EACZ,SAAS;EACT,SAAS;EACT,WAAW;EACX,QAAQ;;UAGO;EACf,SAAS;EACT,QAAQ;EACR,QAAQ;EACR;EACA;;iBAGc,aAAa,gBAAgB,SAAS;;;;;;;iBAuBtC,qBAAqB,gBAAgB,SAAS;iBA4C9C,WAAW,gBAAgB,SAAS;;;;;;;iBAUpC,WAAW,gBAAgB,SAAS;;iBAKpC,cAAc,gBAAgB;iBAI9B,cAAc,gBAAgB;UAI7B;EACf,SAAS;EACT;EACA;;;;;;;;;iBAUc,kCAAkC,YAAY,gBAAgB,iBAAiB;iBAiC/E,oBAAoB,gBAAgB,QAAQ,iBAAiB"}
@@ -1 +1 @@
1
- {"version":3,"file":"selectors.d.mts","names":[],"sources":["../../src/tui/selectors.ts"],"mappings":";;UAEiB;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,YAAY;EACZ,SAAS;EACT,SAAS;EACT,WAAW;EACX,QAAQ;;UAGO;EACf,SAAS;EACT,QAAQ;EACR,QAAQ;EACR;EACA;;iBAGc,aAAa,gBAAgB,SAAS;;;;;;;iBA6BtC,qBAAqB,gBAAgB,SAAS;iBA2C9C,WAAW,gBAAgB,SAAS;;;;;;;iBAUpC,WAAW,gBAAgB,SAAS;;iBAKpC,cAAc,gBAAgB;iBAI9B,cAAc,gBAAgB;UAI7B;EACf,SAAS;EACT;EACA;;;;;;;;;iBAUc,kCAAkC,YAAY,gBAAgB,iBAAiB;iBAiC/E,oBAAoB,gBAAgB,QAAQ,iBAAiB"}
1
+ {"version":3,"file":"selectors.d.mts","names":[],"sources":["../../src/tui/selectors.ts"],"mappings":";;UAGiB;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,YAAY;EACZ,SAAS;EACT,SAAS;EACT,WAAW;EACX,QAAQ;;UAGO;EACf,SAAS;EACT,QAAQ;EACR,QAAQ;EACR;EACA;;iBAGc,aAAa,gBAAgB,SAAS;;;;;;;iBAuBtC,qBAAqB,gBAAgB,SAAS;iBA4C9C,WAAW,gBAAgB,SAAS;;;;;;;iBAUpC,WAAW,gBAAgB,SAAS;;iBAKpC,cAAc,gBAAgB;iBAI9B,cAAc,gBAAgB;UAI7B;EACf,SAAS;EACT;EACA;;;;;;;;;iBAUc,kCAAkC,YAAY,gBAAgB,iBAAiB;iBAiC/E,oBAAoB,gBAAgB,QAAQ,iBAAiB"}
@@ -1,2 +1,2 @@
1
- function e(e){return e.filter(e=>e.status!==`deleted`)}function t(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,n.status);return t}function n(e,t){return e.blockedBy?.some(e=>{let n=t.get(e);return n!==void 0&&n!==`completed`&&n!==`deleted`})??!1}function r(e){let r=t(e),i=[],a={total:0,completed:0,inProgress:0,pending:0,failed:0,blocked:0},o={inProgress:[],blocked:[],pending:[],completed:[],failed:[]},s=!1;for(let t of e)if(t.status!==`deleted`)switch(i.push(t),a.total+=1,s||=!!t.blockedBy?.length,t.status){case`in_progress`:a.inProgress+=1,o.inProgress.push(t);break;case`pending`:a.pending+=1,n(t,r)?(a.blocked+=1,o.blocked.push(t)):o.pending.push(t);break;case`failed`:a.failed+=1,o.failed.push(t);break;case`completed`:a.completed+=1,o.completed.push(t)}return{visible:i,counts:a,groups:o,showIds:s,hasActiveWork:a.inProgress>0}}function i(e){return r(e).counts}function a(e){return r(e).groups}function o(e){return e.some(e=>e.status!==`deleted`&&!!e.blockedBy?.length)}function s(e){return e.some(e=>e.status===`in_progress`)}function c(e,t){let{groups:n,visible:r}=e,i=[...n.inProgress,...n.failed,...n.blocked,...n.pending];if(t<=0)return{visible:[],hiddenCompleted:n.completed.length,truncatedTail:i.length};if(r.length<=t)return{visible:r,hiddenCompleted:0,truncatedTail:0};if(i.length<=t){let e=t-i.length,a=n.completed.slice(0,e),o=new Set([...i,...a]);return{visible:r.filter(e=>o.has(e)),hiddenCompleted:n.completed.length-a.length,truncatedTail:0}}let a=new Set(i.slice(0,t));return{visible:r.filter(e=>a.has(e)),hiddenCompleted:n.completed.length,truncatedTail:i.length-t}}function l(e,t){return c(r(e),t)}export{i as countTasks,r as deriveTaskProjection,a as groupTasks,s as hasActiveWork,l as selectOverlayLayout,c as selectOverlayLayoutFromProjection,o as shouldShowIds,e as visibleTasks};
1
+ import{canonicalizeTasks as e}from"../services/store/invariants.mjs";function t(t){return e(t).filter(e=>e.status!==`deleted`)}function n(e){return new Map(e.map(e=>[e.id,e.status]))}function r(e,t){return e.blockedBy?.some(e=>{let n=t.get(e);return n!==void 0&&n!==`completed`&&n!==`deleted`})??!1}function i(t){let i=e(t),a=n(i),o=[],s={total:0,completed:0,inProgress:0,pending:0,failed:0,blocked:0},c={inProgress:[],blocked:[],pending:[],completed:[],failed:[]},l=!1;for(let e of i)if(e.status!==`deleted`)switch(o.push(e),s.total+=1,l||=!!e.blockedBy?.length,e.status){case`in_progress`:s.inProgress+=1,c.inProgress.push(e);break;case`pending`:s.pending+=1,r(e,a)?(s.blocked+=1,c.blocked.push(e)):c.pending.push(e);break;case`failed`:s.failed+=1,c.failed.push(e);break;case`completed`:s.completed+=1,c.completed.push(e)}return{visible:o,counts:s,groups:c,showIds:l,hasActiveWork:s.inProgress>0}}function a(e){return i(e).counts}function o(e){return i(e).groups}function s(e){return e.some(e=>e.status!==`deleted`&&!!e.blockedBy?.length)}function c(e){return e.some(e=>e.status===`in_progress`)}function l(e,t){let{groups:n,visible:r}=e,i=[...n.inProgress,...n.failed,...n.blocked,...n.pending];if(t<=0)return{visible:[],hiddenCompleted:n.completed.length,truncatedTail:i.length};if(r.length<=t)return{visible:r,hiddenCompleted:0,truncatedTail:0};if(i.length<=t){let e=t-i.length,a=n.completed.slice(0,e),o=new Set([...i,...a]);return{visible:r.filter(e=>o.has(e)),hiddenCompleted:n.completed.length-a.length,truncatedTail:0}}let a=new Set(i.slice(0,t));return{visible:r.filter(e=>a.has(e)),hiddenCompleted:n.completed.length,truncatedTail:i.length-t}}function u(e,t){return l(i(e),t)}export{a as countTasks,i as deriveTaskProjection,o as groupTasks,c as hasActiveWork,u as selectOverlayLayout,l as selectOverlayLayoutFromProjection,s as shouldShowIds,t as visibleTasks};
2
2
  //# sourceMappingURL=selectors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"selectors.mjs","names":[],"sources":["../../src/tui/selectors.ts"],"sourcesContent":["import type { Task } from '../services/store/types.ts';\n\nexport interface TaskCounts {\n total: number;\n completed: number;\n inProgress: number;\n pending: number;\n failed: number;\n blocked: number;\n}\n\nexport interface TaskGroups {\n inProgress: Task[];\n blocked: Task[];\n pending: Task[];\n completed: Task[];\n failed: Task[];\n}\n\nexport interface TaskProjection {\n visible: Task[];\n counts: TaskCounts;\n groups: TaskGroups;\n showIds: boolean;\n hasActiveWork: boolean;\n}\n\nexport function visibleTasks(tasks: readonly Task[]): Task[] {\n return tasks.filter((task) => task.status !== 'deleted');\n}\n\nfunction indexStatuses(tasks: readonly Task[]): Map<number, Task['status']> {\n const statuses = new Map<number, Task['status']>();\n for (const task of tasks) {\n // Valid stores have unique ids. Keeping the first entry also preserves the\n // former `Array.find` behavior if a corrupt document contains duplicates.\n if (!statuses.has(task.id)) statuses.set(task.id, task.status);\n }\n return statuses;\n}\n\nfunction hasUnresolvedBlocker(task: Task, statuses: ReadonlyMap<number, Task['status']>): boolean {\n return (\n task.blockedBy?.some((id) => {\n const status = statuses.get(id);\n return status !== undefined && status !== 'completed' && status !== 'deleted';\n }) ?? false\n );\n}\n\n/**\n * Derive all overlay-facing state in O(tasks + dependency edges).\n *\n * The id index replaces one full task-list scan per dependency, while the\n * ordered pass keeps group ordering identical to the source document.\n */\nexport function deriveTaskProjection(tasks: readonly Task[]): TaskProjection {\n const statuses = indexStatuses(tasks);\n const visible: Task[] = [];\n const counts: TaskCounts = { total: 0, completed: 0, inProgress: 0, pending: 0, failed: 0, blocked: 0 };\n const groups: TaskGroups = { inProgress: [], blocked: [], pending: [], completed: [], failed: [] };\n let showIds = false;\n\n for (const task of tasks) {\n if (task.status === 'deleted') continue;\n\n visible.push(task);\n counts.total += 1;\n showIds ||= Boolean(task.blockedBy?.length);\n\n switch (task.status) {\n case 'in_progress':\n counts.inProgress += 1;\n groups.inProgress.push(task);\n break;\n case 'pending': {\n counts.pending += 1;\n if (hasUnresolvedBlocker(task, statuses)) {\n counts.blocked += 1;\n groups.blocked.push(task);\n } else {\n groups.pending.push(task);\n }\n break;\n }\n case 'failed':\n counts.failed += 1;\n groups.failed.push(task);\n break;\n case 'completed':\n counts.completed += 1;\n groups.completed.push(task);\n break;\n }\n }\n\n return { visible, counts, groups, showIds, hasActiveWork: counts.inProgress > 0 };\n}\n\nexport function countTasks(tasks: readonly Task[]): TaskCounts {\n return deriveTaskProjection(tasks).counts;\n}\n\n/**\n * Group tasks for display.\n *\n * Blocked tasks split out of `pending` because a reader scanning the overlay\n * needs to know at a glance what is actually actionable right now.\n */\nexport function groupTasks(tasks: readonly Task[]): TaskGroups {\n return deriveTaskProjection(tasks).groups;\n}\n\n/** Ids are only worth the visual noise once dependencies are in play. */\nexport function shouldShowIds(tasks: readonly Task[]): boolean {\n return tasks.some((task) => task.status !== 'deleted' && Boolean(task.blockedBy?.length));\n}\n\nexport function hasActiveWork(tasks: readonly Task[]): boolean {\n return tasks.some((task) => task.status === 'in_progress');\n}\n\nexport interface OverlayLayout {\n visible: Task[];\n hiddenCompleted: number;\n truncatedTail: number;\n}\n\n/**\n * Choose which rows fit the overlay budget.\n *\n * Active work wins limited space: in-progress first, then failed, blocked, and\n * pending. Selected rows are always returned in source order, however, so a\n * status update does not reshuffle an otherwise unchanged overlay.\n */\nexport function selectOverlayLayoutFromProjection(projection: TaskProjection, budget: number): OverlayLayout {\n const { groups, visible: sourceOrder } = projection;\n const active = [...groups.inProgress, ...groups.failed, ...groups.blocked, ...groups.pending];\n if (budget <= 0) {\n return {\n visible: [],\n hiddenCompleted: groups.completed.length,\n truncatedTail: active.length,\n };\n }\n if (sourceOrder.length <= budget) {\n return { visible: sourceOrder, hiddenCompleted: 0, truncatedTail: 0 };\n }\n\n if (active.length <= budget) {\n const remaining = budget - active.length;\n const shownCompleted = groups.completed.slice(0, remaining);\n const selected = new Set([...active, ...shownCompleted]);\n return {\n visible: sourceOrder.filter((task) => selected.has(task)),\n hiddenCompleted: groups.completed.length - shownCompleted.length,\n truncatedTail: 0,\n };\n }\n\n const selected = new Set(active.slice(0, budget));\n return {\n visible: sourceOrder.filter((task) => selected.has(task)),\n hiddenCompleted: groups.completed.length,\n truncatedTail: active.length - budget,\n };\n}\n\nexport function selectOverlayLayout(tasks: readonly Task[], budget: number): OverlayLayout {\n return selectOverlayLayoutFromProjection(deriveTaskProjection(tasks), budget);\n}\n"],"mappings":"AA2BA,SAAgB,EAAa,EAAgC,CAC3D,OAAO,EAAM,OAAQ,GAAS,EAAK,SAAW,SAAS,CACzD,CAEA,SAAS,EAAc,EAAqD,CAC1E,IAAM,EAAW,IAAI,IACrB,IAAK,IAAM,KAAQ,EAGZ,EAAS,IAAI,EAAK,EAAE,GAAG,EAAS,IAAI,EAAK,GAAI,EAAK,MAAM,EAE/D,OAAO,CACT,CAEA,SAAS,EAAqB,EAAY,EAAwD,CAChG,OACE,EAAK,WAAW,KAAM,GAAO,CAC3B,IAAM,EAAS,EAAS,IAAI,CAAE,EAC9B,OA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,aAAa,CAC3D,CAeA,SAAgB,EAAkC,EAA4B,EAA+B,CAC3G,GAAM,CAAE,SAAQ,QAAS,GAAgB,EACnC,EAAS,CAAC,GAAG,EAAO,WAAY,GAAG,EAAO,OAAQ,GAAG,EAAO,QAAS,GAAG,EAAO,OAAO,EAC5F,GAAI,GAAU,EACZ,MAAO,CACL,QAAS,CAAC,EACV,gBAAiB,EAAO,UAAU,OAClC,cAAe,EAAO,MACxB,EAEF,GAAI,EAAY,QAAU,EACxB,MAAO,CAAE,QAAS,EAAa,gBAAiB,EAAG,cAAe,CAAE,EAGtE,GAAI,EAAO,QAAU,EAAQ,CAC3B,IAAM,EAAY,EAAS,EAAO,OAC5B,EAAiB,EAAO,UAAU,MAAM,EAAG,CAAS,EACpD,EAAW,IAAI,IAAI,CAAC,GAAG,EAAQ,GAAG,CAAc,CAAC,EACvD,MAAO,CACL,QAAS,EAAY,OAAQ,GAAS,EAAS,IAAI,CAAI,CAAC,EACxD,gBAAiB,EAAO,UAAU,OAAS,EAAe,OAC1D,cAAe,CACjB,CACF,CAEA,IAAM,EAAW,IAAI,IAAI,EAAO,MAAM,EAAG,CAAM,CAAC,EAChD,MAAO,CACL,QAAS,EAAY,OAAQ,GAAS,EAAS,IAAI,CAAI,CAAC,EACxD,gBAAiB,EAAO,UAAU,OAClC,cAAe,EAAO,OAAS,CACjC,CACF,CAEA,SAAgB,EAAoB,EAAwB,EAA+B,CACzF,OAAO,EAAkC,EAAqB,CAAK,EAAG,CAAM,CAC9E"}
1
+ {"version":3,"file":"selectors.mjs","names":[],"sources":["../../src/tui/selectors.ts"],"sourcesContent":["import { canonicalizeTasks } from '../services/store/invariants.ts';\nimport type { Task } from '../services/store/types.ts';\n\nexport interface TaskCounts {\n total: number;\n completed: number;\n inProgress: number;\n pending: number;\n failed: number;\n blocked: number;\n}\n\nexport interface TaskGroups {\n inProgress: Task[];\n blocked: Task[];\n pending: Task[];\n completed: Task[];\n failed: Task[];\n}\n\nexport interface TaskProjection {\n visible: Task[];\n counts: TaskCounts;\n groups: TaskGroups;\n showIds: boolean;\n hasActiveWork: boolean;\n}\n\nexport function visibleTasks(tasks: readonly Task[]): Task[] {\n return canonicalizeTasks(tasks).filter((task) => task.status !== 'deleted');\n}\n\nfunction indexStatuses(tasks: readonly Task[]): Map<number, Task['status']> {\n return new Map(tasks.map((task) => [task.id, task.status]));\n}\n\nfunction hasUnresolvedBlocker(task: Task, statuses: ReadonlyMap<number, Task['status']>): boolean {\n return (\n task.blockedBy?.some((id) => {\n const status = statuses.get(id);\n return status !== undefined && status !== 'completed' && status !== 'deleted';\n }) ?? false\n );\n}\n\n/**\n * Derive all overlay-facing state in O(tasks + dependency edges).\n *\n * The id index replaces one full task-list scan per dependency, while the\n * ordered pass keeps group ordering identical to the source document.\n */\nexport function deriveTaskProjection(tasks: readonly Task[]): TaskProjection {\n const canonical = canonicalizeTasks(tasks);\n const statuses = indexStatuses(canonical);\n const visible: Task[] = [];\n const counts: TaskCounts = { total: 0, completed: 0, inProgress: 0, pending: 0, failed: 0, blocked: 0 };\n const groups: TaskGroups = { inProgress: [], blocked: [], pending: [], completed: [], failed: [] };\n let showIds = false;\n\n for (const task of canonical) {\n if (task.status === 'deleted') continue;\n\n visible.push(task);\n counts.total += 1;\n showIds ||= Boolean(task.blockedBy?.length);\n\n switch (task.status) {\n case 'in_progress':\n counts.inProgress += 1;\n groups.inProgress.push(task);\n break;\n case 'pending': {\n counts.pending += 1;\n if (hasUnresolvedBlocker(task, statuses)) {\n counts.blocked += 1;\n groups.blocked.push(task);\n } else {\n groups.pending.push(task);\n }\n break;\n }\n case 'failed':\n counts.failed += 1;\n groups.failed.push(task);\n break;\n case 'completed':\n counts.completed += 1;\n groups.completed.push(task);\n break;\n }\n }\n\n return { visible, counts, groups, showIds, hasActiveWork: counts.inProgress > 0 };\n}\n\nexport function countTasks(tasks: readonly Task[]): TaskCounts {\n return deriveTaskProjection(tasks).counts;\n}\n\n/**\n * Group tasks for display.\n *\n * Blocked tasks split out of `pending` because a reader scanning the overlay\n * needs to know at a glance what is actually actionable right now.\n */\nexport function groupTasks(tasks: readonly Task[]): TaskGroups {\n return deriveTaskProjection(tasks).groups;\n}\n\n/** Ids are only worth the visual noise once dependencies are in play. */\nexport function shouldShowIds(tasks: readonly Task[]): boolean {\n return tasks.some((task) => task.status !== 'deleted' && Boolean(task.blockedBy?.length));\n}\n\nexport function hasActiveWork(tasks: readonly Task[]): boolean {\n return tasks.some((task) => task.status === 'in_progress');\n}\n\nexport interface OverlayLayout {\n visible: Task[];\n hiddenCompleted: number;\n truncatedTail: number;\n}\n\n/**\n * Choose which rows fit the overlay budget.\n *\n * Active work wins limited space: in-progress first, then failed, blocked, and\n * pending. Selected rows are always returned in source order, however, so a\n * status update does not reshuffle an otherwise unchanged overlay.\n */\nexport function selectOverlayLayoutFromProjection(projection: TaskProjection, budget: number): OverlayLayout {\n const { groups, visible: sourceOrder } = projection;\n const active = [...groups.inProgress, ...groups.failed, ...groups.blocked, ...groups.pending];\n if (budget <= 0) {\n return {\n visible: [],\n hiddenCompleted: groups.completed.length,\n truncatedTail: active.length,\n };\n }\n if (sourceOrder.length <= budget) {\n return { visible: sourceOrder, hiddenCompleted: 0, truncatedTail: 0 };\n }\n\n if (active.length <= budget) {\n const remaining = budget - active.length;\n const shownCompleted = groups.completed.slice(0, remaining);\n const selected = new Set([...active, ...shownCompleted]);\n return {\n visible: sourceOrder.filter((task) => selected.has(task)),\n hiddenCompleted: groups.completed.length - shownCompleted.length,\n truncatedTail: 0,\n };\n }\n\n const selected = new Set(active.slice(0, budget));\n return {\n visible: sourceOrder.filter((task) => selected.has(task)),\n hiddenCompleted: groups.completed.length,\n truncatedTail: active.length - budget,\n };\n}\n\nexport function selectOverlayLayout(tasks: readonly Task[], budget: number): OverlayLayout {\n return selectOverlayLayoutFromProjection(deriveTaskProjection(tasks), budget);\n}\n"],"mappings":"qEA4BA,SAAgB,EAAa,EAAgC,CAC3D,OAAO,EAAkB,CAAK,CAAC,CAAC,O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json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@agimon-ai/doompi-task",
3
- "version": "0.0.1-alpha.21",
4
- "description": "Pi task tracking extension with file-backed tasks and subagent delegation",
3
+ "version": "0.0.1-alpha.23",
4
+ "description": "Persistent, dependency-aware task graphs and subagent delegation for Pi coding sessions.",
5
5
  "keywords": [
6
- "ai",
7
6
  "coding-agent",
8
- "developer-tools",
7
+ "delegation",
9
8
  "doompi",
10
- "pi-package"
9
+ "pi-coding-agent",
10
+ "subagents",
11
+ "task-graph",
12
+ "task-management"
11
13
  ],
12
14
  "homepage": "https://agimon.ai",
13
15
  "license": "MIT",
@@ -149,9 +151,9 @@
149
151
  },
150
152
  "dependencies": {
151
153
  "typebox": "1.1.38",
152
- "@agimon-ai/doompi-extension-contracts": "0.0.1-alpha.21",
153
- "@agimon-ai/doompi-ui": "0.0.1-alpha.21",
154
- "@agimon-ai/doompi-telemetry": "0.0.1-alpha.21"
154
+ "@agimon-ai/doompi-extension-contracts": "0.0.1-alpha.23",
155
+ "@agimon-ai/doompi-ui": "0.0.1-alpha.23",
156
+ "@agimon-ai/doompi-telemetry": "0.0.1-alpha.23"
155
157
  },
156
158
  "devDependencies": {
157
159
  "@earendil-works/pi-coding-agent": "0.84.2",