@unbrained/pm-cli 2026.10.26 → 2026.10.28

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 (159) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +39 -1
  3. package/dist/cli/commander-usage.js +2 -2
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/register-list-query.js +5 -5
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/chunk-2J7I54MQ.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-25MTQAHX.js → chunk-3KMYHYJV.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-7V37RC2L.js +114 -0
  10. package/dist/cli-bundle/chunks/chunk-AHVN4GHF.js +31 -0
  11. package/dist/cli-bundle/chunks/{chunk-VS2IIV3F.js → chunk-CS7QDSUX.js} +28 -28
  12. package/dist/cli-bundle/chunks/{chunk-T7T4WLUY.js → chunk-CXUQEZDX.js} +3 -3
  13. package/dist/cli-bundle/chunks/{chunk-ZT64RDMF.js → chunk-D3AIQZXF.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-7UDQAINZ.js → chunk-D6P6IBPN.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-TGOG5BFM.js → chunk-DKLEDWVW.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-MWCG25PO.js → chunk-DM3PICGU.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-Y42DYMZX.js → chunk-E5QBZ4HI.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-XAIR53QZ.js → chunk-JESLOJD7.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-57YPOOED.js → chunk-LWW4F4G2.js} +2 -2
  20. package/dist/cli-bundle/chunks/chunk-PQLRKFPZ.js +20 -0
  21. package/dist/cli-bundle/chunks/{chunk-ONC4BBQP.js → chunk-RZQNFHXO.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +2 -0
  23. package/dist/cli-bundle/chunks/{chunk-ER7RLJW5.js → chunk-TH5KPAN4.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-OCDRHIVQ.js → chunk-XHONSCLJ.js} +6 -6
  25. package/dist/cli-bundle/chunks/{chunk-NGKTROAO.js → chunk-YUBUNECD.js} +42 -42
  26. package/dist/cli-bundle/chunks/{chunk-Z35XAHUN.js → chunk-YYD5MNAV.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-UF6EXZSP.js → chunk-ZX3XMTZG.js} +2 -2
  28. package/dist/cli-bundle/chunks/indexed-receipt-blobs-LHLE7PSG.js +4 -0
  29. package/dist/cli-bundle/chunks/{mutation-admission-VTNV6JV2.js → mutation-admission-GKDKHRTZ.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-list-query-LZDWUZS4.js → register-list-query-MHJJUM6M.js} +9 -9
  31. package/dist/cli-bundle/chunks/{register-mutation-M2A7PH42.js → register-mutation-SN425O3R.js} +2 -2
  32. package/dist/cli-bundle/chunks/{register-operations-E7P2JTXM.js → register-operations-EYUIUGPW.js} +2 -2
  33. package/dist/cli-bundle/chunks/{register-setup-DOV7KGSH.js → register-setup-WUZ2ZSMY.js} +2 -2
  34. package/dist/cli-bundle/chunks/{settlement-hook-SVD6CO7U.js → settlement-hook-MN3Y7LVX.js} +2 -2
  35. package/dist/cli-bundle/chunks/{stage-LYLEOAQB.js → stage-2FYJGGG3.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/chunk-3EHVI673.js +2 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-46WLWK73.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/{chunk-E5C24MCV.js → chunk-4GN2ZPT5.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-NLZUI234.js → chunk-6L4KKRK7.js} +18 -18
  40. package/dist/cli-bundle/focused-chunks/{chunk-D5YQ4KAE.js → chunk-6VDRAJYX.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-KTXU5WU6.js → chunk-7SZPZOIC.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-YQKLKRMW.js → chunk-B4ZQJEMT.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-NE27VCU7.js → chunk-BZSACRVX.js} +3 -3
  44. package/dist/cli-bundle/focused-chunks/{chunk-ADSBGYLW.js → chunk-C2GLO7HU.js} +55 -55
  45. package/dist/cli-bundle/focused-chunks/{chunk-UP765R2V.js → chunk-DRN4W3YJ.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-CSCZYSNZ.js → chunk-F6UQJJYB.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-I7H3XF25.js → chunk-I4X6AKOO.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-IQKLJFJE.js +79 -0
  50. package/dist/cli-bundle/focused-chunks/{chunk-KERJNFXY.js → chunk-JTCGDODH.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-IF6C43IP.js → chunk-L5GX2FGZ.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-PK5FJIVA.js → chunk-LPWZERVD.js} +11 -11
  53. package/dist/cli-bundle/focused-chunks/{chunk-YW5GHQN2.js → chunk-ML5JIUM6.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-BL77VCRB.js → chunk-OASYSUOH.js} +16 -16
  55. package/dist/cli-bundle/focused-chunks/{chunk-BH7RE2ZY.js → chunk-ON5WFDCG.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-WDWHUJQW.js → chunk-QUPGBO2L.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-226XKW3W.js → chunk-R3EA3SDW.js} +3 -3
  58. package/dist/cli-bundle/focused-chunks/{chunk-B266DDBJ.js → chunk-TUN4M757.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-YTEC2EPM.js → chunk-Z26ZPQH6.js} +3 -3
  60. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-5H6RMRTK.js +4 -0
  61. package/dist/cli-bundle/focused-chunks/{mutation-admission-L42E3U5U.js → mutation-admission-TM3SVU2O.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{settlement-hook-3CADO4XZ.js → settlement-hook-LBVWWSCF.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{stage-TUQHWU7N.js → stage-7ZBRX2Q2.js} +2 -2
  64. package/dist/cli-bundle/main.js +21 -21
  65. package/dist/cli-bundle/sdk-authoring.js +1 -1
  66. package/dist/cli-bundle/sdk-contracts.js +2 -2
  67. package/dist/cli-bundle/sdk-core.js +34 -33
  68. package/dist/cli-bundle/sdk-governance.js +1 -1
  69. package/dist/cli-bundle/sdk-graph.js +1 -1
  70. package/dist/cli-bundle/sdk-merge.js +57 -57
  71. package/dist/cli-bundle/sdk-query.js +1 -1
  72. package/dist/cli-bundle/sdk-runtime.js +1 -1
  73. package/dist/cli-bundle/sdk-testing.js +1 -1
  74. package/dist/cli-bundle/sdk.js +11 -11
  75. package/dist/core/history/event-index.d.ts +6 -0
  76. package/dist/core/history/event-index.js +7 -6
  77. package/dist/core/history/read.d.ts +3 -1
  78. package/dist/core/history/read.js +1 -1
  79. package/dist/core/item/priority.js +1 -1
  80. package/dist/core/shared/errors.d.ts +2 -0
  81. package/dist/core/shared/errors.js +1 -1
  82. package/dist/core/store/item-store.js +1 -1
  83. package/dist/mcp/tool-definitions.js +1 -1
  84. package/dist/sdk/agent/command-recovery.d.ts +5 -0
  85. package/dist/sdk/agent/command-recovery.js +1 -1
  86. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  87. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  88. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  89. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  90. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  91. package/dist/sdk/command-line.d.ts +6 -0
  92. package/dist/sdk/command-line.js +1 -1
  93. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  94. package/dist/sdk/index.d.ts +1 -1
  95. package/dist/sdk/index.js +1 -1
  96. package/dist/sdk/lifecycle/close.js +1 -1
  97. package/dist/sdk/lifecycle/create.js +1 -1
  98. package/dist/sdk/lifecycle/update-many.js +1 -1
  99. package/dist/sdk/lifecycle/update.js +1 -1
  100. package/dist/sdk/merge/indexed-receipt-blobs.d.ts +3 -1
  101. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  102. package/dist/sdk/merge/receipt-file-boundary.d.ts +2 -0
  103. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  104. package/dist/sdk/merge/receipts.js +2 -2
  105. package/dist/sdk/mutation-events.d.ts +6 -0
  106. package/dist/sdk/mutation-events.js +1 -1
  107. package/dist/sdk/public-surface.json +1 -1
  108. package/dist/sdk/query/history.d.ts +4 -0
  109. package/dist/sdk/query/history.js +1 -1
  110. package/dist/sdk/runtime/actions.js +1 -1
  111. package/dist/sdk/runtime-extended-actions.js +1 -1
  112. package/dist/sdk/runtime.js +1 -1
  113. package/dist/sdk/test/command-resolution.d.ts +5 -0
  114. package/dist/sdk/test/command-resolution.js +3 -0
  115. package/dist/sdk/test/execution.js +3 -3
  116. package/dist/sdk/test/receipt-index-snapshot.d.ts +2 -0
  117. package/dist/sdk/test/receipt-index-snapshot.js +2 -0
  118. package/dist/sdk/test/workspace-snapshot.d.ts +1 -1
  119. package/dist/sdk/test/workspace-snapshot.js +1 -1
  120. package/docs/COMMANDS.md +28 -1
  121. package/docs/PERFORMANCE.md +21 -6
  122. package/docs/RELEASING.md +11 -0
  123. package/docs/SDK.md +40 -0
  124. package/docs/SDK_CONTEXT_COORDINATION.md +35 -4
  125. package/docs/TESTING.md +42 -3
  126. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  127. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  128. package/marketplace.json +1 -1
  129. package/package.json +1 -1
  130. package/packages/pm-beads/package.json +1 -1
  131. package/packages/pm-calendar/package.json +1 -1
  132. package/packages/pm-command-kit/package.json +1 -1
  133. package/packages/pm-digital-twin/package.json +1 -1
  134. package/packages/pm-governance-audit/package.json +1 -1
  135. package/packages/pm-guide-shell/package.json +1 -1
  136. package/packages/pm-kanban/package.json +1 -1
  137. package/packages/pm-lifecycle-hooks/package.json +1 -1
  138. package/packages/pm-linked-test-adapters/package.json +1 -1
  139. package/packages/pm-search-advanced/package.json +1 -1
  140. package/packages/pm-templates/package.json +1 -1
  141. package/packages/pm-todos/package.json +1 -1
  142. package/packages/pm-vcs/package.json +1 -1
  143. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  144. package/plugins/pm-claude/package.json +1 -1
  145. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  146. package/plugins/pm-codex/package.json +1 -1
  147. package/plugins/pm-codex/plugin.json +1 -1
  148. package/runtime-dependencies.json +1 -1
  149. package/dist/cli-bundle/chunks/chunk-N6FTEILW.js +0 -20
  150. package/dist/cli-bundle/chunks/chunk-OUDR2HWR.js +0 -113
  151. package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +0 -2
  152. package/dist/cli-bundle/chunks/chunk-YJBIPNDL.js +0 -2
  153. package/dist/cli-bundle/chunks/chunk-ZLVFUZI4.js +0 -30
  154. package/dist/cli-bundle/chunks/indexed-receipt-blobs-NWQIDTH7.js +0 -4
  155. package/dist/cli-bundle/focused-chunks/chunk-ABMNYWV6.js +0 -2
  156. package/dist/cli-bundle/focused-chunks/chunk-NFN2P4TW.js +0 -2
  157. package/dist/cli-bundle/focused-chunks/chunk-UHWTPOM4.js +0 -78
  158. package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-YFDNGHCM.js +0 -4
@@ -10,9 +10,13 @@ stream_id:string;
10
10
  stream_offset:number;
11
11
  /** Authoritative history entry. */
12
12
  entry:HistoryEntry;
13
+ /** Exact recorded values retained by authoritative verification before timestamp normalization. */
14
+ recorded_entry?:HistoryEntry;
13
15
  }
14
16
  /** Index-native filters and continuation bounds for mutation events. */
15
17
  export interface HistoryEventIndexQuery {
18
+ /** Verify every selected authoritative chain before filtering or pagination. */
19
+ verify?:boolean;
16
20
  /** Return events strictly after this timestamp. */
17
21
  after_ts?:string;
18
22
  /** Stream tie-breaker paired with `after_ts`. */
@@ -47,6 +51,8 @@ export interface HistoryEventIndexQueryResult {
47
51
  events:IndexedHistoryEvent[];
48
52
  /** Whether another matching event exists. */
49
53
  has_more:boolean;
54
+ /** Number of complete authoritative streams verified, when requested. */
55
+ verified_streams?:number;
50
56
  }
51
57
  /** Latest substantive immutable event for each requested history stream. */
52
58
  export type LatestSubstantiveHistoryEvents = Readonly<Record<string,IndexedHistoryEvent>>;
@@ -1,7 +1,7 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f0373f8f-7396-57df-9c8d-9a3315168b5a")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";import{setImmediate as yieldToEventLoop}from"node:timers/promises";import{isFileMissingError}from"../fs/fs-utils.js";import{acquireLock,captureProcessIdentity,isProcessIdentityAlive,hasUnexpiredLockOwner}from"../lock/lock.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{isMillisecondPrecisionRfc3339DateTime}from"../shared/time.js";import{readHistoryEntries}from"./read.js";import{classifyHistoryEvent}from"./event-classification.js";import{loadDatabaseSync,loadStableDatabaseSync}from"../store/sqlite-runtime.js";const EVENT_INDEX_FILENAME="history-event-index.sqlite",EVENT_INDEX_VERSION="6",AUTHORITATIVE_HISTORY_CACHE_LIMIT=8,HISTORY_EVENT_INDEX_LOCK_ID="history-event-index",HISTORY_EVENT_INDEX_APPEND_OWNER_PREFIX="history-event-index:append:",HISTORY_EVENT_INDEX_REPAIR_COOLDOWN_MS=5e3,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS=300,HISTORY_EVENT_INDEX_LOCK_WAIT_MS=3e4,HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID="history-event-index-invalidation",HISTORY_EVENT_INDEX_INVALIDATION_DIRECTORY="history-event-index-invalidations",HISTORY_EVENT_INDEX_INVALIDATION_MAX_UNVERIFIED_AGE_MS=HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS*2*1e3,HISTORY_INDEX_CHANGED=Symbol("history-index-changed"),authoritativeHistoryCaches=new Map;function eventIndexPath(pmRoot){return path.join(pmRoot,"runtime",EVENT_INDEX_FILENAME)}function refusedHistoryRepairPath(pmRoot){return path.join(pmRoot,"runtime","history-event-index-repair-deferred")}async function hasRecentRefusedHistoryRepair(pmRoot){try{const deferredAt=Number(await fs.readFile(refusedHistoryRepairPath(pmRoot),"utf8")),age=Date.now()-deferredAt;return age>=0&&age<HISTORY_EVENT_INDEX_REPAIR_COOLDOWN_MS}catch{return!1}}async function deferAutomaticHistoryRepair(pmRoot){try{await fs.writeFile(refusedHistoryRepairPath(pmRoot),`${Date.now()}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c5f096f6-4af4-568e-89ef-1aa0a8718973")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{createRequire}from"node:module";import{setImmediate as yieldToEventLoop}from"node:timers/promises";import{isFileMissingError}from"../fs/fs-utils.js";import{acquireLock,captureProcessIdentity,isProcessIdentityAlive,hasUnexpiredLockOwner}from"../lock/lock.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{isMillisecondPrecisionRfc3339DateTime}from"../shared/time.js";import{readHistorySnapshot}from"./read.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{classifyHistoryEvent}from"./event-classification.js";import{loadDatabaseSync,loadStableDatabaseSync}from"../store/sqlite-runtime.js";const EVENT_INDEX_FILENAME="history-event-index.sqlite",EVENT_INDEX_VERSION="7",AUTHORITATIVE_HISTORY_CACHE_LIMIT=8,HISTORY_STREAM_CONTENT_READ_CONCURRENCY=32,HISTORY_EVENT_INDEX_LOCK_ID="history-event-index",HISTORY_EVENT_INDEX_APPEND_OWNER_PREFIX="history-event-index:append:",HISTORY_EVENT_INDEX_REPAIR_COOLDOWN_MS=5e3,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS=300,HISTORY_EVENT_INDEX_LOCK_WAIT_MS=3e4,HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID="history-event-index-invalidation",HISTORY_EVENT_INDEX_INVALIDATION_DIRECTORY="history-event-index-invalidations",HISTORY_EVENT_INDEX_INVALIDATION_MAX_UNVERIFIED_AGE_MS=HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS*2*1e3,HISTORY_INDEX_CHANGED=Symbol("history-index-changed"),authoritativeHistoryCaches=new Map;function eventIndexPath(pmRoot){return path.join(pmRoot,"runtime",EVENT_INDEX_FILENAME)}function refusedHistoryRepairPath(pmRoot){return path.join(pmRoot,"runtime","history-event-index-repair-deferred")}async function hasRecentRefusedHistoryRepair(pmRoot){try{const deferredAt=Number(await fs.readFile(refusedHistoryRepairPath(pmRoot),"utf8")),age=Date.now()-deferredAt;return age>=0&&age<HISTORY_EVENT_INDEX_REPAIR_COOLDOWN_MS}catch{return!1}}async function deferAutomaticHistoryRepair(pmRoot){try{await fs.writeFile(refusedHistoryRepairPath(pmRoot),`${Date.now()}
2
2
  `)}catch{}}function historyEventIndexInvalidationDirectory(pmRoot){return path.join(pmRoot,"runtime",HISTORY_EVENT_INDEX_INVALIDATION_DIRECTORY)}async function listHistoryEventIndexInvalidations(pmRoot){const entries=await fs.readdir(historyEventIndexInvalidationDirectory(pmRoot)).catch(error=>{if(isFileMissingError(error))return[];throw error});return{pending:entries.filter(name=>name.endsWith(".pending")).sort(),committed:entries.filter(name=>name.endsWith(".committed")).sort()}}async function recoverAbandonedHistoryEventIndexInvalidations(pmRoot){const invalidations=await listHistoryEventIndexInvalidations(pmRoot);return{pending:(await Promise.all(invalidations.pending.map(async name=>{const owner=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(name);if(owner!==null){const processStartIdentity=owner[2];if(await isProcessIdentityAlive({pid:Number(owner[1]),...processStartIdentity==="unknown"?{}:{process_start_identity:processStartIdentity}},Math.max(0,Date.now()-Number(owner[3])),HISTORY_EVENT_INDEX_INVALIDATION_MAX_UNVERIFIED_AGE_MS))return name}return await fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}),null}))).filter(name=>name!==null),committed:invalidations.committed}}async function withHistoryEventIndexInvalidationLock(pmRoot,operation,waitMs=HISTORY_EVENT_INDEX_LOCK_WAIT_MS){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index-invalidation:${process.pid}`,!1,!1,waitMs,waitMs===0?{maxWaitMs:0}:void 0);try{return await operation()}finally{await release()}}async function beginHistoryEventIndexInvalidation(pmRoot){const directory=historyEventIndexInvalidationDirectory(pmRoot);await fs.mkdir(directory,{recursive:!0});const token=randomUUID(),processIdentity=await captureProcessIdentity(),pendingPath=path.join(directory,`${processIdentity.pid}-${processIdentity.process_start_identity??"unknown"}-${Date.now()}-${token}.pending`);return await fs.writeFile(pendingPath,`pending
3
3
  `,{flag:"wx"}),{pendingPath,committedPath:path.join(directory,`${token}.committed`)}}function sameInvalidationNames(left,right){return left.length===right.length&&left.every((name,index)=>name===right[index])}async function invalidateHistoryEventIndex(pmRoot){try{await fs.rm(eventIndexPath(pmRoot),{force:!0})}catch{}}async function recordHistoryEventIndexInvalidation(pmRoot,retainCache){const directory=historyEventIndexInvalidationDirectory(pmRoot);await fs.mkdir(directory,{recursive:!0}),await fs.writeFile(path.join(directory,`${randomUUID()}${retainCache?".contended":""}.committed`),`committed
4
- `,{flag:"wx"}),retainCache||await invalidateHistoryEventIndex(pmRoot)}function hasContendedHistoryEventIndexInvalidation(invalidations){return invalidations.committed.some(name=>name.endsWith(".contended.committed"))}function hasNativeHistoryEventIndexContention(pmRoot,Database){let database;try{return database=new Database(eventIndexPath(pmRoot)),database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN EXCLUSIVE"),!1}catch(error){return isHistoryIndexSqliteContention(error)}finally{database?.close()}}async function historyEventIndexAppendIsActive(pmRoot,invalidations){return invalidations.pending.length>0||await hasUnexpiredLockOwner(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_APPEND_OWNER_PREFIX)}async function withHistoryEventIndexLock(pmRoot,operation,waitMs=HISTORY_EVENT_INDEX_LOCK_WAIT_MS,purpose="rebuild"){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index:${purpose}:${process.pid}`,!1,!1,waitMs,waitMs===0?{maxWaitMs:0}:void 0);try{return await operation()}finally{await release()}}async function readAuthoritativeHistorySnapshot(pmRoot){const historyRoot=path.join(pmRoot,"history"),entries=await fs.readdir(historyRoot,{withFileTypes:!0}).catch(error=>{if(typeof error=="object"&&error!==null&&"code"in error&&error.code==="ENOENT")return[];throw error}),cached=authoritativeHistoryCaches.get(pmRoot)??{streams:new Map,ordered_events:[]},presentStreams=new Set;let changed=!authoritativeHistoryCaches.has(pmRoot);for(const historyFile of entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).sort((left,right)=>left.name.localeCompare(right.name))){const streamId=historyFile.name.slice(0,-6);presentStreams.add(streamId);const historyPath=path.join(historyRoot,historyFile.name),stats=await fs.stat(historyPath,{bigint:!0}),signature=[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":");if(cached.streams.get(streamId)?.signature===signature)continue;const history=await readIndexableHistoryEntries(historyPath,streamId);cached.streams.set(streamId,{signature,byte_size:Number(stats.size),events:history.map((entry,streamOffset)=>({stream_id:streamId,stream_offset:streamOffset,entry}))}),changed=!0}for(const streamId of cached.streams.keys())presentStreams.has(streamId)||(cached.streams.delete(streamId),changed=!0);if(changed&&(cached.ordered_events=[...cached.streams.values()].flatMap(stream=>stream.events).sort(compareHistoryEventPosition)),authoritativeHistoryCaches.delete(pmRoot),authoritativeHistoryCaches.set(pmRoot,cached),authoritativeHistoryCaches.size>AUTHORITATIVE_HISTORY_CACHE_LIMIT){const oldestRoot=authoritativeHistoryCaches.keys().next().value;authoritativeHistoryCaches.delete(oldestRoot)}return{events:cached.ordered_events,stream_byte_sizes:new Map([...cached.streams].map(([streamId,stream])=>[streamId,stream.byte_size]))}}async function readIndexableHistoryEntries(historyPath,streamId){const entries=await readHistoryEntries(historyPath,streamId);for(const[index,entry]of entries.entries())if(typeof entry.ts!="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim()))throw new PmCliError(`History for ${streamId} contains an invalid or sub-millisecond timestamp at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return entries.map(entry=>({...entry,ts:new Date(entry.ts.trim()).toISOString()}))}async function readAuthoritativeHistoryEvents(pmRoot){return(await readAuthoritativeHistorySnapshot(pmRoot)).events}let RuntimeDatabaseSync;function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function createSchema(database){database.exec(`
4
+ `,{flag:"wx"}),retainCache||await invalidateHistoryEventIndex(pmRoot)}function hasContendedHistoryEventIndexInvalidation(invalidations){return invalidations.committed.some(name=>name.endsWith(".contended.committed"))}function hasNativeHistoryEventIndexContention(pmRoot,Database){let database;try{return database=new Database(eventIndexPath(pmRoot)),database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN EXCLUSIVE"),!1}catch(error){return isHistoryIndexSqliteContention(error)}finally{database?.close()}}async function historyEventIndexAppendIsActive(pmRoot,invalidations){return invalidations.pending.length>0||await hasUnexpiredLockOwner(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_APPEND_OWNER_PREFIX)}async function withHistoryEventIndexLock(pmRoot,operation,waitMs=HISTORY_EVENT_INDEX_LOCK_WAIT_MS,purpose="rebuild"){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index:${purpose}:${process.pid}`,!1,!1,waitMs,waitMs===0?{maxWaitMs:0}:void 0);try{return await operation()}finally{await release()}}async function readAuthoritativeHistorySnapshot(pmRoot,requestedStreamIds,verify=!1){const historyRoot=path.join(pmRoot,"history"),entries=await fs.readdir(historyRoot,{withFileTypes:!0}).catch(error=>{if(typeof error=="object"&&error!==null&&"code"in error&&error.code==="ENOENT")return[];throw error}),base=authoritativeHistoryCaches.get(pmRoot)??{streams:new Map,ordered_events:[]},streams=new Map(base.streams);let orderedEvents=base.ordered_events;const presentStreams=new Set;let changed=!authoritativeHistoryCaches.has(pmRoot);for(const historyFile of entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).sort((left,right)=>left.name.localeCompare(right.name))){const streamId=historyFile.name.slice(0,-6);presentStreams.add(streamId);const historyPath=path.join(historyRoot,historyFile.name);if(!historyStreamIsSelected(streamId,requestedStreamIds))continue;const stream=await readChangedHistoryStream(historyPath,streamId,streams.get(streamId),verify);stream!==void 0&&(streams.set(streamId,stream),changed=!0)}for(const streamId of streams.keys())presentStreams.has(streamId)||(streams.delete(streamId),changed=!0);changed&&(orderedEvents=[...streams.values()].flatMap(stream=>stream.events).sort(compareHistoryEventPosition));const cached={streams,ordered_events:orderedEvents};if(authoritativeHistoryCaches.delete(pmRoot),authoritativeHistoryCaches.set(pmRoot,cached),authoritativeHistoryCaches.size>AUTHORITATIVE_HISTORY_CACHE_LIMIT){const oldestRoot=authoritativeHistoryCaches.keys().next().value;authoritativeHistoryCaches.delete(oldestRoot)}return{events:cached.ordered_events.filter(event=>historyStreamIsSelected(event.stream_id,requestedStreamIds)).map(event=>projectRecordedHistoryEvent(event,verify)),stream_receipts:new Map([...cached.streams].filter(([streamId])=>historyStreamIsSelected(streamId,requestedStreamIds)).map(([streamId,stream])=>[streamId,{byte_size:stream.byte_size,content_hash:stream.signature}]))}}function projectRecordedHistoryEvent(event,verify){return verify||event.recorded_entry===void 0?event:{stream_id:event.stream_id,stream_offset:event.stream_offset,entry:event.entry}}function historyStreamIsSelected(streamId,requested){return!requested?.length||requested.includes(streamId)}async function readChangedHistoryStream(historyPath,streamId,previous,verify){if(!verify&&previous!==void 0&&previous.byte_size===(await fs.stat(historyPath)).size){const signature=createHash("sha256").update(await fs.readFile(historyPath)).digest("hex");if(previous.signature===signature)return}return readIndexableHistoryStream(historyPath,streamId,verify)}async function readIndexableHistoryStream(historyPath,streamId,verify){const snapshot=await readHistorySnapshot(historyPath,streamId);if(verify){const result=verifyHistoryChainWithVersion(snapshot.entries);if(!result.ok)throw new PmCliError(`Authoritative history integrity verification failed for ${streamId}.`,EXIT_CODE.GENERIC_FAILURE,{code:"event_history_integrity_failed",why:result.errors.join(", "),nextSteps:[`Run pm history ${streamId} --verify to inspect the authoritative chain before retrying.`]})}const raw=snapshot.raw_bytes??new Uint8Array;return{signature:createHash("sha256").update(raw).digest("hex"),byte_size:raw.byteLength,events:normalizeIndexableHistoryEntries(snapshot.entries,streamId).map((entry,streamOffset)=>({stream_id:streamId,stream_offset:streamOffset,entry,...verify?{recorded_entry:snapshot.entries[streamOffset]}:{}}))}}async function readIndexableHistoryEntries(historyPath,streamId){return normalizeIndexableHistoryEntries((await readHistorySnapshot(historyPath,streamId)).entries,streamId)}function normalizeIndexableHistoryEntries(entries,streamId){for(const[index,entry]of entries.entries())if(typeof entry.ts!="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim()))throw new PmCliError(`History for ${streamId} contains an invalid or sub-millisecond timestamp at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return entries.map(entry=>({...entry,ts:new Date(entry.ts.trim()).toISOString()}))}let RuntimeDatabaseSync;function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function createSchema(database){database.exec(`
5
5
  PRAGMA journal_mode = OFF;
6
6
  PRAGMA synchronous = OFF;
7
7
  CREATE TABLE metadata (
@@ -22,7 +22,8 @@
22
22
  ) STRICT;
23
23
  CREATE TABLE streams (
24
24
  stream_id TEXT PRIMARY KEY,
25
- byte_size INTEGER NOT NULL CHECK(byte_size >= 0)
25
+ byte_size INTEGER NOT NULL CHECK(byte_size >= 0),
26
+ content_hash TEXT NOT NULL
26
27
  ) STRICT;
27
28
  CREATE INDEX events_order
28
29
  ON events(ts, stream_id, stream_offset);
@@ -39,11 +40,11 @@
39
40
  `),database.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(EVENT_INDEX_VERSION)}function insertEvent(database,event){const entry={...event.entry,ts:new Date(event.entry.ts.trim()).toISOString()};database.prepare(`INSERT INTO events(
40
41
  stream_id, stream_offset, ts, author, agent_harness,
41
42
  agent_instance, op, event_class, entry_json
42
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(event.stream_id,event.stream_offset,entry.ts,entry.author,entry.agent_harness??null,entry.agent_instance??null,entry.op,classifyHistoryEvent(entry),JSON.stringify(entry))}function parseIndexedHistoryEvent(row){const entry=JSON.parse(String(row.entry_json));return typeof entry.ts!="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim())?null:{stream_id:String(row.stream_id),stream_offset:Number(row.stream_offset),entry:{...entry,ts:new Date(entry.ts.trim()).toISOString()}}}function upsertStreamByteSize(database,streamId,byteSize){database.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
43
- ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(streamId,byteSize)}async function rebuildHistoryEventIndex(pmRoot,options={}){const Database=resolveDatabaseSync();return Database?withHistoryEventIndexLock(pmRoot,async()=>{let invalidations;try{invalidations=await withHistoryEventIndexInvalidationLock(pmRoot,()=>recoverAbandonedHistoryEventIndexInvalidations(pmRoot),options.lockWaitMs)}catch(error){if(error instanceof PmCliError&&error.code==="lock_conflict")return!1;throw error}if(invalidations.pending.length>0||hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database))return!1;const targetPath=eventIndexPath(pmRoot);await fs.mkdir(path.dirname(targetPath),{recursive:!0});const temporaryPath=`${targetPath}.${randomUUID()}.tmp`;let database;try{database=new Database(temporaryPath),createSchema(database),database.exec("BEGIN IMMEDIATE");const authoritative=await readAuthoritativeHistorySnapshot(pmRoot);await populateHistoryEventIndex(database,authoritative),database.exec("COMMIT"),database.close(),database=void 0;const published=await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const current=await recoverAbandonedHistoryEventIndexInvalidations(pmRoot);return current.pending.length>0||!sameInvalidationNames(invalidations.committed,current.committed)||hasContendedHistoryEventIndexInvalidation(current)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?!1:(await fs.rm(targetPath,{force:!0}),await fs.rename(temporaryPath,targetPath),!0)},options.lockWaitMs);return published&&await Promise.all(invalidations.committed.map(name=>fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}))),published||(await deferAutomaticHistoryRepair(pmRoot),await fs.rm(temporaryPath,{force:!0})),published}catch(error){throw await deferAutomaticHistoryRepair(pmRoot),database?.close(),await fs.rm(temporaryPath,{force:!0}),error}},options.lockWaitMs):!1}async function populateHistoryEventIndex(database,snapshot){let inserted=0;for(const event of snapshot.events)insertEvent(database,event),++inserted%500===0&&await yieldToEventLoop();for(const[streamId,byteSize]of snapshot.stream_byte_sizes)upsertStreamByteSize(database,streamId,byteSize),++inserted%500===0&&await yieldToEventLoop()}function matchesSet(value,accepted){return!accepted||accepted.length===0||accepted.includes(value)}function compareHistoryEventPosition(left,right){return left.entry.ts.localeCompare(right.entry.ts)||left.stream_id.localeCompare(right.stream_id)||left.stream_offset-right.stream_offset}function canonicalHistoryQueryTimestamp(value){const milliseconds=Date.parse(value);return Number.isFinite(milliseconds)?new Date(milliseconds).toISOString():value}function isInsideHistoryEventWindow(event,query){if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){if(compareHistoryEventPosition(event,{stream_id:query.after_stream_id,stream_offset:query.after_stream_offset,entry:{...event.entry,ts:canonicalHistoryQueryTimestamp(query.after_ts)}})<=0)return!1}else if(query.since_ts!==void 0&&event.entry.ts<canonicalHistoryQueryTimestamp(query.since_ts))return!1;return!0}function matchesHistoryEventHarness(event,query){return!query.harnesses||query.harnesses.length===0||query.harnesses.includes(event.entry.agent_harness??"")?!0:event.entry.agent_harness===void 0&&(query.harness_alias_authors??[]).includes(event.entry.author)}function matchesHistoryEventQuery(event,query){return!isInsideHistoryEventWindow(event,query)||!matchesSet(event.entry.op,query.ops)||!matchesSet(event.entry.author,query.authors)||!matchesSet(event.entry.agent_instance??"",query.agent_instances)||!matchesSet(event.stream_id,query.stream_ids)||!matchesHistoryEventHarness(event,query)?!1:(query.provenance??[]).every(predicate=>{const value=event.entry.agent_provenance?.[predicate.dimension]?.value;return value!==void 0&&predicate.values.includes(value)})}async function queryHistoryEventStreams(pmRoot,query){const limit=Math.max(0,Math.floor(query.limit)),rows=(await readAuthoritativeHistoryEvents(pmRoot)).filter(event=>matchesHistoryEventQuery(event,query)).slice(0,limit+1);return{events:rows.slice(0,query.limit),has_more:rows.length>query.limit}}async function historyEventIndexHasAppendBase(database,historyPath){const stored=database.prepare("SELECT byte_size FROM streams WHERE stream_id = ?").get(path.basename(historyPath,".jsonl"));let actualSize=0;try{actualSize=(await fs.stat(historyPath)).size}catch(error){if(!isFileMissingError(error))throw error}return Number(stored?.byte_size??0)===actualSize}async function appendHistoryEntryWithEventIndex(historyPath,entry,append){const pmRoot=path.dirname(path.dirname(historyPath)),Database=resolveDatabaseSync();let authoritativeAppendCommitted=!1;const appendAuthoritative=async()=>{await append(),authoritativeAppendCommitted=!0};if(!Database){await appendUnindexedHistory(pmRoot,appendAuthoritative);return}try{await withHistoryEventIndexLock(pmRoot,async()=>{const targetPath=eventIndexPath(pmRoot);try{await fs.access(targetPath)}catch{await appendAuthoritative();return}let database;try{if(database=new Database(targetPath),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)throw new TypeError("Unsupported history event index version");if(!await historyEventIndexHasAppendBase(database,historyPath))throw new TypeError("Stale history event index append base")}catch(error){if(database?.close(),isHistoryIndexSqliteContention(error))throw error;await recordHistoryEventIndexInvalidation(pmRoot,!0),await appendAuthoritative();return}try{database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN IMMEDIATE")}catch(error){if(database.close(),isHistoryIndexSqliteContention(error)||!(error instanceof Error)||error.code!=="ERR_SQLITE_ERROR")throw error;await recordHistoryEventIndexInvalidation(pmRoot,!1),await appendAuthoritative();return}let appended=!1;try{await appendAuthoritative(),appended=!0;const streamId=path.basename(historyPath,".jsonl"),offset=database.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(streamId);insertEvent(database,{stream_id:streamId,stream_offset:Number(offset.value),entry}),upsertStreamByteSize(database,streamId,(await fs.stat(historyPath)).size),database.exec("COMMIT"),database.close()}catch(error){if(database?.close(),!appended)throw error;await recordHistoryEventIndexInvalidation(pmRoot,isHistoryIndexSqliteContention(error))}},0,"append")}catch(error){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);return}if(!isHistoryIndexWriteContention(error))throw error;await appendUnindexedHistory(pmRoot,appendAuthoritative,isHistoryIndexSqliteContention(error))}}async function appendUnindexedHistory(pmRoot,append,nativeContention=!1){let authoritativeAppendCommitted=!1,pendingMarkerPath;try{await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const contended=nativeContention||hasContendedHistoryEventIndexInvalidation(await listHistoryEventIndexInvalidations(pmRoot)),marker=await beginHistoryEventIndexInvalidation(pmRoot);pendingMarkerPath=marker.pendingPath;try{await append(),authoritativeAppendCommitted=!0}catch(appendError){throw await fs.rm(marker.pendingPath,{force:!0}),appendError}await fs.rename(marker.pendingPath,contended?marker.committedPath.replace(/\.committed$/u,".contended.committed"):marker.committedPath),contended||await invalidateHistoryEventIndex(pmRoot)})}catch(fallbackError){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);try{await fs.rm(pendingMarkerPath,{force:!0})}catch{}return}throw fallbackError}}async function removeHistoryEventIndexForHistoryPath(historyPath){await fs.rm(eventIndexPath(path.dirname(path.dirname(historyPath))),{force:!0})}function appendSetPredicate(clauses,parameters,column,values){!values||values.length===0||(clauses.push(`${column} IN (${values.map(()=>"?").join(", ")})`),parameters.push(...values))}function appendHarnessPredicate(clauses,parameters,harnesses,aliasAuthors){if(!harnesses||harnesses.length===0)return;const harnessPlaceholders=harnesses.map(()=>"?").join(", "),aliases=aliasAuthors??[];if(aliases.length>0){clauses.push(`(agent_harness IN (${harnessPlaceholders}) OR (agent_harness IS NULL AND author IN (${aliases.map(()=>"?").join(", ")})))`),parameters.push(...harnesses,...aliases);return}clauses.push(`agent_harness IN (${harnessPlaceholders})`),parameters.push(...harnesses)}async function readHistoryEventIndexSnapshot(pmRoot,Database,requestedStreamIds,read){let database;try{const invalidations=await listHistoryEventIndexInvalidations(pmRoot);if(await historyEventIndexAppendIsActive(pmRoot,invalidations))return HISTORY_INDEX_CHANGED;const before=await historyEventIndexSignature(pmRoot);if(invalidations.committed.length>0)return hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?HISTORY_INDEX_CHANGED:null;if(database=new Database(eventIndexPath(pmRoot),{readOnly:!0}),database.exec("BEGIN"),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)return null;const result=read(database);if(result===null)return null;const storedSizes=readHistoryEventIndexStreamSizes(database,requestedStreamIds),completed=database;database=void 0,completed.close();const streamIds=await historyIndexValidationStreamIds([...storedSizes.keys()],pmRoot,requestedStreamIds),sizesMatch=await historyIndexMatchesStreamSizes(storedSizes,pmRoot,streamIds),current=await listHistoryEventIndexInvalidations(pmRoot);return current.committed.length>0||await historyEventIndexAppendIsActive(pmRoot,current)||before!==await historyEventIndexSignature(pmRoot)?HISTORY_INDEX_CHANGED:sizesMatch?result:null}catch(error){return isHistoryIndexSqliteContention(error)?HISTORY_INDEX_CHANGED:null}finally{database?.close()}}function isHistoryIndexSqliteContention(error){return typeof error=="object"&&error!==null&&"errcode"in error&&[5,6].includes(error.errcode)}function isHistoryIndexWriteContention(error){return isHistoryIndexSqliteContention(error)||error instanceof PmCliError&&error.code==="lock_conflict"}function readHistoryEventIndexStreamSizes(database,requestedStreamIds){const storedSizes=new Map,ids=requestedStreamIds&&requestedStreamIds.length>0?[...new Set(requestedStreamIds)]:void 0;if(ids===void 0)for(const row of database.prepare("SELECT stream_id, byte_size FROM streams").all())storedSizes.set(String(row.stream_id),Number(row.byte_size));else for(let start=0;start<ids.length;start+=500){const chunk=ids.slice(start,start+500);for(const row of database.prepare(`SELECT stream_id, byte_size FROM streams WHERE stream_id IN (${chunk.map(()=>"?").join(", ")})`).all(...chunk))storedSizes.set(String(row.stream_id),Number(row.byte_size))}return storedSizes}async function historyEventIndexSignature(pmRoot){const stats=await fs.stat(eventIndexPath(pmRoot),{bigint:!0});return[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":")}async function readHistoryEventIndexPage(pmRoot,query){const Database=resolveDatabaseSync();if(!Database)return{result:null,repair_needed:!1};const clauses=[],parameters=[];if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){clauses.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");const afterTimestamp=canonicalHistoryQueryTimestamp(query.after_ts);parameters.push(afterTimestamp,afterTimestamp,query.after_stream_id,afterTimestamp,query.after_stream_id,query.after_stream_offset)}else query.since_ts!==void 0&&(clauses.push("ts >= ?"),parameters.push(canonicalHistoryQueryTimestamp(query.since_ts)));appendSetPredicate(clauses,parameters,"op",query.ops),appendSetPredicate(clauses,parameters,"author",query.authors),appendHarnessPredicate(clauses,parameters,query.harnesses,query.harness_alias_authors),appendSetPredicate(clauses,parameters,"agent_instance",query.agent_instances);for(const predicate of query.provenance??[])clauses.push(`json_extract(entry_json, '$.agent_provenance.${predicate.dimension}.value') IN (${predicate.values.map(()=>"?").join(", ")})`),parameters.push(...predicate.values);appendSetPredicate(clauses,parameters,"stream_id",query.stream_ids);const where=clauses.length===0?"":` WHERE ${clauses.join(" AND ")}`,attempt=await readHistoryEventIndexSnapshot(pmRoot,Database,query.stream_ids,database=>{const rows=database.prepare(`SELECT stream_id, stream_offset, entry_json
43
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(event.stream_id,event.stream_offset,entry.ts,entry.author,entry.agent_harness??null,entry.agent_instance??null,entry.op,classifyHistoryEvent(entry),JSON.stringify(entry))}function parseIndexedHistoryEvent(row){const entry=JSON.parse(String(row.entry_json));return typeof entry.ts!="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim())?null:{stream_id:String(row.stream_id),stream_offset:Number(row.stream_offset),entry:{...entry,ts:new Date(entry.ts.trim()).toISOString()}}}function upsertStreamContentReceipt(database,streamId,receipt){database.prepare(`INSERT INTO streams(stream_id, byte_size, content_hash) VALUES (?, ?, ?)
44
+ ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size, content_hash = excluded.content_hash`).run(streamId,receipt.byte_size,receipt.content_hash)}async function rebuildHistoryEventIndex(pmRoot,options={}){const Database=resolveDatabaseSync();return Database?withHistoryEventIndexLock(pmRoot,async()=>{let invalidations;try{invalidations=await withHistoryEventIndexInvalidationLock(pmRoot,()=>recoverAbandonedHistoryEventIndexInvalidations(pmRoot),options.lockWaitMs)}catch(error){if(error instanceof PmCliError&&error.code==="lock_conflict")return!1;throw error}if(invalidations.pending.length>0||hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database))return!1;const targetPath=eventIndexPath(pmRoot);await fs.mkdir(path.dirname(targetPath),{recursive:!0});const temporaryPath=`${targetPath}.${randomUUID()}.tmp`;let database;try{database=new Database(temporaryPath),createSchema(database),database.exec("BEGIN IMMEDIATE");const authoritative=await readAuthoritativeHistorySnapshot(pmRoot);await populateHistoryEventIndex(database,authoritative),database.exec("COMMIT"),database.close(),database=void 0;const published=await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const current=await recoverAbandonedHistoryEventIndexInvalidations(pmRoot);return current.pending.length>0||!sameInvalidationNames(invalidations.committed,current.committed)||hasContendedHistoryEventIndexInvalidation(current)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?!1:(await fs.rm(targetPath,{force:!0}),await fs.rename(temporaryPath,targetPath),!0)},options.lockWaitMs);return published&&await Promise.all(invalidations.committed.map(name=>fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}))),published||(await deferAutomaticHistoryRepair(pmRoot),await fs.rm(temporaryPath,{force:!0})),published}catch(error){throw await deferAutomaticHistoryRepair(pmRoot),database?.close(),await fs.rm(temporaryPath,{force:!0}),error}},options.lockWaitMs):!1}async function populateHistoryEventIndex(database,snapshot){let inserted=0;for(const event of snapshot.events)insertEvent(database,event),++inserted%500===0&&await yieldToEventLoop();for(const[streamId,receipt]of snapshot.stream_receipts)upsertStreamContentReceipt(database,streamId,receipt),++inserted%500===0&&await yieldToEventLoop()}function matchesSet(value,accepted){return!accepted||accepted.length===0||accepted.includes(value)}function compareHistoryEventPosition(left,right){return left.entry.ts.localeCompare(right.entry.ts)||left.stream_id.localeCompare(right.stream_id)||left.stream_offset-right.stream_offset}function canonicalHistoryQueryTimestamp(value){const milliseconds=Date.parse(value);return Number.isFinite(milliseconds)?new Date(milliseconds).toISOString():value}function isInsideHistoryEventWindow(event,query){if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){if(compareHistoryEventPosition(event,{stream_id:query.after_stream_id,stream_offset:query.after_stream_offset,entry:{...event.entry,ts:canonicalHistoryQueryTimestamp(query.after_ts)}})<=0)return!1}else if(query.since_ts!==void 0&&event.entry.ts<canonicalHistoryQueryTimestamp(query.since_ts))return!1;return!0}function matchesHistoryEventHarness(event,query){return!query.harnesses||query.harnesses.length===0||query.harnesses.includes(event.entry.agent_harness??"")?!0:event.entry.agent_harness===void 0&&(query.harness_alias_authors??[]).includes(event.entry.author)}function matchesHistoryEventQuery(event,query){return!isInsideHistoryEventWindow(event,query)||!matchesSet(event.entry.op,query.ops)||!matchesSet(event.entry.author,query.authors)||!matchesSet(event.entry.agent_instance??"",query.agent_instances)||!matchesSet(event.stream_id,query.stream_ids)||!matchesHistoryEventHarness(event,query)?!1:(query.provenance??[]).every(predicate=>{const value=event.entry.agent_provenance?.[predicate.dimension]?.value;return value!==void 0&&predicate.values.includes(value)})}async function queryHistoryEventStreams(pmRoot,query){const limit=Math.max(0,Math.floor(query.limit)),snapshot=await readAuthoritativeHistorySnapshot(pmRoot,query.stream_ids,query.verify),rows=snapshot.events.filter(event=>matchesHistoryEventQuery(event,query)).slice(0,limit+1);return{events:rows.slice(0,query.limit),has_more:rows.length>query.limit,...query.verify?{verified_streams:snapshot.stream_receipts.size}:{}}}async function historyEventIndexHasAppendBase(database,historyPath){const stored=database.prepare("SELECT byte_size, content_hash FROM streams WHERE stream_id = ?").get(path.basename(historyPath,".jsonl"));let actualSize=0;try{actualSize=(await fs.stat(historyPath)).size}catch(error){if(!isFileMissingError(error))throw error}if(Number(stored?.byte_size??0)!==actualSize)return!1;const current=await readHistoryStreamContentReceipt(path.dirname(path.dirname(historyPath)),path.basename(historyPath,".jsonl"));return stored===void 0?current?.byte_size===0:current?.content_hash===stored.content_hash}async function appendHistoryEntryWithEventIndex(historyPath,entry,append){const pmRoot=path.dirname(path.dirname(historyPath)),Database=resolveDatabaseSync();let authoritativeAppendCommitted=!1;const appendAuthoritative=async()=>{await append(),authoritativeAppendCommitted=!0};if(!Database){await appendUnindexedHistory(pmRoot,appendAuthoritative);return}try{await withHistoryEventIndexLock(pmRoot,async()=>{const targetPath=eventIndexPath(pmRoot);try{await fs.access(targetPath)}catch{await appendAuthoritative();return}let database;try{if(database=new Database(targetPath),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)throw new TypeError("Unsupported history event index version");if(!await historyEventIndexHasAppendBase(database,historyPath))throw new TypeError("Stale history event index append base")}catch(error){if(database?.close(),isHistoryIndexSqliteContention(error))throw error;await recordHistoryEventIndexInvalidation(pmRoot,!0),await appendAuthoritative();return}try{database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN IMMEDIATE")}catch(error){if(database.close(),isHistoryIndexSqliteContention(error)||!(error instanceof Error)||error.code!=="ERR_SQLITE_ERROR")throw error;await recordHistoryEventIndexInvalidation(pmRoot,!1),await appendAuthoritative();return}let appended=!1;try{await appendAuthoritative(),appended=!0;const streamId=path.basename(historyPath,".jsonl"),offset=database.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(streamId);insertEvent(database,{stream_id:streamId,stream_offset:Number(offset.value),entry}),upsertStreamContentReceipt(database,streamId,await readHistoryStreamContentReceipt(pmRoot,streamId)),database.exec("COMMIT"),database.close()}catch(error){if(database?.close(),!appended)throw error;await recordHistoryEventIndexInvalidation(pmRoot,isHistoryIndexSqliteContention(error))}},0,"append")}catch(error){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);return}if(!isHistoryIndexWriteContention(error))throw error;await appendUnindexedHistory(pmRoot,appendAuthoritative,isHistoryIndexSqliteContention(error))}}async function appendUnindexedHistory(pmRoot,append,nativeContention=!1){let authoritativeAppendCommitted=!1,pendingMarkerPath;try{await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const contended=nativeContention||hasContendedHistoryEventIndexInvalidation(await listHistoryEventIndexInvalidations(pmRoot)),marker=await beginHistoryEventIndexInvalidation(pmRoot);pendingMarkerPath=marker.pendingPath;try{await append(),authoritativeAppendCommitted=!0}catch(appendError){throw await fs.rm(marker.pendingPath,{force:!0}),appendError}await fs.rename(marker.pendingPath,contended?marker.committedPath.replace(/\.committed$/u,".contended.committed"):marker.committedPath),contended||await invalidateHistoryEventIndex(pmRoot)})}catch(fallbackError){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);try{await fs.rm(pendingMarkerPath,{force:!0})}catch{}return}throw fallbackError}}async function removeHistoryEventIndexForHistoryPath(historyPath){await fs.rm(eventIndexPath(path.dirname(path.dirname(historyPath))),{force:!0})}function appendSetPredicate(clauses,parameters,column,values){!values||values.length===0||(clauses.push(`${column} IN (${values.map(()=>"?").join(", ")})`),parameters.push(...values))}function appendHarnessPredicate(clauses,parameters,harnesses,aliasAuthors){if(!harnesses||harnesses.length===0)return;const harnessPlaceholders=harnesses.map(()=>"?").join(", "),aliases=aliasAuthors??[];if(aliases.length>0){clauses.push(`(agent_harness IN (${harnessPlaceholders}) OR (agent_harness IS NULL AND author IN (${aliases.map(()=>"?").join(", ")})))`),parameters.push(...harnesses,...aliases);return}clauses.push(`agent_harness IN (${harnessPlaceholders})`),parameters.push(...harnesses)}async function readHistoryEventIndexSnapshot(pmRoot,Database,requestedStreamIds,read){let database;try{const invalidations=await listHistoryEventIndexInvalidations(pmRoot);if(await historyEventIndexAppendIsActive(pmRoot,invalidations))return HISTORY_INDEX_CHANGED;const before=await historyEventIndexSignature(pmRoot);if(invalidations.committed.length>0)return hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?HISTORY_INDEX_CHANGED:null;if(database=new Database(eventIndexPath(pmRoot),{readOnly:!0}),database.exec("BEGIN"),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)return null;const result=read(database);if(result===null)return null;const storedSizes=readHistoryEventIndexStreamReceipts(database,requestedStreamIds),completed=database;database=void 0,completed.close();const streamIds=await historyIndexValidationStreamIds([...storedSizes.keys()],pmRoot,requestedStreamIds),sizesMatch=await historyIndexMatchesStreamContents(storedSizes,pmRoot,streamIds),current=await listHistoryEventIndexInvalidations(pmRoot);return current.committed.length>0||await historyEventIndexAppendIsActive(pmRoot,current)||before!==await historyEventIndexSignature(pmRoot)?HISTORY_INDEX_CHANGED:sizesMatch?result:null}catch(error){return isHistoryIndexSqliteContention(error)?HISTORY_INDEX_CHANGED:null}finally{database?.close()}}function isHistoryIndexSqliteContention(error){return typeof error=="object"&&error!==null&&"errcode"in error&&[5,6].includes(error.errcode)}function isHistoryIndexWriteContention(error){return isHistoryIndexSqliteContention(error)||error instanceof PmCliError&&error.code==="lock_conflict"}function readHistoryEventIndexStreamReceipts(database,requestedStreamIds){const storedSizes=new Map,ids=requestedStreamIds&&requestedStreamIds.length>0?[...new Set(requestedStreamIds)]:void 0;if(ids===void 0)for(const row of database.prepare("SELECT stream_id, byte_size, content_hash FROM streams").all())storedSizes.set(String(row.stream_id),{byte_size:Number(row.byte_size),content_hash:String(row.content_hash)});else for(let start=0;start<ids.length;start+=500){const chunk=ids.slice(start,start+500);for(const row of database.prepare(`SELECT stream_id, byte_size, content_hash FROM streams WHERE stream_id IN (${chunk.map(()=>"?").join(", ")})`).all(...chunk))storedSizes.set(String(row.stream_id),{byte_size:Number(row.byte_size),content_hash:String(row.content_hash)})}return storedSizes}async function historyEventIndexSignature(pmRoot){const stats=await fs.stat(eventIndexPath(pmRoot),{bigint:!0});return[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":")}async function readHistoryEventIndexPage(pmRoot,query){if(query.verify)return{result:await queryHistoryEventStreams(pmRoot,query),repair_needed:!1};const Database=resolveDatabaseSync();if(!Database)return{result:null,repair_needed:!1};const clauses=[],parameters=[];if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){clauses.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");const afterTimestamp=canonicalHistoryQueryTimestamp(query.after_ts);parameters.push(afterTimestamp,afterTimestamp,query.after_stream_id,afterTimestamp,query.after_stream_id,query.after_stream_offset)}else query.since_ts!==void 0&&(clauses.push("ts >= ?"),parameters.push(canonicalHistoryQueryTimestamp(query.since_ts)));appendSetPredicate(clauses,parameters,"op",query.ops),appendSetPredicate(clauses,parameters,"author",query.authors),appendHarnessPredicate(clauses,parameters,query.harnesses,query.harness_alias_authors),appendSetPredicate(clauses,parameters,"agent_instance",query.agent_instances);for(const predicate of query.provenance??[])clauses.push(`json_extract(entry_json, '$.agent_provenance.${predicate.dimension}.value') IN (${predicate.values.map(()=>"?").join(", ")})`),parameters.push(...predicate.values);appendSetPredicate(clauses,parameters,"stream_id",query.stream_ids);const where=clauses.length===0?"":` WHERE ${clauses.join(" AND ")}`,attempt=await readHistoryEventIndexSnapshot(pmRoot,Database,query.stream_ids,database=>{const rows=database.prepare(`SELECT stream_id, stream_offset, entry_json
44
45
  FROM events${where}
45
46
  ORDER BY ts, stream_id, stream_offset
46
- LIMIT ?`).all(...parameters,Math.max(0,Math.floor(query.limit))+1),events=rows.slice(0,query.limit).map(parseIndexedHistoryEvent);return events.includes(null)?null:{events,has_more:rows.length>query.limit}});return{result:attempt===HISTORY_INDEX_CHANGED?null:attempt,repair_needed:attempt===null&&!await hasRecentRefusedHistoryRepair(pmRoot)}}async function queryHistoryEventIndex(pmRoot,query){return(await readHistoryEventIndexPage(pmRoot,query)).result}function collectLatestSubstantiveEvents(events,requested){const latest=Object.create(null);for(const event of events){if(!requested.has(event.stream_id)||classifyHistoryEvent(event.entry)!=="substantive")continue;const current=latest[event.stream_id];(current===void 0||compareHistoryEventPosition(current,event)<0)&&(latest[event.stream_id]=event)}return latest}async function readHistoryStreamByteSize(pmRoot,streamId){if(path.basename(streamId)!==streamId)return null;try{return(await fs.stat(path.join(pmRoot,"history",`${streamId}.jsonl`))).size}catch(error){if(isFileMissingError(error))return 0;throw error}}async function historyIndexMatchesStreamSizes(storedSizes,pmRoot,streamIds){for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500),currentSizes=await Promise.all(chunk.map(streamId=>readHistoryStreamByteSize(pmRoot,streamId)));for(const[index,currentSize]of currentSizes.entries()){if(currentSize===null)return!1;const streamId=chunk[index],storedSize=storedSizes.get(streamId);if(!(currentSize===0&&storedSize===void 0)&&currentSize!==storedSize)return!1}}return!0}async function historyIndexValidationStreamIds(indexed,pmRoot,requestedStreamIds){if(requestedStreamIds&&requestedStreamIds.length>0)return[...new Set(requestedStreamIds.filter(streamId=>streamId.trim().length>0))];const authoritative=await fs.readdir(path.join(pmRoot,"history"),{withFileTypes:!0}).then(entries=>entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).map(entry=>entry.name.slice(0,-6))).catch(error=>{if(isFileMissingError(error))return[];throw error});return[...new Set([...indexed,...authoritative])]}async function readIndexedLatestSubstantiveEvents(Database,pmRoot,streamIds,requested){return Database?readHistoryEventIndexSnapshot(pmRoot,Database,streamIds,database=>{const indexed=[];for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500),parsed=database.prepare(`SELECT stream_id, stream_offset, entry_json
47
+ LIMIT ?`).all(...parameters,Math.max(0,Math.floor(query.limit))+1),events=rows.slice(0,query.limit).map(parseIndexedHistoryEvent);return events.includes(null)?null:{events,has_more:rows.length>query.limit}});return{result:attempt===HISTORY_INDEX_CHANGED?null:attempt,repair_needed:attempt===null&&!await hasRecentRefusedHistoryRepair(pmRoot)}}async function queryHistoryEventIndex(pmRoot,query){return(await readHistoryEventIndexPage(pmRoot,query)).result}function collectLatestSubstantiveEvents(events,requested){const latest=Object.create(null);for(const event of events){if(!requested.has(event.stream_id)||classifyHistoryEvent(event.entry)!=="substantive")continue;const current=latest[event.stream_id];(current===void 0||compareHistoryEventPosition(current,event)<0)&&(latest[event.stream_id]=event)}return latest}async function readHistoryStreamContentReceipt(pmRoot,streamId){if(path.basename(streamId)!==streamId)return null;try{const historyPath=path.join(pmRoot,"history",`${streamId}.jsonl`),stats=await fs.stat(historyPath),raw=await fs.readFile(historyPath);return stats.size!==raw.length?null:{byte_size:raw.length,content_hash:createHash("sha256").update(raw).digest("hex")}}catch(error){if(isFileMissingError(error))return{byte_size:0,content_hash:createHash("sha256").digest("hex")};throw error}}async function historyIndexMatchesStreamContents(storedSizes,pmRoot,streamIds){for(let start=0;start<streamIds.length;start+=HISTORY_STREAM_CONTENT_READ_CONCURRENCY){const chunk=streamIds.slice(start,start+HISTORY_STREAM_CONTENT_READ_CONCURRENCY),currentSizes=await Promise.all(chunk.map(streamId=>readHistoryStreamContentReceipt(pmRoot,streamId)));for(const[index,currentSize]of currentSizes.entries()){if(currentSize===null)return!1;const streamId=chunk[index],storedSize=storedSizes.get(streamId);if(!(currentSize.byte_size===0&&storedSize===void 0)&&(currentSize.byte_size!==storedSize?.byte_size||currentSize.content_hash!==storedSize.content_hash))return!1}}return!0}async function historyIndexValidationStreamIds(indexed,pmRoot,requestedStreamIds){if(requestedStreamIds&&requestedStreamIds.length>0)return[...new Set(requestedStreamIds.filter(streamId=>streamId.trim().length>0))];const authoritative=await fs.readdir(path.join(pmRoot,"history"),{withFileTypes:!0}).then(entries=>entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).map(entry=>entry.name.slice(0,-6))).catch(error=>{if(isFileMissingError(error))return[];throw error});return[...new Set([...indexed,...authoritative])]}async function readIndexedLatestSubstantiveEvents(Database,pmRoot,streamIds,requested){return Database?readHistoryEventIndexSnapshot(pmRoot,Database,streamIds,database=>{const indexed=[];for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500),parsed=database.prepare(`SELECT stream_id, stream_offset, entry_json
47
48
  FROM (
48
49
  SELECT stream_id, stream_offset, entry_json,
49
50
  ROW_NUMBER() OVER (
@@ -3,7 +3,9 @@ import type { HistoryEntry } from "../../types/index.js";
3
3
  export interface HistoryStreamSnapshot {
4
4
  /** Null means the stream did not exist; an empty string means it existed without entries. */
5
5
  raw:string | null;
6
- /** Entries decoded from precisely the bytes in `raw`, after read hooks run. */
6
+ /** Original file bytes, before UTF-8 decoding; null means the stream did not exist. */
7
+ raw_bytes:Uint8Array | null;
8
+ /** Entries decoded from `raw_bytes`, after read hooks run. */
7
9
  entries:HistoryEntry[];
8
10
  }
9
11
  /** Read one history stream once so replay input and the concurrency snapshot cannot disagree. */
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cfedb84f-0525-5e02-af0a-d0e5691b5e0a")}catch{}})();import{readFileIfExists}from"../fs/fs-utils.js";import{runActiveOnReadHooks}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";async function readHistorySnapshot(historyPath,itemId){const raw=await readFileIfExists(historyPath);if(raw===null)return{raw,entries:[]};if(await runActiveOnReadHooks({path:historyPath,scope:"project"}),raw.trim()==="")return{raw,entries:[]};const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History for ${itemId} contains merge conflict markers at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${itemId}`,`pm restore ${itemId} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{entries.push(JSON.parse(line))}catch{throw new PmCliError(`History for ${itemId} contains invalid JSON at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw,entries}}async function readHistoryEntries(historyPath,itemId){return(await readHistorySnapshot(historyPath,itemId)).entries}export{readHistoryEntries,readHistorySnapshot};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="58661057-fa80-5571-9be7-b949723c274b")}catch{}})();import fs from"node:fs/promises";import{isFileAbsentError}from"../fs/fs-utils.js";import{runActiveOnReadHooks}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";async function readHistorySnapshot(historyPath,itemId){const rawBytes=await fs.readFile(historyPath).catch(error=>{if(isFileAbsentError(error))return null;throw error}),raw=rawBytes?.toString("utf8")??null;if(raw===null)return{raw,raw_bytes:rawBytes,entries:[]};if(await runActiveOnReadHooks({path:historyPath,scope:"project"}),raw.trim()==="")return{raw,raw_bytes:rawBytes,entries:[]};const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History for ${itemId} contains merge conflict markers at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${itemId}`,`pm restore ${itemId} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{entries.push(JSON.parse(line))}catch{throw new PmCliError(`History for ${itemId} contains invalid JSON at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw,raw_bytes:rawBytes,entries}}async function readHistoryEntries(historyPath,itemId){return(await readHistorySnapshot(historyPath,itemId)).entries}export{readHistoryEntries,readHistorySnapshot};
2
2
  //# sourceMappingURL=read.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0257ab6d-3ef8-5b98-adfd-c7dabd537c43")}catch{}})();import{PmCliError}from"../shared/errors.js";import{EXIT_CODE}from"../shared/constants.js";const PRIORITY_NAME_TO_VALUE={critical:0,high:1,medium:2,low:3,minimal:4},PRIORITY_NAME_LIST=Object.keys(PRIORITY_NAME_TO_VALUE),PRIORITY_ACCEPTED_FORMS_HINT=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${PRIORITY_NAME_LIST.join(", ")}), case-insensitive`;function priorityUsageError(raw){return new PmCliError(`Invalid priority "${raw}". Accepted values: ${PRIORITY_ACCEPTED_FORMS_HINT}.`,EXIT_CODE.USAGE)}function resolvePriority(raw){if(typeof raw=="number"){if(Number.isInteger(raw)&&raw>=0&&raw<=4)return raw;throw priorityUsageError(String(raw))}if(typeof raw!="string")throw priorityUsageError(String(raw));const trimmed=raw.trim();if(trimmed.length===0)throw priorityUsageError(raw);const normalizedName=trimmed.toLowerCase();if(Object.prototype.hasOwnProperty.call(PRIORITY_NAME_TO_VALUE,normalizedName))return PRIORITY_NAME_TO_VALUE[normalizedName];if(/^[0-4]$/.test(trimmed))return Number(trimmed);throw priorityUsageError(raw)}export{PRIORITY_ACCEPTED_FORMS_HINT,PRIORITY_NAME_TO_VALUE,resolvePriority};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a59d5b7f-9764-53c5-a014-1119868be8ea")}catch{}})();import{PmCliError}from"../shared/errors.js";import{EXIT_CODE}from"../shared/constants.js";const PRIORITY_NAME_TO_VALUE={critical:0,high:1,medium:2,low:3,minimal:4},PRIORITY_NAME_LIST=Object.keys(PRIORITY_NAME_TO_VALUE),PRIORITY_ACCEPTED_FORMS_HINT=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${PRIORITY_NAME_LIST.join(", ")}), case-insensitive`;function priorityUsageError(raw){return new PmCliError(`Invalid priority "${raw}". Accepted values: ${PRIORITY_ACCEPTED_FORMS_HINT}.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:"priority",value:raw,allowed:["0","1","2","3","4",...PRIORITY_NAME_LIST]})}function resolvePriority(raw){if(typeof raw=="number"){if(Number.isInteger(raw)&&raw>=0&&raw<=4)return raw;throw priorityUsageError(String(raw))}if(typeof raw!="string")throw priorityUsageError(String(raw));const trimmed=raw.trim();if(trimmed.length===0)throw priorityUsageError(raw);const normalizedName=trimmed.toLowerCase();if(Object.prototype.hasOwnProperty.call(PRIORITY_NAME_TO_VALUE,normalizedName))return PRIORITY_NAME_TO_VALUE[normalizedName];if(/^[0-4]$/.test(trimmed))return Number(trimmed);throw priorityUsageError(raw)}export{PRIORITY_ACCEPTED_FORMS_HINT,PRIORITY_NAME_TO_VALUE,resolvePriority};
2
2
  //# sourceMappingURL=priority.js.map
@@ -168,6 +168,8 @@ empty?:boolean;
168
168
  reason?:string;
169
169
  /** Metadata field responsible for a validation failure, when known. */
170
170
  field?:string;
171
+ /** Accepted scalar spellings from the active validation domain, without parsing diagnostic prose. */
172
+ allowed?:string[];
171
173
  /** Original branch coordinates of a scalar patch that cannot safely join a history union. */
172
174
  history_merge?:{
173
175
  /** Side supplying the original event. */
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="85f8d656-86eb-52a9-8160-70b60b9da511")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="48da67d7-53a6-5b8e-a73f-58e67cdb9c22")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
2
2
  //# sourceMappingURL=errors.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1b26ef78-61ae-53d1-a0c8-f6cf9d3794a0")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,itemMutationPreconditionHistoryContext}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext}from"../checkpoint/mutation-context.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease}from"../lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const lease=await acquireLockLease(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),assigned=document.metadata.assignee?.trim(),assignedPrincipal=document.metadata.claim_principal?.trim()||assigned,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock,lease}}catch(error){throw await releaseLock(),error}}async function commitLockedItemWrite(lease,located,originalRaw,commit){return lease.fence(async()=>{let currentRaw;try{currentRaw=await fs.readFile(located.itemPath,"utf8")}catch(error){if(!isFileMissingError(error))throw error;currentRaw=null}if(currentRaw!==originalRaw)throw new PmCliError(`Item ${located.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,EXIT_CODE.CONFLICT,{code:"stale_revision",item_id:located.id,reason:currentRaw===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return commit()})}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function resolveItemStoreDeleteOverride(payload){const override=await runActiveServiceOverride("item_store_delete",payload),record=override.handled&&typeof override.result=="object"&&override.result!==null?override.result:{};return{effectiveItemPath:typeof record.item_path=="string"&&record.item_path.trim().length>0?record.item_path:payload.item_path,skipDelete:record.skip_delete===!0,warnings:override.warnings}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument);if(params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext={...params.resolveHistoryContext?.(),...checkpointMutationHistoryContext(params.pmRoot,located.id),...itemMutationPreconditionHistoryContext(params.pmRoot,document)},requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath:effectiveTargetItemPath2,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath2,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath2!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?Object.keys(historyContext).length===0?void 0:historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath:effectiveTargetItemPath2,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath2,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveTargetItemPath:effectiveTargetItemPath2,overrideWarnings:serviceWriteOverride.warnings}}),{derivedIndexWarnings,effectiveTargetItemPath}=committed;advanceItemMutationPreconditions(params.pmRoot,afterDocument);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}}),historyPath=getHistoryPath(params.pmRoot,located.id),runDeleteOverride=()=>resolveItemStoreDeleteOverride({op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});if(params.dryRun===!0){const preview=await runDeleteOverride();return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:preview.effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...preview.warnings]}}const committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const{effectiveItemPath:effectiveItemPath2,skipDelete,warnings}=await runDeleteOverride(),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipDelete||await fs.rm(effectiveItemPath2);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath2,originalRaw),error}skipDelete||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath2,document:null}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveItemPath:effectiveItemPath2,overrideWarnings:warnings}}),{derivedIndexWarnings,effectiveItemPath}=committed,hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="daea02fe-fa67-5891-b31a-517a07faec58")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,itemMutationPreconditionHistoryContext}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext}from"../checkpoint/mutation-context.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease}from"../lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{code:"item_not_found",id:badId,nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const lease=await acquireLockLease(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),assigned=document.metadata.assignee?.trim(),assignedPrincipal=document.metadata.claim_principal?.trim()||assigned,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock,lease}}catch(error){throw await releaseLock(),error}}async function commitLockedItemWrite(lease,located,originalRaw,commit){return lease.fence(async()=>{let currentRaw;try{currentRaw=await fs.readFile(located.itemPath,"utf8")}catch(error){if(!isFileMissingError(error))throw error;currentRaw=null}if(currentRaw!==originalRaw)throw new PmCliError(`Item ${located.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,EXIT_CODE.CONFLICT,{code:"stale_revision",item_id:located.id,reason:currentRaw===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return commit()})}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function resolveItemStoreDeleteOverride(payload){const override=await runActiveServiceOverride("item_store_delete",payload),record=override.handled&&typeof override.result=="object"&&override.result!==null?override.result:{};return{effectiveItemPath:typeof record.item_path=="string"&&record.item_path.trim().length>0?record.item_path:payload.item_path,skipDelete:record.skip_delete===!0,warnings:override.warnings}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument);if(params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext={...params.resolveHistoryContext?.(),...checkpointMutationHistoryContext(params.pmRoot,located.id),...itemMutationPreconditionHistoryContext(params.pmRoot,document)},requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath:effectiveTargetItemPath2,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath2,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath2!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?Object.keys(historyContext).length===0?void 0:historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath:effectiveTargetItemPath2,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath2,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveTargetItemPath:effectiveTargetItemPath2,overrideWarnings:serviceWriteOverride.warnings}}),{derivedIndexWarnings,effectiveTargetItemPath}=committed;advanceItemMutationPreconditions(params.pmRoot,afterDocument);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}}),historyPath=getHistoryPath(params.pmRoot,located.id),runDeleteOverride=()=>resolveItemStoreDeleteOverride({op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});if(params.dryRun===!0){const preview=await runDeleteOverride();return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:preview.effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...preview.warnings]}}const committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const{effectiveItemPath:effectiveItemPath2,skipDelete,warnings}=await runDeleteOverride(),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipDelete||await fs.rm(effectiveItemPath2);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath2,originalRaw),error}skipDelete||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath2,document:null}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveItemPath:effectiveItemPath2,overrideWarnings:warnings}}),{derivedIndexWarnings,effectiveItemPath}=committed,hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
2
2
  //# sourceMappingURL=item-store.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="16979f9d-779a-595a-abe8-94430fb470d5")}catch{}})();import{WORKFLOW_POLICY_ACTIONS,GRAPH_SUBCOMMAND_VALUES,PM_DISCOVERABLE_TOOL_ACTIONS}from"../sdk/cli-contracts/enum-contracts.js";import{buildPmActionToolInputSchema}from"../sdk/cli-contracts/tool-schema.js";import{RUNTIME_STATUS_ROLE_VALUES}from"../types.js";const CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY=buildPmActionToolInputSchema("list").properties.outputSession,READ_OUTPUT_TOOL_PROPERTIES={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},workflowPolicyOptionProperties={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},TOOL_SCHEMA_BASE={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},idSchema={type:"string",description:"pm item id, for example pm-abc1."},PM_RUN_ACTION_DESCRIPTION=`Operation name (one of): ${PM_DISCOVERABLE_TOOL_ACTIONS.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,LIST_TOP_LEVEL_OPTION_PROPERTIES={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},SEARCH_TOP_LEVEL_OPTION_PROPERTIES={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function objectSchema(properties,required=[]){return{...TOOL_SCHEMA_BASE,properties:{...TOOL_SCHEMA_BASE.properties,...properties},required}}const RAW_TOOLS=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:objectSchema({action:{type:"string",enum:[...PM_DISCOVERABLE_TOOL_ACTIONS],description:PM_RUN_ACTION_DESCRIPTION},id:idSchema,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...READ_OUTPUT_TOOL_PROPERTIES},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:objectSchema({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({query:{type:"string"},options:{type:"object"},...SEARCH_TOP_LEVEL_OPTION_PROPERTIES},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({options:{type:"object"},...LIST_TOP_LEVEL_OPTION_PROPERTIES})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:objectSchema({id:idSchema,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:objectSchema({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:objectSchema({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:idSchema,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:objectSchema({id:idSchema,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:objectSchema({subcommand:{type:"string",enum:[...GRAPH_SUBCOMMAND_VALUES]},id:idSchema,target:idSchema,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:objectSchema({...workflowPolicyOptionProperties,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...WORKFLOW_POLICY_ACTIONS],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...RUNTIME_STATUS_ROLE_VALUES]},description:`Lifecycle roles for add-status: ${RUNTIME_STATUS_ROLE_VALUES.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:workflowPolicyOptionProperties}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:objectSchema({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:objectSchema({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:objectSchema({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],NARROW_TOOL_ACTIONS={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},TOOLS=RAW_TOOLS.map(tool=>{const action=NARROW_TOOL_ACTIONS[tool.name];if(!action)return tool;const properties=tool.inputSchema.properties,required=tool.inputSchema.required.map(String);return{...tool,inputSchema:buildPmActionToolInputSchema(action,{properties,required})}});function buildMcpToolContracts(){return TOOLS.map(tool=>{const schemaRequired=tool.inputSchema.required,required=Array.isArray(schemaRequired)?schemaRequired.map(entry=>String(entry)).sort((left,right)=>left.localeCompare(right)):[];return{name:tool.name,description:tool.description,required,input_schema:tool.inputSchema}}).sort((left,right)=>left.name.localeCompare(right.name))}export{NARROW_TOOL_ACTIONS,TOOLS,TOOL_SCHEMA_BASE,buildMcpToolContracts};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cf9867e5-2739-5bb0-b2f0-c432199942b6")}catch{}})();import{WORKFLOW_POLICY_ACTIONS,GRAPH_SUBCOMMAND_VALUES,PM_DISCOVERABLE_TOOL_ACTIONS}from"../sdk/cli-contracts/enum-contracts.js";import{buildPmActionToolInputSchema}from"../sdk/cli-contracts/tool-schema.js";import{RUNTIME_STATUS_ROLE_VALUES}from"../types.js";const CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY=buildPmActionToolInputSchema("list").properties.outputSession,READ_OUTPUT_TOOL_PROPERTIES={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...CANONICAL_OUTPUT_SESSION_TOOL_PROPERTY},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},workflowPolicyOptionProperties={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},TOOL_SCHEMA_BASE={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},idSchema={type:"string",description:"pm item id, for example pm-abc1."},PM_RUN_ACTION_DESCRIPTION=`Operation name (one of): ${PM_DISCOVERABLE_TOOL_ACTIONS.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,LIST_TOP_LEVEL_OPTION_PROPERTIES={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},SEARCH_TOP_LEVEL_OPTION_PROPERTIES={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function objectSchema(properties,required=[]){return{...TOOL_SCHEMA_BASE,properties:{...TOOL_SCHEMA_BASE.properties,...properties},required}}const RAW_TOOLS=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:objectSchema({action:{type:"string",enum:[...PM_DISCOVERABLE_TOOL_ACTIONS],description:PM_RUN_ACTION_DESCRIPTION},id:idSchema,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...READ_OUTPUT_TOOL_PROPERTIES},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:objectSchema({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({query:{type:"string"},options:{type:"object"},...SEARCH_TOP_LEVEL_OPTION_PROPERTIES},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:objectSchema({options:{type:"object"},...LIST_TOP_LEVEL_OPTION_PROPERTIES})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:objectSchema({id:idSchema,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:objectSchema({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:objectSchema({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:idSchema,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:objectSchema({id:idSchema,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:objectSchema({id:idSchema,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:objectSchema({id:idSchema,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:objectSchema({id:idSchema,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:objectSchema({subcommand:{type:"string",enum:[...GRAPH_SUBCOMMAND_VALUES]},id:idSchema,target:idSchema,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:objectSchema({id:idSchema,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:objectSchema({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:objectSchema({...workflowPolicyOptionProperties,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...WORKFLOW_POLICY_ACTIONS],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...RUNTIME_STATUS_ROLE_VALUES]},description:`Lifecycle roles for add-status: ${RUNTIME_STATUS_ROLE_VALUES.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:workflowPolicyOptionProperties}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:objectSchema({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:objectSchema({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:objectSchema({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],NARROW_TOOL_ACTIONS={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},TOOLS=RAW_TOOLS.map(tool=>{const action=NARROW_TOOL_ACTIONS[tool.name];if(!action)return tool;const properties=tool.inputSchema.properties,required=tool.inputSchema.required.map(String);return{...tool,inputSchema:buildPmActionToolInputSchema(action,{properties,required})}});function buildMcpToolContracts(){return TOOLS.map(tool=>{const schemaRequired=tool.inputSchema.required,required=Array.isArray(schemaRequired)?schemaRequired.map(entry=>String(entry)).sort((left,right)=>left.localeCompare(right)):[];return{name:tool.name,description:tool.description,required,input_schema:tool.inputSchema}}).sort((left,right)=>left.name.localeCompare(right.name))}export{NARROW_TOOL_ACTIONS,TOOLS,TOOL_SCHEMA_BASE,buildMcpToolContracts};
2
2
  //# sourceMappingURL=tool-definitions.js.map
@@ -1,4 +1,9 @@
1
1
  export { resolveLinkedResourcePositionalRecovery } from "./linked-resource-recovery.js";
2
+ /** Explain unsupported lifecycle verbs using declared mutation flags, without authorizing or executing a guessed mutation. */
3
+ export declare function resolveLifecycleVerbRecovery(verb:string,availablePaths:readonly string[]):{
4
+ examples:string[][];
5
+ nextSteps:string[];
6
+ } | undefined;
2
7
  /** Derive a same-command read retry for known completeness and encoding mistakes without discarding intent. */
3
8
  export declare function resolveReadOptionRetryArgs(commandName:string,invocationArgv:readonly string[],unknownOption:string):string[] | undefined;
4
9
  /** Identify presentation intent that must not be silently dropped from an unknown-option retry. */
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a1730bf5-914a-5031-ae21-56bd358727e2")}catch{}})();import{renderPmCommand}from"../command-line.js";import{resolveLinkedResourcePositionalRecovery}from"./linked-resource-recovery.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"../read-output/options.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const READ_PROJECTION_FLAGS=new Set([...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS,"--full","--brief","--compact","--summary","--fields","--section","--token-budget"]),MUTATION_RECEIPT_FLAGS=new Set(["--full-changed-fields","--no-changed-fields","--id-only"]);function activitySinceCorrection(token,next){const inline=token.includes("="),value=inline?token.slice(token.indexOf("=")+1):next;if(!(!value||value.startsWith("--")))return{consumed:inline?1:2,replacement:["--from",value],conflicts:["--from"]}}function readOptionCorrection(command,flag,token,next){if(flag==="--since"&&command==="activity")return activitySinceCorrection(token,next);if(flag==="--full"&&command==="context"&&token===flag)return{consumed:1,replacement:["--depth","full"],conflicts:["--depth","--output-include","--fields","--section","--for"]};if(flag==="--depth"&&["list","search"].includes(command)){const inline=token.includes("=");return(inline?token.slice(token.indexOf("=")+1):next)!=="full"?void 0:{consumed:inline?1:2,replacement:["--full"],conflicts:["--full","--brief","--compact","--output-include","--fields","--for"]}}return flag==="--toon"&&token===flag?{consumed:1,replacement:["--output-format","toon"],conflicts:["--json","--format","--output-format","--stream"]}:void 0}function resolveReadOptionRetryArgs(commandName,invocationArgv,unknownOption){const command=commandName==="ctx"?"context":resolvePmCommandOperation(commandName);if(!["context","list","search","get","activity"].includes(command)||invocationArgv.includes("--"))return;const invoked=parseBootstrapCommandName(invocationArgv);if((invoked==="ctx"?"context":invoked)!==command)return;const flag=unknownOption.split("=",1)[0],indices=invocationArgv.flatMap((token,index2)=>token===flag||token.startsWith(`${flag}=`)?[index2]:[]);if(indices.length!==1)return;const index=indices[0],correction=readOptionCorrection(command,flag,invocationArgv[index],invocationArgv[index+1]);if(!correction)return;const{replacement,consumed,conflicts}=correction;if(!invocationArgv.some(argument=>conflicts.includes(argument.split("=",1)[0])))return[...invocationArgv.slice(0,index),...replacement,...invocationArgv.slice(index+consumed)]}function isReadProjectionRecoveryFlag(flag){const normalized=flag.split("=",1)[0].replaceAll("_","-");return READ_PROJECTION_FLAGS.has(normalized)||normalized.length>=5&&[...READ_PROJECTION_FLAGS].some(candidate=>candidate.startsWith(normalized))}function isCompatibleRecoveryFlag(requested,candidate){const unknownFlag=requested.split("=",1)[0].replaceAll("_","-");return isReadProjectionRecoveryFlag(unknownFlag)?!MUTATION_RECEIPT_FLAGS.has(candidate):MUTATION_RECEIPT_FLAGS.has(unknownFlag)?!isReadProjectionRecoveryFlag(candidate):!0}function normalizeMissingFlag(label){return label.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!(!Array.isArray(invocationArgv)||invocationArgv.length===0))return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));return contract?contract.value_type==="boolean"?null:`<${contract.value_name??"value"}>`:"<value>"}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv],terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`)))continue;const placeholder=resolveMissingOptionPlaceholder(commandName,flag),recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption),insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{isCompatibleRecoveryFlag,isReadProjectionRecoveryFlag,renderMissingOptionRetry,resolveLinkedResourcePositionalRecovery,resolveMissingOptionPlaceholder,resolveReadOptionRetryArgs,resolveRecoveryCommandName};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7eec77b5-0b24-5f0f-967c-a75907f4cd66")}catch{}})();import{renderPmCommand}from"../command-line.js";import{resolveLinkedResourcePositionalRecovery}from"./linked-resource-recovery.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"../read-output/options.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const READ_PROJECTION_FLAGS=new Set([...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS,"--full","--brief","--compact","--summary","--fields","--section","--token-budget"]),MUTATION_RECEIPT_FLAGS=new Set(["--full-changed-fields","--no-changed-fields","--id-only"]);function resolveLifecycleVerbRecovery(verb,availablePaths){if(!["block","unblock"].includes(verb)||availablePaths.includes(verb)||!availablePaths.includes("update"))return;const flags=new Set(resolveSubcommandFlagContractsForCommand("update").map(entry=>entry.flag));if((verb==="block"?["--blocked-by","--blocked-reason"]:["--unset","--unblock-note"]).every(flag=>flags.has(flag)))return verb==="block"?{examples:[["update","<item-id>","--blocked-by","<blocker-id>","--blocked-reason","<reason>"]],nextSteps:["Choose the actual item and blocker identifiers before running update. --blocked-by records the blocker field and its blocked_by relationship."]}:{examples:[["update","<item-id>","--unset","blocked-by","--unset","blocked-reason","--unblock-note","<note>"]],nextSteps:["Inspect the item's blockers before running update. --unset blocked-by removes the blocker field and all blocked_by relationships; --unset blocked-reason clears the stale reason. --unblock-note alone records a note and does not unblock the item.","If your project also uses a blocked lifecycle status, choose its appropriate next status separately with update --status."]}}function activitySinceCorrection(token,next){const inline=token.includes("="),value=inline?token.slice(token.indexOf("=")+1):next;if(!(!value||value.startsWith("--")))return{consumed:inline?1:2,replacement:["--from",value],conflicts:["--from"]}}function readOptionCorrection(command,flag,token,next){if(flag==="--since"&&command==="activity")return activitySinceCorrection(token,next);if(flag==="--full"&&command==="context"&&token===flag)return{consumed:1,replacement:["--depth","full"],conflicts:["--depth","--output-include","--fields","--section","--for"]};if(flag==="--depth"&&["list","search"].includes(command)){const inline=token.includes("=");return(inline?token.slice(token.indexOf("=")+1):next)!=="full"?void 0:{consumed:inline?1:2,replacement:["--full"],conflicts:["--full","--brief","--compact","--output-include","--fields","--for"]}}return flag==="--toon"&&token===flag?{consumed:1,replacement:["--output-format","toon"],conflicts:["--json","--format","--output-format","--stream"]}:void 0}function resolveReadOptionRetryArgs(commandName,invocationArgv,unknownOption){const command=commandName==="ctx"?"context":resolvePmCommandOperation(commandName);if(!["context","list","search","get","activity"].includes(command)||invocationArgv.includes("--"))return;const invoked=parseBootstrapCommandName(invocationArgv);if((invoked==="ctx"?"context":invoked)!==command)return;const flag=unknownOption.split("=",1)[0],indices=invocationArgv.flatMap((token,index2)=>token===flag||token.startsWith(`${flag}=`)?[index2]:[]);if(indices.length!==1)return;const index=indices[0],correction=readOptionCorrection(command,flag,invocationArgv[index],invocationArgv[index+1]);if(!correction)return;const{replacement,consumed,conflicts}=correction;if(!invocationArgv.some(argument=>conflicts.includes(argument.split("=",1)[0])))return[...invocationArgv.slice(0,index),...replacement,...invocationArgv.slice(index+consumed)]}function isReadProjectionRecoveryFlag(flag){const normalized=flag.split("=",1)[0].replaceAll("_","-");return READ_PROJECTION_FLAGS.has(normalized)||normalized.length>=5&&[...READ_PROJECTION_FLAGS].some(candidate=>candidate.startsWith(normalized))}function isCompatibleRecoveryFlag(requested,candidate){const unknownFlag=requested.split("=",1)[0].replaceAll("_","-");return isReadProjectionRecoveryFlag(unknownFlag)?!MUTATION_RECEIPT_FLAGS.has(candidate):MUTATION_RECEIPT_FLAGS.has(unknownFlag)?!isReadProjectionRecoveryFlag(candidate):!0}function normalizeMissingFlag(label){return label.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!(!Array.isArray(invocationArgv)||invocationArgv.length===0))return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));return contract?contract.value_type==="boolean"?null:`<${contract.value_name??"value"}>`:"<value>"}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv],terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`)))continue;const placeholder=resolveMissingOptionPlaceholder(commandName,flag),recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption),insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{isCompatibleRecoveryFlag,isReadProjectionRecoveryFlag,renderMissingOptionRetry,resolveLifecycleVerbRecovery,resolveLinkedResourcePositionalRecovery,resolveMissingOptionPlaceholder,resolveReadOptionRetryArgs,resolveRecoveryCommandName};
2
2
  //# sourceMappingURL=command-recovery.js.map