@unbrained/pm-cli 2026.9.28 → 2026.9.30

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 (118) hide show
  1. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +7 -6
  2. package/.agents/skills/pm-user/references/BACKLOG_SHAPING.md +1 -1
  3. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +26 -3
  4. package/.claude-plugin/marketplace.json +2 -2
  5. package/CHANGELOG.md +26 -0
  6. package/dist/cli/error-guidance.js +1 -1
  7. package/dist/cli/help-json-payload.js +2 -2
  8. package/dist/cli/main.js +2 -2
  9. package/dist/cli/runtime/invocation-options.d.ts +3 -1
  10. package/dist/cli/runtime/invocation-options.js +1 -1
  11. package/dist/cli-bundle/bundle-manifest.json +152 -152
  12. package/dist/cli-bundle/chunks/{chunk-UT7GRGHY.js → chunk-6XTJLOKW.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-VMJLM7P2.js → chunk-6YEET7XI.js} +22 -22
  14. package/dist/cli-bundle/chunks/{chunk-NEUIVBFO.js → chunk-A6NDNRCK.js} +3 -3
  15. package/dist/cli-bundle/chunks/{chunk-GLH2LNRH.js → chunk-BNAT4EYR.js} +9 -9
  16. package/dist/cli-bundle/chunks/{chunk-CPOWTIIS.js → chunk-BTCE36JS.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-35DME35A.js → chunk-BX4LEJX4.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-A2G5OG6W.js → chunk-EGAIIWI3.js} +2 -2
  19. package/dist/cli-bundle/chunks/chunk-FYTXVVZG.js +2 -0
  20. package/dist/cli-bundle/chunks/{chunk-ZFHJP7YD.js → chunk-O23CQ5T4.js} +31 -29
  21. package/dist/cli-bundle/chunks/{chunk-NBDB3SRC.js → chunk-UIAH7UFK.js} +67 -67
  22. package/dist/cli-bundle/chunks/{chunk-OYCCWPBM.js → chunk-USTAFHIM.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-PR4UAMI5.js → chunk-XRN3JYNN.js} +85 -85
  24. package/dist/cli-bundle/chunks/{chunk-PLNNUAFZ.js → chunk-YM342ELM.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-list-query-N6RP6PSP.js → register-list-query-SYNBVMNG.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-mutation-CY7JGQE6.js → register-mutation-4GSUK23D.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-operations-53HAD3QP.js → register-operations-7FCJUC4Z.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-setup-NVX6374E.js → register-setup-YTWW2KL5.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-BRLXKRI2.js → chunk-3CAZ7Z4R.js} +4 -4
  30. package/dist/cli-bundle/focused-chunks/{chunk-K7GSZ7YZ.js → chunk-4AORVUT4.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-AZA4AEOR.js → chunk-AKB3JN57.js} +33 -33
  32. package/dist/cli-bundle/focused-chunks/{chunk-OVVCXTIE.js → chunk-EFD4ATS7.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-IJXZQE3D.js → chunk-EVMH4SKN.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-IWLMQLBO.js → chunk-IDB6E3ZV.js} +28 -28
  35. package/dist/cli-bundle/focused-chunks/{chunk-YZB7IPR6.js → chunk-IQBFYQF2.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-BGWF6CMP.js → chunk-KZULQIAG.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-ZMQTIS3L.js → chunk-MOUCTR72.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-6IVQPNYN.js → chunk-OMBDUJWZ.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-DTLRXY77.js → chunk-RIJQQOEZ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-A5O3VYWV.js → chunk-T4PZJQG4.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-V7OPZRL6.js → chunk-UPOMLSW7.js} +14 -14
  42. package/dist/cli-bundle/focused-chunks/{chunk-5KJXX2TZ.js → chunk-XB5Q2P7Z.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-ONDNR3VU.js → chunk-XUCXRZZZ.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-Y5Z3XNGY.js → chunk-ZJ3CLTV4.js} +2 -2
  45. package/dist/cli-bundle/main.js +22 -22
  46. package/dist/cli-bundle/sdk-authoring.js +1 -1
  47. package/dist/cli-bundle/sdk-contracts.js +1 -1
  48. package/dist/cli-bundle/sdk-core.js +22 -21
  49. package/dist/cli-bundle/sdk-governance.js +1 -1
  50. package/dist/cli-bundle/sdk-graph.js +1 -1
  51. package/dist/cli-bundle/sdk-merge.js +38 -38
  52. package/dist/cli-bundle/sdk-query.js +1 -1
  53. package/dist/cli-bundle/sdk-runtime.js +1 -1
  54. package/dist/cli-bundle/sdk-testing.js +1 -1
  55. package/dist/cli-bundle/sdk.js +2 -2
  56. package/dist/core/extensions/extension-types.d.ts +13 -0
  57. package/dist/core/extensions/extension-types.js +1 -1
  58. package/dist/core/history/replay.js +1 -1
  59. package/dist/core/history/workspace-history.d.ts +17 -0
  60. package/dist/core/history/workspace-history.js +1 -1
  61. package/dist/core/output/mutation-projection.js +1 -1
  62. package/dist/core/telemetry/runtime.js +2 -2
  63. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  64. package/dist/sdk/extension-command-context.d.ts +1 -7
  65. package/dist/sdk/extension-command-context.js +1 -1
  66. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  67. package/dist/sdk/index.d.ts +1 -0
  68. package/dist/sdk/index.js +1 -1
  69. package/dist/sdk/lifecycle/plan-mutation-receipt.d.ts +53 -0
  70. package/dist/sdk/lifecycle/plan-mutation-receipt.js +2 -0
  71. package/dist/sdk/lifecycle/plan.d.ts +3 -0
  72. package/dist/sdk/lifecycle/plan.js +1 -1
  73. package/dist/sdk/lifecycle/update.d.ts +2 -0
  74. package/dist/sdk/lifecycle/update.js +1 -1
  75. package/dist/sdk/linked-artifacts.js +1 -1
  76. package/dist/sdk/merge/install.js +1 -1
  77. package/dist/sdk/public-surface.json +1 -1
  78. package/dist/sdk/runtime/actions.js +1 -1
  79. package/dist/sdk/runtime-input.d.ts +2 -0
  80. package/dist/sdk/runtime-input.js +1 -1
  81. package/dist/sdk/runtime.js +1 -1
  82. package/dist/sdk/similarity-scoring.js +1 -1
  83. package/dist/sdk/structured-mutations.js +1 -1
  84. package/dist/sdk/telemetry.d.ts +2 -0
  85. package/dist/sdk/telemetry.js +3 -1
  86. package/dist/sdk/testing.js +1 -1
  87. package/docs/CLI_GRAMMAR.md +18 -1
  88. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +270 -0
  89. package/docs/MERGE_SAFETY.md +11 -6
  90. package/docs/README.md +2 -0
  91. package/docs/RELEASE_RELIABILITY.md +26 -4
  92. package/docs/SDK_AUDITED_MUTATIONS.md +52 -0
  93. package/docs/SDK_EVIDENCE_TRACEABILITY.md +34 -0
  94. package/docs/agent-task-token-baseline.json +28 -2
  95. package/docs/agent-task-transcripts.json +137 -14
  96. package/docs/ecosystem-review-2026-09-28.json +3159 -0
  97. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  98. package/marketplace.json +2 -2
  99. package/package.json +1 -1
  100. package/packages/pm-beads/package.json +1 -1
  101. package/packages/pm-calendar/package.json +1 -1
  102. package/packages/pm-command-kit/package.json +1 -1
  103. package/packages/pm-digital-twin/package.json +1 -1
  104. package/packages/pm-governance-audit/package.json +1 -1
  105. package/packages/pm-guide-shell/package.json +1 -1
  106. package/packages/pm-kanban/package.json +1 -1
  107. package/packages/pm-lifecycle-hooks/package.json +1 -1
  108. package/packages/pm-linked-test-adapters/package.json +1 -1
  109. package/packages/pm-search-advanced/package.json +1 -1
  110. package/packages/pm-templates/package.json +1 -1
  111. package/packages/pm-todos/package.json +1 -1
  112. package/packages/pm-vcs/package.json +1 -1
  113. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  114. package/plugins/pm-claude/package.json +2 -2
  115. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  116. package/plugins/pm-codex/package.json +2 -2
  117. package/plugins/pm-codex/plugin.json +1 -1
  118. package/dist/cli-bundle/chunks/chunk-YERBAGQD.js +0 -2
@@ -600,6 +600,19 @@ export interface ExtensionCommandSdk {
600
600
  }): RelationshipEvent[];
601
601
  /** Commit idempotent item and relationship mutations under one durable journal. */
602
602
  commitWorkspaceTransaction(options: Omit<CommitWorkspaceTransactionOptions, "pmRoot">): Promise<WorkspaceTransactionCommitResult>;
