@unbrained/pm-cli 2026.9.10 → 2026.9.11

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 (157) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +31 -11
  3. package/dist/cli/command-namespaces.d.ts +2 -2
  4. package/dist/cli/command-namespaces.js +1 -1
  5. package/dist/cli/extension-command-help.js +3 -3
  6. package/dist/cli/main.d.ts +4 -0
  7. package/dist/cli/main.js +2 -2
  8. package/dist/cli/register-history-maintenance.js +2 -1
  9. package/dist/cli/register-list-query.js +2 -2
  10. package/dist/cli-bundle/bundle-manifest.json +147 -155
  11. package/dist/cli-bundle/chunks/{chunk-EOCKPCEY.js → chunk-BN5QVWNY.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-DAWH7TGV.js +3 -0
  13. package/dist/cli-bundle/chunks/chunk-FBY6PEIR.js +20 -0
  14. package/dist/cli-bundle/chunks/chunk-IRUNFLLG.js +2 -0
  15. package/dist/cli-bundle/chunks/chunk-JMQKJ7CJ.js +8 -0
  16. package/dist/cli-bundle/chunks/{chunk-I6XT3DLQ.js → chunk-QER6OSOP.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-RJQSCK74.js +6 -0
  18. package/dist/cli-bundle/chunks/chunk-RJZFAXBW.js +235 -0
  19. package/dist/cli-bundle/chunks/{chunk-MACGGTLQ.js → chunk-SGAKQIGQ.js} +29 -29
  20. package/dist/cli-bundle/chunks/{chunk-NKOYVKFM.js → chunk-TDKWJQD7.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-4SFBH77G.js → chunk-TFVKBJJ4.js} +164 -150
  22. package/dist/cli-bundle/chunks/{chunk-PYUITRSV.js → chunk-VFKBNGF6.js} +2 -2
  23. package/dist/cli-bundle/chunks/{register-list-query-CUIW7SSE.js → register-list-query-U6MY437C.js} +6 -6
  24. package/dist/cli-bundle/chunks/{register-mutation-5F5CYUWZ.js → register-mutation-HAPHD4S7.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-operations-XIZPLPQY.js → register-operations-EHWIZW3X.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-setup-JVGPCAIL.js → register-setup-BZYL3HBL.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-ZJHYQOTM.js → chunk-3JVTLBCW.js} +4 -4
  28. package/dist/cli-bundle/focused-chunks/chunk-6JF66HAG.js +2 -0
  29. package/dist/cli-bundle/focused-chunks/{chunk-SL5YVVPV.js → chunk-7WISPJRZ.js} +53 -52
  30. package/dist/cli-bundle/focused-chunks/chunk-BEQAW7OT.js +12 -0
  31. package/dist/cli-bundle/focused-chunks/{chunk-CRY5MHEI.js → chunk-DZ3ATEFS.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-FHUARRMA.js → chunk-FJDEFA64.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-7N5MRONP.js → chunk-GKUF7TM5.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-U5SHHU7E.js → chunk-HM6JS6Q3.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-M74YW332.js +164 -0
  36. package/dist/cli-bundle/focused-chunks/{chunk-ZDNAWWQI.js → chunk-MOT32PR2.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/chunk-ONDKO4EL.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/{chunk-M36SF4GE.js → chunk-TGMSSI3Z.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-TWE3GPQM.js +30 -0
  40. package/dist/cli-bundle/focused-chunks/chunk-UJCQXUD2.js +8 -0
  41. package/dist/cli-bundle/focused-chunks/{chunk-ZAWAL2CG.js → chunk-VS6MR2HT.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-5YU75QLV.js → chunk-YOPNRWSX.js} +2 -2
  43. package/dist/cli-bundle/main.js +21 -21
  44. package/dist/cli-bundle/sdk-authoring.js +1 -1
  45. package/dist/cli-bundle/sdk-contracts.js +2 -2
  46. package/dist/cli-bundle/sdk-core.js +37 -37
  47. package/dist/cli-bundle/sdk-governance.js +1 -1
  48. package/dist/cli-bundle/sdk-graph.js +1 -1
  49. package/dist/cli-bundle/sdk-merge.js +42 -42
  50. package/dist/cli-bundle/sdk-query.js +1 -1
  51. package/dist/cli-bundle/sdk-runtime.js +1 -1
  52. package/dist/cli-bundle/sdk-testing.js +1 -1
  53. package/dist/cli-bundle/sdk.js +10 -10
  54. package/dist/core/history/digest.d.ts +12 -0
  55. package/dist/core/history/digest.js +2 -0
  56. package/dist/core/history/drift-scan.js +1 -1
  57. package/dist/core/history/history.d.ts +5 -3
  58. package/dist/core/history/history.js +2 -2
  59. package/dist/core/history/replay.d.ts +3 -2
  60. package/dist/core/history/replay.js +1 -1
  61. package/dist/core/telemetry/runtime.d.ts +1 -0
  62. package/dist/core/telemetry/runtime.js +2 -2
  63. package/dist/sdk/agent/command-recovery.js +1 -1
  64. package/dist/sdk/agent/item-addressing.js +1 -1
  65. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  66. package/dist/sdk/agent-capability-contracts.js +1 -1
  67. package/dist/sdk/cli-bootstrap.d.ts +2 -1
  68. package/dist/sdk/cli-bootstrap.js +1 -1
  69. package/dist/sdk/cli-contracts/command-aliases.d.ts +2 -0
  70. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  71. package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
  72. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  73. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  74. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  75. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  76. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  77. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  78. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  79. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  80. package/dist/sdk/cli-contracts.d.ts +1 -1
  81. package/dist/sdk/cli-contracts.js +1 -1
  82. package/dist/sdk/completion.d.ts +2 -0
  83. package/dist/sdk/completion.js +26 -14
  84. package/dist/sdk/contracts.d.ts +1 -0
  85. package/dist/sdk/contracts.js +1 -1
  86. package/dist/sdk/governance.d.ts +3 -0
  87. package/dist/sdk/governance.js +1 -1
  88. package/dist/sdk/history/attestation-command.d.ts +22 -0
  89. package/dist/sdk/history/attestation-command.js +3 -0
  90. package/dist/sdk/history/attestation-contract.d.ts +103 -0
  91. package/dist/sdk/history/attestation-contract.js +2 -0
  92. package/dist/sdk/history/attestation-scan.d.ts +16 -0
  93. package/dist/sdk/history/attestation-scan.js +2 -0
  94. package/dist/sdk/history/attestation.d.ts +8 -0
  95. package/dist/sdk/history/attestation.js +2 -0
  96. package/dist/sdk/history/salvage.js +1 -1
  97. package/dist/sdk/history-compact.js +1 -1
  98. package/dist/sdk/history-read.js +1 -1
  99. package/dist/sdk/history-redact.js +1 -1
  100. package/dist/sdk/history-repair.js +1 -1
  101. package/dist/sdk/index.d.ts +2 -1
  102. package/dist/sdk/index.js +1 -1
  103. package/dist/sdk/public-surface.json +1 -1
  104. package/dist/sdk/read-output-budget.d.ts +4 -10
  105. package/dist/sdk/read-output-budget.js +1 -1
  106. package/dist/sdk/read-output-contracts.d.ts +1 -1
  107. package/dist/sdk/read-output-contracts.js +1 -1
  108. package/dist/sdk/read-output-session.d.ts +1 -1
  109. package/dist/sdk/read-output-session.js +1 -1
  110. package/dist/sdk/runtime-input.js +1 -1
  111. package/dist/sdk/runtime.d.ts +3 -0
  112. package/dist/sdk/runtime.js +1 -1
  113. package/dist/types.d.ts +5 -1
  114. package/dist/types.js +1 -1
  115. package/docs/CLI_GRAMMAR.md +23 -0
  116. package/docs/HISTORY_ATTESTATION.md +164 -0
  117. package/docs/README.md +1 -0
  118. package/docs/READ_OUTPUT_CONTRACTS.md +13 -0
  119. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +4 -4
  120. package/docs/generated/AGENT_COMMAND_SURFACE.md +5 -0
  121. package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -0
  122. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -4
  123. package/marketplace.json +2 -2
  124. package/package.json +4 -4
  125. package/packages/pm-beads/package.json +1 -1
  126. package/packages/pm-calendar/package.json +1 -1
  127. package/packages/pm-command-kit/package.json +1 -1
  128. package/packages/pm-digital-twin/package.json +1 -1
  129. package/packages/pm-governance-audit/README.md +9 -7
  130. package/packages/pm-governance-audit/extensions/governance-audit/index.ts +6 -3
  131. package/packages/pm-governance-audit/package.json +1 -1
  132. package/packages/pm-guide-shell/extensions/guide-shell/runtime.ts +7 -19
  133. package/packages/pm-guide-shell/package.json +1 -1
  134. package/packages/pm-kanban/package.json +1 -1
  135. package/packages/pm-lifecycle-hooks/package.json +1 -1
  136. package/packages/pm-linked-test-adapters/package.json +1 -1
  137. package/packages/pm-search-advanced/README.md +9 -5
  138. package/packages/pm-search-advanced/extensions/search-advanced/index.ts +3 -2
  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-codex/.codex-plugin/plugin.json +1 -1
  145. package/dist/cli-bundle/chunks/chunk-74RGSPLL.js +0 -2
  146. package/dist/cli-bundle/chunks/chunk-7WIHZI2M.js +0 -5
  147. package/dist/cli-bundle/chunks/chunk-GLQMKUGP.js +0 -2
  148. package/dist/cli-bundle/chunks/chunk-P6BEYAON.js +0 -8
  149. package/dist/cli-bundle/chunks/chunk-TSWEX72T.js +0 -20
  150. package/dist/cli-bundle/chunks/chunk-YKQTETJI.js +0 -235
  151. package/dist/cli-bundle/focused-chunks/chunk-26O2WB73.js +0 -10
  152. package/dist/cli-bundle/focused-chunks/chunk-B2CMFYRZ.js +0 -2
  153. package/dist/cli-bundle/focused-chunks/chunk-F6WKFXBT.js +0 -8
  154. package/dist/cli-bundle/focused-chunks/chunk-OROZM37I.js +0 -177
  155. package/dist/cli-bundle/focused-chunks/chunk-PNGYYQY7.js +0 -2
  156. package/dist/cli-bundle/focused-chunks/chunk-TPOL4TWE.js +0 -9
  157. package/dist/cli-bundle/focused-chunks/chunk-XSMA2W6Q.js +0 -12
@@ -0,0 +1,12 @@
1
+ /** Digest algorithms supported for item anchors and immutable record envelopes. */
2
+ export declare const HISTORY_HASH_ALGORITHMS: readonly ["sha256", "sha512"];
3
+ /** Explicit algorithm accepted by history writers. */
4
+ export type HistoryHashAlgorithm = (typeof HISTORY_HASH_ALGORITHMS)[number];
5
+ /** Historical default, fixed permanently so unlabeled records remain readable. */
6
+ export declare const LEGACY_HISTORY_HASH_ALGORITHM: "sha256";
7
+ /** Algorithm written on new records unless a caller explicitly selects another. */
8
+ export declare const CURRENT_HISTORY_HASH_ALGORITHM: "sha256";
9
+ /** Validate a persisted algorithm before passing it to the crypto provider. */
10
+ export declare function resolveHistoryHashAlgorithm(value?: string): HistoryHashAlgorithm;
11
+ /** Hash canonical UTF-8 bytes using the declared algorithm, rejecting unknown labels. */
12
+ export declare function historyDigest(value: string, algorithm?: string): string;
@@ -0,0 +1,2 @@
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1e3cba21-c5a4-541a-9841-484cfbb70f4e")}catch(e2){}})();import{createHash}from"node:crypto";const HISTORY_HASH_ALGORITHMS=["sha256","sha512"];const LEGACY_HISTORY_HASH_ALGORITHM="sha256";const CURRENT_HISTORY_HASH_ALGORITHM="sha256";function resolveHistoryHashAlgorithm(value){if(value===void 0)return LEGACY_HISTORY_HASH_ALGORITHM;if(value==="sha256"||value==="sha512")return value;throw new TypeError(`unsupported_history_hash_algorithm:${String(value)}`)}function historyDigest(value,algorithm){return createHash(resolveHistoryHashAlgorithm(algorithm)).update(value,"utf8").digest("hex")}export{CURRENT_HISTORY_HASH_ALGORITHM,HISTORY_HASH_ALGORITHMS,LEGACY_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm};
2
+ //# sourceMappingURL=digest.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="613616a9-118d-5fe7-8871-5406cc2b43a2")}catch(e2){}})();import fs from"node:fs/promises";import{createHash}from"node:crypto";import path from"node:path";import{getHistoryPath}from"../store/paths.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates}from"./history.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{getWorkspaceHistoryPath,inspectWorkspaceHistoryState,WORKSPACE_HISTORY_ID}from"./workspace-history.js";const DRIFT_CACHE_VERSION=10;const DRIFT_CACHE_FILENAME="history-drift-cache.json";function getDriftCachePath(pmRoot){return path.join(pmRoot,"runtime",DRIFT_CACHE_FILENAME)}async function loadDriftCache(pmRoot){try{const raw=await fs.readFile(getDriftCachePath(pmRoot),"utf8");const parsed=JSON.parse(raw);if(parsed.version!==DRIFT_CACHE_VERSION||parsed.history_item_hash_version!==CURRENT_HISTORY_ITEM_HASH_VERSION||typeof parsed.entries!=="object"||parsed.entries===null||Object.values(parsed.entries).some(entry=>typeof entry.chain_ok!=="boolean"||typeof entry.latest_hash_comparable!=="boolean"||!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&entry.version_skew!==true||entry.chain_ok&&entry.version_skew!==true&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&!entry.latest_hash_comparable)){return null}return parsed}catch{return null}}async function scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator){const historyPath=getWorkspaceHistoryPath(pmRoot);let stat;try{stat=await fs.stat(historyPath)}catch(error){if(isFileMissingError(error))return false;accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID);return false}const missingCount=accumulator.missingStreams.length;const resolved=await resolveStreamVerification({itemId:WORKSPACE_HISTORY_ID,historyPath,stat,cached:previousEntries[WORKSPACE_HISTORY_ID],verifyCacheHitByContent,accumulator});if(!resolved.verification){accumulator.missingStreams.splice(missingCount);return resolved.cacheDirty}if(resolved.verification.versionSkew){accumulator.versionSkews.push(WORKSPACE_HISTORY_ID)}if(!resolved.verification.chainOk){accumulator.chainMismatches.push(WORKSPACE_HISTORY_ID)}nextEntries[WORKSPACE_HISTORY_ID]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion};return resolved.cacheDirty}function hashContent(raw){return createHash("sha256").update(raw).digest("hex")}async function verifyHistoryStream(historyPath){const raw=await fs.readFile(historyPath,"utf8");const contentHash=hashContent(raw);if(raw.trim().length===0){return null}const entries=[];let latestAfterHash=null;for(const line of raw.split(/\r?\n/)){const trimmed=line.trim();if(trimmed.length===0){continue}const parsed=JSON.parse(trimmed);if(typeof parsed.after_hash!=="string"||parsed.after_hash.trim().length===0){throw new Error("missing after_hash")}entries.push(parsed);latestAfterHash=parsed.after_hash}if(!latestAfterHash){return null}const verification=verifyHistoryChainWithVersion(entries);const versionSkew=entries.some(entry=>entry.item_hash_version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version));const latestEntry=entries[entries.length-1];const latestExplicitVersion=latestEntry.item_hash_version;const latestExplicitVersionSupported=latestExplicitVersion!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(latestExplicitVersion);const latestHashVersion=latestExplicitVersionSupported?latestExplicitVersion:verification.item_hash_version;return{latestAfterHash,identityDiscontinuities:findHistoryIdentityDiscontinuities(entries),chainOk:verification.ok,versionSkew,latestHashComparable:latestHashVersion!==void 0&&(!versionSkew||latestExplicitVersionSupported||latestExplicitVersion===void 0),contentHash,itemHashVersion:latestHashVersion??CURRENT_HISTORY_ITEM_HASH_VERSION}}function cacheMetadataMatches(cached,stat){return cached!==void 0&&cached.mtime_ms===stat.mtimeMs&&cached.ctime_ms===stat.ctimeMs&&cached.size===stat.size}async function loadFreshStreamVerification(itemId,historyPath,accumulator){try{const loaded=await verifyHistoryStream(historyPath);if(!loaded){accumulator.missingStreams.push(itemId);return null}return loaded}catch{accumulator.unreadableStreams.push(itemId);return null}}async function resolveStreamVerification(params){const cachedContentHash=typeof params.cached?.content_hash==="string"&&params.cached.content_hash.length>0?params.cached.content_hash:void 0;const canUseCache=cacheMetadataMatches(params.cached,params.stat)&&cachedContentHash!==void 0;if(!canUseCache||!params.cached||!params.cached.chain_ok){return{verification:await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator),cacheDirty:true}}if(params.verifyCacheHitByContent){const verification=await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator);return{verification,cacheDirty:verification===null||verification.contentHash!==cachedContentHash||verification.latestAfterHash!==params.cached.latest_after_hash||verification.chainOk!==params.cached.chain_ok||verification.versionSkew!==(params.cached.version_skew===true)||verification.latestHashComparable!==params.cached.latest_hash_comparable||verification.itemHashVersion!==params.cached.item_hash_version}}return{verification:{identityDiscontinuities:[],latestAfterHash:params.cached.latest_after_hash,chainOk:params.cached.chain_ok,versionSkew:params.cached.version_skew===true,latestHashComparable:params.cached.latest_hash_comparable&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(params.cached.item_hash_version),contentHash:cachedContentHash,itemHashVersion:params.cached.item_hash_version},cacheDirty:false}}async function scanItemHistory(pmRoot,item,cache,accumulator){let historyPath;let stat;try{historyPath=getHistoryPath(pmRoot,item.id);stat=await fs.stat(historyPath)}catch(error){(isFileMissingError(error)?accumulator.missingStreams:accumulator.unreadableStreams).push(item.id);return false}const resolved=await resolveStreamVerification({itemId:item.id,historyPath,stat,cached:cache.previousEntries[item.id],verifyCacheHitByContent:cache.verifyCacheHitByContent,accumulator});if(!resolved.verification)return resolved.cacheDirty;if(resolved.verification.identityDiscontinuities.length>0){(accumulator.identityDiscontinuities??=[]).push(...resolved.verification.identityDiscontinuities.map(finding=>({...finding,item_id:item.id})))}if(resolved.verification.versionSkew){accumulator.versionSkews.push(item.id)}if(!resolved.verification.chainOk){accumulator.chainMismatches.push(item.id)}cache.nextEntries[item.id]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion};const{body,...itemMetadata}=item;if(!resolved.verification.latestHashComparable)return resolved.cacheDirty;const currentHashes=hashDocumentVerificationCandidates({metadata:itemMetadata,body},resolved.verification.itemHashVersion);if(!currentHashes.includes(resolved.verification.latestAfterHash))accumulator.hashMismatches.push(item.id);return resolved.cacheDirty}async function scanWorkspaceStateAgreement(pmRoot,accumulator){if(accumulator.unreadableStreams.includes(WORKSPACE_HISTORY_ID)||accumulator.chainMismatches.includes(WORKSPACE_HISTORY_ID)||accumulator.versionSkews.includes(WORKSPACE_HISTORY_ID))return;try{const agreement=await inspectWorkspaceHistoryState(pmRoot);accumulator.workspaceStateMismatches.push(...agreement.mismatched_documents);accumulator.workspaceStateMissing.push(...agreement.missing_documents);accumulator.workspaceStateUnreadable.push(...agreement.unreadable_documents)}catch{accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID)}}async function scanHistoryDrift(pmRoot,items,options={}){const accumulator={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]};const cache=await loadDriftCache(pmRoot);const previousEntries=cache?.entries??{};const nextEntries={};let cacheDirty=false;const verifyCacheHitByContent=options.cacheHitVerification!=="metadata";const cacheState={previousEntries,nextEntries,verifyCacheHitByContent};for(const item of items){if(await scanItemHistory(pmRoot,item,cacheState,accumulator))cacheDirty=true}const workspaceCacheDirty=await scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator);cacheDirty||=workspaceCacheDirty;await scanWorkspaceStateAgreement(pmRoot,accumulator);if(cacheDirty||Object.keys(previousEntries).length!==Object.keys(nextEntries).length){const cachePath=getDriftCachePath(pmRoot);try{await fs.mkdir(path.dirname(cachePath),{recursive:true});await writeFileAtomic(cachePath,JSON.stringify({version:DRIFT_CACHE_VERSION,history_item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,entries:nextEntries}))}catch{}}const driftedItems=[...new Set([...accumulator.missingStreams,...accumulator.unreadableStreams,...accumulator.hashMismatches,...accumulator.chainMismatches,...accumulator.versionSkews,...accumulator.workspaceStateMismatches.length>0||accumulator.workspaceStateMissing.length>0||accumulator.workspaceStateUnreadable.length>0?[WORKSPACE_HISTORY_ID]:[]])].sort((a,b)=>a.localeCompare(b));return{...accumulator,driftedItems}}export{scanHistoryDrift};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d876d1ab-2de0-5c32-b999-721038adafcd")}catch(e2){}})();import{HISTORY_HASH_ALGORITHMS,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import{createHash}from"node:crypto";import path from"node:path";import{getHistoryPath}from"../store/paths.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates}from"./history.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{getWorkspaceHistoryPath,inspectWorkspaceHistoryState,WORKSPACE_HISTORY_ID}from"./workspace-history.js";const READABLE_HISTORY_HASH_ALGORITHMS=new Set([void 0,...HISTORY_HASH_ALGORITHMS]);const DRIFT_CACHE_VERSION=11;const DRIFT_CACHE_FILENAME="history-drift-cache.json";function getDriftCachePath(pmRoot){return path.join(pmRoot,"runtime",DRIFT_CACHE_FILENAME)}async function loadDriftCache(pmRoot){try{const raw=await fs.readFile(getDriftCachePath(pmRoot),"utf8");const parsed=JSON.parse(raw);if(parsed.version!==DRIFT_CACHE_VERSION||parsed.history_item_hash_version!==CURRENT_HISTORY_ITEM_HASH_VERSION||typeof parsed.entries!=="object"||parsed.entries===null||Object.values(parsed.entries).some(entry=>typeof entry.chain_ok!=="boolean"||typeof entry.latest_hash_comparable!=="boolean"||!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&entry.version_skew!==true||entry.chain_ok&&entry.version_skew!==true&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&!entry.latest_hash_comparable)){return null}return parsed}catch{return null}}async function scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator){const historyPath=getWorkspaceHistoryPath(pmRoot);let stat;try{stat=await fs.stat(historyPath)}catch(error){if(isFileMissingError(error))return false;accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID);return false}const missingCount=accumulator.missingStreams.length;const resolved=await resolveStreamVerification({itemId:WORKSPACE_HISTORY_ID,historyPath,stat,cached:previousEntries[WORKSPACE_HISTORY_ID],verifyCacheHitByContent,accumulator});if(!resolved.verification){accumulator.missingStreams.splice(missingCount);return resolved.cacheDirty}if(resolved.verification.versionSkew){accumulator.versionSkews.push(WORKSPACE_HISTORY_ID)}if(!resolved.verification.chainOk){accumulator.chainMismatches.push(WORKSPACE_HISTORY_ID)}nextEntries[WORKSPACE_HISTORY_ID]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm};return resolved.cacheDirty}function hashContent(raw){return createHash("sha256").update(raw).digest("hex")}function hasUnsupportedHistoryCapability(entry){return!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||entry.item_hash_version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)}async function verifyHistoryStream(historyPath){const raw=await fs.readFile(historyPath,"utf8");const contentHash=hashContent(raw);if(raw.trim().length===0){return null}const entries=[];let latestAfterHash=null;for(const line of raw.split(/\r?\n/)){const trimmed=line.trim();if(trimmed.length===0){continue}const parsed=JSON.parse(trimmed);if(typeof parsed.after_hash!=="string"||parsed.after_hash.trim().length===0){throw new Error("missing after_hash")}entries.push(parsed);latestAfterHash=parsed.after_hash}if(!latestAfterHash){return null}const verification=verifyHistoryChainWithVersion(entries);const versionSkew=entries.some(hasUnsupportedHistoryCapability);const latestEntry=entries[entries.length-1];const algorithmSupported=READABLE_HISTORY_HASH_ALGORITHMS.has(latestEntry.hash_algorithm);const latestExplicitVersion=latestEntry.item_hash_version;const latestExplicitVersionSupported=latestExplicitVersion!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(latestExplicitVersion);const latestHashVersion=latestExplicitVersionSupported?latestExplicitVersion:verification.item_hash_version;return{latestAfterHash,hashAlgorithm:algorithmSupported?resolveHistoryHashAlgorithm(latestEntry.hash_algorithm):void 0,identityDiscontinuities:findHistoryIdentityDiscontinuities(entries),chainOk:verification.ok,versionSkew,latestHashComparable:algorithmSupported&&latestHashVersion!==void 0&&(!versionSkew||latestExplicitVersionSupported||latestExplicitVersion===void 0),contentHash,itemHashVersion:latestHashVersion??CURRENT_HISTORY_ITEM_HASH_VERSION}}function cacheMetadataMatches(cached,stat){return cached!==void 0&&cached.mtime_ms===stat.mtimeMs&&cached.ctime_ms===stat.ctimeMs&&cached.size===stat.size}async function loadFreshStreamVerification(itemId,historyPath,accumulator){try{const loaded=await verifyHistoryStream(historyPath);if(!loaded){accumulator.missingStreams.push(itemId);return null}return loaded}catch{accumulator.unreadableStreams.push(itemId);return null}}function matchesCachedVerification(verification,cached){return verification!==null&&verification.contentHash===cached.content_hash&&verification.latestAfterHash===cached.latest_after_hash&&verification.chainOk===cached.chain_ok&&verification.versionSkew===(cached.version_skew===true)&&verification.latestHashComparable===cached.latest_hash_comparable&&verification.itemHashVersion===cached.item_hash_version&&verification.hashAlgorithm===cached.hash_algorithm}async function resolveStreamVerification(params){const cachedContentHash=typeof params.cached?.content_hash==="string"&&params.cached.content_hash.length>0?params.cached.content_hash:void 0;const canUseCache=cacheMetadataMatches(params.cached,params.stat)&&cachedContentHash!==void 0;if(!canUseCache||!params.cached||!params.cached.chain_ok){return{verification:await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator),cacheDirty:true}}if(params.verifyCacheHitByContent){const verification=await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator);return{verification,cacheDirty:!matchesCachedVerification(verification,params.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:params.cached.latest_after_hash,chainOk:params.cached.chain_ok,versionSkew:params.cached.version_skew===true,latestHashComparable:params.cached.latest_hash_comparable&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(params.cached.item_hash_version),contentHash:cachedContentHash,itemHashVersion:params.cached.item_hash_version,hashAlgorithm:params.cached.hash_algorithm},cacheDirty:false}}async function scanItemHistory(pmRoot,item,cache,accumulator){let historyPath;let stat;try{historyPath=getHistoryPath(pmRoot,item.id);stat=await fs.stat(historyPath)}catch(error){(isFileMissingError(error)?accumulator.missingStreams:accumulator.unreadableStreams).push(item.id);return false}const resolved=await resolveStreamVerification({itemId:item.id,historyPath,stat,cached:cache.previousEntries[item.id],verifyCacheHitByContent:cache.verifyCacheHitByContent,accumulator});if(!resolved.verification)return resolved.cacheDirty;if(resolved.verification.identityDiscontinuities.length>0){(accumulator.identityDiscontinuities??=[]).push(...resolved.verification.identityDiscontinuities.map(finding=>({...finding,item_id:item.id})))}if(resolved.verification.versionSkew){accumulator.versionSkews.push(item.id)}if(!resolved.verification.chainOk){accumulator.chainMismatches.push(item.id)}cache.nextEntries[item.id]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm};const{body,...itemMetadata}=item;if(!resolved.verification.latestHashComparable)return resolved.cacheDirty;const currentHashes=hashDocumentVerificationCandidates({metadata:itemMetadata,body},resolved.verification.itemHashVersion,resolved.verification.hashAlgorithm);if(!currentHashes.includes(resolved.verification.latestAfterHash))accumulator.hashMismatches.push(item.id);return resolved.cacheDirty}async function scanWorkspaceStateAgreement(pmRoot,accumulator){if(accumulator.unreadableStreams.includes(WORKSPACE_HISTORY_ID)||accumulator.chainMismatches.includes(WORKSPACE_HISTORY_ID)||accumulator.versionSkews.includes(WORKSPACE_HISTORY_ID))return;try{const agreement=await inspectWorkspaceHistoryState(pmRoot);accumulator.workspaceStateMismatches.push(...agreement.mismatched_documents);accumulator.workspaceStateMissing.push(...agreement.missing_documents);accumulator.workspaceStateUnreadable.push(...agreement.unreadable_documents)}catch{accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID)}}async function scanHistoryDrift(pmRoot,items,options={}){const accumulator={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]};const cache=await loadDriftCache(pmRoot);const previousEntries=cache?.entries??{};const nextEntries={};let cacheDirty=false;const verifyCacheHitByContent=options.cacheHitVerification!=="metadata";const cacheState={previousEntries,nextEntries,verifyCacheHitByContent};for(const item of items){if(await scanItemHistory(pmRoot,item,cacheState,accumulator))cacheDirty=true}const workspaceCacheDirty=await scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator);cacheDirty||=workspaceCacheDirty;await scanWorkspaceStateAgreement(pmRoot,accumulator);if(cacheDirty||Object.keys(previousEntries).length!==Object.keys(nextEntries).length){const cachePath=getDriftCachePath(pmRoot);try{await fs.mkdir(path.dirname(cachePath),{recursive:true});await writeFileAtomic(cachePath,JSON.stringify({version:DRIFT_CACHE_VERSION,history_item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,entries:nextEntries}))}catch{}}const driftedItems=[...new Set([...accumulator.missingStreams,...accumulator.unreadableStreams,...accumulator.hashMismatches,...accumulator.chainMismatches,...accumulator.versionSkews,...accumulator.workspaceStateMismatches.length>0||accumulator.workspaceStateMissing.length>0||accumulator.workspaceStateUnreadable.length>0?[WORKSPACE_HISTORY_ID]:[]])].sort((a,b)=>a.localeCompare(b));return{...accumulator,driftedItems}}export{scanHistoryDrift};
2
2
  //# sourceMappingURL=drift-scan.js.map
@@ -1,3 +1,4 @@
1
+ import { type HistoryHashAlgorithm } from "./digest.js";
1
2
  import { type AuthorSource } from "../shared/author.js";
2
3
  import type { HistoryEntry, HistoryPatchOp, ItemDocument } from "../../types/index.js";
3
4
  /** Hash epoch for the current canonical item surface written into immutable history. */
@@ -26,7 +27,7 @@ export declare function verifyHistoryRecordHash(entry: HistoryEntry): {
26
27
  coverage: "record_and_item_state" | "item_state_only";
27
28
  } | {
28
29
  ok: false;
29
- error: "incomplete_record_hash_envelope" | "record_hash_mismatch" | "unsupported_record_hash_version";
30
+ error: "incomplete_record_hash_envelope" | "record_hash_mismatch" | "unsupported_record_hash_version" | "unsupported_history_hash_algorithm";
30
31
  };
31
32
  /** Reseal a maintenance rewrite and retain the anchors and patch digest it replaced. */
32
33
  export declare function resealHistoryRewrite(original: HistoryEntry, rewritten: HistoryEntry, options?: Readonly<{
@@ -47,13 +48,13 @@ declare function isDefinedPointerPath(document: unknown, path: string): boolean;
47
48
  /** Implements hash document for the public runtime surface of this module. */
48
49
  export declare function hashDocument(document: ItemDocument): string;
49
50
  /** Hash an item with an explicit canonicalization epoch for replay compatibility. */
50
- export declare function hashDocumentForVersion(document: ItemDocument, version: HistoryItemHashVersion): string;
51
+ export declare function hashDocumentForVersion(document: ItemDocument, version: HistoryItemHashVersion, algorithm?: HistoryHashAlgorithm): string;
51
52
  /**
52
53
  * Return the ordered hash candidates accepted when verifying one immutable
53
54
  * history epoch. Epoch 2 has both its established expanded hash first and the
54
55
  * earlier field-frozen writer hash second; the other epochs have one form.
55
56
  */
56
- export declare function hashDocumentVerificationCandidates(document: ItemDocument, version: HistoryItemHashVersion): [string, ...string[]];
57
+ export declare function hashDocumentVerificationCandidates(document: ItemDocument, version: HistoryItemHashVersion, algorithm?: HistoryHashAlgorithm): [string, ...string[]];
57
58
  /** Implements hash empty document for the public runtime surface of this module. */
58
59
  export declare function hashEmptyDocument(): string;
59
60
  /** Implements create history entry for the public runtime surface of this module. */
@@ -66,6 +67,7 @@ export declare function createHistoryEntry(params: {
66
67
  after: ItemDocument;
67
68
  message?: string;
68
69
  context?: Record<string, unknown>;
70
+ hashAlgorithm?: HistoryHashAlgorithm;
69
71
  }): HistoryEntry;
70
72
  /** Implements append history entry for the public runtime surface of this module. */
71
73
  export declare function appendHistoryEntry(historyPath: string, entry: HistoryEntry): Promise<void>;
@@ -1,3 +1,3 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="70eda133-68fd-5dd6-afe9-c892f23e50a5")}catch(e2){}})();import jsonPatch from"fast-json-patch";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""};const CURRENT_HISTORY_ITEM_HASH_VERSION=3;const SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3];const CURRENT_HISTORY_RECORD_HASH_VERSION=1;const SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return sha256Hex(stableStringify(entry))}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION};const{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function verifyHistoryRecordHash(entry){if(entry.record_hash_version===void 0&&entry.record_hash===void 0){return{ok:true,coverage:"item_state_only"}}if(entry.record_hash_version===void 0||entry.record_hash===void 0){return{ok:false,error:"incomplete_record_hash_envelope"}}if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version)){return{ok:false,error:"unsupported_record_hash_version"}}const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:true,coverage:"record_and_item_state"}:{ok:false,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};if(original.item_hash_version!==void 0){evidence.item_hash_version=original.item_hash_version}if(options.retainOriginalPatch){evidence.patch=structuredClone(original.patch)}if(options.retainPriorRecordHash!==false&&original.record_hash_version!==void 0&&original.record_hash!==void 0){evidence.record_hash_version=original.record_hash_version;evidence.record_hash=original.record_hash;evidence.record=structuredClone(original)}return evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok){throw new TypeError(originalRecordVerification.error)}const originalPatchHash=hashHistoryPatch(original.patch);const retainsRewriteEvidence=options.retainPriorRecord===true||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||originalPatchHash!==hashHistoryPatch(rewritten.patch);const sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}});const evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok){throw new TypeError(evidenceVerification.error)}return sealed}function isHistoryPatch(value){if(!Array.isArray(value)||Object.keys(value).length!==value.length){return false}return value.every(operation=>{if(!isRecord(operation)||typeof operation.path!=="string"){return false}if(operation.op==="move"||operation.op==="copy"){return typeof operation.from==="string"}if(["add","replace","test"].includes(operation.op)){return Object.hasOwn(operation,"value")}return operation.op==="remove"})}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts==="string"&&typeof value.author==="string"&&typeof value.op==="string"&&typeof value.before_hash==="string"&&typeof value.after_hash==="string"&&isHistoryPatch(value.patch)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0;const hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){if(!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!=="string"||typeof evidence.after_hash!=="string"||typeof evidence.patch_hash!=="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!=="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!=="string"||!/^[a-f0-9]{64}$/u.test(evidence.record_hash))){return false}return evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash){return{kind:"patch_hash_mismatch"}}if(evidence.record){if(!matchesRetainedHistoryRecord(evidence)){return{kind:"record_hash_mismatch"}}return{kind:"record",entry:evidence.record}}const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash){return{kind:"digest_only"}}const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};if(priorEvidence.length===0)delete priorRecord.reanchor_evidence;if(evidence.item_hash_version===void 0){delete priorRecord.item_hash_version}return evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:true,coverage:"none"};if(!Array.isArray(evidenceEntries)){return{ok:false,error:"rewrite_evidence_invalid"}}if(evidenceEntries.length===0)return{ok:true,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index];if(!(index in evidenceEntries)||!isHistoryReanchorEvidence(evidence)){return{ok:false,error:"rewrite_evidence_invalid"}}const prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch"){return{ok:false,error:"rewrite_evidence_patch_hash_mismatch"}}if(prior.kind==="record_hash_mismatch"){return{ok:false,error:"rewrite_evidence_record_hash_mismatch"}}if(prior.kind==="digest_only"){return{ok:true,coverage:"digest_only"}}if(prior.kind==="legacy"){return{ok:true,coverage:"legacy_anchor_only"}}if(!verifyHistoryRecordHash(prior.entry).ok){return{ok:false,error:"rewrite_evidence_record_hash_mismatch"}}reconstructed=prior.entry}return{ok:true,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){const comparisons=[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),Number(Boolean(left.shared_host_safe))-Number(Boolean(right.shared_host_safe)),compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)];return comparisons.find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){if(!path2||path2==="/"){return[]}if(!path2.startsWith("/")){return[]}return path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~"))}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0){return true}let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1;const next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return false;cursor=next}return true}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation);replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],true,true).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=false){const hasMetadata=document.metadata&&Object.keys(document.metadata).length>0;if(!hasMetadata){return{front_matter:{},body:document.body??""}}const canonical=canonicalDocument(document);const usesLegacyFields=version===1||version===2&&legacyV2Fields;const epochMetadata=usesLegacyFields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata;const metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;const orderedMetadata=orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER);return{front_matter:orderedMetadata,body:canonical.body}}function canonicalPatchDocument(document){const hasMetadata=document.metadata&&Object.keys(document.metadata).length>0;if(!hasMetadata){return{metadata:{},body:document.body??""}}const canonical=canonicalDocument(document);const orderedMetadata=orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER);return{metadata:orderedMetadata,body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version)){throw new TypeError(`unsupported_item_hash_version:${String(version)}`)}return sha256Hex(stableStringify(canonicalHashDocument(document,version)))}function hashDocumentVerificationCandidates(document,version){const canonicalHash=hashDocumentForVersion(document,version);return version===2?[canonicalHash,sha256Hex(stableStringify(canonicalHashDocument(document,version,true)))]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION);const afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION);const beforePatchCanonical=canonicalPatchDocument(params.before);const afterPatchCanonical=canonicalPatchDocument(params.after);const rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical);const patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch);const agentIdentity=resolveHistoryAgentIdentity(params.author);const provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([,outcome])=>outcome.resolver!==void 0&&outcome.status!=="resolved")):void 0;const context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes};const entry={ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:params.op,patch,before_hash:sha256Hex(stableStringify(beforeHashCanonical)),after_hash:sha256Hex(stableStringify(afterHashCanonical)),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts)){throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision")}if(ts!==entry.ts){throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace")}return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts==="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts)){throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision")}return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value==="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}if(isRecord(parsed)){return JSON.stringify(withHistoryTimestamp(parsed,fallbackTs))}return value}if(isRecord(value)){return JSON.stringify(withHistoryTimestamp(value,fallbackTs))}return JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===false)return true;if(typeof result==="string"){const line2=serializeHistoryLine(result,entry);await appendHistoryLineWithIdentityReservation(historyPath,line2);await invalidateHistoryDriftCacheForPath(historyPath);await removeHistoryEventIndexForHistoryPath(historyPath);return true}if(typeof result!=="object"||result===null)return false;const record=result;if(record.skip===true)return true;const nextHistoryPath=typeof record.history_path==="string"?record.history_path:historyPath;const line=serializeHistoryLine(typeof record.line==="string"?record.line:record.entry??entry,entry);await appendHistoryLineWithIdentityReservation(nextHistoryPath,line);await invalidateHistoryDriftCacheForPath(nextHistoryPath);await removeHistoryEventIndexForHistoryPath(nextHistoryPath);return true}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:true});try{await fs.writeFile(historyPath,`${line}
2
- `,{encoding:"utf8",flag:"wx"})}catch(error){if(error.code!=="EEXIST")throw error;throw new PmCliError("This item identity is reserved by an existing history stream.",EXIT_CODE.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function appendHistoryEntry(historyPath,entry){const override=await runActiveServiceOverride("history_append",{history_path:historyPath,entry});if(override.handled&&await applyHistoryAppendOverride(historyPath,entry,override.result)){return}const timestampedEntry=entry.ts.trim().length>0?entry:{...entry,ts:fallbackHistoryTimestamp(entry)};const normalizedEntry=sealHistoryRecord({...timestampedEntry,event_class:classifyHistoryEvent(timestampedEntry)});await appendHistoryEntryWithEventIndex(historyPath,normalizedEntry,async()=>{await appendHistoryLineWithIdentityReservation(historyPath,serializeHistoryLine(normalizedEntry,normalizedEntry))});await invalidateHistoryDriftCacheForPath(historyPath)}const _testOnly={decodeJsonPointer,isDefinedPointerPath};export{CURRENT_HISTORY_ITEM_HASH_VERSION,CURRENT_HISTORY_RECORD_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,_testOnly,appendHistoryEntry,createHistoryEntry,hashDocument,hashDocumentForVersion,hashDocumentVerificationCandidates,hashEmptyDocument,hashHistoryPatch,hashHistoryRecord,hashHistoryStream,resealHistoryRewrite,sealHistoryRecord,verifyHistoryRecordHash,verifyHistoryRewriteEvidence};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2e7d6dba-0f9a-5bcf-a095-8bb7725efeff")}catch(e2){}})();import jsonPatch from"fast-json-patch";import{CURRENT_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""};const CURRENT_HISTORY_ITEM_HASH_VERSION=3;const SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3];const CURRENT_HISTORY_RECORD_HASH_VERSION=1;const SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return historyDigest(stableStringify(entry),entry.hash_algorithm)}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION};const{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function verifyHistoryRecordHash(entry){try{resolveHistoryHashAlgorithm(entry.hash_algorithm)}catch{return{ok:false,error:"unsupported_history_hash_algorithm"}}if(entry.record_hash_version===void 0&&entry.record_hash===void 0){return{ok:true,coverage:"item_state_only"}}if(entry.record_hash_version===void 0||entry.record_hash===void 0){return{ok:false,error:"incomplete_record_hash_envelope"}}if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version)){return{ok:false,error:"unsupported_record_hash_version"}}const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:true,coverage:"record_and_item_state"}:{ok:false,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};if(original.hash_algorithm!==void 0)evidence.hash_algorithm=original.hash_algorithm;if(original.item_hash_version!==void 0){evidence.item_hash_version=original.item_hash_version}if(options.retainOriginalPatch){evidence.patch=structuredClone(original.patch)}if(options.retainPriorRecordHash!==false&&original.record_hash_version!==void 0&&original.record_hash!==void 0){evidence.record_hash_version=original.record_hash_version;evidence.record_hash=original.record_hash;evidence.record=structuredClone(original)}return evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok){throw new TypeError(originalRecordVerification.error)}const originalPatchHash=hashHistoryPatch(original.patch);const retainsRewriteEvidence=options.retainPriorRecord===true||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||original.hash_algorithm!==rewritten.hash_algorithm||originalPatchHash!==hashHistoryPatch(rewritten.patch);const sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}});const evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok){throw new TypeError(evidenceVerification.error)}return sealed}function isHistoryPatch(value){if(!Array.isArray(value)||Object.keys(value).length!==value.length){return false}return value.every(operation=>{if(!isRecord(operation)||typeof operation.path!=="string"){return false}if(operation.op==="move"||operation.op==="copy"){return typeof operation.from==="string"}if(["add","replace","test"].includes(operation.op)){return Object.hasOwn(operation,"value")}return operation.op==="remove"})}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts==="string"&&typeof value.author==="string"&&typeof value.op==="string"&&typeof value.before_hash==="string"&&typeof value.after_hash==="string"&&isHistoryPatch(value.patch)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0;const hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){if(!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!=="string"||typeof evidence.after_hash!=="string"||typeof evidence.patch_hash!=="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!=="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!=="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(evidence.record_hash))){return false}return evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function isHistoryRewriteEvidenceList(evidenceEntries){try{for(const evidence of evidenceEntries){if(!isHistoryReanchorEvidence(evidence))return false;resolveHistoryHashAlgorithm(evidence.hash_algorithm)}return true}catch{return false}}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.hash_algorithm===evidence.hash_algorithm&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash){return{kind:"patch_hash_mismatch"}}if(evidence.record){if(!matchesRetainedHistoryRecord(evidence)){return{kind:"record_hash_mismatch"}}return{kind:"record",entry:evidence.record}}const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash){return{kind:"digest_only"}}const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,hash_algorithm:evidence.hash_algorithm,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};if(evidence.hash_algorithm===void 0)delete priorRecord.hash_algorithm;if(priorEvidence.length===0)delete priorRecord.reanchor_evidence;if(evidence.item_hash_version===void 0){delete priorRecord.item_hash_version}return evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:true,coverage:"none"};if(!Array.isArray(evidenceEntries)||!isHistoryRewriteEvidenceList(evidenceEntries)){return{ok:false,error:"rewrite_evidence_invalid"}}if(evidenceEntries.length===0)return{ok:true,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index];const prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch"){return{ok:false,error:"rewrite_evidence_patch_hash_mismatch"}}if(prior.kind==="record_hash_mismatch"){return{ok:false,error:"rewrite_evidence_record_hash_mismatch"}}if(prior.kind==="digest_only"){return{ok:true,coverage:"digest_only"}}if(prior.kind==="legacy"){return{ok:true,coverage:"legacy_anchor_only"}}if(!verifyHistoryRecordHash(prior.entry).ok){return{ok:false,error:"rewrite_evidence_record_hash_mismatch"}}reconstructed=prior.entry}return{ok:true,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){const comparisons=[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),Number(Boolean(left.shared_host_safe))-Number(Boolean(right.shared_host_safe)),compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)];return comparisons.find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){if(!path2||path2==="/"){return[]}if(!path2.startsWith("/")){return[]}return path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~"))}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0){return true}let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1;const next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return false;cursor=next}return true}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation);replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],true,true).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=false){const hasMetadata=document.metadata&&Object.keys(document.metadata).length>0;if(!hasMetadata){return{front_matter:{},body:document.body??""}}const canonical=canonicalDocument(document);const usesLegacyFields=version===1||version===2&&legacyV2Fields;const epochMetadata=usesLegacyFields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata;const metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;const orderedMetadata=orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER);return{front_matter:orderedMetadata,body:canonical.body}}function canonicalPatchDocument(document){const hasMetadata=document.metadata&&Object.keys(document.metadata).length>0;if(!hasMetadata){return{metadata:{},body:document.body??""}}const canonical=canonicalDocument(document);const orderedMetadata=orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER);return{metadata:orderedMetadata,body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version,algorithm){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version)){throw new TypeError(`unsupported_item_hash_version:${String(version)}`)}return historyDigest(stableStringify(canonicalHashDocument(document,version)),algorithm)}function hashDocumentVerificationCandidates(document,version,algorithm){const canonicalHash=hashDocumentForVersion(document,version,algorithm);return version===2?[canonicalHash,historyDigest(stableStringify(canonicalHashDocument(document,version,true)),algorithm)]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION);const afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION);const beforePatchCanonical=canonicalPatchDocument(params.before);const afterPatchCanonical=canonicalPatchDocument(params.after);const rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical);const patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch);const agentIdentity=resolveHistoryAgentIdentity(params.author);const provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([,outcome])=>outcome.resolver!==void 0&&outcome.status!=="resolved")):void 0;const context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes};const algorithm=params.hashAlgorithm??CURRENT_HISTORY_HASH_ALGORITHM;const entry={hash_algorithm:algorithm,ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:params.op,patch,before_hash:historyDigest(stableStringify(beforeHashCanonical),algorithm),after_hash:historyDigest(stableStringify(afterHashCanonical),algorithm),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts)){throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision")}if(ts!==entry.ts){throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace")}return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts==="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts)){throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision")}return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value==="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}if(isRecord(parsed)){return JSON.stringify(withHistoryTimestamp(parsed,fallbackTs))}return value}if(isRecord(value)){return JSON.stringify(withHistoryTimestamp(value,fallbackTs))}return JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===false)return true;if(typeof result==="string"){const line2=serializeHistoryLine(result,entry);await appendHistoryLineWithIdentityReservation(historyPath,line2);await invalidateHistoryDriftCacheForPath(historyPath);await removeHistoryEventIndexForHistoryPath(historyPath);return true}if(typeof result!=="object"||result===null)return false;const record=result;if(record.skip===true)return true;const nextHistoryPath=typeof record.history_path==="string"?record.history_path:historyPath;const line=serializeHistoryLine(typeof record.line==="string"?record.line:record.entry??entry,entry);await appendHistoryLineWithIdentityReservation(nextHistoryPath,line);await invalidateHistoryDriftCacheForPath(nextHistoryPath);await removeHistoryEventIndexForHistoryPath(nextHistoryPath);return true}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:true});try{await fs.writeFile(historyPath,`${line}
2
+ `,{encoding:"utf8",flag:"wx"})}catch(error){if(error.code!=="EEXIST")throw error;throw new PmCliError("This item identity is reserved by an existing history stream.",EXIT_CODE.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function appendHistoryEntry(historyPath,entry){const override=await runActiveServiceOverride("history_append",{history_path:historyPath,entry});if(override.handled&&await applyHistoryAppendOverride(historyPath,entry,override.result)){return}const timestampedEntry=entry.ts.trim().length>0?entry:{...entry,ts:fallbackHistoryTimestamp(entry)};const normalizedEntry=sealHistoryRecord({...timestampedEntry,hash_algorithm:resolveHistoryHashAlgorithm(timestampedEntry.hash_algorithm),event_class:classifyHistoryEvent(timestampedEntry)});await appendHistoryEntryWithEventIndex(historyPath,normalizedEntry,async()=>{await appendHistoryLineWithIdentityReservation(historyPath,serializeHistoryLine(normalizedEntry,normalizedEntry))});await invalidateHistoryDriftCacheForPath(historyPath)}const _testOnly={decodeJsonPointer,isDefinedPointerPath};export{CURRENT_HISTORY_ITEM_HASH_VERSION,CURRENT_HISTORY_RECORD_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,_testOnly,appendHistoryEntry,createHistoryEntry,hashDocument,hashDocumentForVersion,hashDocumentVerificationCandidates,hashEmptyDocument,hashHistoryPatch,hashHistoryRecord,hashHistoryStream,resealHistoryRewrite,sealHistoryRecord,verifyHistoryRecordHash,verifyHistoryRewriteEvidence};
3
3
  //# sourceMappingURL=history.js.map
@@ -1,3 +1,4 @@
1
+ import { type HistoryHashAlgorithm } from "./digest.js";
1
2
  import { canonicalDocument } from "../item/item-format.js";
2
3
  import { type HistoryItemHashVersion } from "./history.js";
3
4
  import type { HistoryEntry, HistoryPatchOp, ItemDocument } from "../../types/index.js";
@@ -20,13 +21,13 @@ export declare const EMPTY_REPLAY_DOCUMENT: ReplayDocument;
20
21
  /** Implements clone empty replay document for the public runtime surface of this module. */
21
22
  export declare function cloneEmptyReplayDocument(): ReplayDocument;
22
23
  /** Implements replay hash for the public runtime surface of this module. */
23
- export declare function replayHash(document: ReplayDocument, version?: HistoryItemHashVersion): string;
24
+ export declare function replayHash(document: ReplayDocument, version?: HistoryItemHashVersion, algorithm?: HistoryHashAlgorithm): string;
24
25
  /**
25
26
  * Return hash candidates that preserve the semantic variant within an epoch.
26
27
  * Duplicate values are intentional: before and after candidates use the same
27
28
  * index when a patch introduces a field that distinguishes legacy epoch 2.
28
29
  */
29
- export declare function replayHashVerificationCandidates(document: ReplayDocument, version: HistoryItemHashVersion): [string, ...string[]];
30
+ export declare function replayHashVerificationCandidates(document: ReplayDocument, version: HistoryItemHashVersion, algorithm?: HistoryHashAlgorithm): [string, ...string[]];
30
31
  /** Implements replay to item document for the public runtime surface of this module. */
31
32
  export declare function replayToItemDocument(document: ReplayDocument): ItemDocument;
32
33
  /** Converts a materialized replay document into a canonical item document. Use this when callers have already rejected the empty/deleted replay state and need restored metadata validated through the normal item-metadata rules. */
@@ -1,3 +1,3 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="19838bc7-d35d-5fae-a023-2e39697ffec9")}catch(e2){}})();import jsonPatch from"fast-json-patch";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates,resealHistoryRewrite,verifyHistoryRecordHash,verifyHistoryRewriteEvidence}from"./history.js";const EMPTY_REPLAY_DOCUMENT={metadata:{},body:""};function cloneEmptyReplayDocument(){return structuredClone(EMPTY_REPLAY_DOCUMENT)}function replayHash(document,version=CURRENT_HISTORY_ITEM_HASH_VERSION){return replayHashVerificationCandidates(document,version)[0]}function replayHashVerificationCandidates(document,version){if(Object.keys(document.metadata).length===0||Array.isArray(document.metadata.tags)){try{return hashDocumentVerificationCandidates(replayToItemDocument(document),version)}catch{}}const fallback=sha256Hex(stableStringify({replay_fallback:true,metadata:document.metadata,body:document.body}));return version===2?[fallback,fallback]:[fallback]}function matchReplayHashCandidates(before,after,version,entry){const beforeHashes=replayHashVerificationCandidates(before,version);const afterHashes=replayHashVerificationCandidates(after,version);return{beforeHashes,afterHashes,pairIndex:beforeHashes.findIndex((beforeHash,hashIndex)=>beforeHash===entry.before_hash&&afterHashes[hashIndex]===entry.after_hash),beforeIndex:beforeHashes.indexOf(entry.before_hash),afterIndex:afterHashes.indexOf(entry.after_hash)}}function replayToItemDocument(document){return{metadata:document.metadata,body:document.body}}function replayToCanonicalItemDocument(document,options={}){return canonicalDocument(replayToItemDocument(document),options)}function toReplayDocument(document){if(!document.metadata||Object.keys(document.metadata).length===0){return{metadata:{},body:document.body??""}}const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function normalizeReplayPatchPath(path){if(path==="/front_matter"){return"/metadata"}if(path.startsWith("/front_matter/")){return`/metadata/${path.slice("/front_matter/".length)}`}return path}function isHistoryPatchOp(value){return typeof value==="object"&&value!==null&&typeof value.op==="string"&&typeof value.path==="string"}function normalizeReplayPatchOps(patch){if(!Array.isArray(patch)){return[]}return patch.filter(isHistoryPatchOp).map(operation=>({...operation,path:normalizeReplayPatchPath(operation.path),from:typeof operation.from==="string"?normalizeReplayPatchPath(operation.from):void 0}))}function isReplayDocumentShape(value){return typeof value==="object"&&value!==null&&"metadata"in value&&"body"in value&&typeof value.body==="string"&&typeof value.metadata==="object"&&value.metadata!==null}function tryApplyReplayPatch(current,patch){try{const normalizedPatch=normalizeReplayPatchOps(patch);const applied=jsonPatch.applyPatch(structuredClone(current),normalizedPatch,true,false).newDocument;if(!isReplayDocumentShape(applied)){return{ok:false,error:new Error("history_replay_invalid_document_shape")}}return{ok:true,document:{metadata:applied.metadata,body:applied.body}}}catch(error){return{ok:false,error}}}function supportedExplicitHistoryItemHashVersions(entries){return[...new Set(entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)))]}function isUnsupportedExplicitHistoryItemHashVersion(version){return version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)}function historyEntryHashCandidates(explicitVersion,authoritativeVersion){if(explicitVersion!==void 0){return[explicitVersion]}return authoritativeVersion===void 0?[...SUPPORTED_HISTORY_ITEM_HASH_VERSIONS]:[authoritativeVersion]}function historyEntryIntegrityError(entry){const recordVerification=verifyHistoryRecordHash(entry);if(!recordVerification.ok)return recordVerification.error;const rewriteVerification=verifyHistoryRewriteEvidence(entry);return rewriteVerification.ok?void 0:rewriteVerification.error}function verifyHistoryEntryInput(entry,replay){const integrityError=historyEntryIntegrityError(entry);if(integrityError)return{ok:false,error:integrityError};const applied=tryApplyReplayPatch(replay,entry.patch);return applied.ok?{ok:true,document:applied.document}:{ok:false,error:"patch_apply_failed"}}function assertHistoryEntryIntegrity(entry,index){const integrityError=historyEntryIntegrityError(entry);if(integrityError){throw new TypeError(`${integrityError}:entry_${index+1}`)}}function verifyHistoryChainWithVersion(entries){let replay=cloneEmptyReplayDocument();let detectedVersion;let authoritativeExplicitVersion;const errors=findHistoryIdentityDiscontinuities(entries).map(finding=>`verify_failed:duplicate_create:entry_${finding.repeated_create_index}:prior_${finding.prior_genesis_index}`);for(let index=0;index<entries.length;index+=1){const entry=entries[index];const explicitVersion=entry.item_hash_version;const unsupportedVersion=isUnsupportedExplicitHistoryItemHashVersion(explicitVersion);if(unsupportedVersion){errors.push(`verify_failed:unsupported_item_hash_version:${String(explicitVersion)}:entry_${index+1}`)}const input=verifyHistoryEntryInput(entry,replay);if(!input.ok){return{ok:false,errors:[...errors,`verify_failed:${input.error}:entry_${index+1}`]}}if(unsupportedVersion){replay=input.document;detectedVersion=void 0;authoritativeExplicitVersion=void 0;continue}const candidates=historyEntryHashCandidates(explicitVersion,authoritativeExplicitVersion);const candidateMatches=candidates.map(version2=>({version:version2,match:matchReplayHashCandidates(replay,input.document,version2,entry)}));const matchingVersion=candidateMatches.find(({match})=>match.pairIndex>=0);if(matchingVersion===void 0){const beforeMatches=candidateMatches.some(({match})=>match.beforeIndex>=0);return{ok:false,errors:[...errors,`verify_failed:${beforeMatches?"after":"before"}_hash_mismatch:entry_${index+1}`]}}const version=matchingVersion.version;replay=input.document;detectedVersion=version;authoritativeExplicitVersion=explicitVersion??authoritativeExplicitVersion}if(errors.length>0){return{ok:false,errors,...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}}return{ok:true,errors:[],...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}}function verifyHistoryChain(entries){const result=verifyHistoryChainWithVersion(entries);return{ok:result.ok,errors:result.errors}}function tryApplySingleOp(document,op){try{const applied=jsonPatch.applyPatch(structuredClone(document),[op],true,false).newDocument;return{ok:true,document:applied}}catch{return{ok:false}}}function lenientApplyReplayPatch(current,patch){let working=structuredClone(current);let convertedReplaceToAdd=0;let skippedOps=0;for(const op of normalizeReplayPatchOps(patch)){const direct=tryApplySingleOp(working,op);if(direct.ok){working=direct.document;continue}if(op.op==="replace"){const asAdd=tryApplySingleOp(working,{...op,op:"add"});if(asAdd.ok){working=asAdd.document;convertedReplaceToAdd+=1;continue}}skippedOps+=1}const candidate=working;const document={metadata:typeof candidate.metadata==="object"&&candidate.metadata!==null?candidate.metadata:{},body:typeof candidate.body==="string"?candidate.body:current.body};return{document,convertedReplaceToAdd,skippedOps}}function resolveHistoryRepairItemHashVersion(entries){const explicitVersions=supportedExplicitHistoryItemHashVersions(entries);if(explicitVersions.length===1){return explicitVersions[0]}const verified=verifyHistoryChainWithVersion(entries);if(verified.ok&&verified.item_hash_version!==void 0){return verified.item_hash_version}if(explicitVersions.length===0){return 1}return CURRENT_HISTORY_ITEM_HASH_VERSION}function applyReanchorPatch(replay,entry){const strict=tryApplyReplayPatch(replay,entry.patch);if(strict.ok){return{next:strict.document,patch:entry.patch,repaired:false,converted:0,skipped:0}}const lenient=lenientApplyReplayPatch(replay,entry.patch);return{next:lenient.document,patch:jsonPatch.compare(replay,lenient.document),repaired:true,converted:lenient.convertedReplaceToAdd,skipped:lenient.skippedOps}}function reanchorHistoryEntries(entries,itemHashVersion=resolveHistoryRepairItemHashVersion(entries),options={}){const unsupportedIndex=entries.findIndex(entry=>isUnsupportedExplicitHistoryItemHashVersion(entry.item_hash_version));if(unsupportedIndex>=0){throw new TypeError(`unsupported_item_hash_version:${String(entries[unsupportedIndex]?.item_hash_version)}:entry_${unsupportedIndex+1}`)}let replay=cloneEmptyReplayDocument();const rewritten=[];const details=[];let entriesRehashed=0;let entriesPatchRepaired=0;let convertedReplaceToAdd=0;let skippedOps=0;let semanticIndex;const explicitItemHashVersion=itemHashVersion!==1||entries.some(entry=>entry.item_hash_version!==void 0);for(let index=0;index<entries.length;index+=1){const entry=entries[index];assertHistoryEntryIntegrity(entry,index);const patchApplication=applyReanchorPatch(replay,entry);const{next,patch:outPatch,repaired:patchRepaired,converted:entryConverted,skipped:entrySkipped}=patchApplication;convertedReplaceToAdd+=entryConverted;skippedOps+=entrySkipped;entriesPatchRepaired+=Number(patchRepaired);const hashMatch=matchReplayHashCandidates(replay,next,itemHashVersion,entry);if(semanticIndex===void 0||options.continuousHashSurface!==true){semanticIndex=[hashMatch.pairIndex,hashMatch.beforeIndex,hashMatch.afterIndex,Math.min(semanticIndex??0,hashMatch.beforeHashes.length-1)].find(candidate=>candidate>=0)}else{semanticIndex=Math.min(semanticIndex,hashMatch.beforeHashes.length-1)}const beforeHash=hashMatch.beforeHashes[semanticIndex];const afterHash=hashMatch.afterHashes[semanticIndex];const rehashed=beforeHash!==entry.before_hash||afterHash!==entry.after_hash;if(rehashed){entriesRehashed+=1}let rewrittenEntry={...entry,patch:outPatch,before_hash:beforeHash,after_hash:afterHash};if(explicitItemHashVersion){rewrittenEntry.item_hash_version=itemHashVersion}else{delete rewrittenEntry.item_hash_version}const versionChanged=rewrittenEntry.item_hash_version!==entry.item_hash_version;if(rehashed||patchRepaired||versionChanged){rewrittenEntry=resealHistoryRewrite(entry,rewrittenEntry,{retainOriginalPatch:patchRepaired})}rewritten.push(rewrittenEntry);details.push({index:index+1,rehashed,patch_repaired:patchRepaired,converted_replace_to_add:entryConverted,skipped_ops:entrySkipped});replay=next}return{entries:rewritten,finalDocument:replay,entriesRehashed,entriesPatchRepaired,convertedReplaceToAdd,skippedOps,details,itemHashVersion,explicitItemHashVersion}}function historyEntriesToRaw(entries){if(entries.length===0){return""}return`${entries.map(entry=>JSON.stringify(entry)).join("\n")}
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7a0fa585-7e3c-57fd-b29c-c26e9c522cb1")}catch(e2){}})();import jsonPatch from"fast-json-patch";import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,stableStringify}from"../shared/serialization.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates,resealHistoryRewrite,verifyHistoryRecordHash,verifyHistoryRewriteEvidence}from"./history.js";const EMPTY_REPLAY_DOCUMENT={metadata:{},body:""};function cloneEmptyReplayDocument(){return structuredClone(EMPTY_REPLAY_DOCUMENT)}function replayHash(document,version=CURRENT_HISTORY_ITEM_HASH_VERSION,algorithm){return replayHashVerificationCandidates(document,version,algorithm)[0]}function replayHashVerificationCandidates(document,version,algorithm){if(Object.keys(document.metadata).length===0||Array.isArray(document.metadata.tags)){try{return hashDocumentVerificationCandidates(replayToItemDocument(document),version,algorithm)}catch{}}const fallback=historyDigest(stableStringify({replay_fallback:true,metadata:document.metadata,body:document.body}),algorithm);return version===2?[fallback,fallback]:[fallback]}function matchReplayHashCandidates(before,after,version,entry){const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm);const beforeHashes=replayHashVerificationCandidates(before,version,algorithm);const afterHashes=replayHashVerificationCandidates(after,version,algorithm);return{beforeHashes,afterHashes,pairIndex:beforeHashes.findIndex((beforeHash,hashIndex)=>beforeHash===entry.before_hash&&afterHashes[hashIndex]===entry.after_hash),beforeIndex:beforeHashes.indexOf(entry.before_hash),afterIndex:afterHashes.indexOf(entry.after_hash)}}function replayToItemDocument(document){return{metadata:document.metadata,body:document.body}}function replayToCanonicalItemDocument(document,options={}){return canonicalDocument(replayToItemDocument(document),options)}function toReplayDocument(document){if(!document.metadata||Object.keys(document.metadata).length===0){return{metadata:{},body:document.body??""}}const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function normalizeReplayPatchPath(path){if(path==="/front_matter"){return"/metadata"}if(path.startsWith("/front_matter/")){return`/metadata/${path.slice("/front_matter/".length)}`}return path}function isHistoryPatchOp(value){return typeof value==="object"&&value!==null&&typeof value.op==="string"&&typeof value.path==="string"}function normalizeReplayPatchOps(patch){if(!Array.isArray(patch)){return[]}return patch.filter(isHistoryPatchOp).map(operation=>({...operation,path:normalizeReplayPatchPath(operation.path),from:typeof operation.from==="string"?normalizeReplayPatchPath(operation.from):void 0}))}function isReplayDocumentShape(value){return typeof value==="object"&&value!==null&&"metadata"in value&&"body"in value&&typeof value.body==="string"&&typeof value.metadata==="object"&&value.metadata!==null}function tryApplyReplayPatch(current,patch){try{const normalizedPatch=normalizeReplayPatchOps(patch);const applied=jsonPatch.applyPatch(structuredClone(current),normalizedPatch,true,false).newDocument;if(!isReplayDocumentShape(applied)){return{ok:false,error:new Error("history_replay_invalid_document_shape")}}return{ok:true,document:{metadata:applied.metadata,body:applied.body}}}catch(error){return{ok:false,error}}}function supportedExplicitHistoryItemHashVersions(entries){return[...new Set(entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)))]}function isUnsupportedExplicitHistoryItemHashVersion(version){return version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)}function historyEntryHashCandidates(explicitVersion,authoritativeVersion){if(explicitVersion!==void 0){return[explicitVersion]}return authoritativeVersion===void 0?[...SUPPORTED_HISTORY_ITEM_HASH_VERSIONS]:[authoritativeVersion]}function historyEntryIntegrityError(entry){const recordVerification=verifyHistoryRecordHash(entry);if(!recordVerification.ok)return recordVerification.error;const rewriteVerification=verifyHistoryRewriteEvidence(entry);return rewriteVerification.ok?void 0:rewriteVerification.error}function verifyHistoryEntryInput(entry,replay){const integrityError=historyEntryIntegrityError(entry);if(integrityError)return{ok:false,error:integrityError};const applied=tryApplyReplayPatch(replay,entry.patch);return applied.ok?{ok:true,document:applied.document}:{ok:false,error:"patch_apply_failed"}}function assertHistoryEntryIntegrity(entry,index){const integrityError=historyEntryIntegrityError(entry);if(integrityError){throw new TypeError(`${integrityError}:entry_${index+1}`)}}function verifyHistoryChainWithVersion(entries){let replay=cloneEmptyReplayDocument();let detectedVersion;let authoritativeExplicitVersion;const errors=findHistoryIdentityDiscontinuities(entries).map(finding=>`verify_failed:duplicate_create:entry_${finding.repeated_create_index}:prior_${finding.prior_genesis_index}`);for(let index=0;index<entries.length;index+=1){const entry=entries[index];const explicitVersion=entry.item_hash_version;const unsupportedVersion=isUnsupportedExplicitHistoryItemHashVersion(explicitVersion);if(unsupportedVersion){errors.push(`verify_failed:unsupported_item_hash_version:${String(explicitVersion)}:entry_${index+1}`)}const input=verifyHistoryEntryInput(entry,replay);if(!input.ok){return{ok:false,errors:[...errors,`verify_failed:${input.error}:entry_${index+1}`]}}if(unsupportedVersion){replay=input.document;detectedVersion=void 0;authoritativeExplicitVersion=void 0;continue}const candidates=historyEntryHashCandidates(explicitVersion,authoritativeExplicitVersion);const candidateMatches=candidates.map(version2=>({version:version2,match:matchReplayHashCandidates(replay,input.document,version2,entry)}));const matchingVersion=candidateMatches.find(({match})=>match.pairIndex>=0);if(matchingVersion===void 0){const beforeMatches=candidateMatches.some(({match})=>match.beforeIndex>=0);return{ok:false,errors:[...errors,`verify_failed:${beforeMatches?"after":"before"}_hash_mismatch:entry_${index+1}`]}}const version=matchingVersion.version;replay=input.document;detectedVersion=version;authoritativeExplicitVersion=explicitVersion??authoritativeExplicitVersion}if(errors.length>0){return{ok:false,errors,...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}}return{ok:true,errors:[],...detectedVersion===void 0?{}:{item_hash_version:detectedVersion}}}function verifyHistoryChain(entries){const result=verifyHistoryChainWithVersion(entries);return{ok:result.ok,errors:result.errors}}function tryApplySingleOp(document,op){try{const applied=jsonPatch.applyPatch(structuredClone(document),[op],true,false).newDocument;return{ok:true,document:applied}}catch{return{ok:false}}}function lenientApplyReplayPatch(current,patch){let working=structuredClone(current);let convertedReplaceToAdd=0;let skippedOps=0;for(const op of normalizeReplayPatchOps(patch)){const direct=tryApplySingleOp(working,op);if(direct.ok){working=direct.document;continue}if(op.op==="replace"){const asAdd=tryApplySingleOp(working,{...op,op:"add"});if(asAdd.ok){working=asAdd.document;convertedReplaceToAdd+=1;continue}}skippedOps+=1}const candidate=working;const document={metadata:typeof candidate.metadata==="object"&&candidate.metadata!==null?candidate.metadata:{},body:typeof candidate.body==="string"?candidate.body:current.body};return{document,convertedReplaceToAdd,skippedOps}}function resolveHistoryRepairItemHashVersion(entries){const explicitVersions=supportedExplicitHistoryItemHashVersions(entries);if(explicitVersions.length===1){return explicitVersions[0]}const verified=verifyHistoryChainWithVersion(entries);if(verified.ok&&verified.item_hash_version!==void 0){return verified.item_hash_version}if(explicitVersions.length===0){return 1}return CURRENT_HISTORY_ITEM_HASH_VERSION}function applyReanchorPatch(replay,entry){const strict=tryApplyReplayPatch(replay,entry.patch);if(strict.ok){return{next:strict.document,patch:entry.patch,repaired:false,converted:0,skipped:0}}const lenient=lenientApplyReplayPatch(replay,entry.patch);return{next:lenient.document,patch:jsonPatch.compare(replay,lenient.document),repaired:true,converted:lenient.convertedReplaceToAdd,skipped:lenient.skippedOps}}function reanchorHistoryEntries(entries,itemHashVersion=resolveHistoryRepairItemHashVersion(entries),options={}){const unsupportedIndex=entries.findIndex(entry=>isUnsupportedExplicitHistoryItemHashVersion(entry.item_hash_version));if(unsupportedIndex>=0){throw new TypeError(`unsupported_item_hash_version:${String(entries[unsupportedIndex]?.item_hash_version)}:entry_${unsupportedIndex+1}`)}let replay=cloneEmptyReplayDocument();const rewritten=[];const details=[];let entriesRehashed=0;let entriesPatchRepaired=0;let convertedReplaceToAdd=0;let skippedOps=0;let semanticIndex;const explicitItemHashVersion=itemHashVersion!==1||entries.some(entry=>entry.item_hash_version!==void 0);for(let index=0;index<entries.length;index+=1){const entry=entries[index];assertHistoryEntryIntegrity(entry,index);const patchApplication=applyReanchorPatch(replay,entry);const{next,patch:outPatch,repaired:patchRepaired,converted:entryConverted,skipped:entrySkipped}=patchApplication;convertedReplaceToAdd+=entryConverted;skippedOps+=entrySkipped;entriesPatchRepaired+=Number(patchRepaired);const hashMatch=matchReplayHashCandidates(replay,next,itemHashVersion,entry);if(semanticIndex===void 0||options.continuousHashSurface!==true){semanticIndex=[hashMatch.pairIndex,hashMatch.beforeIndex,hashMatch.afterIndex,Math.min(semanticIndex??0,hashMatch.beforeHashes.length-1)].find(candidate=>candidate>=0)}else{semanticIndex=Math.min(semanticIndex,hashMatch.beforeHashes.length-1)}const beforeHash=hashMatch.beforeHashes[semanticIndex];const afterHash=hashMatch.afterHashes[semanticIndex];const rehashed=beforeHash!==entry.before_hash||afterHash!==entry.after_hash;if(rehashed){entriesRehashed+=1}let rewrittenEntry={...entry,patch:outPatch,before_hash:beforeHash,after_hash:afterHash};if(explicitItemHashVersion){rewrittenEntry.item_hash_version=itemHashVersion}else{delete rewrittenEntry.item_hash_version}const versionChanged=rewrittenEntry.item_hash_version!==entry.item_hash_version;if(rehashed||patchRepaired||versionChanged){rewrittenEntry=resealHistoryRewrite(entry,rewrittenEntry,{retainOriginalPatch:patchRepaired})}rewritten.push(rewrittenEntry);details.push({index:index+1,rehashed,patch_repaired:patchRepaired,converted_replace_to_add:entryConverted,skipped_ops:entrySkipped});replay=next}return{entries:rewritten,finalDocument:replay,entriesRehashed,entriesPatchRepaired,convertedReplaceToAdd,skippedOps,details,itemHashVersion,explicitItemHashVersion}}function historyEntriesToRaw(entries){if(entries.length===0){return""}return`${entries.map(entry=>JSON.stringify(entry)).join("\n")}
2
2
  `}export{EMPTY_REPLAY_DOCUMENT,cloneEmptyReplayDocument,historyEntriesToRaw,lenientApplyReplayPatch,normalizeReplayPatchOps,normalizeReplayPatchPath,reanchorHistoryEntries,replayHash,replayHashVerificationCandidates,replayToCanonicalItemDocument,replayToItemDocument,resolveHistoryRepairItemHashVersion,toReplayDocument,tryApplyReplayPatch,verifyHistoryChain,verifyHistoryChainWithVersion};
