@agimon-ai/po-task 0.0.0-alpha.2 → 0.0.0-alpha.4

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.
Files changed (104) hide show
  1. package/README.md +8 -8
  2. package/dist/apiContracts.cjs +1 -1
  3. package/dist/apiContracts.cjs.map +1 -1
  4. package/dist/apiContracts.d.mts +18 -18
  5. package/dist/apiContracts.mjs +1 -1
  6. package/dist/apiContracts.mjs.map +1 -1
  7. package/dist/{config-CdX-Bv8q.cjs → config-BC-bztyx.cjs} +8 -8
  8. package/dist/config-BC-bztyx.cjs.map +1 -0
  9. package/dist/{config-CFSs3iku.mjs → config-BTadoGeF.mjs} +8 -8
  10. package/dist/config-BTadoGeF.mjs.map +1 -0
  11. package/dist/config.cjs +1 -1
  12. package/dist/config.d.mts +1 -1
  13. package/dist/config.mjs +1 -2
  14. package/dist/{delegation-CdMqOZB4.mjs → delegation-Dsqf7fUM.mjs} +11 -11
  15. package/dist/delegation-Dsqf7fUM.mjs.map +1 -0
  16. package/dist/{delegation-DsnKjMbJ.cjs → delegation-frvEXhIz.cjs} +10 -10
  17. package/dist/delegation-frvEXhIz.cjs.map +1 -0
  18. package/dist/delegationManager.cjs +1 -1
  19. package/dist/delegationManager.d.mts +1 -1
  20. package/dist/delegationManager.mjs +1 -1
  21. package/dist/extensions/mcp-ui.mjs.map +1 -1
  22. package/dist/extensions/mcp.cjs +23 -23
  23. package/dist/extensions/mcp.cjs.map +1 -1
  24. package/dist/extensions/mcp.d.mts +1 -1
  25. package/dist/extensions/mcp.mjs +23 -23
  26. package/dist/extensions/mcp.mjs.map +1 -1
  27. package/dist/extensions/native.mjs +14 -0
  28. package/dist/extensions/native.mjs.map +1 -1
  29. package/dist/extensions/server.cjs +70 -15
  30. package/dist/extensions/server.cjs.map +1 -1
  31. package/dist/extensions/server.d.mts +1 -1
  32. package/dist/extensions/server.mjs +75 -20
  33. package/dist/extensions/server.mjs.map +1 -1
  34. package/dist/extensions/web.mjs +28 -28
  35. package/dist/extensions/web.mjs.map +1 -1
  36. package/dist/{index-teIf67qQ.d.mts → index-B9QNwUBr.d.mts} +8 -8
  37. package/dist/{index-teIf67qQ.d.mts.map → index-B9QNwUBr.d.mts.map} +1 -1
  38. package/dist/{index-B-3sCF2S.d.mts → index-BsZ8DxpJ.d.mts} +7 -7
  39. package/dist/{index-B-3sCF2S.d.mts.map → index-BsZ8DxpJ.d.mts.map} +1 -1
  40. package/dist/{index-XY9VPmfm.d.mts → index-CA4Opp4r.d.mts} +2 -2
  41. package/dist/{index-XY9VPmfm.d.mts.map → index-CA4Opp4r.d.mts.map} +1 -1
  42. package/dist/{index-Dvb8X_qB.d.mts → index-qQGWsPum.d.mts} +2 -2
  43. package/dist/index-qQGWsPum.d.mts.map +1 -0
  44. package/dist/index.cjs +4 -4
  45. package/dist/index.d.mts +5 -5
  46. package/dist/index.mjs +4 -4
  47. package/dist/{logSinkTelemetry-B23qGiP-.cjs → logSinkTelemetry-BGb8WQBz.cjs} +4 -4
  48. package/dist/logSinkTelemetry-BGb8WQBz.cjs.map +1 -0
  49. package/dist/{logSinkTelemetry-BMBsC54p.mjs → logSinkTelemetry-BhbKdn-x.mjs} +5 -5
  50. package/dist/logSinkTelemetry-BhbKdn-x.mjs.map +1 -0
  51. package/dist/logSinkTelemetry.cjs +2 -2
  52. package/dist/logSinkTelemetry.d.mts +3 -3
  53. package/dist/logSinkTelemetry.mjs +2 -2
  54. package/dist/{paths-Cah1vFGv.mjs → paths-DajceJig.mjs} +4 -4
  55. package/dist/paths-DajceJig.mjs.map +1 -0
  56. package/dist/{paths-CSya2l9_.cjs → paths-P-XvOUuH.cjs} +4 -4
  57. package/dist/paths-P-XvOUuH.cjs.map +1 -0
  58. package/dist/storeInvariants.mjs +1 -2
  59. package/dist/storePaths.cjs +1 -1
  60. package/dist/storePaths.d.mts +1 -1
  61. package/dist/storePaths.mjs +1 -2
  62. package/dist/storeProcessLiveness.mjs +1 -2
  63. package/dist/storeReconcile.mjs +1 -2
  64. package/dist/storeReducer.mjs +1 -2
  65. package/dist/storeTaskGraph.mjs +1 -2
  66. package/dist/storeTaskStore.cjs +1 -1
  67. package/dist/storeTaskStore.d.mts +1 -1
  68. package/dist/storeTaskStore.mjs +1 -2
  69. package/dist/storeTypes.mjs +1 -2
  70. package/dist/{task-Dhta7JyA.d.mts → task-4HeGAS8o.d.mts} +6 -6
  71. package/dist/{task-Dhta7JyA.d.mts.map → task-4HeGAS8o.d.mts.map} +1 -1
  72. package/dist/{taskStore-pAJ971Ml.mjs → taskStore-BAi54FKL.mjs} +4 -4
  73. package/dist/{taskStore-pAJ971Ml.mjs.map → taskStore-BAi54FKL.mjs.map} +1 -1
  74. package/dist/{taskStore-DjU60rMm.cjs → taskStore-C4vcUOzA.cjs} +4 -4
  75. package/dist/{taskStore-DjU60rMm.cjs.map → taskStore-C4vcUOzA.cjs.map} +1 -1
  76. package/dist/telemetry-DYfgUFF8.d.mts +35 -0
  77. package/dist/telemetry-DYfgUFF8.d.mts.map +1 -0
  78. package/dist/telemetry-gEGWTaMI.mjs +25 -0
  79. package/dist/telemetry-gEGWTaMI.mjs.map +1 -0
  80. package/dist/telemetry-x3JxCA5K.cjs +30 -0
  81. package/dist/telemetry-x3JxCA5K.cjs.map +1 -0
  82. package/dist/toolPromptGuidelines.cjs +1 -1
  83. package/dist/toolPromptGuidelines.cjs.map +1 -1
  84. package/dist/toolPromptGuidelines.mjs +1 -1
  85. package/dist/toolPromptGuidelines.mjs.map +1 -1
  86. package/dist/toolResponseEnvelope.mjs +1 -2
  87. package/dist/toolSchema.d.mts +1 -1
  88. package/dist/toolSchema.mjs +1 -2
  89. package/package.json +16 -15
  90. package/dist/config-CFSs3iku.mjs.map +0 -1
  91. package/dist/config-CdX-Bv8q.cjs.map +0 -1
  92. package/dist/delegation-CdMqOZB4.mjs.map +0 -1
  93. package/dist/delegation-DsnKjMbJ.cjs.map +0 -1
  94. package/dist/index-Dvb8X_qB.d.mts.map +0 -1
  95. package/dist/logSinkTelemetry-B23qGiP-.cjs.map +0 -1
  96. package/dist/logSinkTelemetry-BMBsC54p.mjs.map +0 -1
  97. package/dist/paths-CSya2l9_.cjs.map +0 -1
  98. package/dist/paths-Cah1vFGv.mjs.map +0 -1
  99. package/dist/telemetry-Ca0I3Tqo.cjs +0 -30
  100. package/dist/telemetry-Ca0I3Tqo.cjs.map +0 -1
  101. package/dist/telemetry-DyS44zAD.mjs +0 -25
  102. package/dist/telemetry-DyS44zAD.mjs.map +0 -1
  103. package/dist/telemetry-FMGRovb4.d.mts +0 -35
  104. package/dist/telemetry-FMGRovb4.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logSinkTelemetry-BhbKdn-x.mjs","names":[],"sources":["../src/services/logSinkTelemetry/index.ts"],"sourcesContent":["import { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } from '@agimon-ai/po-telemetry';\n\nimport { TASK_EVENT, type TaskErrorAttributes, type TaskFailureReporter } from '../../types/telemetry';\n\nexport {\n TASK_EVENT,\n type TaskErrorAttributes,\n type TaskErrorSink,\n type TaskEventName,\n type TaskEventSink,\n type TaskFailureReporter,\n} from '../../types/telemetry';\n\nconst SERVICE_NAME = 'po-task';\nconst PACKAGE_NAME = '@agimon-ai/po-task';\nconst NOTIFICATION_OPERATION = 'completion_notification';\n\nexport interface TaskErrorReporterOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<PoTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface TaskErrorReporter {\n recordError(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordWarning(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordEvent(event: string, attributes?: TaskErrorAttributes): Promise<void>;\n recordNotificationError(error: unknown, taskId: number): Promise<void>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createTaskErrorReporter(options: TaskErrorReporterOptions = {}): TaskErrorReporter {\n const telemetry: PoTelemetry = createPoTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n recordNotificationError: (error, taskId) =>\n telemetry.recordError(TASK_EVENT.notificationFailed, error, {\n 'task.id': taskId,\n 'task.operation': NOTIFICATION_OPERATION,\n }),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n\nexport function toFailureReporter(reporter: TaskErrorReporter): TaskFailureReporter {\n return {\n error: (event, error, attributes) => void reporter.recordError(event, error, attributes),\n warn: (event, error, attributes) => void reporter.recordWarning(event, error, attributes),\n event: (event, attributes) => void reporter.recordEvent(event, attributes),\n };\n}\n"],"mappings":";;;AAaA,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,yBAAyB;AAmB/B,SAAgB,wBAAwB,UAAoC,CAAC,GAAsB;CACjG,MAAM,YAAyB,kBAAkB;EAC/C,aAAa;EACb,aAAa;EACb,KAAK,QAAQ;EACb,eAAe,QAAQ;EACvB,KAAK,QAAQ;EACb,kBAAkB,QAAQ;EAC1B,MAAM,QAAQ;EACd,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO;EACL,cAAc,OAAO,OAAO,eAAe,UAAU,YAAY,OAAO,OAAO,UAAU;EACzF,gBAAgB,OAAO,OAAO,eAAe,UAAU,cAAc,OAAO,OAAO,UAAU;EAC7F,cAAc,OAAO,eAAe,UAAU,YAAY,OAAO,UAAU;EAC3E,0BAA0B,OAAO,WAC/B,UAAU,YAAY,WAAW,oBAAoB,OAAO;GAC1D,WAAW;GACX,kBAAkB;EACpB,CAAC;EACH,aAAa,UAAU,MAAM;EAC7B,gBAAgB,UAAU,SAAS;CACrC;AACF;AAEA,SAAgB,kBAAkB,UAAkD;CAClF,OAAO;EACL,QAAQ,OAAO,OAAO,eAAe,KAAK,SAAS,YAAY,OAAO,OAAO,UAAU;EACvF,OAAO,OAAO,OAAO,eAAe,KAAK,SAAS,cAAc,OAAO,OAAO,UAAU;EACxF,QAAQ,OAAO,eAAe,KAAK,SAAS,YAAY,OAAO,UAAU;CAC3E;AACF"}
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_telemetry = require("./telemetry-Ca0I3Tqo.cjs");
3
- const require_logSinkTelemetry = require("./logSinkTelemetry-B23qGiP-.cjs");
2
+ const require_telemetry = require("./telemetry-x3JxCA5K.cjs");
3
+ const require_logSinkTelemetry = require("./logSinkTelemetry-BGb8WQBz.cjs");
4
4
  exports.TASK_EVENT = require_telemetry.TASK_EVENT;
5
5
  exports.createTaskErrorReporter = require_logSinkTelemetry.createTaskErrorReporter;
6
6
  exports.toFailureReporter = require_logSinkTelemetry.toFailureReporter;
@@ -1,11 +1,11 @@
1
- import { a as TaskEventSink, i as TaskEventName, n as TaskErrorAttributes, o as TaskFailureReporter, r as TaskErrorSink, t as TASK_EVENT } from "./telemetry-FMGRovb4.mjs";
2
- import { DoomTelemetryOptions } from "@agimon-ai/po-telemetry";
1
+ import { a as TaskEventSink, i as TaskEventName, n as TaskErrorAttributes, o as TaskFailureReporter, r as TaskErrorSink, t as TASK_EVENT } from "./telemetry-DYfgUFF8.mjs";
2
+ import { PoTelemetryOptions } from "@agimon-ai/po-telemetry";
3
3
  //#region src/services/logSinkTelemetry/index.d.ts
4
4
  export interface TaskErrorReporterOptions {
5
5
  cwd?: string;
6
6
  workspaceRoot?: string;
7
7
  env?: NodeJS.ProcessEnv;
8
- telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;
8
+ telemetryFactory?: NonNullable<PoTelemetryOptions['telemetryFactory']>;
9
9
  warn?: (message: string) => void;
10
10
  }
11
11
  export interface TaskErrorReporter {
@@ -1,3 +1,3 @@
1
- import { t as TASK_EVENT } from "./telemetry-DyS44zAD.mjs";
2
- import { n as toFailureReporter, t as createTaskErrorReporter } from "./logSinkTelemetry-BMBsC54p.mjs";
1
+ import { t as TASK_EVENT } from "./telemetry-gEGWTaMI.mjs";
2
+ import { n as toFailureReporter, t as createTaskErrorReporter } from "./logSinkTelemetry-BhbKdn-x.mjs";
3
3
  export { TASK_EVENT, createTaskErrorReporter, toFailureReporter };
@@ -4,8 +4,8 @@ import path from "node:path";
4
4
  import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "@agimon-ai/po-core/childProcess";
5
5
  import { piAgentDirectory } from "@agimon-ai/po-core/piSettings";
6
6
  //#region src/services/paths/index.ts
7
- const STORE_PATH_ENV = "DOOM_TASK_STORE";
8
- const STORE_DIR_NAME = "doom-task";
7
+ const STORE_PATH_ENV = "PO_TASK_STORE";
8
+ const STORE_DIR_NAME = "po-task";
9
9
  const STORE_FILE_NAME = "tasks.json";
10
10
  const FILE_ENCODING = "utf8";
11
11
  const NOT_FOUND_ERROR_CODE = "ENOENT";
@@ -56,7 +56,7 @@ function resolveStorePath(_cwd = process.cwd(), env = process.env, sessionKey =
56
56
  const override = env[STORE_PATH_ENV]?.trim();
57
57
  if (override) return path.resolve(override);
58
58
  const trimmedSessionKey = sessionKey.trim();
59
- if (!trimmedSessionKey) throw new Error("doom-task session id cannot be blank");
59
+ if (!trimmedSessionKey) throw new Error("po-task session id cannot be blank");
60
60
  return path.join(piAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);
61
61
  }
62
62
  /** Whether a deliberate unscoped task-store override is active. */
@@ -204,4 +204,4 @@ function tempPathFor(storePath, pid = process.pid) {
204
204
  //#endregion
205
205
  export { removeLegacyStoreDirectoryAsync as a, resolveSessionKey as c, sweepStoreFilesAsync as d, tempPathFor as f, removeLegacyStoreDirectory as i, resolveStorePath as l, hasStorePathOverride as n, resolveLegacyStoreDirectory as o, lockPathFor as r, resolveLegacyStoreDirectoryAsync as s, STORE_PATH_ENV as t, sweepStoreFiles as u };
206
206
 
207
- //# sourceMappingURL=paths-Cah1vFGv.mjs.map
207
+ //# sourceMappingURL=paths-DajceJig.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths-DajceJig.mjs","names":[],"sources":["../src/services/paths/index.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/po-core/childProcess';\nimport { piAgentDirectory } from '@agimon-ai/po-core/piSettings';\n\nexport const STORE_PATH_ENV = 'PO_TASK_STORE';\n\nconst STORE_DIR_NAME = 'po-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n if (error) {\n resolve(undefined);\n return;\n }\n const trimmed = stdout.trim();\n resolve(trimmed.length > 0 ? trimmed : undefined);\n });\n });\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(\n rootSessionId: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: Readonly<Record<string, string | undefined>> = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('po-task session id cannot be blank');\n return path.join(piAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: Readonly<Record<string, string | undefined>> = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n currentStorePath: string,\n cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = await resolveLegacyStoreDirectoryAsync(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n await fs.promises.access(target);\n await fs.promises.rm(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport async function sweepStoreFilesAsync(\n currentStorePath: string,\n ttlMs: number,\n now: number = Date.now(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = await fs.promises.readdir(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory) continue;\n try {\n await fs.promises.access(candidate);\n try {\n await fs.promises.access(lockPathFor(candidate));\n continue;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n }\n JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":";;;;;;AAOA,MAAa,iBAAiB;AAE9B,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,uBAAuB;AAE7B,SAAS,IAAI,MAAgB,KAAiC;CAC5D,IAAI;EAMF,MAAM,UALS,aAAa,OAAO,MAAM;GACvC;GACA,UAAU;GACV,OAAO;IAAC;IAAU;IAAQ;GAAQ;EACpC,CACqB,CAAC,CAAC,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
29
  let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
30
30
  //#region src/services/paths/index.ts
31
- const STORE_PATH_ENV = "DOOM_TASK_STORE";
32
- const STORE_DIR_NAME = "doom-task";
31
+ const STORE_PATH_ENV = "PO_TASK_STORE";
32
+ const STORE_DIR_NAME = "po-task";
33
33
  const STORE_FILE_NAME = "tasks.json";
34
34
  const FILE_ENCODING = "utf8";
35
35
  const NOT_FOUND_ERROR_CODE = "ENOENT";
@@ -80,7 +80,7 @@ function resolveStorePath(_cwd = process.cwd(), env = process.env, sessionKey =
80
80
  const override = env[STORE_PATH_ENV]?.trim();
81
81
  if (override) return node_path.default.resolve(override);
82
82
  const trimmedSessionKey = sessionKey.trim();
83
- if (!trimmedSessionKey) throw new Error("doom-task session id cannot be blank");
83
+ if (!trimmedSessionKey) throw new Error("po-task session id cannot be blank");
84
84
  return node_path.default.join((0, _agimon_ai_po_core_piSettings.piAgentDirectory)(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);
85
85
  }
86
86
  /** Whether a deliberate unscoped task-store override is active. */
@@ -305,4 +305,4 @@ Object.defineProperty(exports, "tempPathFor", {
305
305
  }
306
306
  });
307
307
 
308
- //# sourceMappingURL=paths-CSya2l9_.cjs.map
308
+ //# sourceMappingURL=paths-P-XvOUuH.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths-P-XvOUuH.cjs","names":["execFileSync","path","SUBAGENT_CHILD_ENV","SUBAGENT_PARENT_SESSION_ENV","piAgentDirectory","fs"],"sources":["../src/services/paths/index.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/po-core/childProcess';\nimport { piAgentDirectory } from '@agimon-ai/po-core/piSettings';\n\nexport const STORE_PATH_ENV = 'PO_TASK_STORE';\n\nconst STORE_DIR_NAME = 'po-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n if (error) {\n resolve(undefined);\n return;\n }\n const trimmed = stdout.trim();\n resolve(trimmed.length > 0 ? trimmed : undefined);\n });\n });\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(\n rootSessionId: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: Readonly<Record<string, string | undefined>> = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('po-task session id cannot be blank');\n return path.join(piAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: Readonly<Record<string, string | undefined>> = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n currentStorePath: string,\n cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = await resolveLegacyStoreDirectoryAsync(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n await fs.promises.access(target);\n await fs.promises.rm(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport async function sweepStoreFilesAsync(\n currentStorePath: string,\n ttlMs: number,\n now: number = Date.now(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = await fs.promises.readdir(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory) continue;\n try {\n await fs.promises.access(candidate);\n try {\n await fs.promises.access(lockPathFor(candidate));\n continue;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n }\n JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,MAAa,iBAAiB;AAE9B,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,uBAAuB;AAE7B,SAAS,IAAI,MAAgB,KAAiC;CAC5D,IAAI;EAMF,MAAM,WAAA,GALSA,mBAAAA,aAAAA,CAAa,OAAO,MAAM;GACvC;GACA,UAAU;GACV,OAAO;IAAC;IAAU;IAAQ;GAAQ;EACpC,CACqB,CAAC,CAAC,KAAK;EAC5B,OAAO,QAAQ,SAAS,IAAI,UAAU,KAAA;CACxC,QAAQ;EACN;CACF;AACF;AAEA,eAAe,SAAS,MAAgB,KAA0C;CAChF,OAAO,IAAI,SAAS,YAAY;EAC9B,CAAA,GAAA,mBAAA,SAAA,CAAS,OAAO,MAAM;GAAE;GAAK,UAAU;EAAc,IAAI,OAAO,WAAW;GACzE,IAAI,OAAO;IACT,QAAQ,KAAA,CAAS;IACjB;GACF;GACA,MAAM,UAAU,OAAO,KAAK;GAC5B,QAAQ,QAAQ,SAAS,IAAI,UAAU,KAAA,CAAS;EAClD,CAAC;CACH,CAAC;AACH;AAEA,SAAS,SAAS,MAAc,WAA4B;CAC1D,MAAM,WAAWC,UAAAA,QAAK,SAASA,UAAAA,QAAK,QAAQ,IAAI,GAAGA,UAAAA,QAAK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E,OAAO,OAAO,KAAK,uCAAuC,eAAe,IAAI,OAAO,KAAK,GAAG;EAC5F,OAAO;CACT;CAEA,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,mBAAmBJ,UAAAA,QAAK,KAAK,gBAAgB,KAAK;EACxD,MAAM,YAAYA,UAAAA,QAAK,KAAK,kBAAkB,eAAe;EAC7D,IAAI,qBAAqB,yBAAyB;EAClD,IAAI;GACF,MAAMI,QAAAA,QAAG,SAAS,OAAO,SAAS;GAClC,IAAI;IACF,MAAMA,QAAAA,QAAG,SAAS,OAAO,YAAY,SAAS,CAAC;IAC/C;GACF,SAAS,OAAO;IACd,IAAK,MAAgC,SAAS,sBAAsB,MAAM;GAC5E;GACA,KAAK,MAAM,MAAMA,QAAAA,QAAG,SAAS,SAAS,WAAW,aAAa,CAAC;GAC/D,IAAI,OAAO,MAAMA,QAAAA,QAAG,SAAS,KAAK,SAAS,EAAA,CAAG,WAAW,OAAO;GAChE,MAAMA,QAAAA,QAAG,SAAS,GAAG,kBAAkB;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GACvE,OAAO,QAAQ,KAAK,gBAAgB;EACtC,SAAS,OAAO;GACd,IAAK,MAAgC,SAAS,sBAAsB;GACpE,OAAO,OAAO,KAAK,8BAA8B,UAAU,IAAI,OAAO,KAAK,GAAG;EAChF;CACF;CACA,OAAO;AACT;AAEA,SAAgB,YAAY,WAA2B;CACrD,OAAO,GAAG,UAAU;AACtB;AAEA,SAAgB,YAAY,WAAmB,MAAc,QAAQ,KAAa;CAChF,OAAO,GAAG,UAAU,OAAO;AAC7B"}
@@ -1,2 +1 @@
1
- import { n as canonicalizeTasks, r as isTransitionValid, t as VALID_TRANSITIONS } from "./invariants-q_UamF7D.mjs";
2
- export { VALID_TRANSITIONS, canonicalizeTasks, isTransitionValid };
1
+ export { t as VALID_TRANSITIONS, n as canonicalizeTasks, r as isTransitionValid } from "./invariants-q_UamF7D.mjs";
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_paths = require("./paths-CSya2l9_.cjs");
2
+ const require_paths = require("./paths-P-XvOUuH.cjs");
3
3
  exports.STORE_PATH_ENV = require_paths.STORE_PATH_ENV;
4
4
  exports.hasStorePathOverride = require_paths.hasStorePathOverride;
5
5
  exports.lockPathFor = require_paths.lockPathFor;
@@ -1,2 +1,2 @@
1
- import { a as removeLegacyStoreDirectory, c as resolveLegacyStoreDirectoryAsync, d as sweepStoreFiles, f as sweepStoreFilesAsync, i as lockPathFor, l as resolveSessionKey, n as StoreSweepResult, o as removeLegacyStoreDirectoryAsync, p as tempPathFor, r as hasStorePathOverride, s as resolveLegacyStoreDirectory, t as STORE_PATH_ENV, u as resolveStorePath } from "./index-XY9VPmfm.mjs";
1
+ import { a as removeLegacyStoreDirectory, c as resolveLegacyStoreDirectoryAsync, d as sweepStoreFiles, f as sweepStoreFilesAsync, i as lockPathFor, l as resolveSessionKey, n as StoreSweepResult, o as removeLegacyStoreDirectoryAsync, p as tempPathFor, r as hasStorePathOverride, s as resolveLegacyStoreDirectory, t as STORE_PATH_ENV, u as resolveStorePath } from "./index-CA4Opp4r.mjs";
2
2
  export { STORE_PATH_ENV, StoreSweepResult, hasStorePathOverride, lockPathFor, removeLegacyStoreDirectory, removeLegacyStoreDirectoryAsync, resolveLegacyStoreDirectory, resolveLegacyStoreDirectoryAsync, resolveSessionKey, resolveStorePath, sweepStoreFiles, sweepStoreFilesAsync, tempPathFor };
@@ -1,2 +1 @@
1
- import { a as removeLegacyStoreDirectoryAsync, c as resolveSessionKey, d as sweepStoreFilesAsync, f as tempPathFor, i as removeLegacyStoreDirectory, l as resolveStorePath, n as hasStorePathOverride, o as resolveLegacyStoreDirectory, r as lockPathFor, s as resolveLegacyStoreDirectoryAsync, t as STORE_PATH_ENV, u as sweepStoreFiles } from "./paths-Cah1vFGv.mjs";
2
- export { STORE_PATH_ENV, hasStorePathOverride, lockPathFor, removeLegacyStoreDirectory, removeLegacyStoreDirectoryAsync, resolveLegacyStoreDirectory, resolveLegacyStoreDirectoryAsync, resolveSessionKey, resolveStorePath, sweepStoreFiles, sweepStoreFilesAsync, tempPathFor };
1
+ export { t as STORE_PATH_ENV, n as hasStorePathOverride, r as lockPathFor, i as removeLegacyStoreDirectory, a as removeLegacyStoreDirectoryAsync, o as resolveLegacyStoreDirectory, s as resolveLegacyStoreDirectoryAsync, c as resolveSessionKey, l as resolveStorePath, u as sweepStoreFiles, d as sweepStoreFilesAsync, f as tempPathFor } from "./paths-DajceJig.mjs";
@@ -1,2 +1 @@
1
- import { t as isProcessAlive } from "./processLiveness-Ccd9wenT.mjs";
2
- export { isProcessAlive };
1
+ export { t as isProcessAlive } from "./processLiveness-Ccd9wenT.mjs";
@@ -1,2 +1 @@
1
- import { n as ERR_ORPHANED_BY_SESSION, r as reconcileOrphanedDelegations, t as ERR_ORPHANED_BY_RESTART } from "./reconcile-BcD-hTbd.mjs";
2
- export { ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, reconcileOrphanedDelegations };
1
+ export { t as ERR_ORPHANED_BY_RESTART, n as ERR_ORPHANED_BY_SESSION, r as reconcileOrphanedDelegations } from "./reconcile-BcD-hTbd.mjs";
@@ -1,2 +1 @@
1
- import { a as isCommittingOp, i as formatUpsertFailure, n as REF_PATTERN, o as singleItemOutcome, r as applyTaskMutation, t as MAX_UPSERT_ITEMS } from "./reducer-BEfJFM5L.mjs";
2
- export { MAX_UPSERT_ITEMS, REF_PATTERN, applyTaskMutation, formatUpsertFailure, isCommittingOp, singleItemOutcome };
1
+ export { t as MAX_UPSERT_ITEMS, n as REF_PATTERN, r as applyTaskMutation, i as formatUpsertFailure, a as isCommittingOp, o as singleItemOutcome } from "./reducer-BEfJFM5L.mjs";
@@ -1,2 +1 @@
1
- import { a as unresolvedBlockers, i as isTaskListComplete, n as detectCycle, r as isBlocked, t as deriveBlocks } from "./taskGraph-BOQvT0-M.mjs";
2
- export { deriveBlocks, detectCycle, isBlocked, isTaskListComplete, unresolvedBlockers };
1
+ export { t as deriveBlocks, n as detectCycle, r as isBlocked, i as isTaskListComplete, a as unresolvedBlockers } from "./taskGraph-BOQvT0-M.mjs";
@@ -1,3 +1,3 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_taskStore = require("./taskStore-DjU60rMm.cjs");
2
+ const require_taskStore = require("./taskStore-C4vcUOzA.cjs");
3
3
  exports.TaskStore = require_taskStore.TaskStore;
@@ -1,2 +1,2 @@
1
- import { n as TaskStoreOptions, t as TaskStore } from "./index-Dvb8X_qB.mjs";
1
+ import { n as TaskStoreOptions, t as TaskStore } from "./index-qQGWsPum.mjs";
2
2
  export { TaskStore, TaskStoreOptions };
@@ -1,2 +1 @@
1
- import { t as TaskStore } from "./taskStore-pAJ971Ml.mjs";
2
- export { TaskStore };
1
+ export { t as TaskStore } from "./taskStore-BAi54FKL.mjs";
@@ -1,2 +1 @@
1
- import { i as isDelegationActive, n as STORE_SCHEMA_VERSION, r as emptyDocument, t as DELETED_STATUS } from "./task-giCbpKzV.mjs";
2
- export { DELETED_STATUS, STORE_SCHEMA_VERSION, emptyDocument, isDelegationActive };
1
+ export { t as DELETED_STATUS, n as STORE_SCHEMA_VERSION, r as emptyDocument, i as isDelegationActive } from "./task-giCbpKzV.mjs";
@@ -4,9 +4,9 @@ import { Static, Type } from "typebox";
4
4
  declare const COMMAND_NAME = "tasks";
5
5
  //#endregion
6
6
  //#region src/schemas/task.d.ts
7
- declare const TASK_ACTIONS: readonly ['upsert', 'list', 'get', 'delete', 'clear', 'assign', 'cancel'];
8
- declare const TASK_STATUSES: readonly ['pending', 'in_progress', 'completed', 'failed', 'deleted'];
9
- declare const TASK_CONTEXTS: readonly ['fresh', 'fork'];
7
+ declare const TASK_ACTIONS: readonly ["upsert", "list", "get", "delete", "clear", "assign", "cancel"];
8
+ declare const TASK_STATUSES: readonly ["pending", "in_progress", "completed", "failed", "deleted"];
9
+ declare const TASK_CONTEXTS: readonly ["fresh", "fork"];
10
10
  declare const TOOL_NAME = "task";
11
11
  declare const TOOL_LABEL = "Task";
12
12
  declare const ERR_REQUIRES_INTERACTIVE = "/tasks requires interactive mode";
@@ -98,8 +98,9 @@ declare const TaskParamsSchema: Type.TObject<{
98
98
  includeDeleted: Type.TOptional<Type.TBoolean>;
99
99
  }>;
100
100
  /** Remote MCP connections track tasks only; delegation stays with the local agent. */
101
- declare const REMOTE_TASK_ACTIONS: readonly ['upsert', 'list', 'get', 'delete', 'clear'];
101
+ declare const REMOTE_TASK_ACTIONS: readonly ["upsert", "list", "get", "delete", "clear"];
102
102
  declare const RemoteTaskParamsSchema: Type.TObject<{
103
+ action: Type.TString;
103
104
  tasks: Type.TOptional<Type.TArray<Type.TObject<{
104
105
  id: Type.TOptional<Type.TInteger>;
105
106
  ref: Type.TOptional<Type.TString>;
@@ -116,11 +117,10 @@ declare const RemoteTaskParamsSchema: Type.TObject<{
116
117
  id: Type.TOptional<Type.TInteger>;
117
118
  status: Type.TOptional<Type.TString>;
118
119
  includeDeleted: Type.TOptional<Type.TBoolean>;
119
- action: Type.TString;
120
120
  }>;
121
121
  type TaskItemParams = Static<typeof TaskItemSchema>;
122
122
  type TaskAssignmentParams = Static<typeof TaskAssignmentSchema>;
123
123
  type TaskParams = Static<typeof TaskParamsSchema>;
124
124
  //#endregion
125
125
  export { TaskParamsSchema as _, RemoteTaskParamsSchema as a, TASK_CONTEXTS as c, TOOL_NAME as d, TaskAssignmentParams as f, TaskParams as g, TaskItemSchema as h, REMOTE_TASK_ACTIONS as i, TASK_STATUSES as l, TaskItemParams as m, MSG_NO_TASKS as n, TASK_ACTIONS as o, TaskAssignmentSchema as p, MSG_UPSERT_FIELD_MISPLACED as r, TASK_ACTION_FIELDS as s, ERR_REQUIRES_INTERACTIVE as t, TOOL_LABEL as u, taskActionAcceptsField as v, COMMAND_NAME as y };
126
- //# sourceMappingURL=task-Dhta7JyA.d.mts.map
126
+ //# sourceMappingURL=task-4HeGAS8o.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"task-Dhta7JyA.d.mts","names":[],"sources":["../src/constants/task.ts","../src/schemas/task.ts"],"mappings":";;;cAAa;;;cCOA;cACA;cACA;cAEA;cACA;cAEA;cACA;;;;;;;;;cAUA;;;;;;;;;iBAUG,uBAAuB,QAAQ,YAAY;;cAK9C;;;;;;cAcA,gBAAc,KAAA;;;;;;;;;;;;;;cA2Dd,sBAAoB,KAAA;;;;;;;;;;;;;;;;cA6BpB,kBAAgB,KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAiChB;cAEA,wBAAsB,KAAA;;;;;;;;;;;;;;;;;;;KAKvB,iBAAiB,cAAc;KAC/B,uBAAuB,cAAc;KACrC,aAAa,cAAc"}
1
+ {"version":3,"file":"task-4HeGAS8o.d.mts","names":[],"sources":["../src/constants/task.ts","../src/schemas/task.ts"],"mappings":";;;cAAa;;;cCOA;cACA;cACA;cAEA;cACA;cAEA;cACA;;;;;;;;;cAUA;;;;;;;;;iBAUG,uBAAuB,QAAQ,YAAY;;cAK9C;;;;;;cAcA,gBAAc,KAAA;;;;;;;;;;;;;;cA2Dd,sBAAoB,KAAA;;;;;;;;;;;;;;;;cA6BpB,kBAAgB,KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAiChB;cAEA,wBAAsB,KAAA;;;;;;;;;;;;;;;;;;;KAKvB,iBAAiB,cAAc;KAC/B,uBAAuB,cAAc;KACrC,aAAa,cAAc"}
@@ -1,7 +1,7 @@
1
- import { t as TASK_EVENT } from "./telemetry-DyS44zAD.mjs";
1
+ import { t as TASK_EVENT } from "./telemetry-gEGWTaMI.mjs";
2
2
  import { r as emptyDocument } from "./task-giCbpKzV.mjs";
3
3
  import { t as isProcessAlive } from "./processLiveness-Ccd9wenT.mjs";
4
- import { f as tempPathFor, l as resolveStorePath, r as lockPathFor } from "./paths-Cah1vFGv.mjs";
4
+ import { f as tempPathFor, l as resolveStorePath, r as lockPathFor } from "./paths-DajceJig.mjs";
5
5
  import { n as canonicalizeTasks } from "./invariants-q_UamF7D.mjs";
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
@@ -61,7 +61,7 @@ var TaskStore = class {
61
61
  }
62
62
  /** Bind a default store to the current session tree before reading it. */
63
63
  configureSession(sessionKey) {
64
- if (this.env["DOOM_TASK_STORE"]?.trim()) return;
64
+ if (this.env["PO_TASK_STORE"]?.trim()) return;
65
65
  this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);
66
66
  this.cached = emptyDocument();
67
67
  }
@@ -205,4 +205,4 @@ var TaskStore = class {
205
205
  //#endregion
206
206
  export { TaskStore as t };
207
207
 
208
- //# sourceMappingURL=taskStore-pAJ971Ml.mjs.map
208
+ //# sourceMappingURL=taskStore-BAi54FKL.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"taskStore-pAJ971Ml.mjs","names":[],"sources":["../src/services/taskStore/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\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 UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: Readonly<Record<string, string | undefined>>;\n storePath?: string;\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: Readonly<Record<string, string | undefined>>;\n private cached: TaskDocument = emptyDocument();\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\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.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\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 return this.cached;\n }\n\n async readAsync(\n shouldApply: () => boolean = () => true,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n const storePath = this.storePath;\n const document = await this.readDocumentAsync(storePath, onReadError);\n if (!shouldApply()) return document;\n this.cached = document;\n return document;\n }\n\n private async readDocumentAsync(\n storePath: string = this.storePath,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(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]: storePath });\n try {\n onReadError?.(error);\n } catch {\n // Diagnostic failures must not change fail-open reads.\n }\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: committed,\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification);\n }\n return outcome.result;\n }\n\n private notifyCommitted(committed: TaskDocument): void {\n for (const listener of this.listeners) {\n try {\n listener(committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\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 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 * Listen for commits made through this store instance.\n *\n * Live cross-process updates use the owning session's direct event bus. This\n * listener publishes local commits to that bus and never watches the filesystem.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n"],"mappings":";;;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAY7B,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;;;;;;;AAQA,SAAS,kBAAkB,QAA+B;CACxD,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO,cAAc;CAChE,MAAM,YAAY;CAClB,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,GAAG,OAAO,cAAc;CAE1D,MAAM,QAAQ,kBACZ,UAAU,MAAM,QACb,SAAu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AAI,IAAI,OAAO,OAAO;GAC9E,MAAM,OAAO,OAAO,OAAO,QAAQ,YAAY,CAAC,eAAe,OAAO,GAAG;GACzE,IAAI,CAAC,WAAW,CAAC,MAAM,OAAO;GAC9B,GAAG,WAAW,QAAQ;GACtB,OAAO;EACT,SAAS,OAAO;GAGd,IAAK,MAAgC,SAAS,mBAC5C,KAAK,QAAQ,KAAK,WAAW,sBAAsB,OAAO,GAAG,uBAAuB,SAAS,CAAC;GAEhG,OAAO;EACT;CACF;;;;;;;CAQA,iBAAiB,UAAwD;EACvE,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,KAAK,UAAU,MAAM;CACvB;AACF"}
1
+ {"version":3,"file":"taskStore-BAi54FKL.mjs","names":[],"sources":["../src/services/taskStore/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\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 UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: Readonly<Record<string, string | undefined>>;\n storePath?: string;\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: Readonly<Record<string, string | undefined>>;\n private cached: TaskDocument = emptyDocument();\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\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.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\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 return this.cached;\n }\n\n async readAsync(\n shouldApply: () => boolean = () => true,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n const storePath = this.storePath;\n const document = await this.readDocumentAsync(storePath, onReadError);\n if (!shouldApply()) return document;\n this.cached = document;\n return document;\n }\n\n private async readDocumentAsync(\n storePath: string = this.storePath,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(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]: storePath });\n try {\n onReadError?.(error);\n } catch {\n // Diagnostic failures must not change fail-open reads.\n }\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: committed,\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification);\n }\n return outcome.result;\n }\n\n private notifyCommitted(committed: TaskDocument): void {\n for (const listener of this.listeners) {\n try {\n listener(committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\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 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 * Listen for commits made through this store instance.\n *\n * Live cross-process updates use the owning session's direct event bus. This\n * listener publishes local commits to that bus and never watches the filesystem.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n"],"mappings":";;;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAY7B,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;;;;;;;AAQA,SAAS,kBAAkB,QAA+B;CACxD,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO,cAAc;CAChE,MAAM,YAAY;CAClB,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,GAAG,OAAO,cAAc;CAE1D,MAAM,QAAQ,kBACZ,UAAU,MAAM,QACb,SAAuB,QAAQ,IAAI,KAAK,OAAO,SAAS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AM,OAAO,OAAO,OAAO,QAAQ,YAAY,CAAC,eAAe,OAAO,GAAG;GACzE,IAAI,CAAC,WAAW,CAAC,MAAM,OAAO;GAC9B,GAAG,WAAW,QAAQ;GACtB,OAAO;EACT,SAAS,OAAO;GAGd,IAAK,MAAgC,SAAS,mBAC5C,KAAK,QAAQ,KAAK,WAAW,sBAAsB,OAAO,GAAG,uBAAuB,SAAS,CAAC;GAEhG,OAAO;EACT;CACF;;;;;;;CAQA,iBAAiB,UAAwD;EACvE,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,KAAK,UAAU,MAAM;CACvB;AACF"}
@@ -1,5 +1,5 @@
1
- const require_paths = require("./paths-CSya2l9_.cjs");
2
- const require_telemetry = require("./telemetry-Ca0I3Tqo.cjs");
1
+ const require_paths = require("./paths-P-XvOUuH.cjs");
2
+ const require_telemetry = require("./telemetry-x3JxCA5K.cjs");
3
3
  const require_task = require("./task-CXF9VULl.cjs");
4
4
  const require_processLiveness = require("./processLiveness-umpNgsPR.cjs");
5
5
  const require_invariants = require("./invariants-DhjEjBPU.cjs");
@@ -63,7 +63,7 @@ var TaskStore = class {
63
63
  }
64
64
  /** Bind a default store to the current session tree before reading it. */
65
65
  configureSession(sessionKey) {
66
- if (this.env["DOOM_TASK_STORE"]?.trim()) return;
66
+ if (this.env["PO_TASK_STORE"]?.trim()) return;
67
67
  this.storePath = require_paths.resolveStorePath(this.cwd, this.env, sessionKey);
68
68
  this.cached = require_task.emptyDocument();
69
69
  }
@@ -212,4 +212,4 @@ Object.defineProperty(exports, "TaskStore", {
212
212
  }
213
213
  });
214
214
 
215
- //# sourceMappingURL=taskStore-DjU60rMm.cjs.map
215
+ //# sourceMappingURL=taskStore-C4vcUOzA.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"taskStore-DjU60rMm.cjs","names":["emptyDocument","canonicalizeTasks","resolveStorePath","fs","TASK_EVENT","path","tempPathFor","lockPathFor","isProcessAlive"],"sources":["../src/services/taskStore/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\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 UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: Readonly<Record<string, string | undefined>>;\n storePath?: string;\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: Readonly<Record<string, string | undefined>>;\n private cached: TaskDocument = emptyDocument();\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\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.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\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 return this.cached;\n }\n\n async readAsync(\n shouldApply: () => boolean = () => true,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n const storePath = this.storePath;\n const document = await this.readDocumentAsync(storePath, onReadError);\n if (!shouldApply()) return document;\n this.cached = document;\n return document;\n }\n\n private async readDocumentAsync(\n storePath: string = this.storePath,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(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]: storePath });\n try {\n onReadError?.(error);\n } catch {\n // Diagnostic failures must not change fail-open reads.\n }\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: committed,\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification);\n }\n return outcome.result;\n }\n\n private notifyCommitted(committed: TaskDocument): void {\n for (const listener of this.listeners) {\n try {\n listener(committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\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 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 * Listen for commits made through this store instance.\n *\n * Live cross-process updates use the owning session's direct event bus. This\n * listener publishes local commits to that bus and never watches the filesystem.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n"],"mappings":";;;;;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAY7B,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;;;;;;;AAQA,SAAS,kBAAkB,QAA+B;CACxD,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAOA,aAAAA,cAAc;CAChE,MAAM,YAAY;CAClB,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,GAAG,OAAOA,aAAAA,cAAc;CAE1D,MAAM,QAAQC,mBAAAA,kBACZ,UAAU,MAAM,QACb,SAAuB,QAAQ,IAAI,KAAK,OAAO,SAAS,YAAY,OAAQ,KAAc,OAAO,QACpG,CACF;CACA,MAAM,QAAQ,MAAM,QAAQ,KAAK,SAAS,KAAK,IAAI,KAAK,KAAK,EAAE,GAAG,CAAC;CACnE,OAAO;EACL,SAAS,OAAO,UAAU,YAAY,WAAW,UAAU,UAAA;EAC3D,KAAK,OAAO,UAAU,QAAQ,WAAW,UAAU,MAAM;EACzD,QAAQ,OAAO,UAAU,WAAW,YAAY,UAAU,SAAS,QAAQ,UAAU,SAAS,QAAQ;EACtG;CACF;AACF;;;;;;;;;AAUA,IAAa,YAAb,MAAuB;CACrB;CAEA;CACA;CACA,SAA+BD,aAAAA,cAAc;CAC7C,4BAA6B,IAAI,IAAsC;CACvE;CACA;CAEA,YAAY,UAA4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G,uBAAuB,SAAS,CAAC;GAEhG,OAAO;EACT;CACF;;;;;;;CAQA,iBAAiB,UAAwD;EACvE,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,KAAK,UAAU,MAAM;CACvB;AACF"}
1
+ {"version":3,"file":"taskStore-C4vcUOzA.cjs","names":["emptyDocument","canonicalizeTasks","resolveStorePath","fs","TASK_EVENT","path","tempPathFor","lockPathFor","isProcessAlive"],"sources":["../src/services/taskStore/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\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 UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: Readonly<Record<string, string | undefined>>;\n storePath?: string;\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: Readonly<Record<string, string | undefined>>;\n private cached: TaskDocument = emptyDocument();\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\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.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\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 return this.cached;\n }\n\n async readAsync(\n shouldApply: () => boolean = () => true,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n const storePath = this.storePath;\n const document = await this.readDocumentAsync(storePath, onReadError);\n if (!shouldApply()) return document;\n this.cached = document;\n return document;\n }\n\n private async readDocumentAsync(\n storePath: string = this.storePath,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(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]: storePath });\n try {\n onReadError?.(error);\n } catch {\n // Diagnostic failures must not change fail-open reads.\n }\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: committed,\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification);\n }\n return outcome.result;\n }\n\n private notifyCommitted(committed: TaskDocument): void {\n for (const listener of this.listeners) {\n try {\n listener(committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\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 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 * Listen for commits made through this store instance.\n *\n * Live cross-process updates use the owning session's direct event bus. This\n * listener publishes local commits to that bus and never watches the filesystem.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n"],"mappings":";;;;;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAY7B,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;;;;;;;AAQA,SAAS,kBAAkB,QAA+B;CACxD,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAOA,aAAAA,cAAc;CAChE,MAAM,YAAY;CAClB,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,GAAG,OAAOA,aAAAA,cAAc;CAE1D,MAAM,QAAQC,mBAAAA,kBACZ,UAAU,MAAM,QACb,SAAuB,QAAQ,IAAI,KAAK,OAAO,SAAS,YAAY,OAAQ,KAAc,OAAO,QACpG,CACF;CACA,MAAM,QAAQ,MAAM,QAAQ,KAAK,SAAS,KAAK,IAAI,KAAK,KAAK,EAAE,GAAG,CAAC;CACnE,OAAO;EACL,SAAS,OAAO,UAAU,YAAY,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K,IAAI,IAAI,OAAO,OAAO;GAC9E,MAAM,OAAO,OAAO,OAAO,QAAQ,YAAY,CAACK,wBAAAA,eAAe,OAAO,GAAG;GACzE,IAAI,CAAC,WAAW,CAAC,MAAM,OAAO;GAC9B,QAAA,QAAG,WAAW,QAAQ;GACtB,OAAO;EACT,SAAS,OAAO;GAGd,IAAK,MAAgC,SAAS,mBAC5C,KAAK,QAAQ,KAAKJ,kBAAAA,WAAW,sBAAsB,OAAO,GAAG,uBAAuB,SAAS,CAAC;GAEhG,OAAO;EACT;CACF;;;;;;;CAQA,iBAAiB,UAAwD;EACvE,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,KAAK,UAAU,MAAM;CACvB;AACF"}
@@ -0,0 +1,35 @@
1
+ //#region src/types/telemetry.d.ts
2
+ declare const TASK_EVENT: {
3
+ readonly notificationFailed: "po_task.notification_failed";
4
+ readonly storeReadFailed: "po_task.store_read_failed";
5
+ readonly storeLockTimeout: "po_task.store_lock_timeout";
6
+ readonly storeLockBreakFailed: "po_task.store_lock_break_failed";
7
+ readonly storeWatchFailed: "po_task.store_watch_failed";
8
+ readonly storeListenerFailed: "po_task.store_listener_failed";
9
+ readonly storeSweepFailed: "po_task.store_sweep_failed";
10
+ readonly sessionStartFailed: "po_task.session_start_failed";
11
+ readonly sessionStartDegraded: "po_task.session_start_degraded";
12
+ readonly toolFailed: "po_task.tool_failed";
13
+ readonly delegationRequestFailed: "po_task.delegation_request_failed";
14
+ readonly delegationStartFailed: "po_task.delegation_start_failed";
15
+ readonly delegationResponseFailed: "po_task.delegation_response_failed";
16
+ readonly delegationSettleFailed: "po_task.delegation_settle_failed";
17
+ readonly delegationTimedOut: "po_task.delegation_timed_out";
18
+ readonly delegationOrphaned: "po_task.delegation_orphaned";
19
+ readonly delegationAssigned: "po_task.delegation_assigned";
20
+ readonly delegationCompleted: "po_task.delegation_completed";
21
+ };
22
+ type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];
23
+ type TaskErrorAttributes = Record<string, string | number | boolean>;
24
+ type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;
25
+ type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;
26
+ /** Host-neutral telemetry port consumed by Task services and store adapters. */
27
+ interface TaskFailureReporter {
28
+ error: TaskErrorSink;
29
+ warn: TaskErrorSink;
30
+ /** Info-level event sink. Required so an unwired reporter fails to compile. */
31
+ event: TaskEventSink;
32
+ }
33
+ //#endregion
34
+ export { TaskEventSink as a, TaskEventName as i, TaskErrorAttributes as n, TaskFailureReporter as o, TaskErrorSink as r, TASK_EVENT as t };
35
+ //# sourceMappingURL=telemetry-DYfgUFF8.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry-DYfgUFF8.d.mts","names":[],"sources":["../src/types/telemetry.ts"],"mappings":";cAAa;;;;;;;;;;;;;;;;;;;;KAuBD,wBAAwB,yBAAyB;KACjD,sBAAsB;KACtB,iBAAiB,OAAO,eAAe,gBAAgB,aAAa;KACpE,iBAAiB,OAAO,eAAe,aAAa;;UAG/C;EACf,OAAO;EACP,MAAM;;EAEN,OAAO"}
@@ -0,0 +1,25 @@
1
+ //#region src/types/telemetry.ts
2
+ const TASK_EVENT = {
3
+ notificationFailed: "po_task.notification_failed",
4
+ storeReadFailed: "po_task.store_read_failed",
5
+ storeLockTimeout: "po_task.store_lock_timeout",
6
+ storeLockBreakFailed: "po_task.store_lock_break_failed",
7
+ storeWatchFailed: "po_task.store_watch_failed",
8
+ storeListenerFailed: "po_task.store_listener_failed",
9
+ storeSweepFailed: "po_task.store_sweep_failed",
10
+ sessionStartFailed: "po_task.session_start_failed",
11
+ sessionStartDegraded: "po_task.session_start_degraded",
12
+ toolFailed: "po_task.tool_failed",
13
+ delegationRequestFailed: "po_task.delegation_request_failed",
14
+ delegationStartFailed: "po_task.delegation_start_failed",
15
+ delegationResponseFailed: "po_task.delegation_response_failed",
16
+ delegationSettleFailed: "po_task.delegation_settle_failed",
17
+ delegationTimedOut: "po_task.delegation_timed_out",
18
+ delegationOrphaned: "po_task.delegation_orphaned",
19
+ delegationAssigned: "po_task.delegation_assigned",
20
+ delegationCompleted: "po_task.delegation_completed"
21
+ };
22
+ //#endregion
23
+ export { TASK_EVENT as t };
24
+
25
+ //# sourceMappingURL=telemetry-gEGWTaMI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry-gEGWTaMI.mjs","names":[],"sources":["../src/types/telemetry.ts"],"sourcesContent":["export const TASK_EVENT = {\n notificationFailed: 'po_task.notification_failed',\n storeReadFailed: 'po_task.store_read_failed',\n storeLockTimeout: 'po_task.store_lock_timeout',\n storeLockBreakFailed: 'po_task.store_lock_break_failed',\n storeWatchFailed: 'po_task.store_watch_failed',\n storeListenerFailed: 'po_task.store_listener_failed',\n storeSweepFailed: 'po_task.store_sweep_failed',\n sessionStartFailed: 'po_task.session_start_failed',\n sessionStartDegraded: 'po_task.session_start_degraded',\n toolFailed: 'po_task.tool_failed',\n delegationRequestFailed: 'po_task.delegation_request_failed',\n delegationStartFailed: 'po_task.delegation_start_failed',\n delegationResponseFailed: 'po_task.delegation_response_failed',\n delegationSettleFailed: 'po_task.delegation_settle_failed',\n delegationTimedOut: 'po_task.delegation_timed_out',\n delegationOrphaned: 'po_task.delegation_orphaned',\n // Info-level lifecycle events. These are the measurement pair: the shape of\n // the brief that went out, and the cost of the run it produced.\n delegationAssigned: 'po_task.delegation_assigned',\n delegationCompleted: 'po_task.delegation_completed',\n} as const;\n\nexport type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];\nexport type TaskErrorAttributes = Record<string, string | number | boolean>;\nexport type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;\nexport type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;\n\n/** Host-neutral telemetry port consumed by Task services and store adapters. */\nexport interface TaskFailureReporter {\n error: TaskErrorSink;\n warn: TaskErrorSink;\n /** Info-level event sink. Required so an unwired reporter fails to compile. */\n event: TaskEventSink;\n}\n"],"mappings":";AAAA,MAAa,aAAa;CACxB,oBAAoB;CACpB,iBAAiB;CACjB,kBAAkB;CAClB,sBAAsB;CACtB,kBAAkB;CAClB,qBAAqB;CACrB,kBAAkB;CAClB,oBAAoB;CACpB,sBAAsB;CACtB,YAAY;CACZ,yBAAyB;CACzB,uBAAuB;CACvB,0BAA0B;CAC1B,wBAAwB;CACxB,oBAAoB;CACpB,oBAAoB;CAGpB,oBAAoB;CACpB,qBAAqB;AACvB"}
@@ -0,0 +1,30 @@
1
+ //#region src/types/telemetry.ts
2
+ const TASK_EVENT = {
3
+ notificationFailed: "po_task.notification_failed",
4
+ storeReadFailed: "po_task.store_read_failed",
5
+ storeLockTimeout: "po_task.store_lock_timeout",
6
+ storeLockBreakFailed: "po_task.store_lock_break_failed",
7
+ storeWatchFailed: "po_task.store_watch_failed",
8
+ storeListenerFailed: "po_task.store_listener_failed",
9
+ storeSweepFailed: "po_task.store_sweep_failed",
10
+ sessionStartFailed: "po_task.session_start_failed",
11
+ sessionStartDegraded: "po_task.session_start_degraded",
12
+ toolFailed: "po_task.tool_failed",
13
+ delegationRequestFailed: "po_task.delegation_request_failed",
14
+ delegationStartFailed: "po_task.delegation_start_failed",
15
+ delegationResponseFailed: "po_task.delegation_response_failed",
16
+ delegationSettleFailed: "po_task.delegation_settle_failed",
17
+ delegationTimedOut: "po_task.delegation_timed_out",
18
+ delegationOrphaned: "po_task.delegation_orphaned",
19
+ delegationAssigned: "po_task.delegation_assigned",
20
+ delegationCompleted: "po_task.delegation_completed"
21
+ };
22
+ //#endregion
23
+ Object.defineProperty(exports, "TASK_EVENT", {
24
+ enumerable: true,
25
+ get: function() {
26
+ return TASK_EVENT;
27
+ }
28
+ });
29
+
30
+ //# sourceMappingURL=telemetry-x3JxCA5K.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry-x3JxCA5K.cjs","names":[],"sources":["../src/types/telemetry.ts"],"sourcesContent":["export const TASK_EVENT = {\n notificationFailed: 'po_task.notification_failed',\n storeReadFailed: 'po_task.store_read_failed',\n storeLockTimeout: 'po_task.store_lock_timeout',\n storeLockBreakFailed: 'po_task.store_lock_break_failed',\n storeWatchFailed: 'po_task.store_watch_failed',\n storeListenerFailed: 'po_task.store_listener_failed',\n storeSweepFailed: 'po_task.store_sweep_failed',\n sessionStartFailed: 'po_task.session_start_failed',\n sessionStartDegraded: 'po_task.session_start_degraded',\n toolFailed: 'po_task.tool_failed',\n delegationRequestFailed: 'po_task.delegation_request_failed',\n delegationStartFailed: 'po_task.delegation_start_failed',\n delegationResponseFailed: 'po_task.delegation_response_failed',\n delegationSettleFailed: 'po_task.delegation_settle_failed',\n delegationTimedOut: 'po_task.delegation_timed_out',\n delegationOrphaned: 'po_task.delegation_orphaned',\n // Info-level lifecycle events. These are the measurement pair: the shape of\n // the brief that went out, and the cost of the run it produced.\n delegationAssigned: 'po_task.delegation_assigned',\n delegationCompleted: 'po_task.delegation_completed',\n} as const;\n\nexport type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];\nexport type TaskErrorAttributes = Record<string, string | number | boolean>;\nexport type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;\nexport type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;\n\n/** Host-neutral telemetry port consumed by Task services and store adapters. */\nexport interface TaskFailureReporter {\n error: TaskErrorSink;\n warn: TaskErrorSink;\n /** Info-level event sink. Required so an unwired reporter fails to compile. */\n event: TaskEventSink;\n}\n"],"mappings":";AAAA,MAAa,aAAa;CACxB,oBAAoB;CACpB,iBAAiB;CACjB,kBAAkB;CAClB,sBAAsB;CACtB,kBAAkB;CAClB,qBAAqB;CACrB,kBAAkB;CAClB,oBAAoB;CACpB,sBAAsB;CACtB,YAAY;CACZ,yBAAyB;CACzB,uBAAuB;CACvB,0BAA0B;CAC1B,wBAAwB;CACxB,oBAAoB;CACpB,oBAAoB;CAGpB,oBAAoB;CACpB,qBAAqB;AACvB"}