603
+ /** Mutate governed project settings under the host's workspace audit lock. */
604
+ mutateWorkspaceSettings(options: {
605
+ /** Stable identity for replay-safe retries of this invocation. */
606
+ operationId: string;
607
+ /** Compute a preview without changing settings or workspace history. */
608
+ dryRun?: boolean;
609
+ /** Derive the complete next settings tree from the locked current tree. */
610
+ mutate: (current: PmSettings) => PmSettings | Promise<PmSettings>;
611
+ }): Promise<{
612
+ changed: boolean;
613
+ dry_run: boolean;
614
+ replayed: boolean;
615
+ }>;
603
616
  }
604
617
  /** Documents the parser override context payload exchanged by command, SDK, and package integrations. */
605
618
  export type ParserOverrideContext = CommandHandlerContext;
@@ -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]="9ddd9ea4-8586-5d3d-9ed8-0bf9da49b9a5")}catch(e2){}})();const KNOWN_EXTENSION_CAPABILITIES=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"];const EXTENSION_CAPABILITY_CONTRACT_VERSION=2;const EXTENSION_CAPABILITY_LEGACY_ALIASES=Object.freeze({migration:"schema",validation:"schema"});const EXTENSION_CAPABILITY_CONTRACT=Object.freeze({version:EXTENSION_CAPABILITY_CONTRACT_VERSION,capabilities:[...KNOWN_EXTENSION_CAPABILITIES],legacy_aliases:{...EXTENSION_CAPABILITY_LEGACY_ALIASES}});const KNOWN_EXTENSION_POLICY_MODES=["off","warn","enforce"];const KNOWN_EXTENSION_TRUST_MODES=["off","warn","enforce"];const KNOWN_EXTENSION_SANDBOX_PROFILES=["none","restricted","strict"];const KNOWN_PM_MAX_VERSION_EXCEEDED_MODES=["block","warn"];const KNOWN_EXTENSION_POLICY_SURFACES=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore","services.assuranceprovider"];const KNOWN_EXTENSION_SERVICE_NAMES=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function createDefaultExtensionGovernancePolicy(){return{mode:"off",trust_mode:"off",require_provenance:false,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]}}export{EXTENSION_CAPABILITY_CONTRACT,EXTENSION_CAPABILITY_CONTRACT_VERSION,EXTENSION_CAPABILITY_LEGACY_ALIASES,KNOWN_EXTENSION_CAPABILITIES,KNOWN_EXTENSION_POLICY_MODES,KNOWN_EXTENSION_POLICY_SURFACES,KNOWN_EXTENSION_SANDBOX_PROFILES,KNOWN_EXTENSION_SERVICE_NAMES,KNOWN_EXTENSION_TRUST_MODES,KNOWN_PM_MAX_VERSION_EXCEEDED_MODES,createDefaultExtensionGovernancePolicy};
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]="e88ce29f-3547-5b51-856f-bb4618ae53b1")}catch(e2){}})();const KNOWN_EXTENSION_CAPABILITIES=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"];const EXTENSION_CAPABILITY_CONTRACT_VERSION=2;const EXTENSION_CAPABILITY_LEGACY_ALIASES=Object.freeze({migration:"schema",validation:"schema"});const EXTENSION_CAPABILITY_CONTRACT=Object.freeze({version:EXTENSION_CAPABILITY_CONTRACT_VERSION,capabilities:[...KNOWN_EXTENSION_CAPABILITIES],legacy_aliases:{...EXTENSION_CAPABILITY_LEGACY_ALIASES}});const KNOWN_EXTENSION_POLICY_MODES=["off","warn","enforce"];const KNOWN_EXTENSION_TRUST_MODES=["off","warn","enforce"];const KNOWN_EXTENSION_SANDBOX_PROFILES=["none","restricted","strict"];const KNOWN_PM_MAX_VERSION_EXCEEDED_MODES=["block","warn"];const KNOWN_EXTENSION_POLICY_SURFACES=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore","services.assuranceprovider"];const KNOWN_EXTENSION_SERVICE_NAMES=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function createDefaultExtensionGovernancePolicy(){return{mode:"off",trust_mode:"off",require_provenance:false,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]}}export{EXTENSION_CAPABILITY_CONTRACT,EXTENSION_CAPABILITY_CONTRACT_VERSION,EXTENSION_CAPABILITY_LEGACY_ALIASES,KNOWN_EXTENSION_CAPABILITIES,KNOWN_EXTENSION_POLICY_MODES,KNOWN_EXTENSION_POLICY_SURFACES,KNOWN_EXTENSION_SANDBOX_PROFILES,KNOWN_EXTENSION_SERVICE_NAMES,KNOWN_EXTENSION_TRUST_MODES,KNOWN_PM_MAX_VERSION_EXCEEDED_MODES,createDefaultExtensionGovernancePolicy};
2
2
  //# sourceMappingURL=extension-types.js.map