3
3
  //# sourceMappingURL=replay.js.map
@@ -220,6 +220,7 @@ declare function buildOtelSpanRequest(activeCommand: ActiveTelemetryCommand, out
220
220
  endpoint: string;
221
221
  payload: unknown;
222
222
  } | null;
223
+ /** Build a bounded, capture-level-sanitized result preview. Omit undefined object values as JSON does so optional fields cannot prevent completion telemetry. */
223
224
  declare function summarizeResult(result: unknown, captureLevel?: Exclude<TelemetryCaptureLevel, "minimal">): Record<string, unknown>;
224
225
  declare function buildCommandStartPayload(params: {
225
226
  captureLevel: TelemetryCaptureLevel;
@@ -1,5 +1,5 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a80b4f33-b43b-5056-a4eb-ba784c9746a4")}catch(e2){}})();import crypto from"node:crypto";import{spawn}from"node:child_process";import{mkdirSync,rmSync,statSync}from"node:fs";import{mkdir,readdir,rm,stat}from"node:fs/promises";import{request as httpRequest}from"node:http";import{request as httpsRequest}from"node:https";import os from"node:os";import path from"node:path";import{resolvePmPackageRootFromModule}from"../packages/root.js";import{isFileMissingError,appendLineAtomic,readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{resolveTelemetryErrorCategory}from"../shared/constants.js";import{nowIso}from"../shared/time.js";import{detectAgentIdentity,readAuthorEnvironment}from"../shared/author.js";import{resolveGlobalPmRoot}from"../store/paths.js";import{readSettings,writeSettings}from"../store/settings.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy,inferTelemetryErrorCode}from"./observability.js";const TELEMETRY_QUEUE_RELATIVE_PATH=path.join("runtime","telemetry","events.jsonl");const TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json");const TELEMETRY_OTEL_SPANS_RELATIVE_PATH=path.join("runtime","telemetry","otel-spans.jsonl");const TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE=8;const TELEMETRY_OTEL_SPANS_MAX_PENDING=500;const TELEMETRY_SCHEMA_VERSION=1;const TELEMETRY_CLIENT_SCHEMA_VERSION=1;const TELEMETRY_FLUSH_BATCH_SIZE=100;const TELEMETRY_MAX_RETRY_DELAY_MS=36e5;const TELEMETRY_RETRY_BASE_DELAY_MS=3e4;const TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS=2e4;const TELEMETRY_HTTP_TIMEOUT_MIN_MS=1e3;const TELEMETRY_HTTP_TIMEOUT_MAX_MS=25e3;const MILLISECONDS_PER_DAY=864e5;const TELEMETRY_MAX_EVENT_BYTES=65536;const TELEMETRY_SANITIZE_MAX_DEPTH=6;const TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS=20;const TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS=15;const TELEMETRY_RESULT_PREVIEW_MAX_BYTES=8192;const TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS=[25,50,100,200];const TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS=60*60*1e3;const TELEMETRY_FLUSH_LOCK_STALE_MS=6e4;const TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS=6e4;const OTEL_TRACES_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT";const OTEL_BASE_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_ENDPOINT";const OTEL_SERVICE_NAME_ENV="OTEL_SERVICE_NAME";const PM_TELEMETRY_DISABLED_ENV="PM_TELEMETRY_DISABLED";const PM_NO_TELEMETRY_ENV="PM_NO_TELEMETRY";const PM_TELEMETRY_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_OTEL_DISABLED_ENV="PM_TELEMETRY_OTEL_DISABLED";const PM_TELEMETRY_OTEL_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_INLINE_FLUSH_ENV="PM_TELEMETRY_INLINE_FLUSH";const PM_TELEMETRY_FLUSH_CHILD_ENV="PM_TELEMETRY_FLUSH_CHILD";const PM_TELEMETRY_SOURCE_CONTEXT_ENV="PM_TELEMETRY_SOURCE_CONTEXT";const PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV="PM_TELEMETRY_HTTP_TIMEOUT_MS";const NATIVE_FETCH=globalThis.fetch;const PM_TELEMETRY_SOURCE_CONTEXT_VALUES=["user","automation","test","dogfood"];let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();async function waitForPendingFlush(){await _lastFlushPromise;await _queueMutationPromise}const PM_TELEMETRY_SOURCE_CONTEXT_SET=new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);const BOOLEAN_TRUE_VALUES=new Set(["1","true","yes","on"]);const PROCESS_SESSION_ID=crypto.randomUUID();const SENSITIVE_KEYWORDS=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"];const REDACTION_INPUT_KEYS=new Set(["literal","literals","regex","regexes","replacement","replacements"]);const SENSITIVE_INLINE_KEY_PATTERN="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)";const INLINE_SENSITIVE_ASSIGNMENT_PATTERN=new RegExp(`\\b(${SENSITIVE_INLINE_KEY_PATTERN})\\s*([:=])\\s*([^\\s,;]+)`,"giu");const INLINE_SENSITIVE_FLAG_PATTERN=new RegExp(`(--${SENSITIVE_INLINE_KEY_PATTERN})(=|\\s+)([^\\s,;]+)`,"giu");const ABSOLUTE_PATH_TOKEN_PATTERN=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g;const BEARER_TOKEN_PATTERN=/bearer\s+[a-z0-9._=-]+/giu;const PRIVATE_IP_PATTERN=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function queuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_QUEUE_RELATIVE_PATH)}function otelSpansQueuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_OTEL_SPANS_RELATIVE_PATH)}function telemetryRuntimeDirectory(globalPmRoot){return path.dirname(queuePath(globalPmRoot))}function runtimeStatePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH)}function flushLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.lock")}function flushSpawnLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.spawn.lock")}function telemetryFlushRunnerPath(){return path.join(resolvePmPackageRootFromModule(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function shouldFlushInline(){if(parseBooleanTrueLike(process.env[PM_TELEMETRY_INLINE_FLUSH_ENV])){return true}if(parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])){return true}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"}async function readRuntimeState(globalPmRoot){const raw=await readFileIfExists(runtimeStatePath(globalPmRoot));if(!raw||raw.trim().length===0){return{}}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return{}}return parsed}catch{return{}}}async function writeRuntimeState(globalPmRoot,patch){try{const current=await readRuntimeState(globalPmRoot);const next={...current,...patch};const normalized=Object.fromEntries(Object.entries(next).filter(([,value])=>value!==void 0).sort((left,right)=>left[0].localeCompare(right[0])));await writeFileAtomic(runtimeStatePath(globalPmRoot),`${JSON.stringify(normalized,null,2)}
2
- `)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_");const tokens=normalized.split("_").filter(token=>token.length>0);return REDACTION_INPUT_KEYS.has(normalized)||SENSITIVE_KEYWORDS.some(keyword=>normalized===keyword||normalized.endsWith(`_${keyword}`)||tokens.includes(keyword))}function redactInlineSensitiveAssignments(input){const withoutAssignments=input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`);return withoutAssignments.replaceAll(INLINE_SENSITIVE_FLAG_PATTERN,(_match,flag,delimiter)=>`${flag}${delimiter}[redacted]`)}function redactAbsolutePathTokens(input){return input.replaceAll(ABSOLUTE_PATH_TOKEN_PATTERN,(_match,prefix)=>`${prefix}[redacted_path]`)}function isAsciiLetterOrDigitCode(code){const isUpper=code>=65&&code<=90;const isLower=code>=97&&code<=122;const isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1){return false}const localPart=token.slice(0,atIndex);const domainPart=token.slice(atIndex+1);const lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1){return false}if(domainPart.length-(lastDot+1)<2){return false}for(const character of localPart){if(!isEmailLocalCharacter(character)){return false}}for(const character of domainPart){if(!isEmailDomainCharacter(character)){return false}}return true}function redactEmailTokens(input){let redacted="";let cursor=0;while(cursor<input.length){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;while(start>=cursor&&isEmailLocalCharacter(input[start])){start-=1}start+=1;let end=atIndex+1;while(end<input.length&&isEmailDomainCharacter(input[end])){end+=1}const candidate=input.slice(start,end);if(looksLikeEmailToken(candidate)){redacted+=input.slice(cursor,start);redacted+="[redacted_email]";cursor=end;continue}redacted+=input.slice(cursor,atIndex+1);cursor=atIndex+1}return redacted}function sanitizeCommonSensitiveTokens(input){const withoutEmails=redactEmailTokens(input);const withoutBearer=withoutEmails.replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]");return withoutBearer.replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>512){return`${withoutAbsolutePaths.slice(0,509)}...`}return withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>2048){return`${withoutAbsolutePaths.slice(0,2045)}...`}return withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){if(captureLevel==="max"){return sanitizeStringMax(input)}return sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint)){return"[redacted]"}if(value===null||value===void 0){return value}if(typeof value==="string"){return sanitizeString(value,captureLevel)}if(typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>sanitizeValue(entry,void 0,captureLevel,depth+1))}if(typeof value==="object"){const record=value;const sanitized={};for(const[key,nested]of Object.entries(record)){sanitized[key]=sanitizeValue(nested,key,captureLevel,depth+1)}return sanitized}return String(value)}function sanitizeCommandArgs(args,captureLevel="redacted"){const sanitized=[];let nextIsSensitiveValue=false;for(const rawArg of args){const arg=sanitizeString(rawArg,captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]");nextIsSensitiveValue=false;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2);const delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex);const value=withoutPrefix.slice(delimiterIndex+1);if(isSensitiveKey(key)){sanitized.push(`--${key}=[redacted]`)}else{sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`)}continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`);nextIsSensitiveValue=true;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();if(normalized==="minimal"||normalized==="redacted"||normalized==="max"){return normalized}return"redacted"}function parseBooleanTrueLike(value){return BOOLEAN_TRUE_VALUES.has((value??"").trim().toLowerCase())}function resolveTelemetryHttpTimeoutMs(){const rawConfigured=process.env[PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV]?.trim();if(!rawConfigured){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}const configured=Number(rawConfigured);if(!Number.isFinite(configured)){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}return Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured)))}async function postTelemetryJson(endpoint,headers,body){const url=new URL(endpoint);if(globalThis.fetch!==NATIVE_FETCH){const controller=new AbortController;let timeout;const deadline=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>{controller.abort();reject(new Error("telemetry_http_timeout"))},resolveTelemetryHttpTimeoutMs())});try{const response=await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline]);return response.status}finally{clearTimeout(timeout)}}const request=url.protocol==="https:"?httpsRequest:url.protocol==="http:"?httpRequest:void 0;if(!request){throw new Error(`telemetry_http_protocol_unsupported_${url.protocol}`)}return new Promise((resolve,reject)=>{const timeoutMs=resolveTelemetryHttpTimeoutMs();const requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)};const clientRequest=request(url,requestOptions,response=>{response.once("error",reject);response.once("end",()=>resolve(response.statusCode));response.resume()});clientRequest.once("error",reject);clientRequest.end(body)})}function normalizePmVersion(value){const trimmed=typeof value==="string"?value.trim():"";return trimmed.length>0?trimmed:"0.0.0"}function normalizeTelemetryErrorCode(value){const normalized=value?.trim();return normalized&&normalized.length>0?normalized:void 0}function normalizeTelemetryExitCode(exitCode,ok){if(Number.isFinite(exitCode)){return Math.max(0,Math.trunc(exitCode))}return ok?0:1}function normalizeTelemetryErrorCategory(params){if(params.ok){return void 0}if(typeof params.errorCategory==="string"&&params.errorCategory.trim().length>0){return params.errorCategory}if(typeof params.errorCode==="string"&&params.errorCode.trim().length>0){return resolveTelemetryErrorCategory(params.errorCode)}return"unknown"}function resolveTelemetrySourceContext(globalOptions){const override=(process.env[PM_TELEMETRY_SOURCE_CONTEXT_ENV]??"").trim().toLowerCase();if(PM_TELEMETRY_SOURCE_CONTEXT_SET.has(override)){return{source_context:override,source_context_source:"env_override"}}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return{source_context:"test",source_context_source:"inferred"}}const nonTty=process.stdin.isTTY!==true||process.stdout.isTTY!==true;const ci=parseBooleanTrueLike(process.env.CI);const scriptLikeMode=globalOptions.json===true||globalOptions.quiet===true;if(nonTty||ci||scriptLikeMode){return{source_context:"automation",source_context_source:"inferred"}}return{source_context:"user",source_context_source:"inferred"}}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim();const agent=detectAgentIdentity({env:process.env,argv:process.argv});const hasAgentContext=agent.harness!==void 0||agent.model!==void 0;if(captureLevel==="minimal"){return{has_author_context:author.length>0,has_agent_context:hasAgentContext}}return{...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value===null||value===void 0){return value}if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1))}if(typeof value==="object"){const record=value;const normalized={};const sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys){normalized[key]=normalizeForHash(record[key],depth+1)}return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage==="string"?errorMessage:"","redacted");const normalizedCode=typeof errorCode2==="string"&&errorCode2.length>0?errorCode2:"unknown_error";const fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function telemetryDisabledByEnvironment(){return PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_TELEMETRY_DISABLED_ENV]??"").trim().toLowerCase())||PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_NO_TELEMETRY_ENV]??"").trim().toLowerCase())}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase())){return null}const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0){try{return new URL(directEndpoint).toString()}catch{return null}}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0){return null}try{const url=new URL(baseEndpoint);const normalizedPath=url.pathname.replace(/\/+$/,"");if(!normalizedPath.endsWith("/v1/traces")){url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`}return url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso);const epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs){if(typeof activeCommand.otel_traces_endpoint!=="string"||activeCommand.otel_traces_endpoint.trim().length===0||typeof activeCommand.otel_trace_id!=="string"||activeCommand.otel_trace_id.length===0||typeof activeCommand.otel_span_id!=="string"||activeCommand.otel_span_id.length===0){return null}const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim());const serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli";const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code);const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs)];if(typeof normalizedErrorCode==="string"){attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode))}if(typeof normalizedErrorCategory==="string"){attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory))}if(typeof outcome.error==="string"&&outcome.error.trim().length>0){attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)))}const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error==="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint:activeCommand.otel_traces_endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result===null||result===void 0){return{type:"nullish"}}if(typeof result==="string"){return{type:"string",value:sanitizeString(result,captureLevel)}}if(typeof result==="number"||typeof result==="boolean"){return{type:typeof result,value:result}}if(Array.isArray(result)){return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))}}if(typeof result==="object"){const record=result;const keys=Object.keys(record).sort((left,right)=>left.localeCompare(right));const sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize;sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params;const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const hashedArgs=hashCommandArgs(installationId,context.args);const commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`);const commandOptionsDigest=hashTelemetryValue(installationId,context.options);const globalOptionsDigest=hashTelemetryValue(installationId,context.global);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}}return{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params;const errorFingerprint=outcome.ok===false?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0;const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params;const attemptedArgHashes=hashCommandArgs(installationId,args);const attemptedCommandDigest=hashWithInstallationId(installationId,command);const attemptedOptionsDigest=hashTelemetryValue(installationId,options);const errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);let changed=false;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();changed=true}if(changed){await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days))}}async function enqueueTelemetryEvent(globalPmRoot,event){const queued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0};let serialized=JSON.stringify(queued);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:true,reason:"payload_size_exceeded",original_bytes:serialized.length}}};const trimmedQueued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0};serialized=JSON.stringify(trimmedQueued)}await withQueueMutation(async()=>{await appendLineAtomic(queuePath(globalPmRoot),serialized)})}function parseQueueLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&parsed.event&&typeof parsed.event==="object"&&typeof parsed.attempts==="number"&&(parsed.client_schema_version===void 0||typeof parsed.client_schema_version==="number"&&Number.isFinite(parsed.client_schema_version))){entries.push(parsed)}}catch{}}return entries}function nextRetryIso(attempts){const delay=Math.min(TELEMETRY_RETRY_BASE_DELAY_MS*2**Math.max(attempts-1,0),TELEMETRY_MAX_RETRY_DELAY_MS);return new Date(Date.now()+delay).toISOString()}function isDueForRetryAt(nextAttemptAfter){if(typeof nextAttemptAfter!=="string"||nextAttemptAfter.trim().length===0){return true}const dueAtMs=Date.parse(nextAttemptAfter);if(Number.isNaN(dueAtMs)){return true}return dueAtMs<=Date.now()}function isDueForRetry(entry){return isDueForRetryAt(entry.next_attempt_after)}function retentionCutoffMs(retentionDays){const normalizedDays=Number.isFinite(retentionDays)?Math.max(1,Math.trunc(retentionDays)):1;return Date.now()-normalizedDays*MILLISECONDS_PER_DAY}function isExpiredQueueEntry(entry,cutoffMs){const occurredAt=entry.event?.occurred_at;if(typeof occurredAt!=="string"||occurredAt.trim().length===0){return false}const occurredAtMs=Date.parse(occurredAt);if(Number.isNaN(occurredAtMs)){return false}return occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const serializedSize=JSON.stringify(entry).length;const oversized=serializedSize>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredQueueEntry(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}return{entries:retained,prunedCount}}async function rewriteQueue(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="18834273-7639-5a1e-b8ea-39a0ea945de1")}catch(e2){}})();import crypto from"node:crypto";import{spawn}from"node:child_process";import{mkdirSync,rmSync,statSync}from"node:fs";import{mkdir,readdir,rm,stat}from"node:fs/promises";import{request as httpRequest}from"node:http";import{request as httpsRequest}from"node:https";import os from"node:os";import path from"node:path";import{resolvePmPackageRootFromModule}from"../packages/root.js";import{isFileMissingError,appendLineAtomic,readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{resolveTelemetryErrorCategory}from"../shared/constants.js";import{nowIso}from"../shared/time.js";import{detectAgentIdentity,readAuthorEnvironment}from"../shared/author.js";import{resolveGlobalPmRoot}from"../store/paths.js";import{readSettings,writeSettings}from"../store/settings.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy,inferTelemetryErrorCode}from"./observability.js";const TELEMETRY_QUEUE_RELATIVE_PATH=path.join("runtime","telemetry","events.jsonl");const TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json");const TELEMETRY_OTEL_SPANS_RELATIVE_PATH=path.join("runtime","telemetry","otel-spans.jsonl");const TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE=8;const TELEMETRY_OTEL_SPANS_MAX_PENDING=500;const TELEMETRY_SCHEMA_VERSION=1;const TELEMETRY_CLIENT_SCHEMA_VERSION=1;const TELEMETRY_FLUSH_BATCH_SIZE=100;const TELEMETRY_MAX_RETRY_DELAY_MS=36e5;const TELEMETRY_RETRY_BASE_DELAY_MS=3e4;const TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS=2e4;const TELEMETRY_HTTP_TIMEOUT_MIN_MS=1e3;const TELEMETRY_HTTP_TIMEOUT_MAX_MS=25e3;const MILLISECONDS_PER_DAY=864e5;const TELEMETRY_MAX_EVENT_BYTES=65536;const TELEMETRY_SANITIZE_MAX_DEPTH=6;const TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS=20;const TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS=15;const TELEMETRY_RESULT_PREVIEW_MAX_BYTES=8192;const TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS=[25,50,100,200];const TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS=60*60*1e3;const TELEMETRY_FLUSH_LOCK_STALE_MS=6e4;const TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS=6e4;const OTEL_TRACES_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT";const OTEL_BASE_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_ENDPOINT";const OTEL_SERVICE_NAME_ENV="OTEL_SERVICE_NAME";const PM_TELEMETRY_DISABLED_ENV="PM_TELEMETRY_DISABLED";const PM_NO_TELEMETRY_ENV="PM_NO_TELEMETRY";const PM_TELEMETRY_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_OTEL_DISABLED_ENV="PM_TELEMETRY_OTEL_DISABLED";const PM_TELEMETRY_OTEL_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_INLINE_FLUSH_ENV="PM_TELEMETRY_INLINE_FLUSH";const PM_TELEMETRY_FLUSH_CHILD_ENV="PM_TELEMETRY_FLUSH_CHILD";const PM_TELEMETRY_SOURCE_CONTEXT_ENV="PM_TELEMETRY_SOURCE_CONTEXT";const PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV="PM_TELEMETRY_HTTP_TIMEOUT_MS";const NATIVE_FETCH=globalThis.fetch;const PM_TELEMETRY_SOURCE_CONTEXT_VALUES=["user","automation","test","dogfood"];let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();async function waitForPendingFlush(){await _lastFlushPromise;await _queueMutationPromise}const PM_TELEMETRY_SOURCE_CONTEXT_SET=new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);const BOOLEAN_TRUE_VALUES=new Set(["1","true","yes","on"]);const PROCESS_SESSION_ID=crypto.randomUUID();const SENSITIVE_KEYWORDS=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"];const REDACTION_INPUT_KEYS=new Set(["literal","literals","regex","regexes","replacement","replacements"]);const SENSITIVE_INLINE_KEY_PATTERN="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)";const INLINE_SENSITIVE_ASSIGNMENT_PATTERN=new RegExp(`\\b(${SENSITIVE_INLINE_KEY_PATTERN})\\s*([:=])\\s*([^\\s,;]+)`,"giu");const INLINE_SENSITIVE_FLAG_PATTERN=new RegExp(`(--${SENSITIVE_INLINE_KEY_PATTERN})(=|\\s+)([^\\s,;]+)`,"giu");const ABSOLUTE_PATH_TOKEN_PATTERN=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g;const BEARER_TOKEN_PATTERN=/bearer\s+[a-z0-9._=-]+/giu;const PRIVATE_IP_PATTERN=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function queuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_QUEUE_RELATIVE_PATH)}function otelSpansQueuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_OTEL_SPANS_RELATIVE_PATH)}function telemetryRuntimeDirectory(globalPmRoot){return path.dirname(queuePath(globalPmRoot))}function runtimeStatePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH)}function flushLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.lock")}function flushSpawnLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.spawn.lock")}function telemetryFlushRunnerPath(){return path.join(resolvePmPackageRootFromModule(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function shouldFlushInline(){if(parseBooleanTrueLike(process.env[PM_TELEMETRY_INLINE_FLUSH_ENV])){return true}if(parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])){return true}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"}async function readRuntimeState(globalPmRoot){const raw=await readFileIfExists(runtimeStatePath(globalPmRoot));if(!raw||raw.trim().length===0){return{}}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return{}}return parsed}catch{return{}}}async function writeRuntimeState(globalPmRoot,patch){try{const current=await readRuntimeState(globalPmRoot);const next={...current,...patch};const normalized=Object.fromEntries(Object.entries(next).filter(([,value])=>value!==void 0).sort((left,right)=>left[0].localeCompare(right[0])));await writeFileAtomic(runtimeStatePath(globalPmRoot),`${JSON.stringify(normalized,null,2)}
2
+ `)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_");const tokens=normalized.split("_").filter(token=>token.length>0);return REDACTION_INPUT_KEYS.has(normalized)||SENSITIVE_KEYWORDS.some(keyword=>normalized===keyword||normalized.endsWith(`_${keyword}`)||tokens.includes(keyword))}function redactInlineSensitiveAssignments(input){const withoutAssignments=input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`);return withoutAssignments.replaceAll(INLINE_SENSITIVE_FLAG_PATTERN,(_match,flag,delimiter)=>`${flag}${delimiter}[redacted]`)}function redactAbsolutePathTokens(input){return input.replaceAll(ABSOLUTE_PATH_TOKEN_PATTERN,(_match,prefix)=>`${prefix}[redacted_path]`)}function isAsciiLetterOrDigitCode(code){const isUpper=code>=65&&code<=90;const isLower=code>=97&&code<=122;const isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1){return false}const localPart=token.slice(0,atIndex);const domainPart=token.slice(atIndex+1);const lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1){return false}if(domainPart.length-(lastDot+1)<2){return false}for(const character of localPart){if(!isEmailLocalCharacter(character)){return false}}for(const character of domainPart){if(!isEmailDomainCharacter(character)){return false}}return true}function redactEmailTokens(input){let redacted="";let cursor=0;while(cursor<input.length){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;while(start>=cursor&&isEmailLocalCharacter(input[start])){start-=1}start+=1;let end=atIndex+1;while(end<input.length&&isEmailDomainCharacter(input[end])){end+=1}const candidate=input.slice(start,end);if(looksLikeEmailToken(candidate)){redacted+=input.slice(cursor,start);redacted+="[redacted_email]";cursor=end;continue}redacted+=input.slice(cursor,atIndex+1);cursor=atIndex+1}return redacted}function sanitizeCommonSensitiveTokens(input){const withoutEmails=redactEmailTokens(input);const withoutBearer=withoutEmails.replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]");return withoutBearer.replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>512){return`${withoutAbsolutePaths.slice(0,509)}...`}return withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>2048){return`${withoutAbsolutePaths.slice(0,2045)}...`}return withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){if(captureLevel==="max"){return sanitizeStringMax(input)}return sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint)){return"[redacted]"}if(value===null||value===void 0){return value}if(typeof value==="string"){return sanitizeString(value,captureLevel)}if(typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>sanitizeValue(entry,void 0,captureLevel,depth+1))}if(typeof value==="object"){const record=value;const sanitized={};for(const[key,nested]of Object.entries(record)){sanitized[key]=sanitizeValue(nested,key,captureLevel,depth+1)}return sanitized}return String(value)}function sanitizeCommandArgs(args,captureLevel="redacted"){const sanitized=[];let nextIsSensitiveValue=false;for(const rawArg of args){const arg=sanitizeString(rawArg,captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]");nextIsSensitiveValue=false;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2);const delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex);const value=withoutPrefix.slice(delimiterIndex+1);if(isSensitiveKey(key)){sanitized.push(`--${key}=[redacted]`)}else{sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`)}continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`);nextIsSensitiveValue=true;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();if(normalized==="minimal"||normalized==="redacted"||normalized==="max"){return normalized}return"redacted"}function parseBooleanTrueLike(value){return BOOLEAN_TRUE_VALUES.has((value??"").trim().toLowerCase())}function resolveTelemetryHttpTimeoutMs(){const rawConfigured=process.env[PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV]?.trim();if(!rawConfigured){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}const configured=Number(rawConfigured);if(!Number.isFinite(configured)){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}return Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured)))}async function postTelemetryJson(endpoint,headers,body){const url=new URL(endpoint);if(globalThis.fetch!==NATIVE_FETCH){const controller=new AbortController;let timeout;const deadline=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>{controller.abort();reject(new Error("telemetry_http_timeout"))},resolveTelemetryHttpTimeoutMs())});try{const response=await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline]);return response.status}finally{clearTimeout(timeout)}}const request=url.protocol==="https:"?httpsRequest:url.protocol==="http:"?httpRequest:void 0;if(!request){throw new Error(`telemetry_http_protocol_unsupported_${url.protocol}`)}return new Promise((resolve,reject)=>{const timeoutMs=resolveTelemetryHttpTimeoutMs();const requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)};const clientRequest=request(url,requestOptions,response=>{response.once("error",reject);response.once("end",()=>resolve(response.statusCode));response.resume()});clientRequest.once("error",reject);clientRequest.end(body)})}function normalizePmVersion(value){const trimmed=typeof value==="string"?value.trim():"";return trimmed.length>0?trimmed:"0.0.0"}function normalizeTelemetryErrorCode(value){const normalized=value?.trim();return normalized&&normalized.length>0?normalized:void 0}function normalizeTelemetryExitCode(exitCode,ok){if(Number.isFinite(exitCode)){return Math.max(0,Math.trunc(exitCode))}return ok?0:1}function normalizeTelemetryErrorCategory(params){if(params.ok){return void 0}if(typeof params.errorCategory==="string"&&params.errorCategory.trim().length>0){return params.errorCategory}if(typeof params.errorCode==="string"&&params.errorCode.trim().length>0){return resolveTelemetryErrorCategory(params.errorCode)}return"unknown"}function resolveTelemetrySourceContext(globalOptions){const override=(process.env[PM_TELEMETRY_SOURCE_CONTEXT_ENV]??"").trim().toLowerCase();if(PM_TELEMETRY_SOURCE_CONTEXT_SET.has(override)){return{source_context:override,source_context_source:"env_override"}}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return{source_context:"test",source_context_source:"inferred"}}const nonTty=process.stdin.isTTY!==true||process.stdout.isTTY!==true;const ci=parseBooleanTrueLike(process.env.CI);const scriptLikeMode=globalOptions.json===true||globalOptions.quiet===true;if(nonTty||ci||scriptLikeMode){return{source_context:"automation",source_context_source:"inferred"}}return{source_context:"user",source_context_source:"inferred"}}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim();const agent=detectAgentIdentity({env:process.env,argv:process.argv});const hasAgentContext=agent.harness!==void 0||agent.model!==void 0;if(captureLevel==="minimal"){return{has_author_context:author.length>0,has_agent_context:hasAgentContext}}return{...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value===null||value===void 0){return value}if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1))}if(typeof value==="object"){const record=value;const normalized={};const sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys){normalized[key]=normalizeForHash(record[key],depth+1)}return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage==="string"?errorMessage:"","redacted");const normalizedCode=typeof errorCode2==="string"&&errorCode2.length>0?errorCode2:"unknown_error";const fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function telemetryDisabledByEnvironment(){return PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_TELEMETRY_DISABLED_ENV]??"").trim().toLowerCase())||PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_NO_TELEMETRY_ENV]??"").trim().toLowerCase())}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase())){return null}const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0){try{return new URL(directEndpoint).toString()}catch{return null}}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0){return null}try{const url=new URL(baseEndpoint);const normalizedPath=url.pathname.replace(/\/+$/,"");if(!normalizedPath.endsWith("/v1/traces")){url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`}return url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso);const epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs){if(typeof activeCommand.otel_traces_endpoint!=="string"||activeCommand.otel_traces_endpoint.trim().length===0||typeof activeCommand.otel_trace_id!=="string"||activeCommand.otel_trace_id.length===0||typeof activeCommand.otel_span_id!=="string"||activeCommand.otel_span_id.length===0){return null}const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim());const serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli";const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code);const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs)];if(typeof normalizedErrorCode==="string"){attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode))}if(typeof normalizedErrorCategory==="string"){attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory))}if(typeof outcome.error==="string"&&outcome.error.trim().length>0){attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)))}const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error==="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint:activeCommand.otel_traces_endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result===null||result===void 0){return{type:"nullish"}}if(typeof result==="string"){return{type:"string",value:sanitizeString(result,captureLevel)}}if(typeof result==="number"||typeof result==="boolean"){return{type:typeof result,value:result}}if(Array.isArray(result)){return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))}}if(typeof result==="object"){const record=result;const keys=Object.keys(record).sort((left,right)=>left.localeCompare(right));const sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);if(sanitizedValue===void 0)continue;const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize;sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params;const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const hashedArgs=hashCommandArgs(installationId,context.args);const commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`);const commandOptionsDigest=hashTelemetryValue(installationId,context.options);const globalOptionsDigest=hashTelemetryValue(installationId,context.global);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}}return{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params;const errorFingerprint=outcome.ok===false?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0;const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params;const attemptedArgHashes=hashCommandArgs(installationId,args);const attemptedCommandDigest=hashWithInstallationId(installationId,command);const attemptedOptionsDigest=hashTelemetryValue(installationId,options);const errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);let changed=false;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();changed=true}if(changed){await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days))}}async function enqueueTelemetryEvent(globalPmRoot,event){const queued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0};let serialized=JSON.stringify(queued);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:true,reason:"payload_size_exceeded",original_bytes:serialized.length}}};const trimmedQueued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0};serialized=JSON.stringify(trimmedQueued)}await withQueueMutation(async()=>{await appendLineAtomic(queuePath(globalPmRoot),serialized)})}function parseQueueLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&parsed.event&&typeof parsed.event==="object"&&typeof parsed.attempts==="number"&&(parsed.client_schema_version===void 0||typeof parsed.client_schema_version==="number"&&Number.isFinite(parsed.client_schema_version))){entries.push(parsed)}}catch{}}return entries}function nextRetryIso(attempts){const delay=Math.min(TELEMETRY_RETRY_BASE_DELAY_MS*2**Math.max(attempts-1,0),TELEMETRY_MAX_RETRY_DELAY_MS);return new Date(Date.now()+delay).toISOString()}function isDueForRetryAt(nextAttemptAfter){if(typeof nextAttemptAfter!=="string"||nextAttemptAfter.trim().length===0){return true}const dueAtMs=Date.parse(nextAttemptAfter);if(Number.isNaN(dueAtMs)){return true}return dueAtMs<=Date.now()}function isDueForRetry(entry){return isDueForRetryAt(entry.next_attempt_after)}function retentionCutoffMs(retentionDays){const normalizedDays=Number.isFinite(retentionDays)?Math.max(1,Math.trunc(retentionDays)):1;return Date.now()-normalizedDays*MILLISECONDS_PER_DAY}function isExpiredQueueEntry(entry,cutoffMs){const occurredAt=entry.event?.occurred_at;if(typeof occurredAt!=="string"||occurredAt.trim().length===0){return false}const occurredAtMs=Date.parse(occurredAt);if(Number.isNaN(occurredAtMs)){return false}return occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const serializedSize=JSON.stringify(entry).length;const oversized=serializedSize>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredQueueEntry(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}return{entries:retained,prunedCount}}async function rewriteQueue(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
3
3
  `:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(queuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}function isRetryableQueueRewriteError(error){if(typeof error!=="object"||error===null||!("code"in error)){return false}const code=error.code;return code==="EACCES"||code==="EBUSY"||code==="EPERM"}function sleep(milliseconds){return new Promise(resolve=>{setTimeout(resolve,milliseconds)})}async function enqueuePendingOtelSpan(globalPmRoot,request){const pending={id:crypto.randomUUID(),endpoint:request.endpoint,payload:request.payload,enqueued_at:nowIso(),attempts:0};const serialized=JSON.stringify(pending);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){return}await withQueueMutation(async()=>{await appendLineAtomic(otelSpansQueuePath(globalPmRoot),serialized)})}function backfillPendingOtelSpanId(entry){const material=JSON.stringify([entry.endpoint,entry.enqueued_at,entry.payload]);return crypto.createHash("sha256").update(material).digest("hex").slice(0,32)}function parsePendingOtelSpanLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&typeof parsed.endpoint==="string"&&parsed.endpoint.trim().length>0&&"payload"in parsed&&typeof parsed.attempts==="number"&&Number.isFinite(parsed.attempts)){if(typeof parsed.id!=="string"||parsed.id.length===0){parsed.id=backfillPendingOtelSpanId(parsed)}entries.push(parsed)}}catch{}}return entries}function isExpiredPendingOtelSpan(entry,cutoffMs){if(typeof entry.enqueued_at!=="string"||entry.enqueued_at.trim().length===0){return false}const enqueuedAtMs=Date.parse(entry.enqueued_at);if(Number.isNaN(enqueuedAtMs)){return false}return enqueuedAtMs<cutoffMs}function prunePendingOtelSpans(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const oversized=JSON.stringify(entry).length>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredPendingOtelSpan(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}if(retained.length>TELEMETRY_OTEL_SPANS_MAX_PENDING){const overflow=retained.length-TELEMETRY_OTEL_SPANS_MAX_PENDING;prunedCount+=overflow;return{entries:retained.slice(overflow),prunedCount}}return{entries:retained,prunedCount}}async function rewritePendingOtelSpans(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
4
4
  `:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(otelSpansQueuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}async function reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates){return withQueueMutation(async()=>{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));const current=raw===null?[]:parsePendingOtelSpanLines(raw);const reconciled=[];for(const entry of current){if(succeededIds.has(entry.id)){continue}const failure=failedUpdates.get(entry.id);reconciled.push(failure?{...entry,attempts:failure.attempts,next_attempt_after:failure.next_attempt_after}:entry)}const{entries:retained}=prunePendingOtelSpans(reconciled,retentionDays);await rewritePendingOtelSpans(globalPmRoot,retained);return retained.length})}async function flushPendingOtelSpans(globalPmRoot,retentionDays){const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{pending_otel_spans:0});return}const entries=parsePendingOtelSpanLines(raw);const{entries:retained,prunedCount}=prunePendingOtelSpans(entries,retentionDays);const due=retained.filter(entry=>isDueForRetryAt(entry.next_attempt_after)).slice(0,TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE);if(due.length===0){const remaining2=prunedCount>0?await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,new Set,new Map):retained.length;await writeRuntimeState(globalPmRoot,{pending_otel_spans:remaining2});return}const attemptTime=nowIso();const succeededIds=new Set;const failedUpdates=new Map;let succeededCount=0;let lastError;await Promise.all(due.map(async span=>{try{const status=await postTelemetryJson(span.endpoint,{"content-type":"application/json"},JSON.stringify(span.payload));if(status<200||status>=300){throw new Error(`local_otel_export_http_${status}`)}succeededIds.add(span.id);succeededCount+=1}catch(error){lastError=error instanceof Error?sanitizeString(error.message,"redacted"):"local_otel_export_failed";const nextAttempts=span.attempts+1;failedUpdates.set(span.id,{attempts:nextAttempts,next_attempt_after:nextRetryIso(nextAttempts)})}}));const remaining=await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates);const statePatch={pending_otel_spans:remaining,last_otel_attempt_at:attemptTime};if(succeededCount>0){statePatch.last_otel_success_at=attemptTime}if(lastError!==void 0){statePatch.last_otel_failure_at=attemptTime;statePatch.last_otel_failure_error=lastError}else if(remaining===0){statePatch.last_otel_failure_at=void 0;statePatch.last_otel_failure_error=void 0}await writeRuntimeState(globalPmRoot,statePatch)}async function flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays){try{await flushQueue(globalPmRoot,endpoint,retentionDays)}catch{}try{await flushPendingOtelSpans(globalPmRoot,retentionDays)}catch{}}async function cleanupTelemetryQueueTempOrphans(globalPmRoot,maxAgeMs=TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS){try{const dirPath=telemetryRuntimeDirectory(globalPmRoot);const entries=await readdir(dirPath,{withFileTypes:true});const cutoffMs=Date.now()-Math.max(0,maxAgeMs);await Promise.all(entries.filter(entry=>entry.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(entry.name)).map(async entry=>{const candidate=path.join(dirPath,entry.name);const candidateStats=await stat(candidate);if(candidateStats.mtimeMs<cutoffMs){await rm(candidate,{force:true})}}))}catch{}}async function withQueueMutation(operation){const run=_queueMutationPromise.catch(()=>{}).then(operation);_queueMutationPromise=run.catch(()=>{});return run}async function readCurrentQueueEntries(globalPmRoot){const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){return[]}return parseQueueLines(raw)}async function removeFlushedEntriesFromCurrentQueue(globalPmRoot,flushedIds,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const remaining=retainedEntries.filter(entry=>!flushedIds.has(entry.event.event_id));await rewriteQueue(globalPmRoot,remaining);return remaining})}async function markFailedEntriesInCurrentQueue(globalPmRoot,failedIds,attemptTime,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const retried=retainedEntries.map(entry=>{if(!failedIds.has(entry.event.event_id)){return entry}const attempts=entry.attempts+1;return{...entry,attempts,last_attempt_at:attemptTime,next_attempt_after:nextRetryIso(attempts)}});await rewriteQueue(globalPmRoot,retried);return retried})}async function flushQueue(globalPmRoot,endpoint,retentionDays){await cleanupTelemetryQueueTempOrphans(globalPmRoot);const normalizedEndpoint=endpoint.trim();if(normalizedEndpoint.length===0){return}const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const queueEntries=parseQueueLines(raw);if(queueEntries.length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const{entries:retainedEntries,prunedCount}=pruneExpiredQueueEntries(queueEntries,retentionDays);if(retainedEntries.length===0){await rewriteQueue(globalPmRoot,[]);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){if(prunedCount>0){await rewriteQueue(globalPmRoot,retainedEntries)}await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retainedEntries.length});return}const dueIds=new Set(dueEntries.map(entry=>entry.event.event_id));const attemptTime=nowIso();const requestHeaders={"content-type":"application/json"};const ingestKey=process.env.PM_TELEMETRY_INGEST_KEY?.trim();if(ingestKey){requestHeaders["x-pm-telemetry-key"]=ingestKey}try{const status=await postTelemetryJson(normalizedEndpoint,requestHeaders,JSON.stringify({schema_version:TELEMETRY_SCHEMA_VERSION,events:dueEntries.map(entry=>entry.event)}));if(status<200||status>=300){throw new Error(`telemetry_flush_http_${status}`)}}catch(error){const retried=await markFailedEntriesInCurrentQueue(globalPmRoot,dueIds,attemptTime,retentionDays);const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retried.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage});return}try{const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,dueIds,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length,last_attempted_flush_at:attemptTime,last_successful_flush_at:attemptTime,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(error){const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();const currentEntries=await readCurrentQueueEntries(globalPmRoot).catch(()=>retainedEntries);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:currentEntries.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage})}}async function acquireTelemetryFlushLock(globalPmRoot){const lockPath=flushLockPath(globalPmRoot);await mkdir(path.dirname(lockPath),{recursive:true});try{await mkdir(lockPath);return true}catch(error){if(typeof error!=="object"||error===null||!("code"in error)||error.code!=="EEXIST"){throw error}}try{const lockStats=await stat(lockPath);if(Date.now()-lockStats.mtimeMs<TELEMETRY_FLUSH_LOCK_STALE_MS){return false}await rm(lockPath,{recursive:true,force:true});await mkdir(lockPath);return true}catch{return false}}function isFreshDirectoryLock(lockPath,staleMs){try{return Date.now()-statSync(lockPath).mtimeMs<staleMs}catch{return false}}function removeDirectoryLockBestEffort(lockPath){try{rmSync(lockPath,{recursive:true,force:true})}catch{}}function errorCode(error){if(typeof error!=="object"||error===null||!("code"in error)){return void 0}const code=error.code;return typeof code==="string"?code:void 0}function createDirectoryLock(lockPath){try{mkdirSync(lockPath);return true}catch(error){const code=errorCode(error);if(code==="EEXIST"){return false}if(!isFileMissingError(error)){return false}}try{mkdirSync(path.dirname(lockPath),{recursive:true});mkdirSync(lockPath);return true}catch{return false}}function acquireTelemetryFlushSpawnGate(globalPmRoot){if(isFreshDirectoryLock(flushLockPath(globalPmRoot),TELEMETRY_FLUSH_LOCK_STALE_MS)){return false}const lockPath=flushSpawnLockPath(globalPmRoot);try{if(Date.now()-statSync(lockPath).mtimeMs<TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS){return false}removeDirectoryLockBestEffort(lockPath)}catch(error){if(!isFileMissingError(error)){return false}}return createDirectoryLock(lockPath)}function releaseTelemetryFlushSpawnGate(globalPmRoot){removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot))}const _testOnly={acquireTelemetryFlushSpawnGate,acquireTelemetryFlushLock,buildAuthorContextPayloadFields,buildCommandErrorPayload,buildCommandFinishPayload,buildCommandStartPayload,buildOtelSpanRequest,createDirectoryLock,enqueuePendingOtelSpan,enqueueTelemetryEvent,errorCode,flushPendingOtelSpans,flushQueue,flushQueueWithProcessLock,flushTelemetryArtifacts,hashTelemetryErrorFingerprint,hashTelemetryValue,isEmailDomainCharacter,isEmailLocalCharacter,isExpiredPendingOtelSpan,isExpiredQueueEntry,isFreshDirectoryLock,isDueForRetry,isDueForRetryAt,isRetryableQueueRewriteError,looksLikeEmailToken,otelSpansQueuePath,parseBooleanTrueLike,postTelemetryJson,parsePendingOtelSpanLines,prunePendingOtelSpans,reconcilePendingOtelSpansAfterFlush,retentionCutoffMs,resolveOtelTracesEndpoint,resolveTelemetryHttpTimeoutMs,rewritePendingOtelSpans,normalizeForHash,normalizeCaptureLevel,normalizePmVersion,normalizeTelemetryErrorCategory,normalizeTelemetryErrorCode,normalizeTelemetryExitCode,parseQueueLines,pruneExpiredQueueEntries,readRuntimeState,readCurrentQueueEntries,releaseTelemetryFlushSpawnGate,removeFlushedEntriesFromCurrentQueue,removeDirectoryLockBestEffort,resolveTelemetrySourceContext,rewriteQueue,sanitizeCommandArgs,sanitizeStringMax,sanitizeStringRedacted,sanitizeValue,scheduleTelemetryFlush,shouldFlushInline,sleep,summarizeResult,telemetryFlushRunnerPath,withQueueMutation,flushLockPath,flushSpawnLockPath,runtimeStatePath,writeRuntimeState};async function flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays){const acquired=await acquireTelemetryFlushLock(globalPmRoot);releaseTelemetryFlushSpawnGate(globalPmRoot);if(!acquired){return}try{await flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)}finally{try{await rm(flushLockPath(globalPmRoot),{recursive:true,force:true})}catch{}}}function scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays){if(shouldFlushInline()){const previousFlush=_lastFlushPromise;const nextFlush=flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays);_lastFlushPromise=Promise.allSettled([previousFlush,nextFlush]).then(()=>{});return}try{const acquiredSpawnGate=acquireTelemetryFlushSpawnGate(globalPmRoot);if(!acquiredSpawnGate){return}const child=spawn(process.execPath,[telemetryFlushRunnerPath()],{detached:true,stdio:"ignore",cwd:os.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:globalPmRoot,[PM_TELEMETRY_FLUSH_CHILD_ENV]:"1"}});child.on("error",()=>{releaseTelemetryFlushSpawnGate(globalPmRoot)});child.unref()}catch{releaseTelemetryFlushSpawnGate(globalPmRoot)}}async function flushTelemetryQueueNow(globalPmRoot=resolveGlobalPmRoot(process.cwd())){if(telemetryDisabledByEnvironment()){return}try{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const{endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);await flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays)}catch{}}async function startTelemetryCommand(context){if(telemetryDisabledByEnvironment()){return null}if(context.command==="telemetry"&&context.args.some(token=>token.trim().toLowerCase()==="clear")){return null}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return null}const captureLevel=normalizeCaptureLevel(settings.telemetry.capture_level);const{installationId,endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const otelTracesEndpoint=resolveOtelTracesEndpoint();const occurredAt=nowIso();const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_start",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:context.command,payload:buildCommandStartPayload({captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId})};await enqueueTelemetryEvent(globalPmRoot,event);scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays);const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);return{started_at:occurredAt,started_at_ms:Date.now(),command:context.command,command_taxonomy:commandTaxonomy,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,installation_id:installationId,pm_root_hash:pmRootHash,cwd_hash:cwdHash,endpoint,retention_days:retentionDays,global_pm_root:globalPmRoot,capture_level:captureLevel,otel_traces_endpoint:otelTracesEndpoint??void 0,otel_trace_id:otelTracesEndpoint?crypto.randomBytes(16).toString("hex"):void 0,otel_span_id:otelTracesEndpoint?crypto.randomBytes(8).toString("hex"):void 0}}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!activeCommand){return}try{const finishedAt=nowIso();const durationMs=Math.max(0,Date.now()-activeCommand.started_at_ms);const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:outcome.ok,errorCode:outcome.error_code,errorMessage:outcome.error,exitCode:outcome.exit_code}));const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const commandResolution=outcome.command_resolution??deriveTelemetryCommandResolution({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=outcome.resolution_stage??"execute";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_finish",occurred_at:finishedAt,installation_id:activeCommand.installation_id,session_id:PROCESS_SESSION_ID,command:activeCommand.command,payload:buildCommandFinishPayload({captureLevel:activeCommand.capture_level,pmVersion:activeCommand.pm_version,sourceContext:{source_context:activeCommand.source_context,source_context_source:activeCommand.source_context_source},outcome,durationMs,startedAt:activeCommand.started_at,command:activeCommand.command,installationId:activeCommand.installation_id,commandTaxonomy:activeCommand.command_taxonomy,exitCode:normalizedExitCode,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,commandResolution,resolutionStage})};await enqueueTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs);if(otelRequest){await enqueuePendingOtelSpan(activeCommand.global_pm_root,otelRequest)}scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(telemetryDisabledByEnvironment()){return}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const captureLevel=normalizeCaptureLevel(settings.telemetry.capture_level);const{installationId,endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const occurredAt=nowIso();const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:false,errorCode:context.error_code,errorMessage:context.error_message,exitCode:context.exit_code}));const normalizedErrorCategory=context.error_category??resolveTelemetryErrorCategory(normalizedErrorCode);const normalizedExitCode=normalizeTelemetryExitCode(context.exit_code,false);const normalizedCommand=context.command.trim().length>0?context.command:"<unknown>";const commandTaxonomy=deriveTelemetryCommandTaxonomy(normalizedCommand);const commandResolution=context.command_resolution??deriveTelemetryCommandResolution({ok:false,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=context.resolution_stage??"unknown";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_error",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:sanitizeString(normalizedCommand,"redacted"),payload:buildCommandErrorPayload({captureLevel,pmVersion,sourceContext,command:normalizedCommand,commandTaxonomy,commandResolution,resolutionStage,args:context.args,options:context.options,pmRootHash,cwdHash,installationId,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,exitCode:normalizedExitCode,errorMessage:context.error_message})};await enqueueTelemetryEvent(globalPmRoot,event);scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush};
5
5
  //# sourceMappingURL=runtime.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4d9c6abe-2ec0-5f25-be99-d70f7b43814c")}catch(e2){}})();import{renderPmCommand}from"../command-line.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";function normalizeMissingFlag(label){const match=label.trim().match(/--[a-z0-9][a-z0-9_-]*/i);return match?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!Array.isArray(invocationArgv)||invocationArgv.length===0){return void 0}return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return void 0;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));if(!contract)return"<value>";if(contract.value_type==="boolean"){return null}return`<${contract.value_name??"value"}>`}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv];const 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);const recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption);insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{renderMissingOptionRetry,resolveMissingOptionPlaceholder,resolveRecoveryCommandName};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4f7274c6-547e-5590-b7c9-a4d6418bf860")}catch(e2){}})();import{renderPmCommand}from"../command-line.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";function normalizeMissingFlag(label){const match=label.trim().match(/--[a-z0-9][a-z0-9_-]*/i);return match?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!Array.isArray(invocationArgv)||invocationArgv.length===0){return void 0}return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return void 0;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));if(!contract)return"<value>";if(contract.value_type==="boolean"){return null}return`<${contract.value_name??"value"}>`}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv];const 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);const recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption);insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{renderMissingOptionRetry,resolveMissingOptionPlaceholder,resolveRecoveryCommandName};
2
2
  //# sourceMappingURL=command-recovery.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7f321c80-d72d-5c89-9686-4d09d2be0d55")}catch(e2){}})();import{findBootstrapCommandTokenIndex}from"../cli-contracts/bootstrap-command-scanner.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts.js";const ITEM_ID_ALIAS_COMMANDS=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]);const ITEM_ID_ALIAS_SUBCOMMANDS=new Map([["files","discover"],["item","complete"]]);const TRAILING_POSITIONAL_COUNTS=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function supportsItemIdAlias(commandName){const normalized=resolvePmCommandOperation(commandName?.trim().toLowerCase()??"");return ITEM_ID_ALIAS_COMMANDS.has(normalized)||ITEM_ID_ALIAS_SUBCOMMANDS.has(normalized)}function resolveNamespacedItemAddressIndex(argv,commandIndex,commandName){const fallback=ITEM_ID_ALIAS_COMMANDS.has(commandName)?commandIndex+1:void 0;const leafOffset=findBootstrapCommandTokenIndex(argv.slice(commandIndex+1));if(leafOffset===void 0)return fallback;const leafIndex=commandIndex+1+leafOffset;const candidate=`${commandName} ${argv[leafIndex]}`;const operation=resolvePmCommandOperation(candidate);if(operation===candidate)return fallback;return supportsItemIdAlias(operation)?leafIndex+1:void 0}function resolveItemAddressIndex(argv,commandIndex,commandName){if(["history","context","ctx","update","close"].includes(commandName)){return resolveNamespacedItemAddressIndex(argv,commandIndex,commandName)}const declaredSubcommand=ITEM_ID_ALIAS_SUBCOMMANDS.get(commandName);if(declaredSubcommand===void 0)return commandIndex+1;const usesDeclaredSubcommand=argv[commandIndex+1]?.toLowerCase()===declaredSubcommand;if(!usesDeclaredSubcommand&&!ITEM_ID_ALIAS_COMMANDS.has(commandName)){return void 0}return commandIndex+(usesDeclaredSubcommand?2:1)}function buildFlagContractMap(commandPath){const contractsByFlag=new Map;for(const contract of resolveSubcommandFlagContractsForCommand(commandPath)){for(const flag of[contract.flag,contract.short,...contract.aliases??[]]){if(flag)contractsByFlag.set(flag,contract)}}return contractsByFlag}function collectNamedItemIds(argv){const namedIds=[];for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){namedIds.push({index,consumed:2,value:argv[index+1]});index+=1}else if(token.startsWith("--id=")){namedIds.push({index,consumed:1,value:token.slice("--id=".length)})}}return namedIds}function consumesSeparateFlagValue(token,nextToken,contractsByFlag){const separatorIndex=token.indexOf("=");if(separatorIndex>=0||nextToken===void 0||nextToken.startsWith("-")){return false}const contract=contractsByFlag.get(token);return contract!==void 0&&contract.value_type!=="boolean"}function hasPositionalItemId(argv,addressIndex,commandPath,namedIndex,contractsByFlag){let trailingPositionals=0;for(let index=addressIndex;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){index+=1;continue}if(token.startsWith("--id="))continue;if(!token.startsWith("-")){if(index<namedIndex)return true;trailingPositionals+=1;continue}if(consumesSeparateFlagValue(token,argv[index+1],contractsByFlag)){index+=1}}return trailingPositionals>(TRAILING_POSITIONAL_COUNTS.get(resolvePmCommandOperation(commandPath))??0)}function normalizeItemAddressInvocation(argv){const commandIndex=findBootstrapCommandTokenIndex(argv);const commandName=commandIndex===void 0?void 0:argv[commandIndex]?.toLowerCase();if(commandName!=="context"&&commandName!=="ctx"&&!supportsItemIdAlias(commandName)){return{argv:[...argv],changed:false,conflict:false}}const addressIndex=resolveItemAddressIndex(argv,commandIndex,commandName);if(addressIndex===void 0){return{argv:[...argv],changed:false,conflict:false}}const commandPath=addressIndex>commandIndex+1?`${commandName} ${argv[addressIndex-1]}`:commandName;const contractsByFlag=buildFlagContractMap(commandPath);const namedIds=collectNamedItemIds(argv);const named=namedIds[0];if(!named||!named.value?.trim()){return{argv:[...argv],changed:false,conflict:false}}if(namedIds.length>1||hasPositionalItemId(argv,addressIndex,commandPath,named.index,contractsByFlag)){return{argv:[...argv],changed:false,conflict:true,itemId:named.value}}const withoutNamed=[...argv.slice(0,named.index),...argv.slice(named.index+named.consumed)];const normalizedCommandIndex=findBootstrapCommandTokenIndex(withoutNamed);const normalizedAddressIndex=resolveItemAddressIndex(withoutNamed,normalizedCommandIndex,commandName);withoutNamed.splice(normalizedAddressIndex,0,named.value);return{argv:withoutNamed,changed:true,conflict:false,itemId:named.value}}export{normalizeItemAddressInvocation,supportsItemIdAlias};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3fa186e5-1c33-5761-87c5-3ca7b95ab501")}catch(e2){}})();import{findBootstrapCommandTokenIndex}from"../cli-contracts/bootstrap-command-scanner.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";const ITEM_ID_ALIAS_COMMANDS=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]);const ITEM_ID_ALIAS_SUBCOMMANDS=new Map([["files","discover"],["item","complete"]]);const TRAILING_POSITIONAL_COUNTS=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function supportsItemIdAlias(commandName){const normalized=resolvePmCommandOperation(commandName?.trim().toLowerCase()??"");return ITEM_ID_ALIAS_COMMANDS.has(normalized)||ITEM_ID_ALIAS_SUBCOMMANDS.has(normalized)}function resolveNamespacedItemAddressIndex(argv,commandIndex,commandName){const fallback=ITEM_ID_ALIAS_COMMANDS.has(commandName)?commandIndex+1:void 0;const leafOffset=findBootstrapCommandTokenIndex(argv.slice(commandIndex+1));if(leafOffset===void 0)return fallback;const leafIndex=commandIndex+1+leafOffset;const candidate=`${commandName} ${argv[leafIndex]}`;const operation=resolvePmCommandOperation(candidate);if(operation===candidate)return commandName==="item"&&argv[leafIndex]==="complete"?leafIndex+1:fallback;return supportsItemIdAlias(operation)?leafIndex+1:void 0}function resolveItemAddressIndex(argv,commandIndex,commandName){if(["history","context","ctx","update","close","item"].includes(commandName)){return resolveNamespacedItemAddressIndex(argv,commandIndex,commandName)}const declaredSubcommand=ITEM_ID_ALIAS_SUBCOMMANDS.get(commandName);if(declaredSubcommand===void 0)return commandIndex+1;const usesDeclaredSubcommand=argv[commandIndex+1]?.toLowerCase()===declaredSubcommand;return commandIndex+(usesDeclaredSubcommand?2:1)}function buildFlagContractMap(commandPath){const contractsByFlag=new Map;for(const contract of resolveSubcommandFlagContractsForCommand(commandPath)){for(const flag of[contract.flag,contract.short,...contract.aliases??[]]){if(flag)contractsByFlag.set(flag,contract)}}return contractsByFlag}function collectNamedItemIds(argv){const namedIds=[];for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){namedIds.push({index,consumed:2,value:argv[index+1]});index+=1}else if(token.startsWith("--id=")){namedIds.push({index,consumed:1,value:token.slice("--id=".length)})}}return namedIds}function consumesSeparateFlagValue(token,nextToken,contractsByFlag){const separatorIndex=token.indexOf("=");if(separatorIndex>=0||nextToken===void 0||nextToken.startsWith("-")){return false}const contract=contractsByFlag.get(token);return contract!==void 0&&contract.value_type!=="boolean"}function hasPositionalItemId(argv,addressIndex,commandPath,namedIndex,contractsByFlag){let trailingPositionals=0;for(let index=addressIndex;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){index+=1;continue}if(token.startsWith("--id="))continue;if(!token.startsWith("-")){if(index<namedIndex)return true;trailingPositionals+=1;continue}if(consumesSeparateFlagValue(token,argv[index+1],contractsByFlag)){index+=1}}return trailingPositionals>(TRAILING_POSITIONAL_COUNTS.get(resolvePmCommandOperation(commandPath))??0)}function normalizeItemAddressInvocation(argv){const commandIndex=findBootstrapCommandTokenIndex(argv);const commandName=commandIndex===void 0?void 0:argv[commandIndex]?.toLowerCase();if(commandName!=="context"&&commandName!=="ctx"&&!supportsItemIdAlias(commandName)){return{argv:[...argv],changed:false,conflict:false}}const addressIndex=resolveItemAddressIndex(argv,commandIndex,commandName);if(addressIndex===void 0){return{argv:[...argv],changed:false,conflict:false}}const commandPath=addressIndex>commandIndex+1?`${commandName} ${argv[addressIndex-1]}`:commandName;const contractsByFlag=buildFlagContractMap(commandPath);const namedIds=collectNamedItemIds(argv);const named=namedIds[0];if(!named||!named.value?.trim()){return{argv:[...argv],changed:false,conflict:false}}if(namedIds.length>1||hasPositionalItemId(argv,addressIndex,commandPath,named.index,contractsByFlag)){return{argv:[...argv],changed:false,conflict:true,itemId:named.value}}const withoutNamed=[...argv.slice(0,named.index),...argv.slice(named.index+named.consumed)];const normalizedCommandIndex=findBootstrapCommandTokenIndex(withoutNamed);const normalizedAddressIndex=resolveItemAddressIndex(withoutNamed,normalizedCommandIndex,commandName);withoutNamed.splice(normalizedAddressIndex,0,named.value);return{argv:withoutNamed,changed:true,conflict:false,itemId:named.value}}export{normalizeItemAddressInvocation,supportsItemIdAlias};
2
2
  //# sourceMappingURL=item-addressing.js.map