@@ -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]="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")}
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]="8c80fb7b-da68-5bb8-a985-7de2d81aabd7")}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,memo){const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm);const memoKey=`${version}:${algorithm}`;const beforeHashes=memo?.before.get(memoKey)??replayHashVerificationCandidates(before,version,algorithm);const afterHashes=replayHashVerificationCandidates(after,version,algorithm);memo?.after.set(memoKey,afterHashes);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,true).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 matchReplayEpochCandidates(before,after,candidates,entry,memo){const matches=[];for(const version of candidates){const match=matchReplayHashCandidates(before,after,version,entry,memo);matches.push({version,match});if(match.pairIndex>=0)break}return matches}function verifyHistoryChainWithVersion(entries){let replay=cloneEmptyReplayDocument();let beforeHashMemo=new Map;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;beforeHashMemo=new Map;detectedVersion=void 0;authoritativeExplicitVersion=void 0;continue}const candidates=historyEntryHashCandidates(explicitVersion,authoritativeExplicitVersion);const memo={before:beforeHashMemo,after:new Map};const candidateMatches=matchReplayEpochCandidates(replay,input.document,candidates,entry,memo);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;beforeHashMemo=memo.after;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
@@ -36,6 +36,8 @@ export interface WorkspaceJsonWriteOptions {
36
36
  raw: string;
37
37
  /** Stable operation name. */
38
38
  op: string;
39
+ /** Optional operation identity that prevents replaying a completed write. */
40
+ idempotencyKey?: string;
39
41
  /** Attributable mutation actor. */
40
42
  author: string;
41
43
  /** Lock time-to-live in seconds. */
@@ -58,6 +60,8 @@ export interface WorkspaceJsonMutation<Result> {
58
60
  export interface WorkspaceJsonMutationOptions<Result> extends Omit<WorkspaceJsonWriteOptions, "raw"> {
59
61
  /** Derive the next snapshot and receipt from the locked serialized state. */
60
62
  mutate: (beforeRaw: string | null) => WorkspaceJsonMutation<Result> | Promise<WorkspaceJsonMutation<Result>>;
63
+ /** Preview the locked mutation without writing the singleton or its history. */
64
+ dryRun?: boolean;
61
65
  }
62
66
  /** Options for one append-only workspace audit event that leaves state unchanged. */
63
67
  export interface WorkspaceAuditEventOptions {
@@ -135,9 +139,22 @@ export declare function appendWorkspaceAuditEvent(options: WorkspaceAuditEventOp
135
139
  * Derive and persist an audited singleton mutation from one lock-protected
136
140
  * before-state, preventing read-modify-write callers from losing updates.
137
141
  */
142
+ export declare function mutateWorkspaceJsonWithHistory<Result>(params: WorkspaceJsonMutationOptions<Result> & {
143
+ idempotencyKey?: undefined;
144
+ }): Promise<{
145
+ changed: boolean;
146
+ result: Result;
147
+ replayed?: false;
148
+ }>;
149
+ /** Mutate an audited singleton while reporting a completed operation replay. */
138
150
  export declare function mutateWorkspaceJsonWithHistory<Result>(params: WorkspaceJsonMutationOptions<Result>): Promise<{
139
151
  changed: boolean;
140
152
  result: Result;
153
+ replayed?: false;
154
+ } | {
155
+ changed: false;
156
+ result: undefined;
157
+ replayed: true;
141
158
  }>;
142
159
  /**
143
160
  * Atomically persist one caller-serialized JSON singleton and its audit entry
@@ -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]="e2a2001e-b162-599e-b262-76d2223a343c")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{nowIso}from"../shared/time.js";import{appendHistoryEntry,createHistoryEntry}from"./history.js";import{readHistoryEntries}from"./read.js";import{cloneEmptyReplayDocument,replayToItemDocument,tryApplyReplayPatch,verifyHistoryChain}from"./replay.js";const WORKSPACE_HISTORY_ID="_workspace";function getWorkspaceHistoryPath(pmRoot){return path.join(pmRoot,"history",`${WORKSPACE_HISTORY_ID}.jsonl`)}function workspaceDocument(documents,timestamp){const metadata={id:WORKSPACE_HISTORY_ID,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:timestamp,updated_at:timestamp,documents};return{metadata,body:""}}function replayWorkspaceEntries(entries,count=entries.length){let replay=cloneEmptyReplayDocument();for(const entry of entries.slice(0,count)){const applied=tryApplyReplayPatch(replay,entry.patch);replay=applied.document}return replayToItemDocument(replay)}function workspaceDocuments(document){return"documents"in document.metadata&&typeof document.metadata.documents==="object"&&document.metadata.documents!==null&&!Array.isArray(document.metadata.documents)?document.metadata.documents:{}}function throwWorkspaceHistoryVerificationFailure(errors){throw new PmCliError(`Workspace history verification failed: ${errors.join(", ")}`,EXIT_CODE.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...errors],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function resolveGovernedDocumentPath(pmRoot,filePath){const absolutePath=path.resolve(filePath);const documentPath=path.relative(pmRoot,absolutePath).replaceAll("\\","/");if(documentPath.length===0||documentPath===".."||documentPath.startsWith("../")||path.isAbsolute(documentPath)){throw new TypeError("Workspace history document path must stay inside the tracker root")}return{documentPath,absolutePath}}async function inspectWorkspaceHistoryState(pmRoot){const entries=await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const documents=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries));const matching=[];const mismatched=[];const missing=[];const unreadable=[];for(const documentPath of Object.keys(documents).sort()){let raw;try{const resolved=resolveGovernedDocumentPath(pmRoot,path.resolve(pmRoot,documentPath));raw=await readFileIfExists(resolved.absolutePath);if(raw===null){missing.push(documentPath);continue}const current=JSON.parse(raw);(stableStringify(current)===stableStringify(documents[documentPath])?matching:mismatched).push(documentPath)}catch{unreadable.push(documentPath)}}return{ok:mismatched.length===0&&missing.length===0&&unreadable.length===0,document_count:Object.keys(documents).length,matching_documents:matching,mismatched_documents:mismatched,missing_documents:missing,unreadable_documents:unreadable}}async function appendWorkspaceHistoryChangeLocked(change){const historyPath=getWorkspaceHistoryPath(change.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const idempotentEntry=change.idempotencyKey===void 0?void 0:entries.find(entry2=>entry2.op===`${change.op}:${change.idempotencyKey}`);if(idempotentEntry){return{entry:idempotentEntry,historyPath}}const timestamp=nowIso();const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries);const priorDocuments=workspaceDocuments(beforeDocument);const recordedBefore=priorDocuments[change.documentPath];if(recordedBefore!==void 0&&stableStringify(recordedBefore)!==stableStringify(change.before)){throw new PmCliError(`Workspace history state for "${change.documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}})}const afterDocument=workspaceDocument({...priorDocuments,[change.documentPath]:change.after},entries.length===0?timestamp:beforeDocument.metadata.created_at);const entry=createHistoryEntry({nowIso:timestamp,author:change.author,op:change.idempotencyKey===void 0?change.op:`${change.op}:${change.idempotencyKey}`,before:beforeDocument,after:afterDocument,message:change.message});await appendHistoryEntry(historyPath,entry);return{entry,historyPath}}async function appendWorkspaceHistoryChange(change){const release=await acquireLock(change.pmRoot,"workspace-history",change.lockTtlSeconds,change.author,false,false,change.lockWaitMs);try{return await appendWorkspaceHistoryChangeLocked(change)}finally{await release()}}async function appendWorkspaceAuditEvent(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const historyPath=getWorkspaceHistoryPath(options.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries);const entry=createHistoryEntry({nowIso:nowIso(),author:options.author,op:options.op,before:beforeDocument,after:beforeDocument,message:options.message,context:options.context});await appendHistoryEntry(historyPath,entry);return{entry,historyPath}}finally{await release()}}async function writeWorkspaceJsonWithHistoryLocked(params,beforeRaw){if(beforeRaw===params.raw)return false;const before=beforeRaw===null?null:JSON.parse(beforeRaw);const after=JSON.parse(params.raw);await writeFileAtomic(params.filePath,params.raw);try{if(beforeRaw!==null||params.recordCreation!==false){await appendWorkspaceHistoryChangeLocked({pmRoot:params.pmRoot,documentPath:path.relative(params.pmRoot,params.filePath).replaceAll("\\","/"),before,after,op:params.op,author:params.author,lockTtlSeconds:params.lockTtlSeconds,lockWaitMs:params.lockWaitMs,message:params.message})}}catch(error){if(beforeRaw===null){await fs.rm(params.filePath,{force:true})}else{await writeFileAtomic(params.filePath,beforeRaw)}throw error}return true}async function mutateWorkspaceJsonWithHistory(params){const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,false,false,params.lockWaitMs);try{const beforeRaw=await readFileIfExists(params.filePath);const mutation=await params.mutate(beforeRaw);return{changed:await writeWorkspaceJsonWithHistoryLocked({...params,raw:mutation.raw},beforeRaw),result:mutation.result}}finally{await release()}}async function writeWorkspaceJsonWithHistory(params){const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,false,false,params.lockWaitMs);try{return await writeWorkspaceJsonWithHistoryLocked(params,await readFileIfExists(params.filePath))}finally{await release()}}async function reconcileWorkspaceJsonHistory(options){const authorizationDecision=options.authorizationDecision.trim();if(!authorizationDecision){throw new TypeError("Workspace history reconciliation requires an authorization decision")}const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath);const historyPath=getWorkspaceHistoryPath(options.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const beforeDocument=replayWorkspaceEntries(entries);const priorDocuments=workspaceDocuments(beforeDocument);if(!Object.hasOwn(priorDocuments,documentPath)){throw new TypeError(`Workspace history does not govern document ${documentPath}`)}const raw=await readFileIfExists(absolutePath);if(raw===null){throw new TypeError(`Workspace history document is missing: ${documentPath}`)}const current=JSON.parse(raw);if(stableStringify(priorDocuments[documentPath])===stableStringify(current)){return{changed:false,historyPath}}const timestamp=nowIso();const entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...priorDocuments,[documentPath]:current},beforeDocument.metadata.created_at),message:options.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:documentPath,authorization_decision:authorizationDecision}});await appendHistoryEntry(historyPath,entry);return{changed:true,entry,historyPath}}finally{await release()}}async function restoreWorkspaceJsonFromHistory(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath);const entries=await readHistoryEntries(getWorkspaceHistoryPath(options.pmRoot),WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}if(!Number.isInteger(options.targetVersion)||options.targetVersion<1||options.targetVersion>entries.length){throw new TypeError(`Invalid workspace history target version: ${String(options.targetVersion)}`)}const target=workspaceDocuments(replayWorkspaceEntries(entries,options.targetVersion))[documentPath];if(target===void 0){throw new TypeError(`Workspace history version ${options.targetVersion} does not contain ${documentPath}`)}const beforeRaw=await readFileIfExists(absolutePath);const targetRaw=`${JSON.stringify(target,null,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]="b6012be6-13b6-54b9-91ed-c9093423b1c2")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{nowIso}from"../shared/time.js";import{appendHistoryEntry,createHistoryEntry}from"./history.js";import{readHistoryEntries}from"./read.js";import{cloneEmptyReplayDocument,replayToItemDocument,tryApplyReplayPatch,verifyHistoryChain}from"./replay.js";const WORKSPACE_HISTORY_ID="_workspace";function getWorkspaceHistoryPath(pmRoot){return path.join(pmRoot,"history",`${WORKSPACE_HISTORY_ID}.jsonl`)}function workspaceDocument(documents,timestamp){const metadata={id:WORKSPACE_HISTORY_ID,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:timestamp,updated_at:timestamp,documents};return{metadata,body:""}}function replayWorkspaceEntries(entries,count=entries.length){let replay=cloneEmptyReplayDocument();for(const entry of entries.slice(0,count)){const applied=tryApplyReplayPatch(replay,entry.patch);replay=applied.document}return replayToItemDocument(replay)}function workspaceDocuments(document){return"documents"in document.metadata&&typeof document.metadata.documents==="object"&&document.metadata.documents!==null&&!Array.isArray(document.metadata.documents)?document.metadata.documents:{}}function throwWorkspaceHistoryVerificationFailure(errors){throw new PmCliError(`Workspace history verification failed: ${errors.join(", ")}`,EXIT_CODE.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...errors],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function resolveGovernedDocumentPath(pmRoot,filePath){const absolutePath=path.resolve(filePath);const documentPath=path.relative(pmRoot,absolutePath).replaceAll("\\","/");if(documentPath.length===0||documentPath===".."||documentPath.startsWith("../")||path.isAbsolute(documentPath)){throw new TypeError("Workspace history document path must stay inside the tracker root")}return{documentPath,absolutePath}}async function inspectWorkspaceHistoryState(pmRoot){const entries=await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const documents=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries));const matching=[];const mismatched=[];const missing=[];const unreadable=[];for(const documentPath of Object.keys(documents).sort()){let raw;try{const resolved=resolveGovernedDocumentPath(pmRoot,path.resolve(pmRoot,documentPath));raw=await readFileIfExists(resolved.absolutePath);if(raw===null){missing.push(documentPath);continue}const current=JSON.parse(raw);(stableStringify(current)===stableStringify(documents[documentPath])?matching:mismatched).push(documentPath)}catch{unreadable.push(documentPath)}}return{ok:mismatched.length===0&&missing.length===0&&unreadable.length===0,document_count:Object.keys(documents).length,matching_documents:matching,mismatched_documents:mismatched,missing_documents:missing,unreadable_documents:unreadable}}async function appendWorkspaceHistoryChangeLocked(change){const historyPath=getWorkspaceHistoryPath(change.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const idempotentEntry=change.idempotencyKey===void 0?void 0:entries.find(entry2=>entry2.op===`${change.op}:${change.idempotencyKey}`);if(idempotentEntry){return{entry:idempotentEntry,historyPath}}const timestamp=nowIso();const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries);const priorDocuments=workspaceDocuments(beforeDocument);const recordedBefore=priorDocuments[change.documentPath];if(recordedBefore!==void 0&&stableStringify(recordedBefore)!==stableStringify(change.before)){throw new PmCliError(`Workspace history state for "${change.documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}})}const afterDocument=workspaceDocument({...priorDocuments,[change.documentPath]:change.after},entries.length===0?timestamp:beforeDocument.metadata.created_at);const entry=createHistoryEntry({nowIso:timestamp,author:change.author,op:change.idempotencyKey===void 0?change.op:`${change.op}:${change.idempotencyKey}`,before:beforeDocument,after:afterDocument,message:change.message});await appendHistoryEntry(historyPath,entry);return{entry,historyPath}}async function appendWorkspaceHistoryChange(change){const release=await acquireLock(change.pmRoot,"workspace-history",change.lockTtlSeconds,change.author,false,false,change.lockWaitMs);try{return await appendWorkspaceHistoryChangeLocked(change)}finally{await release()}}async function appendWorkspaceAuditEvent(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const historyPath=getWorkspaceHistoryPath(options.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries);const entry=createHistoryEntry({nowIso:nowIso(),author:options.author,op:options.op,before:beforeDocument,after:beforeDocument,message:options.message,context:options.context});await appendHistoryEntry(historyPath,entry);return{entry,historyPath}}finally{await release()}}async function writeWorkspaceJsonWithHistoryLocked(params,beforeRaw){if(beforeRaw===params.raw)return false;const before=beforeRaw===null?null:JSON.parse(beforeRaw);const after=JSON.parse(params.raw);await writeFileAtomic(params.filePath,params.raw);try{if(beforeRaw!==null||params.recordCreation!==false){await appendWorkspaceHistoryChangeLocked({pmRoot:params.pmRoot,documentPath:path.relative(params.pmRoot,params.filePath).replaceAll("\\","/"),before,after,op:params.op,idempotencyKey:params.idempotencyKey,author:params.author,lockTtlSeconds:params.lockTtlSeconds,lockWaitMs:params.lockWaitMs,message:params.message})}}catch(error){if(beforeRaw===null){await fs.rm(params.filePath,{force:true})}else{await writeFileAtomic(params.filePath,beforeRaw)}throw error}return true}async function mutateWorkspaceJsonWithHistory(params){const{documentPath}=resolveGovernedDocumentPath(params.pmRoot,params.filePath);const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,false,false,params.lockWaitMs);try{const beforeRaw=await readFileIfExists(params.filePath);if(params.dryRun===true||params.idempotencyKey!==void 0){const entries=await readHistoryEntries(getWorkspaceHistoryPath(params.pmRoot),WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok)throwWorkspaceHistoryVerificationFailure(verification.errors);const recorded=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries))[documentPath];if(recorded!==void 0&&stableStringify(recorded)!==stableStringify(beforeRaw===null?null:JSON.parse(beforeRaw))){throw new PmCliError(`Workspace history state for "${documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict"})}if(params.idempotencyKey!==void 0&&entries.some(entry=>entry.op===`${params.op}:${params.idempotencyKey}`)){return{changed:false,result:void 0,replayed:true}}}const mutation=await params.mutate(beforeRaw);JSON.parse(mutation.raw);if(params.dryRun===true){return{changed:beforeRaw!==mutation.raw,result:mutation.result}}return{changed:await writeWorkspaceJsonWithHistoryLocked({...params,raw:mutation.raw},beforeRaw),result:mutation.result}}finally{await release()}}async function writeWorkspaceJsonWithHistory(params){const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,false,false,params.lockWaitMs);try{return await writeWorkspaceJsonWithHistoryLocked(params,await readFileIfExists(params.filePath))}finally{await release()}}async function reconcileWorkspaceJsonHistory(options){const authorizationDecision=options.authorizationDecision.trim();if(!authorizationDecision){throw new TypeError("Workspace history reconciliation requires an authorization decision")}const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath);const historyPath=getWorkspaceHistoryPath(options.pmRoot);const entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}const beforeDocument=replayWorkspaceEntries(entries);const priorDocuments=workspaceDocuments(beforeDocument);if(!Object.hasOwn(priorDocuments,documentPath)){throw new TypeError(`Workspace history does not govern document ${documentPath}`)}const raw=await readFileIfExists(absolutePath);if(raw===null){throw new TypeError(`Workspace history document is missing: ${documentPath}`)}const current=JSON.parse(raw);if(stableStringify(priorDocuments[documentPath])===stableStringify(current)){return{changed:false,historyPath}}const timestamp=nowIso();const entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...priorDocuments,[documentPath]:current},beforeDocument.metadata.created_at),message:options.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:documentPath,authorization_decision:authorizationDecision}});await appendHistoryEntry(historyPath,entry);return{changed:true,entry,historyPath}}finally{await release()}}async function restoreWorkspaceJsonFromHistory(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,false,false,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath);const entries=await readHistoryEntries(getWorkspaceHistoryPath(options.pmRoot),WORKSPACE_HISTORY_ID);const verification=verifyHistoryChain(entries);if(!verification.ok){throwWorkspaceHistoryVerificationFailure(verification.errors)}if(!Number.isInteger(options.targetVersion)||options.targetVersion<1||options.targetVersion>entries.length){throw new TypeError(`Invalid workspace history target version: ${String(options.targetVersion)}`)}const target=workspaceDocuments(replayWorkspaceEntries(entries,options.targetVersion))[documentPath];if(target===void 0){throw new TypeError(`Workspace history version ${options.targetVersion} does not contain ${documentPath}`)}const beforeRaw=await readFileIfExists(absolutePath);const targetRaw=`${JSON.stringify(target,null,2)}
2
2
  `;if(beforeRaw===targetRaw)return{document_path:documentPath,restored_from_version:options.targetVersion,changed:false};const beforeDocument=replayWorkspaceEntries(entries);const timestamp=nowIso();const entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...workspaceDocuments(beforeDocument),[documentPath]:target},beforeDocument.metadata.created_at),message:options.message,context:{reason:"workspace_state_restore",document_path:documentPath,restored_from_version:options.targetVersion,replaced_out_of_band_state:true}});await writeFileAtomic(absolutePath,targetRaw);try{await appendHistoryEntry(getWorkspaceHistoryPath(options.pmRoot),entry)}catch(error){if(beforeRaw===null)await fs.rm(absolutePath,{force:true});else await writeFileAtomic(absolutePath,beforeRaw);throw error}return{document_path:documentPath,restored_from_version:options.targetVersion,changed:true}}finally{await release()}}export{WORKSPACE_HISTORY_ID,appendWorkspaceAuditEvent,appendWorkspaceHistoryChange,getWorkspaceHistoryPath,inspectWorkspaceHistoryState,mutateWorkspaceJsonWithHistory,reconcileWorkspaceJsonHistory,restoreWorkspaceJsonFromHistory,writeWorkspaceJsonWithHistory};
3
3
  //# sourceMappingURL=workspace-history.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]="6e88d6b7-aa5f-5515-8ea4-481916b12ef1")}catch(e2){}})();const CHANGED_FIELDS_KEY="changed_fields";const CHANGED_FIELD_COUNT_KEY="changed_field_count";const ROWS_KEY="rows";const UPDATE_MANY_MUTATION_MODES=new Set(["apply","rollback"]);const DELETE_OUTCOMES=new Set(["deleted","would_delete"]);const COMPACT_RECURRENCE_TEXT_LIMIT=256;const COMPOUND_MUTATION_STEPS={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function projectCompoundMutation(result,options){if(!isPlainObject(result)||typeof result.action!=="string"||typeof result.id!=="string"||result.id.length===0)return null;const steps=Object.hasOwn(COMPOUND_MUTATION_STEPS,result.action)?COMPOUND_MUTATION_STEPS[result.action]:void 0;if(!steps||!steps.every(step=>{const value=result[step];return isPlainObject(value)&&isPlainObject(value.item)&&value.item.id===result.id&&Array.isArray(value.changed_fields)&&value.changed_fields.every(field=>typeof field==="string")}))return null;const final=result[steps.at(-1)];const identity=projectIdOnlyResult(final);if(options.idOnly)return identity;if(!options.compactEnvelope&&options.changedFields!=="compact")return null;return{...result,...options.compactEnvelope?{...identity,changed_field_count:new Set(steps.flatMap(step=>result[step].changed_fields)).size}:{},...Object.fromEntries(steps.map(step=>[step,projectMutationResult(result[step],options)]))}}function truncateCompactRecurrenceText(value){if(typeof value!=="string"||value.length<=COMPACT_RECURRENCE_TEXT_LIMIT){return value}return`${value.slice(0,COMPACT_RECURRENCE_TEXT_LIMIT-1)}\u2026`}function projectCompactRecurrence(value){if(!isPlainObject(value))return null;const recurrence={...value};recurrence.reason=truncateCompactRecurrenceText(recurrence.reason);if(isPlainObject(recurrence.previous_terminal)){recurrence.previous_terminal=Object.fromEntries(Object.entries(recurrence.previous_terminal).map(([key,entry])=>[key,truncateCompactRecurrenceText(entry)]))}return recurrence}function isPlainObject(value){if(typeof value!=="object"||value===null||Array.isArray(value)){return false}const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function compactOwnChangedFields(envelope){const changedFields=envelope[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields)){return null}const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};for(const[key,value]of Object.entries(envelope)){if(key!==CHANGED_FIELDS_KEY){projected[key]=value}}projected[CHANGED_FIELD_COUNT_KEY]=changedFields.length;return projected}function isMutationEnvelope(value){return"item"in value&&Array.isArray(value[CHANGED_FIELDS_KEY])}function isUpdateManyMutationEnvelope(value){return typeof value.mode==="string"&&UPDATE_MANY_MUTATION_MODES.has(value.mode)&&Array.isArray(value[ROWS_KEY])}function replaceRows(envelope,rows){const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};Object.assign(projected,envelope);projected[ROWS_KEY]=rows;return projected}function projectIdOnlyResult(result){if(!isPlainObject(result)){return null}const subject=isPlainObject(result.item)?result.item:isPlainObject(result.plan)?result.plan:null;if(subject===null){return null}const id=typeof subject.id==="string"?subject.id:void 0;const status=typeof result.outcome==="string"&&DELETE_OUTCOMES.has(result.outcome)?result.outcome:typeof subject.status==="string"?subject.status:void 0;if(!id){return null}return status?{id,status,...typeof result.deleted==="boolean"?{deleted:result.deleted}:{}}:{id}}function projectCompactMutationEnvelope(result){if(!isPlainObject(result)||!isPlainObject(result.item))return null;if(typeof result.item.id!=="string")return null;const changedFields=result[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields))return null;const compact={id:result.item.id,...typeof result.outcome==="string"&&DELETE_OUTCOMES.has(result.outcome)?{status:result.outcome}:typeof result.item.status==="string"?{status:result.item.status}:{},...typeof result.deleted==="boolean"?{deleted:result.deleted}:{},...typeof result.previous_status==="string"?{previous_status:result.previous_status}:{},changed_field_count:changedFields.length};appendCompactMutationEvidence(result,result.item,compact);return compact}function appendCompactMutationEvidence(result,item,compact){const closeReason=typeof result.close_reason==="string"?result.close_reason:typeof item.close_reason==="string"?item.close_reason:void 0;if(closeReason!==void 0)compact.close_reason=closeReason;const recurrence=projectCompactRecurrence(result.recurrence);if(recurrence!==null)compact.recurrence=recurrence;if(Array.isArray(result.warnings)&&result.warnings.length>0)compact.warnings=result.warnings;if(isPlainObject(result.recovery))compact.recovery=result.recovery;if(typeof result.claimed_by==="string"||typeof result.released_by==="string"){for(const key of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","suggestions"]){if(Object.hasOwn(result,key))compact[key]=result[key]}}}function compactUpdateManyRows(envelope){const rows=isUpdateManyMutationEnvelope(envelope)?envelope[ROWS_KEY]:void 0;if(!Array.isArray(rows)){return{projected:envelope,changed:false}}let rowsChanged=false;const nextRows=rows.map(row=>{if(!isPlainObject(row)){return row}const compactedRow=compactOwnChangedFields(row);if(compactedRow){rowsChanged=true;return compactedRow}return row});return rowsChanged?{projected:replaceRows(envelope,nextRows),changed:true}:{projected:envelope,changed:false}}function projectMutationResult(result,options={}){const compound=projectCompoundMutation(result,options);if(compound!==null)return compound;if(options.idOnly===true){const idOnly=projectIdOnlyResult(result);if(idOnly!==null){return idOnly}}if(options.compactEnvelope===true){const compact=projectCompactMutationEnvelope(result);if(compact!==null)return compact}const mode=options.changedFields??"full";if(mode==="full"||!isPlainObject(result)){return result}let changed=false;let projected=result;const compactedTop=isMutationEnvelope(result)?compactOwnChangedFields(result):null;if(compactedTop!==null){projected=compactedTop;changed=true}const rowProjection=compactUpdateManyRows(projected);if(rowProjection.changed){projected=rowProjection.projected;changed=true}return changed?projected:result}export{projectMutationResult};
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]="fd8576c5-0011-5aa2-ad8c-f6ec5715e419")}catch(e2){}})();const CHANGED_FIELDS_KEY="changed_fields";const CHANGED_FIELD_COUNT_KEY="changed_field_count";const ROWS_KEY="rows";const UPDATE_MANY_MUTATION_MODES=new Set(["apply","rollback"]);const DELETE_OUTCOMES=new Set(["deleted","would_delete"]);const COMPACT_RECURRENCE_TEXT_LIMIT=256;const COMPOUND_MUTATION_STEPS={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function projectCompoundMutation(result,options){if(!isPlainObject(result)||typeof result.action!=="string"||typeof result.id!=="string"||result.id.length===0)return null;const steps=Object.hasOwn(COMPOUND_MUTATION_STEPS,result.action)?COMPOUND_MUTATION_STEPS[result.action]:void 0;if(!steps||!steps.every(step=>{const value=result[step];return isPlainObject(value)&&isPlainObject(value.item)&&value.item.id===result.id&&Array.isArray(value.changed_fields)&&value.changed_fields.every(field=>typeof field==="string")}))return null;const final=result[steps.at(-1)];const identity=projectIdOnlyResult(final);if(options.idOnly)return identity;if(!options.compactEnvelope&&options.changedFields!=="compact")return null;return{...result,...options.compactEnvelope?{...identity,changed_field_count:new Set(steps.flatMap(step=>result[step].changed_fields)).size}:{},...Object.fromEntries(steps.map(step=>[step,projectMutationResult(result[step],options)]))}}function truncateCompactRecurrenceText(value){if(typeof value!=="string"||value.length<=COMPACT_RECURRENCE_TEXT_LIMIT){return value}return`${value.slice(0,COMPACT_RECURRENCE_TEXT_LIMIT-1)}\u2026`}function projectCompactRecurrence(value){if(!isPlainObject(value))return null;const recurrence={...value};recurrence.reason=truncateCompactRecurrenceText(recurrence.reason);if(isPlainObject(recurrence.previous_terminal)){recurrence.previous_terminal=Object.fromEntries(Object.entries(recurrence.previous_terminal).map(([key,entry])=>[key,truncateCompactRecurrenceText(entry)]))}return recurrence}function isPlainObject(value){if(typeof value!=="object"||value===null||Array.isArray(value)){return false}const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function compactOwnChangedFields(envelope){const changedFields=envelope[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields)){return null}const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};for(const[key,value]of Object.entries(envelope)){if(key!==CHANGED_FIELDS_KEY){projected[key]=value}}projected[CHANGED_FIELD_COUNT_KEY]=changedFields.length;return projected}function isMutationEnvelope(value){return"item"in value&&Array.isArray(value[CHANGED_FIELDS_KEY])}function isUpdateManyMutationEnvelope(value){return typeof value.mode==="string"&&UPDATE_MANY_MUTATION_MODES.has(value.mode)&&Array.isArray(value[ROWS_KEY])}function replaceRows(envelope,rows){const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};Object.assign(projected,envelope);projected[ROWS_KEY]=rows;return projected}function projectIdOnlyResult(result){if(!isPlainObject(result)){return null}const subject=isPlainObject(result.item)?result.item:isPlainObject(result.plan)?result.plan:null;if(subject===null){return null}const id=typeof subject.id==="string"?subject.id:void 0;const status=typeof result.outcome==="string"&&DELETE_OUTCOMES.has(result.outcome)?result.outcome:typeof subject.status==="string"?subject.status:void 0;if(!id){return null}return status?{id,status,...typeof result.deleted==="boolean"?{deleted:result.deleted}:{}}:{id}}function projectCompactMutationEnvelope(result,includeItem){if(!isPlainObject(result))return null;if(isPlainObject(result.plan)&&isPlainObject(result.mutation_receipt)&&result.mutation_receipt.kind==="plan_mutation"&&result.mutation_receipt.id===result.plan.id&&result.mutation_receipt.action===result.action)return result.mutation_receipt;if(!includeItem||!isPlainObject(result.item))return null;if(typeof result.item.id!=="string")return null;const changedFields=result[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields))return null;const compact={id:result.item.id,...typeof result.outcome==="string"&&DELETE_OUTCOMES.has(result.outcome)?{status:result.outcome}:typeof result.item.status==="string"?{status:result.item.status}:{},...typeof result.deleted==="boolean"?{deleted:result.deleted}:{},...typeof result.previous_status==="string"?{previous_status:result.previous_status}:{},changed_field_count:changedFields.length};appendCompactMutationEvidence(result,result.item,compact);return compact}function appendCompactMutationEvidence(result,item,compact){const closeReason=typeof result.close_reason==="string"?result.close_reason:typeof item.close_reason==="string"?item.close_reason:void 0;if(closeReason!==void 0)compact.close_reason=closeReason;const recurrence=projectCompactRecurrence(result.recurrence);if(recurrence!==null)compact.recurrence=recurrence;if(Array.isArray(result.warnings)&&result.warnings.length>0)compact.warnings=result.warnings;if(isPlainObject(result.recovery))compact.recovery=result.recovery;if(typeof result.claimed_by==="string"||typeof result.released_by==="string"){for(const key of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","suggestions"]){if(Object.hasOwn(result,key))compact[key]=result[key]}}}function compactUpdateManyRows(envelope){const rows=isUpdateManyMutationEnvelope(envelope)?envelope[ROWS_KEY]:void 0;if(!Array.isArray(rows)){return{projected:envelope,changed:false}}let rowsChanged=false;const nextRows=rows.map(row=>{if(!isPlainObject(row)){return row}const compactedRow=compactOwnChangedFields(row);if(compactedRow){rowsChanged=true;return compactedRow}return row});return rowsChanged?{projected:replaceRows(envelope,nextRows),changed:true}:{projected:envelope,changed:false}}function projectMutationResult(result,options={}){const compound=projectCompoundMutation(result,options);if(compound!==null)return compound;if(options.idOnly===true){const idOnly=projectIdOnlyResult(result);if(idOnly!==null){return idOnly}}if(options.compactEnvelope===true||options.changedFields==="compact"){const compact=projectCompactMutationEnvelope(result,options.compactEnvelope===true);if(compact!==null)return compact}const mode=options.changedFields??"full";if(mode==="full"||!isPlainObject(result)){return result}let changed=false;let projected=result;const compactedTop=isMutationEnvelope(result)?compactOwnChangedFields(result):null;if(compactedTop!==null){projected=compactedTop;changed=true}const rowProjection=compactUpdateManyRows(projected);if(rowProjection.changed){projected=rowProjection.projected;changed=true}return changed?projected:result}export{projectMutationResult};
2
2
  //# sourceMappingURL=mutation-projection.js.map
@@ -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]="9d073708-29b1-56b5-bcff-b964bfdcb43d")}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{acquireLock}from"../lock/lock.js";import{isActiveCommandUnextended,runWithIsolatedExtensionRuntime}from"../extensions/index.js";import{resolveAutomaticReadSampleRate}from"./read-sampling.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,resolveTelemetryEnvironmentPolicy}from"./policy.js";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{clearSettingsReadCache}from"../store/settings-read-cache.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 TELEMETRY_FOREGROUND_LOCK_WAIT_MS=250;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_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;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as PM_TELEMETRY_SOURCE_CONTEXT_VALUES2}from"./policy.js";let sourceContextWarningEmitted=false;let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();const deferredReadStarts=new WeakMap;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 TELEMETRY_HARNESSES=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]);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 source=override.length>0?"env_override_rejected":"inferred";if(source==="env_override_rejected"&&!sourceContextWarningEmitted&&!globalOptions.quiet){sourceContextWarningEmitted=true;process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${PM_TELEMETRY_SOURCE_CONTEXT_VALUES.join("|")}; ignoring override.
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]="f0ef8253-1b96-56d2-bf94-6ff5debcab08")}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{acquireLock}from"../lock/lock.js";import{isActiveCommandUnextended,runWithIsolatedExtensionRuntime}from"../extensions/index.js";import{resolveAutomaticReadSampleRate}from"./read-sampling.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,resolveTelemetryEnvironmentPolicy}from"./policy.js";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{clearSettingsReadCache}from"../store/settings-read-cache.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 TELEMETRY_FOREGROUND_LOCK_WAIT_MS=250;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_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;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as PM_TELEMETRY_SOURCE_CONTEXT_VALUES2}from"./policy.js";let sourceContextWarningEmitted=false;let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();const deferredReadStarts=new WeakMap;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 TELEMETRY_HARNESSES=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]);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{await withQueueMutation(async()=>{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
+ `)},globalPmRoot)}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 source=override.length>0?"env_override_rejected":"inferred";if(source==="env_override_rejected"&&!sourceContextWarningEmitted&&!globalOptions.quiet){sourceContextWarningEmitted=true;process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${PM_TELEMETRY_SOURCE_CONTEXT_VALUES.join("|")}; ignoring override.
3
3
  `)}return{source_context:inferTelemetrySourceContext(globalOptions),source_context_source:source}}function inferTelemetrySourceContext(globalOptions){const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return"test"}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"automation"}return"user"}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{agent_harness:agent.harness?TELEMETRY_HARNESSES.has(agent.harness)?agent.harness:"other":"none",ci:parseBooleanTrueLike(process.env.CI),...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 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,sampleRate=1){const endpoint=activeCommand.otel_traces_endpoint;if(typeof endpoint!=="string"||endpoint.trim().length===0||[activeCommand.otel_trace_id,activeCommand.otel_span_id].some(id=>typeof id!=="string"||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),otlpStringAttribute("pm.sample_rate",String(sampleRate))];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,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);if(!settings.telemetry.enabled||resolveTelemetryEnvironmentPolicy().telemetry_disabled)return null;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();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)),captureLevel:normalizeCaptureLevel(settings.telemetry.capture_level)}}async function appendTelemetryEvent(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 appendLineAtomic(queuePath(globalPmRoot),serialized)}async function enqueueTelemetryEvent(globalPmRoot,event){await withQueueMutation(()=>appendTelemetryEvent(globalPmRoot,event),globalPmRoot)}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}
4
4
  `:"";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 appendPendingOtelSpan(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 appendLineAtomic(otelSpansQueuePath(globalPmRoot),serialized)}async function enqueuePendingOtelSpan(globalPmRoot,request){await withQueueMutation(()=>appendPendingOtelSpan(globalPmRoot,request),globalPmRoot)}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}
5
5
  `:"";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},globalPmRoot)}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,globalPmRoot=resolveGlobalPmRoot(process.cwd()),waitMs=5e3){const run=_queueMutationPromise.catch(()=>{}).then(()=>runWithIsolatedExtensionRuntime(async()=>{const release=await acquireLock(globalPmRoot,"telemetry-queue",60,"telemetry",false,false,waitMs);try{clearSettingsReadCache(globalPmRoot);return await operation()}finally{await release()}}));_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},globalPmRoot)}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},globalPmRoot)}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){const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){const remaining=prunedCount>0?await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays):retainedEntries;await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.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(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const installation=await withQueueMutation(()=>ensureInstallationId(globalPmRoot),globalPmRoot);if(!installation)return;await flushQueueWithProcessLock(globalPmRoot,installation.endpoint,installation.retentionDays)}catch{}}async function startTelemetryCommand(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){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 coreReadOwned=context.global.noExtensions===true||isActiveCommandUnextended(context.command);const activeCommand=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,endpoint,retentionDays,captureLevel}=installation;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})};const sampleRate=await resolveAutomaticReadSampleRate(globalPmRoot,context.command,coreReadOwned);if(sampleRate===1){await appendTelemetryEvent(globalPmRoot,event)}const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const active={...sampleRate<1?{sample_rate:sampleRate}:{},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};if(sampleRate<1)deferredReadStarts.set(active,event);return active},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(activeCommand&&activeCommand.sample_rate===void 0){scheduleTelemetryFlush(globalPmRoot,activeCommand.endpoint,activeCommand.retention_days)}return activeCommand}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!activeCommand||resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const captured=await withQueueMutation(async()=>{const settings=await readSettings(activeCommand.global_pm_root);if(resolveTelemetryEnvironmentPolicy().telemetry_disabled||!settings.telemetry.enabled||settings.telemetry.installation_id!==activeCommand.installation_id){deferredReadStarts.delete(activeCommand);return false}const deferredStart=deferredReadStarts.get(activeCommand);const sampleRate=outcome.ok?activeCommand.sample_rate??1:1;if(deferredStart){deferredReadStarts.delete(activeCommand);if(crypto.randomBytes(6).readUIntBE(0,6)/2**48>=sampleRate)return false;deferredStart.payload.sample_rate=sampleRate;await appendTelemetryEvent(activeCommand.global_pm_root,deferredStart)}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:{...deferredStart?{sample_rate:sampleRate}:{},...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 appendTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs,sampleRate);if(otelRequest){await appendPendingOtelSpan(activeCommand.global_pm_root,otelRequest)}return true},activeCommand.global_pm_root,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(!captured)return;scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled){return}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const captured=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,captureLevel}=installation;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 appendTelemetryEvent(globalPmRoot,event);return installation},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);if(captured)scheduleTelemetryFlush(globalPmRoot,captured.endpoint,captured.retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES2 as PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush,withQueueMutation as withTelemetryQueueMutation};
@@ -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]="c42420db-459b-5ce7-a9b5-e6d44873253a")}catch(e2){}})();const PM_HISTORY_COMMAND_ALIASES=[["history-redact","history redact"],["history-repair","history repair"],["history-compact","history compact"],["activity","history activity"],["restore","history restore"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"commander",owner:"pm-tqel"}));const PM_CONTEXT_OPS_COMMAND_ALIASES=[...["next","focus"].map(alias=>({alias,canonical:`context ${alias}`,owner:"pm-kcs4"})),...["stats","health","validate","gc","telemetry","eval","test-all"].map(alias=>({alias,canonical:`ops ${alias}`,owner:"pm-6apl"})),...["normalize","reindex"].map(alias=>({alias,canonical:`ops ${alias}`,owner:"pm-3i9q8g"})),{alias:"events",canonical:"history events",owner:"pm-3i9q8g"}].map(entry=>({...entry,canonical_argv:entry.canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap"}));const PM_BULK_LIFECYCLE_COMMAND_ALIASES=[["update-many","update many"],["close-many","close many"],["delete","close delete"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap",owner:"pm-ik19"}));const PM_RELOCATED_COMMAND_ALIASES=[...PM_CONTEXT_OPS_COMMAND_ALIASES,...PM_BULK_LIFECYCLE_COMMAND_ALIASES,...["init","config","schema","profile"].map(alias=>({alias,canonical:`workspace ${alias}`,canonical_argv:["workspace",alias],lifecycle:"permanent",hidden:true,registration:"bootstrap",owner:"pm-npr3"})),...[...["comments","notes","learnings","files","docs","deps","append","test"].map(facet=>[facet,`item ${facet}`,"pm-yql1"]),["test-runs-worker","item test worker","pm-lp4j"],...["statuses","tags","types"].map(facet=>[`completion-${facet}`,`completion ${facet}`,"pm-szdc"]),["history-author-acknowledge","history acknowledge","pm-djyvbk"],["copy","item copy","pm-m6g87m"],["merge","workspace merge","pm-m6g87m"],["duplicates","item duplicates","pm-fmy9ih"],["dedupe-audit","item duplicates audit","pm-fmy9ih"],["dedupe-merge","item duplicates merge","pm-fmy9ih"],["comments-audit","item audit-comments","pm-fmy9ih"],["search-advanced","search advanced","pm-wfskfn"],...["meet","event","remind"].map(command=>[command,`calendar ${command}`,"pm-o3fh"])].map(([alias,canonical,owner])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap",owner}))];const PM_NAMESPACED_COMMAND_ALIASES=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:true,registration:"commander",owner:"pm-3z0k"},...PM_HISTORY_COMMAND_ALIASES,...PM_RELOCATED_COMMAND_ALIASES,...["discover","lookup"].map(action=>({alias:`files ${action}`,canonical:`item files ${action}`,canonical_argv:["item","files",action],lifecycle:"permanent",hidden:true,registration:"bootstrap",owner:"pm-yql1"}))];function findPmNamespacedCommand(tokens){let matched;for(const alias of PM_NAMESPACED_COMMAND_ALIASES){if(alias.canonical_argv.length<=(matched?.canonical_argv.length??0))continue;if(alias.canonical_argv.every((token,index)=>token===(index===0&&tokens[index]==="ctx"?"context":tokens[index])))matched=alias}return matched}function resolvePmCommandOperation(command){const normalized=command.trim().replace(/\s+/gu," ");return PM_NAMESPACED_COMMAND_ALIASES.find(alias=>alias.canonical===normalized.replace(/^ctx /u,"context "))?.alias??normalized}function resolvePmHistoryOperation(command){return resolvePmCommandOperation(command)}const PM_COMMAND_ALIAS_CONTRACTS=[...PM_NAMESPACED_COMMAND_ALIASES,...[["ctx","context"],["packages","package"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:[canonical],lifecycle:"permanent",hidden:false,registration:"commander",owner:"pm-pbyu"})),...[["start-task","claim","--start"],["pause-task","release","--pause"],["close-task","close","--release-assignment"]].map(([alias,canonical,flag])=>({alias,canonical,canonical_argv:[canonical,flag],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-eq4x"})),{alias:"tests",canonical:"item test",canonical_argv:["item","test"],lifecycle:"permanent",hidden:false,registration:"bootstrap",owner:"pm-u4t9gp"},...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([alias,canonical])=>({alias,canonical:["comments","notes","learnings"].includes(canonical)?`item ${canonical}`:canonical,canonical_argv:["comments","notes","learnings"].includes(canonical)?["item",canonical]:[canonical],lifecycle:"permanent",hidden:false,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","packages catalog"],["packages scaffold","packages init"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:false,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([alias,status])=>({alias,canonical:"list",canonical_argv:["list","--status",status],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-tnud"}))];const EXECUTABLE_COMMAND_ALIASES=Object.fromEntries(PM_COMMAND_ALIAS_CONTRACTS.filter(contract=>contract.registration==="bootstrap").map(contract=>[contract.alias,contract.canonical]));function resolvePmCommandAlias(alias){const normalized=alias.trim().toLowerCase();return PM_COMMAND_ALIAS_CONTRACTS.find(contract=>contract.alias===normalized)}function renderPmCommandAliasMigrationHint(contract){return`Deprecated command \`${contract.alias}\`; use \`pm ${contract.canonical_argv.join(" ")}\`.`}export{EXECUTABLE_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_HISTORY_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,findPmNamespacedCommand,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,resolvePmCommandOperation,resolvePmHistoryOperation};
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]="dd0b1f79-0f4c-5042-8915-23adfc1f3b8d")}catch(e2){}})();const PM_HISTORY_COMMAND_ALIASES=[["history-redact","history redact"],["history-repair","history repair"],["history-compact","history compact"],["activity","history activity"],["restore","history restore"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"commander",owner:"pm-tqel"}));const PM_CONTEXT_OPS_COMMAND_ALIASES=[...["next","focus"].map(alias=>({alias,canonical:`context ${alias}`,owner:"pm-kcs4"})),...["stats","health","validate","gc","telemetry","eval","test-all"].map(alias=>({alias,canonical:`ops ${alias}`,owner:"pm-6apl"})),...["normalize","reindex"].map(alias=>({alias,canonical:`ops ${alias}`,owner:"pm-3i9q8g"})),{alias:"events",canonical:"history events",owner:"pm-3i9q8g"}].map(entry=>({...entry,canonical_argv:entry.canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap"}));const PM_BULK_LIFECYCLE_COMMAND_ALIASES=[["update-many","update many"],["close-many","close many"],["delete","close delete"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap",owner:"pm-ik19"}));const PM_RELOCATED_COMMAND_ALIASES=[...PM_CONTEXT_OPS_COMMAND_ALIASES,...PM_BULK_LIFECYCLE_COMMAND_ALIASES,...["init","config","schema","profile"].map(alias=>({alias,canonical:`workspace ${alias}`,canonical_argv:["workspace",alias],lifecycle:"permanent",hidden:true,registration:"bootstrap",owner:"pm-npr3"})),...[...["comments","notes","learnings","files","docs","deps","append","test"].map(facet=>[facet,`item ${facet}`,"pm-yql1"]),["test-runs-worker","item test worker","pm-lp4j"],...["statuses","tags","types"].map(facet=>[`completion-${facet}`,`completion ${facet}`,"pm-szdc"]),["history-author-acknowledge","history acknowledge","pm-djyvbk"],["copy","item copy","pm-m6g87m"],["merge","workspace merge","pm-m6g87m"],["duplicates","item duplicates","pm-fmy9ih"],["dedupe-audit","item duplicates audit","pm-fmy9ih"],["dedupe-merge","item duplicates merge","pm-fmy9ih"],["comments-audit","item audit-comments","pm-fmy9ih"],["search-advanced","search advanced","pm-wfskfn"],...["meet","event","remind"].map(command=>[command,`calendar ${command}`,"pm-o3fh"])].map(([alias,canonical,owner])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:true,registration:"bootstrap",owner}))];const PM_NAMESPACED_COMMAND_ALIASES=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:true,registration:"commander",owner:"pm-3z0k"},...PM_HISTORY_COMMAND_ALIASES,...PM_RELOCATED_COMMAND_ALIASES,...["discover","lookup"].map(action=>({alias:`files ${action}`,canonical:`item files ${action}`,canonical_argv:["item","files",action],lifecycle:"permanent",hidden:true,registration:"bootstrap",owner:"pm-yql1"}))];function findPmNamespacedCommand(tokens){let matched;for(const alias of PM_NAMESPACED_COMMAND_ALIASES){if(alias.canonical_argv.length<=(matched?.canonical_argv.length??0))continue;if(alias.canonical_argv.every((token,index)=>token===(index===0&&tokens[index]==="ctx"?"context":tokens[index])))matched=alias}return matched}function resolvePmCommandOperation(command){const normalized=command.trim().replace(/\s+/gu," ");return PM_NAMESPACED_COMMAND_ALIASES.find(alias=>alias.canonical===normalized.replace(/^ctx /u,"context "))?.alias??normalized}function resolvePmHistoryOperation(command){return resolvePmCommandOperation(command)}const PM_COMMAND_ALIAS_CONTRACTS=[...PM_NAMESPACED_COMMAND_ALIASES,...[["ctx","context"],["packages","package"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:[canonical],lifecycle:"permanent",hidden:false,registration:"commander",owner:"pm-pbyu"})),...[["start-task","claim","--start"],["pause-task","release","--pause"],["close-task","close","--release-assignment"]].map(([alias,canonical,flag])=>({alias,canonical,canonical_argv:[canonical,flag],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-eq4x"})),{alias:"tests",canonical:"item test",canonical_argv:["item","test"],lifecycle:"permanent",hidden:false,registration:"bootstrap",owner:"pm-u4t9gp"},...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([alias,canonical])=>({alias,canonical:["comments","notes","learnings"].includes(canonical)?`item ${canonical}`:canonical,canonical_argv:["comments","notes","learnings"].includes(canonical)?["item",canonical]:[canonical],lifecycle:"permanent",hidden:false,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","package catalog"],["packages scaffold","package init"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"permanent",hidden:false,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([alias,status])=>({alias,canonical:"list",canonical_argv:["list","--status",status],lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([alias,canonical])=>({alias,canonical,canonical_argv:canonical.split(" "),lifecycle:"deprecated",hidden:true,registration:"commander",owner:"pm-tnud"}))];const EXECUTABLE_COMMAND_ALIASES=Object.fromEntries(PM_COMMAND_ALIAS_CONTRACTS.filter(contract=>contract.registration==="bootstrap").map(contract=>[contract.alias,contract.canonical]));function resolvePmCommandAlias(alias){const normalized=alias.trim().toLowerCase();return PM_COMMAND_ALIAS_CONTRACTS.find(contract=>contract.alias===normalized)}function renderPmCommandAliasMigrationHint(contract){return`Deprecated command \`${contract.alias}\`; use \`pm ${contract.canonical_argv.join(" ")}\`.`}export{EXECUTABLE_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_HISTORY_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,findPmNamespacedCommand,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,resolvePmCommandOperation,resolvePmHistoryOperation};
2
2
  //# sourceMappingURL=command-aliases.js.map
@@ -1,10 +1,4 @@
1
- /**
2
- * @module sdk/extension-command-context
3
- *
4
- * Builds the host-owned SDK services injected into extension commands so
5
- * package runtimes never need private imports or runtime package resolution.
6
- */
7
1
  import type { ExtensionCommandSdk } from "../core/extensions/extension-types.js";
8
2
  import type { PmClient } from "./runtime.js";
9
3
  /** Bind public SDK services to one tracker and one caller-owned client. */
10
- export declare function createExtensionCommandSdk(pmRoot: string, client: PmClient): ExtensionCommandSdk;
4
+ export declare function createExtensionCommandSdk(pmRoot: string, client: PmClient, invocationAuthor?: string, invocationCommand?: string): ExtensionCommandSdk;
@@ -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]="3113ad4b-282a-50af-a836-8e9abfde7d7e")}catch(e2){}})();import{EXIT_CODE}from"../core/shared/constants.js";import{isPmCliExpectedError}from"./errors.js";import{getItemAt}from"./history-read.js";import{RelationshipEventLog,RelationshipEventStore}from"./relationship-history.js";import{analyzeGraphImpact}from"./relationship-analytics.js";import{RelationshipGraph,createRelationshipKindRegistry}from"./relationships.js";import{commitWorkspaceTransaction}from"./workspace-transaction.js";function buildRelationshipKindRegistry(definitions){const registry=createRelationshipKindRegistry();for(const definition of definitions)registry.register(definition);return registry}function createExtensionCommandSdk(pmRoot,client){return{client,isItemNotFoundError:error=>isPmCliExpectedError(error)&&error.exitCode===EXIT_CODE.NOT_FOUND,getItemAt:(id,target)=>getItemAt(id,target,{pmRoot}),openRelationshipEventStore:options=>{return RelationshipEventStore.open({pmRoot,nodes:options.nodes,registry:buildRelationshipKindRegistry(options.definitions),...options.relativePath===void 0?{}:{relativePath:options.relativePath}})},createRelationshipGraph:options=>new RelationshipGraph(options.nodes,options.edges,buildRelationshipKindRegistry(options.definitions)),analyzeRelationshipImpact:(graph,root,options)=>analyzeGraphImpact(graph,root,options),validateRelationshipEvents:options=>{const log=new RelationshipEventLog(options.nodes,{registry:buildRelationshipKindRegistry(options.definitions)});return options.events.map(event=>log.append({...event,expectedVersion:log.version}))},commitWorkspaceTransaction:options=>commitWorkspaceTransaction({...options,pmRoot})}}export{createExtensionCommandSdk};
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]="4c3bb78a-4b63-51ef-a854-c4520cfd3f32")}catch(e2){}})();import{createHash}from"node:crypto";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{mutateWorkspaceJsonWithHistory}from"../core/history/workspace-history.js";import{resolveAuthor}from"../core/shared/author.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{stableValueEquals}from"../core/shared/serialization.js";import{getSettingsPath}from"../core/store/paths.js";import{readSettings,serializeSettings}from"../core/store/settings.js";import{clearSettingsReadCache}from"../core/store/settings-read-cache.js";import{validateSettings}from"../core/store/settings-validator.js";import{isPmCliExpectedError}from"./errors.js";import{getItemAt}from"./history-read.js";import{RelationshipEventLog,RelationshipEventStore}from"./relationship-history.js";import{analyzeGraphImpact}from"./relationship-analytics.js";import{RelationshipGraph,createRelationshipKindRegistry}from"./relationships.js";import{commitWorkspaceTransaction}from"./workspace-transaction.js";function buildRelationshipKindRegistry(definitions){const registry=createRelationshipKindRegistry();for(const definition of definitions)registry.register(definition);return registry}function createExtensionCommandSdk(pmRoot,client,invocationAuthor,invocationCommand){return{client,isItemNotFoundError:error=>isPmCliExpectedError(error)&&error.exitCode===EXIT_CODE.NOT_FOUND,getItemAt:(id,target)=>getItemAt(id,target,{pmRoot}),openRelationshipEventStore:options=>{return RelationshipEventStore.open({pmRoot,nodes:options.nodes,registry:buildRelationshipKindRegistry(options.definitions),...options.relativePath===void 0?{}:{relativePath:options.relativePath}})},createRelationshipGraph:options=>new RelationshipGraph(options.nodes,options.edges,buildRelationshipKindRegistry(options.definitions)),analyzeRelationshipImpact:(graph,root,options)=>analyzeGraphImpact(graph,root,options),validateRelationshipEvents:options=>{const log=new RelationshipEventLog(options.nodes,{registry:buildRelationshipKindRegistry(options.definitions)});return options.events.map(event=>log.append({...event,expectedVersion:log.version}))},commitWorkspaceTransaction:options=>commitWorkspaceTransaction({...options,pmRoot}),mutateWorkspaceSettings:async options=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(options.operationId)){throw new PmCliError("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",EXIT_CODE.USAGE)}const settings=await readSettings(pmRoot);try{const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:getSettingsPath(pmRoot),op:"extension:pm:settings",idempotencyKey:invocationCommand===void 0?options.operationId:`${createHash("sha256").update(invocationCommand).digest("hex").slice(0,16)}:${options.operationId}`,author:invocationAuthor??resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:false,dryRun:options.dryRun===true,mutate:async beforeRaw=>{const current=beforeRaw===null?null:JSON.parse(beforeRaw);if(!validateSettings(current).success){throw new PmCliError("Workspace settings mutation requires a valid initialized settings.json.",EXIT_CODE.USAGE)}const next=await options.mutate(structuredClone(current));if(!validateSettings(next).success){throw new PmCliError("Workspace settings mutation returned invalid settings.json.",EXIT_CODE.USAGE)}return{raw:stableValueEquals(current,next)?beforeRaw:serializeSettings(next),result:void 0}}});if(mutation.changed&&options.dryRun!==true){await runActiveOnWriteHooks({path:getSettingsPath(pmRoot),scope:"project",op:"extension:pm:settings"})}return{changed:mutation.changed,dry_run:options.dryRun===true,replayed:mutation.replayed===true}}finally{clearSettingsReadCache(pmRoot)}}}}export{createExtensionCommandSdk};
2
2
  //# sourceMappingURL=extension-command-context.js.map