@unbrained/pm-cli 2026.9.10 → 2026.9.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +53 -11
- package/dist/cli/command-namespaces.d.ts +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/error-guidance.d.ts +10 -0
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/extension-command-help.js +3 -3
- package/dist/cli/main.d.ts +4 -0
- package/dist/cli/main.js +2 -2
- package/dist/cli/option-values.d.ts +3 -0
- package/dist/cli/option-values.js +2 -0
- package/dist/cli/register-history-maintenance.js +2 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-mutation.d.ts +5 -0
- package/dist/cli/register-mutation.js +2 -16
- package/dist/cli/schema/registration.d.ts +4 -0
- package/dist/cli/schema/registration.js +16 -0
- package/dist/cli-bundle/bundle-manifest.json +156 -156
- package/dist/cli-bundle/chunks/{chunk-NKOYVKFM.js → chunk-2JAY4LFI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-I6XT3DLQ.js → chunk-3ZJDGTYC.js} +53 -53
- package/dist/cli-bundle/chunks/chunk-67H4PKQ5.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-EOCKPCEY.js → chunk-7H33WPDF.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7KF6HCRC.js +20 -0
- package/dist/cli-bundle/chunks/chunk-DEGRLB6Y.js +235 -0
- package/dist/cli-bundle/chunks/chunk-GKY655T7.js +6 -0
- package/dist/cli-bundle/chunks/chunk-I6VQUHK6.js +8 -0
- package/dist/cli-bundle/chunks/chunk-PTX2JRFR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-PYUITRSV.js → chunk-TAGDYARO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-X6POOZKD.js +29 -0
- package/dist/cli-bundle/chunks/{chunk-4SFBH77G.js → chunk-YU75JRTW.js} +156 -142
- package/dist/cli-bundle/chunks/{register-list-query-CUIW7SSE.js → register-list-query-KEZPDR6X.js} +6 -6
- package/dist/cli-bundle/chunks/register-mutation-HEXA3ZDM.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-XIZPLPQY.js → register-operations-TEZT65JF.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-JVGPCAIL.js → register-setup-IIL74WUG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZAWAL2CG.js → chunk-2BQ4JSJQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5CRND7UA.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-5PSYV3AT.js +164 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SL5YVVPV.js → chunk-7EKXAUKF.js} +53 -52
- package/dist/cli-bundle/focused-chunks/chunk-BIOWOU6S.js +30 -0
- package/dist/cli-bundle/focused-chunks/chunk-EIXGDI77.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GAKFECOQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-HFAW3FJQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-U5SHHU7E.js → chunk-IURELABV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KK7KSXUP.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZDNAWWQI.js → chunk-LWJBBM6X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MFVABYEU.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7N5MRONP.js → chunk-PERRTPIY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FHUARRMA.js → chunk-SDQOOL34.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-M36SF4GE.js → chunk-TTRB47KM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VWMP6W7Y.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-YNBACVQ2.js +2 -0
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +29 -29
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +42 -42
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +10 -10
- package/dist/core/history/digest.d.ts +12 -0
- package/dist/core/history/digest.js +2 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/history.d.ts +5 -3
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/operation-contract.d.ts +30 -0
- package/dist/core/history/operation-contract.js +2 -0
- package/dist/core/history/replay.d.ts +3 -2
- package/dist/core/history/replay.js +1 -1
- package/dist/core/history/tombstone.d.ts +3 -0
- package/dist/core/history/tombstone.js +2 -0
- package/dist/core/item/id.d.ts +8 -7
- package/dist/core/item/id.js +1 -1
- package/dist/core/output/mutation-projection.d.ts +1 -0
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/shared/command-line.d.ts +10 -0
- package/dist/core/shared/command-line.js +2 -0
- package/dist/core/shared/errors.d.ts +13 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-store.d.ts +5 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/telemetry/runtime.d.ts +1 -0
- package/dist/core/telemetry/runtime.js +2 -2
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +1 -1
- package/dist/sdk/cli-bootstrap.d.ts +2 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.d.ts +2 -0
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/command-line.d.ts +1 -6
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/completion.d.ts +2 -0
- package/dist/sdk/completion.js +26 -14
- package/dist/sdk/contracts.d.ts +2 -0
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +2 -2
- package/dist/sdk/governance.d.ts +3 -0
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/history/attestation-command.d.ts +22 -0
- package/dist/sdk/history/attestation-command.js +3 -0
- package/dist/sdk/history/attestation-contract.d.ts +103 -0
- package/dist/sdk/history/attestation-contract.js +2 -0
- package/dist/sdk/history/attestation-scan.d.ts +16 -0
- package/dist/sdk/history/attestation-scan.js +2 -0
- package/dist/sdk/history/attestation.d.ts +8 -0
- package/dist/sdk/history/attestation.js +2 -0
- package/dist/sdk/history/salvage.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +3 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/claim.d.ts +2 -0
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.d.ts +4 -0
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/task-composition.d.ts +2 -0
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/three-way.js +2 -2
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output-budget.d.ts +4 -10
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-session.d.ts +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.d.ts +3 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/types.d.ts +5 -1
- package/dist/types.js +1 -1
- package/docs/AGENT_UX_CONTRACTS.md +8 -0
- package/docs/ARCHITECTURE.md +7 -0
- package/docs/CLI_GRAMMAR.md +23 -0
- package/docs/HISTORY_ATTESTATION.md +164 -0
- package/docs/HISTORY_OPERATIONS.md +46 -0
- package/docs/HISTORY_RECOVERY.md +27 -2
- package/docs/LIFECYCLE_COMMANDS.md +19 -2
- package/docs/MERGE_SAFETY.md +64 -3
- package/docs/README.md +1 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +13 -0
- package/docs/WORKFLOW_POLICIES.md +47 -3
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +4 -4
- package/docs/generated/AGENT_COMMAND_SURFACE.md +5 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -0
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +10 -7
- package/marketplace.json +2 -2
- package/package.json +4 -4
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/README.md +31 -7
- package/packages/pm-governance-audit/extensions/governance-audit/index.ts +6 -3
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/extensions/guide-shell/runtime.ts +7 -19
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/README.md +9 -5
- package/packages/pm-search-advanced/extensions/search-advanced/index.ts +3 -2
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-74RGSPLL.js +0 -2
- package/dist/cli-bundle/chunks/chunk-7WIHZI2M.js +0 -5
- package/dist/cli-bundle/chunks/chunk-GLQMKUGP.js +0 -2
- package/dist/cli-bundle/chunks/chunk-MACGGTLQ.js +0 -29
- package/dist/cli-bundle/chunks/chunk-P6BEYAON.js +0 -8
- package/dist/cli-bundle/chunks/chunk-TSWEX72T.js +0 -20
- package/dist/cli-bundle/chunks/chunk-YKQTETJI.js +0 -235
- package/dist/cli-bundle/chunks/register-mutation-5F5CYUWZ.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-26O2WB73.js +0 -10
- package/dist/cli-bundle/focused-chunks/chunk-5YU75QLV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-B2CMFYRZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CRY5MHEI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-F6WKFXBT.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-OROZM37I.js +0 -177
- package/dist/cli-bundle/focused-chunks/chunk-PNGYYQY7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TPOL4TWE.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-XSMA2W6Q.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-ZJHYQOTM.js +0 -20
|
@@ -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]="abd6941f-b4cc-50e4-a64e-d0720d73cdba")}catch(e2){}})();import fs from"node:fs/promises";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{acquireLock}from"../lock/lock.js";import{writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{await fs.access(targetPath);return true}catch{return false}}function isErrno(error,code){return typeof error==="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){if(!warnings){return}if(!warnings.includes(warning)){warnings.push(warning)}}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){if(preferredFormat==="toon"){return["toon","json_markdown"]}if(preferredFormat==="json_markdown"){return["json_markdown","toon"]}return["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim();const exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0){return null}const normalizedId=normalizeItemId(rawId,idPrefix);const rawNormalizedId=normalizeRawItemId(rawId);const candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0);const entries=Object.entries(typeToFolder);const searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){for(const[type]of entries){for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);if(await fileExists(itemPath)){return{id:candidateId,type,itemPath,item_format:itemFormat}}}}}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes)){throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:false})}const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_document_invalid"){return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})}}throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);recordItemMetadataEnumeration(documents.length);return documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);recordItemMetadataEnumeration(documents.length);return documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:true,forceSourceScan:options.forceSourceScan});recordItemMetadataEnumeration(candidates.length);return candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder));const allIds=[];await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries){for(const ext of ITEM_FILE_EXTENSIONS){if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}}}catch{}}));return allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix);const ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));const scored=ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id);return scored}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder);const nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];if(suggestions.length>0){nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`)}return new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===true&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder;const located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located){throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder)}const releaseLock=await acquireLock(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,Boolean(params.force),params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const warnings=[];const{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings});const assigned=document.metadata.assignee?.trim();const assignedPrincipal=document.metadata.claim_principal?.trim()||assigned;const callerPrincipal=resolveClaimPrincipal(params.author);const governance=resolveGovernanceKnobs(params.settings);const hasOwnershipConflict=assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict);if(hasOwnershipConflict){if(governance.ownership_enforcement==="strict"){throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT)}if(governance.ownership_enforcement==="warn"){warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}}return{typeToFolder,located,originalRaw,document,warnings,releaseLock}}catch(error){await releaseLock();throw error}}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!=="object"||serviceWriteOverride.result===null){return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:false}}const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path==="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents==="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===true}}async function rollbackMutatedItemWrite(params){if(params.skipItemWrite){return}if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw);await fs.rm(params.effectiveTargetItemPath,{force:true});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}async function mutateItemWithDeferredHistoryContext(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder});const{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock}=prepared;try{const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames});const mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames});const mutation=await params.mutate(mutableDocument);if(params.skipNoop===true&&mutation.changedFields.length===0){return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]}}const historyContext=params.resolveHistoryContext?.();mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames});const workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op});const targetItemFormat="toon";const serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames});const targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder);const historyPath=getHistoryPath(params.pmRoot,located.id);const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter});const{effectiveTargetItemPath,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter);const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings=[];try{if(!skipItemWrite){await writeFileAtomic(effectiveTargetItemPath,effectiveSerializedAfter)}if(!skipItemWrite&&effectiveTargetItemPath!==located.itemPath){await fs.rm(located.itemPath)}const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath,originalItemPath:located.itemPath,originalRaw});throw error}if(!skipItemWrite){derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath,previousItemPath:located.itemPath,document:afterDocument})}}finally{await releaseDerivedIndexLock()}const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields});return{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...serviceWriteOverride.warnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force});const{located,originalRaw,document,warnings:parseWarnings,releaseLock}=prepared;try{const extensionFieldNames=resolveActiveExtensionFieldNames(void 0);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames});const workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"});const deletionTimestamp=nowIso();const tombstoneDocument=EMPTY_CANONICAL_DOCUMENT;const historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});const historyPath=getHistoryPath(params.pmRoot,located.id);const serviceDeleteOverride=await runActiveServiceOverride("item_store_delete",{op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});let effectiveItemPath=located.itemPath;let skipDelete=false;if(serviceDeleteOverride.handled&&typeof serviceDeleteOverride.result==="object"&&serviceDeleteOverride.result!==null){const overrideRecord=serviceDeleteOverride.result;if(typeof overrideRecord.item_path==="string"&&overrideRecord.item_path.trim().length>0){effectiveItemPath=overrideRecord.item_path}if(overrideRecord.skip_delete===true){skipDelete=true}}if(params.dryRun===true){return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...serviceDeleteOverride.warnings]}}const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings=[];try{if(!skipDelete){await fs.rm(effectiveItemPath)}try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){if(!skipDelete){await writeFileAtomic(effectiveItemPath,originalRaw)}throw error}if(!skipDelete){derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath,document:null})}}finally{await releaseDerivedIndexLock()}const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]});return{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...serviceDeleteOverride.warnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
|
|
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]="02383f73-64f0-5ffc-a802-f8ef2b3cc038")}catch(e2){}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{acquireLock}from"../lock/lock.js";import{writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{await fs.access(targetPath);return true}catch{return false}}function isErrno(error,code){return typeof error==="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){if(!warnings){return}if(!warnings.includes(warning)){warnings.push(warning)}}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){if(preferredFormat==="toon"){return["toon","json_markdown"]}if(preferredFormat==="json_markdown"){return["json_markdown","toon"]}return["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim();const exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0){return null}const normalizedId=normalizeItemId(rawId,idPrefix);const rawNormalizedId=normalizeRawItemId(rawId);const candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0);const entries=Object.entries(typeToFolder);const searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries){for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);if(await fileExists(itemPath)){matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}}}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes)){throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:false})}const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_document_invalid"){return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})}}throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);recordItemMetadataEnumeration(documents.length);return documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);recordItemMetadataEnumeration(documents.length);return documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:true,forceSourceScan:options.forceSourceScan});recordItemMetadataEnumeration(candidates.length);return candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder));const allIds=[];await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries){for(const ext of ITEM_FILE_EXTENSIONS){if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}}}catch{}}));return allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix);const ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));const scored=ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id);return scored}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder);const nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];if(suggestions.length>0){nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`)}return new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===true&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder;const located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located){throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder)}const releaseLock=await acquireLock(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,Boolean(params.force),params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const warnings=[];const{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings});const assigned=document.metadata.assignee?.trim();const assignedPrincipal=document.metadata.claim_principal?.trim()||assigned;const callerPrincipal=resolveClaimPrincipal(params.author);const governance=resolveGovernanceKnobs(params.settings);const hasOwnershipConflict=assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict);if(hasOwnershipConflict){if(governance.ownership_enforcement==="strict"){throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT)}if(governance.ownership_enforcement==="warn"){warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}}return{typeToFolder,located,originalRaw,document,warnings,releaseLock}}catch(error){await releaseLock();throw error}}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!=="object"||serviceWriteOverride.result===null){return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:false}}const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path==="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents==="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===true}}async function rollbackMutatedItemWrite(params){if(params.skipItemWrite){return}if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw);await fs.rm(params.effectiveTargetItemPath,{force:true});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder});const{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock}=prepared;try{const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames});const mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames});const mutation=await params.mutate(mutableDocument);if(params.skipNoop===true&&mutation.changedFields.length===0){return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]}}const historyContext=params.resolveHistoryContext?.();mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames});const workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op});const targetItemFormat="toon";const serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames});const targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder);const historyPath=getHistoryPath(params.pmRoot,located.id);const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter});const{effectiveTargetItemPath,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter);const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings=[];try{if(!skipItemWrite){await writeFileAtomic(effectiveTargetItemPath,effectiveSerializedAfter)}if(!skipItemWrite&&effectiveTargetItemPath!==located.itemPath){await fs.rm(located.itemPath)}const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath,originalItemPath:located.itemPath,originalRaw});throw error}if(!skipItemWrite){derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath,previousItemPath:located.itemPath,document:afterDocument})}}finally{await releaseDerivedIndexLock()}const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields});return{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...serviceWriteOverride.warnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force});const{located,originalRaw,document,warnings:parseWarnings,releaseLock}=prepared;try{const extensionFieldNames=resolveActiveExtensionFieldNames(void 0);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames});const workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"});const deletionTimestamp=nowIso();const tombstoneDocument=EMPTY_CANONICAL_DOCUMENT;const historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});const historyPath=getHistoryPath(params.pmRoot,located.id);const serviceDeleteOverride=await runActiveServiceOverride("item_store_delete",{op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});let effectiveItemPath=located.itemPath;let skipDelete=false;if(serviceDeleteOverride.handled&&typeof serviceDeleteOverride.result==="object"&&serviceDeleteOverride.result!==null){const overrideRecord=serviceDeleteOverride.result;if(typeof overrideRecord.item_path==="string"&&overrideRecord.item_path.trim().length>0){effectiveItemPath=overrideRecord.item_path}if(overrideRecord.skip_delete===true){skipDelete=true}}if(params.dryRun===true){return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...serviceDeleteOverride.warnings]}}const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings=[];try{if(!skipDelete){await fs.rm(effectiveItemPath)}try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){if(!skipDelete){await writeFileAtomic(effectiveItemPath,originalRaw)}throw error}if(!skipDelete){derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath,document:null})}}finally{await releaseDerivedIndexLock()}const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]});return{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...serviceDeleteOverride.warnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
|
|
2
2
|
//# sourceMappingURL=item-store.js.map
|
|
@@ -220,6 +220,7 @@ declare function buildOtelSpanRequest(activeCommand: ActiveTelemetryCommand, out
|
|
|
220
220
|
endpoint: string;
|
|
221
221
|
payload: unknown;
|
|
222
222
|
} | null;
|
|
223
|
+
/** Build a bounded, capture-level-sanitized result preview. Omit undefined object values as JSON does so optional fields cannot prevent completion telemetry. */
|
|
223
224
|
declare function summarizeResult(result: unknown, captureLevel?: Exclude<TelemetryCaptureLevel, "minimal">): Record<string, unknown>;
|
|
224
225
|
declare function buildCommandStartPayload(params: {
|
|
225
226
|
captureLevel: TelemetryCaptureLevel;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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"&¶ms.errorCategory.trim().length>0){return params.errorCategory}if(typeof params.errorCode==="string"&¶ms.errorCode.trim().length>0){return resolveTelemetryErrorCategory(params.errorCode)}return"unknown"}function resolveTelemetrySourceContext(globalOptions){const override=(process.env[PM_TELEMETRY_SOURCE_CONTEXT_ENV]??"").trim().toLowerCase();if(PM_TELEMETRY_SOURCE_CONTEXT_SET.has(override)){return{source_context:override,source_context_source:"env_override"}}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return{source_context:"test",source_context_source:"inferred"}}const nonTty=process.stdin.isTTY!==true||process.stdout.isTTY!==true;const ci=parseBooleanTrueLike(process.env.CI);const scriptLikeMode=globalOptions.json===true||globalOptions.quiet===true;if(nonTty||ci||scriptLikeMode){return{source_context:"automation",source_context_source:"inferred"}}return{source_context:"user",source_context_source:"inferred"}}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim();const agent=detectAgentIdentity({env:process.env,argv:process.argv});const hasAgentContext=agent.harness!==void 0||agent.model!==void 0;if(captureLevel==="minimal"){return{has_author_context:author.length>0,has_agent_context:hasAgentContext}}return{...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value===null||value===void 0){return value}if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1))}if(typeof value==="object"){const record=value;const normalized={};const sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys){normalized[key]=normalizeForHash(record[key],depth+1)}return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage==="string"?errorMessage:"","redacted");const normalizedCode=typeof errorCode2==="string"&&errorCode2.length>0?errorCode2:"unknown_error";const fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function telemetryDisabledByEnvironment(){return PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_TELEMETRY_DISABLED_ENV]??"").trim().toLowerCase())||PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_NO_TELEMETRY_ENV]??"").trim().toLowerCase())}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase())){return null}const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0){try{return new URL(directEndpoint).toString()}catch{return null}}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0){return null}try{const url=new URL(baseEndpoint);const normalizedPath=url.pathname.replace(/\/+$/,"");if(!normalizedPath.endsWith("/v1/traces")){url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`}return url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso);const epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs){if(typeof activeCommand.otel_traces_endpoint!=="string"||activeCommand.otel_traces_endpoint.trim().length===0||typeof activeCommand.otel_trace_id!=="string"||activeCommand.otel_trace_id.length===0||typeof activeCommand.otel_span_id!=="string"||activeCommand.otel_span_id.length===0){return null}const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim());const serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli";const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code);const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs)];if(typeof normalizedErrorCode==="string"){attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode))}if(typeof normalizedErrorCategory==="string"){attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory))}if(typeof outcome.error==="string"&&outcome.error.trim().length>0){attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)))}const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error==="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint:activeCommand.otel_traces_endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result===null||result===void 0){return{type:"nullish"}}if(typeof result==="string"){return{type:"string",value:sanitizeString(result,captureLevel)}}if(typeof result==="number"||typeof result==="boolean"){return{type:typeof result,value:result}}if(Array.isArray(result)){return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))}}if(typeof result==="object"){const record=result;const keys=Object.keys(record).sort((left,right)=>left.localeCompare(right));const sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize;sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params;const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const hashedArgs=hashCommandArgs(installationId,context.args);const commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`);const commandOptionsDigest=hashTelemetryValue(installationId,context.options);const globalOptionsDigest=hashTelemetryValue(installationId,context.global);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}}return{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params;const errorFingerprint=outcome.ok===false?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0;const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params;const attemptedArgHashes=hashCommandArgs(installationId,args);const attemptedCommandDigest=hashWithInstallationId(installationId,command);const attemptedOptionsDigest=hashTelemetryValue(installationId,options);const errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);let changed=false;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();changed=true}if(changed){await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days))}}async function enqueueTelemetryEvent(globalPmRoot,event){const queued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0};let serialized=JSON.stringify(queued);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:true,reason:"payload_size_exceeded",original_bytes:serialized.length}}};const trimmedQueued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0};serialized=JSON.stringify(trimmedQueued)}await withQueueMutation(async()=>{await appendLineAtomic(queuePath(globalPmRoot),serialized)})}function parseQueueLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&parsed.event&&typeof parsed.event==="object"&&typeof parsed.attempts==="number"&&(parsed.client_schema_version===void 0||typeof parsed.client_schema_version==="number"&&Number.isFinite(parsed.client_schema_version))){entries.push(parsed)}}catch{}}return entries}function nextRetryIso(attempts){const delay=Math.min(TELEMETRY_RETRY_BASE_DELAY_MS*2**Math.max(attempts-1,0),TELEMETRY_MAX_RETRY_DELAY_MS);return new Date(Date.now()+delay).toISOString()}function isDueForRetryAt(nextAttemptAfter){if(typeof nextAttemptAfter!=="string"||nextAttemptAfter.trim().length===0){return true}const dueAtMs=Date.parse(nextAttemptAfter);if(Number.isNaN(dueAtMs)){return true}return dueAtMs<=Date.now()}function isDueForRetry(entry){return isDueForRetryAt(entry.next_attempt_after)}function retentionCutoffMs(retentionDays){const normalizedDays=Number.isFinite(retentionDays)?Math.max(1,Math.trunc(retentionDays)):1;return Date.now()-normalizedDays*MILLISECONDS_PER_DAY}function isExpiredQueueEntry(entry,cutoffMs){const occurredAt=entry.event?.occurred_at;if(typeof occurredAt!=="string"||occurredAt.trim().length===0){return false}const occurredAtMs=Date.parse(occurredAt);if(Number.isNaN(occurredAtMs)){return false}return occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const serializedSize=JSON.stringify(entry).length;const oversized=serializedSize>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredQueueEntry(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}return{entries:retained,prunedCount}}async function rewriteQueue(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="18834273-7639-5a1e-b8ea-39a0ea945de1")}catch(e2){}})();import crypto from"node:crypto";import{spawn}from"node:child_process";import{mkdirSync,rmSync,statSync}from"node:fs";import{mkdir,readdir,rm,stat}from"node:fs/promises";import{request as httpRequest}from"node:http";import{request as httpsRequest}from"node:https";import os from"node:os";import path from"node:path";import{resolvePmPackageRootFromModule}from"../packages/root.js";import{isFileMissingError,appendLineAtomic,readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{resolveTelemetryErrorCategory}from"../shared/constants.js";import{nowIso}from"../shared/time.js";import{detectAgentIdentity,readAuthorEnvironment}from"../shared/author.js";import{resolveGlobalPmRoot}from"../store/paths.js";import{readSettings,writeSettings}from"../store/settings.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy,inferTelemetryErrorCode}from"./observability.js";const TELEMETRY_QUEUE_RELATIVE_PATH=path.join("runtime","telemetry","events.jsonl");const TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json");const TELEMETRY_OTEL_SPANS_RELATIVE_PATH=path.join("runtime","telemetry","otel-spans.jsonl");const TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE=8;const TELEMETRY_OTEL_SPANS_MAX_PENDING=500;const TELEMETRY_SCHEMA_VERSION=1;const TELEMETRY_CLIENT_SCHEMA_VERSION=1;const TELEMETRY_FLUSH_BATCH_SIZE=100;const TELEMETRY_MAX_RETRY_DELAY_MS=36e5;const TELEMETRY_RETRY_BASE_DELAY_MS=3e4;const TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS=2e4;const TELEMETRY_HTTP_TIMEOUT_MIN_MS=1e3;const TELEMETRY_HTTP_TIMEOUT_MAX_MS=25e3;const MILLISECONDS_PER_DAY=864e5;const TELEMETRY_MAX_EVENT_BYTES=65536;const TELEMETRY_SANITIZE_MAX_DEPTH=6;const TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS=20;const TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS=15;const TELEMETRY_RESULT_PREVIEW_MAX_BYTES=8192;const TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS=[25,50,100,200];const TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS=60*60*1e3;const TELEMETRY_FLUSH_LOCK_STALE_MS=6e4;const TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS=6e4;const OTEL_TRACES_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT";const OTEL_BASE_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_ENDPOINT";const OTEL_SERVICE_NAME_ENV="OTEL_SERVICE_NAME";const PM_TELEMETRY_DISABLED_ENV="PM_TELEMETRY_DISABLED";const PM_NO_TELEMETRY_ENV="PM_NO_TELEMETRY";const PM_TELEMETRY_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_OTEL_DISABLED_ENV="PM_TELEMETRY_OTEL_DISABLED";const PM_TELEMETRY_OTEL_DISABLED_VALUES=new Set(["1","true","yes","on"]);const PM_TELEMETRY_INLINE_FLUSH_ENV="PM_TELEMETRY_INLINE_FLUSH";const PM_TELEMETRY_FLUSH_CHILD_ENV="PM_TELEMETRY_FLUSH_CHILD";const PM_TELEMETRY_SOURCE_CONTEXT_ENV="PM_TELEMETRY_SOURCE_CONTEXT";const PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV="PM_TELEMETRY_HTTP_TIMEOUT_MS";const NATIVE_FETCH=globalThis.fetch;const PM_TELEMETRY_SOURCE_CONTEXT_VALUES=["user","automation","test","dogfood"];let _lastFlushPromise=Promise.resolve();let _queueMutationPromise=Promise.resolve();async function waitForPendingFlush(){await _lastFlushPromise;await _queueMutationPromise}const PM_TELEMETRY_SOURCE_CONTEXT_SET=new Set(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);const BOOLEAN_TRUE_VALUES=new Set(["1","true","yes","on"]);const PROCESS_SESSION_ID=crypto.randomUUID();const SENSITIVE_KEYWORDS=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"];const REDACTION_INPUT_KEYS=new Set(["literal","literals","regex","regexes","replacement","replacements"]);const SENSITIVE_INLINE_KEY_PATTERN="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)";const INLINE_SENSITIVE_ASSIGNMENT_PATTERN=new RegExp(`\\b(${SENSITIVE_INLINE_KEY_PATTERN})\\s*([:=])\\s*([^\\s,;]+)`,"giu");const INLINE_SENSITIVE_FLAG_PATTERN=new RegExp(`(--${SENSITIVE_INLINE_KEY_PATTERN})(=|\\s+)([^\\s,;]+)`,"giu");const ABSOLUTE_PATH_TOKEN_PATTERN=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g;const BEARER_TOKEN_PATTERN=/bearer\s+[a-z0-9._=-]+/giu;const PRIVATE_IP_PATTERN=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function queuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_QUEUE_RELATIVE_PATH)}function otelSpansQueuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_OTEL_SPANS_RELATIVE_PATH)}function telemetryRuntimeDirectory(globalPmRoot){return path.dirname(queuePath(globalPmRoot))}function runtimeStatePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH)}function flushLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.lock")}function flushSpawnLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.spawn.lock")}function telemetryFlushRunnerPath(){return path.join(resolvePmPackageRootFromModule(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function shouldFlushInline(){if(parseBooleanTrueLike(process.env[PM_TELEMETRY_INLINE_FLUSH_ENV])){return true}if(parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])){return true}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"}async function readRuntimeState(globalPmRoot){const raw=await readFileIfExists(runtimeStatePath(globalPmRoot));if(!raw||raw.trim().length===0){return{}}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return{}}return parsed}catch{return{}}}async function writeRuntimeState(globalPmRoot,patch){try{const current=await readRuntimeState(globalPmRoot);const next={...current,...patch};const normalized=Object.fromEntries(Object.entries(next).filter(([,value])=>value!==void 0).sort((left,right)=>left[0].localeCompare(right[0])));await writeFileAtomic(runtimeStatePath(globalPmRoot),`${JSON.stringify(normalized,null,2)}
|
|
2
|
+
`)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_");const tokens=normalized.split("_").filter(token=>token.length>0);return REDACTION_INPUT_KEYS.has(normalized)||SENSITIVE_KEYWORDS.some(keyword=>normalized===keyword||normalized.endsWith(`_${keyword}`)||tokens.includes(keyword))}function redactInlineSensitiveAssignments(input){const withoutAssignments=input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`);return withoutAssignments.replaceAll(INLINE_SENSITIVE_FLAG_PATTERN,(_match,flag,delimiter)=>`${flag}${delimiter}[redacted]`)}function redactAbsolutePathTokens(input){return input.replaceAll(ABSOLUTE_PATH_TOKEN_PATTERN,(_match,prefix)=>`${prefix}[redacted_path]`)}function isAsciiLetterOrDigitCode(code){const isUpper=code>=65&&code<=90;const isLower=code>=97&&code<=122;const isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character){return false}const code=character.charCodeAt(0);if(isAsciiLetterOrDigitCode(code)){return true}return character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1){return false}const localPart=token.slice(0,atIndex);const domainPart=token.slice(atIndex+1);const lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1){return false}if(domainPart.length-(lastDot+1)<2){return false}for(const character of localPart){if(!isEmailLocalCharacter(character)){return false}}for(const character of domainPart){if(!isEmailDomainCharacter(character)){return false}}return true}function redactEmailTokens(input){let redacted="";let cursor=0;while(cursor<input.length){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;while(start>=cursor&&isEmailLocalCharacter(input[start])){start-=1}start+=1;let end=atIndex+1;while(end<input.length&&isEmailDomainCharacter(input[end])){end+=1}const candidate=input.slice(start,end);if(looksLikeEmailToken(candidate)){redacted+=input.slice(cursor,start);redacted+="[redacted_email]";cursor=end;continue}redacted+=input.slice(cursor,atIndex+1);cursor=atIndex+1}return redacted}function sanitizeCommonSensitiveTokens(input){const withoutEmails=redactEmailTokens(input);const withoutBearer=withoutEmails.replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]");return withoutBearer.replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>512){return`${withoutAbsolutePaths.slice(0,509)}...`}return withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input);const withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens);const withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets);const trimmed=withoutAbsolutePaths.trim();if(trimmed.startsWith("/")&&trimmed.length>1){return"[redacted_path]"}if(withoutAbsolutePaths.length>2048){return`${withoutAbsolutePaths.slice(0,2045)}...`}return withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){if(captureLevel==="max"){return sanitizeStringMax(input)}return sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint)){return"[redacted]"}if(value===null||value===void 0){return value}if(typeof value==="string"){return sanitizeString(value,captureLevel)}if(typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>sanitizeValue(entry,void 0,captureLevel,depth+1))}if(typeof value==="object"){const record=value;const sanitized={};for(const[key,nested]of Object.entries(record)){sanitized[key]=sanitizeValue(nested,key,captureLevel,depth+1)}return sanitized}return String(value)}function sanitizeCommandArgs(args,captureLevel="redacted"){const sanitized=[];let nextIsSensitiveValue=false;for(const rawArg of args){const arg=sanitizeString(rawArg,captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]");nextIsSensitiveValue=false;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2);const delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex);const value=withoutPrefix.slice(delimiterIndex+1);if(isSensitiveKey(key)){sanitized.push(`--${key}=[redacted]`)}else{sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`)}continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`);nextIsSensitiveValue=true;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();if(normalized==="minimal"||normalized==="redacted"||normalized==="max"){return normalized}return"redacted"}function parseBooleanTrueLike(value){return BOOLEAN_TRUE_VALUES.has((value??"").trim().toLowerCase())}function resolveTelemetryHttpTimeoutMs(){const rawConfigured=process.env[PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV]?.trim();if(!rawConfigured){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}const configured=Number(rawConfigured);if(!Number.isFinite(configured)){return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}return Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured)))}async function postTelemetryJson(endpoint,headers,body){const url=new URL(endpoint);if(globalThis.fetch!==NATIVE_FETCH){const controller=new AbortController;let timeout;const deadline=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>{controller.abort();reject(new Error("telemetry_http_timeout"))},resolveTelemetryHttpTimeoutMs())});try{const response=await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline]);return response.status}finally{clearTimeout(timeout)}}const request=url.protocol==="https:"?httpsRequest:url.protocol==="http:"?httpRequest:void 0;if(!request){throw new Error(`telemetry_http_protocol_unsupported_${url.protocol}`)}return new Promise((resolve,reject)=>{const timeoutMs=resolveTelemetryHttpTimeoutMs();const requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)};const clientRequest=request(url,requestOptions,response=>{response.once("error",reject);response.once("end",()=>resolve(response.statusCode));response.resume()});clientRequest.once("error",reject);clientRequest.end(body)})}function normalizePmVersion(value){const trimmed=typeof value==="string"?value.trim():"";return trimmed.length>0?trimmed:"0.0.0"}function normalizeTelemetryErrorCode(value){const normalized=value?.trim();return normalized&&normalized.length>0?normalized:void 0}function normalizeTelemetryExitCode(exitCode,ok){if(Number.isFinite(exitCode)){return Math.max(0,Math.trunc(exitCode))}return ok?0:1}function normalizeTelemetryErrorCategory(params){if(params.ok){return void 0}if(typeof params.errorCategory==="string"&¶ms.errorCategory.trim().length>0){return params.errorCategory}if(typeof params.errorCode==="string"&¶ms.errorCode.trim().length>0){return resolveTelemetryErrorCategory(params.errorCode)}return"unknown"}function resolveTelemetrySourceContext(globalOptions){const override=(process.env[PM_TELEMETRY_SOURCE_CONTEXT_ENV]??"").trim().toLowerCase();if(PM_TELEMETRY_SOURCE_CONTEXT_SET.has(override)){return{source_context:override,source_context_source:"env_override"}}const nodeEnv=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST==="string"||typeof process.env.VITEST_WORKER_ID==="string"||nodeEnv==="test"){return{source_context:"test",source_context_source:"inferred"}}const nonTty=process.stdin.isTTY!==true||process.stdout.isTTY!==true;const ci=parseBooleanTrueLike(process.env.CI);const scriptLikeMode=globalOptions.json===true||globalOptions.quiet===true;if(nonTty||ci||scriptLikeMode){return{source_context:"automation",source_context_source:"inferred"}}return{source_context:"user",source_context_source:"inferred"}}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim();const agent=detectAgentIdentity({env:process.env,argv:process.argv});const hasAgentContext=agent.harness!==void 0||agent.model!==void 0;if(captureLevel==="minimal"){return{has_author_context:author.length>0,has_agent_context:hasAgentContext}}return{...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value===null||value===void 0){return value}if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH){return"[depth_truncated]"}if(Array.isArray(value)){return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1))}if(typeof value==="object"){const record=value;const normalized={};const sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys){normalized[key]=normalizeForHash(record[key],depth+1)}return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage==="string"?errorMessage:"","redacted");const normalizedCode=typeof errorCode2==="string"&&errorCode2.length>0?errorCode2:"unknown_error";const fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function telemetryDisabledByEnvironment(){return PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_TELEMETRY_DISABLED_ENV]??"").trim().toLowerCase())||PM_TELEMETRY_DISABLED_VALUES.has((process.env[PM_NO_TELEMETRY_ENV]??"").trim().toLowerCase())}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase())){return null}const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0){try{return new URL(directEndpoint).toString()}catch{return null}}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0){return null}try{const url=new URL(baseEndpoint);const normalizedPath=url.pathname.replace(/\/+$/,"");if(!normalizedPath.endsWith("/v1/traces")){url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`}return url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso);const epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs){if(typeof activeCommand.otel_traces_endpoint!=="string"||activeCommand.otel_traces_endpoint.trim().length===0||typeof activeCommand.otel_trace_id!=="string"||activeCommand.otel_trace_id.length===0||typeof activeCommand.otel_span_id!=="string"||activeCommand.otel_span_id.length===0){return null}const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim());const serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli";const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code);const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs)];if(typeof normalizedErrorCode==="string"){attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode))}if(typeof normalizedErrorCategory==="string"){attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory))}if(typeof outcome.error==="string"&&outcome.error.trim().length>0){attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)))}const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error==="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint:activeCommand.otel_traces_endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result===null||result===void 0){return{type:"nullish"}}if(typeof result==="string"){return{type:"string",value:sanitizeString(result,captureLevel)}}if(typeof result==="number"||typeof result==="boolean"){return{type:typeof result,value:result}}if(Array.isArray(result)){return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))}}if(typeof result==="object"){const record=result;const keys=Object.keys(record).sort((left,right)=>left.localeCompare(right));const sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);if(sanitizedValue===void 0)continue;const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize;sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params;const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);const hashedArgs=hashCommandArgs(installationId,context.args);const commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`);const commandOptionsDigest=hashTelemetryValue(installationId,context.options);const globalOptionsDigest=hashTelemetryValue(installationId,context.global);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}}return{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params;const errorFingerprint=outcome.ok===false?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0;const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params;const attemptedArgHashes=hashCommandArgs(installationId,args);const attemptedCommandDigest=hashWithInstallationId(installationId,command);const attemptedOptionsDigest=hashTelemetryValue(installationId,options);const errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage);const authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);if(captureLevel==="minimal"){return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}}return{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===true,stdout_tty:process.stdout.isTTY===true}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);let changed=false;if(settings.telemetry.installation_id.trim().length===0){settings.telemetry.installation_id=crypto.randomUUID();changed=true}if(changed){await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days))}}async function enqueueTelemetryEvent(globalPmRoot,event){const queued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0};let serialized=JSON.stringify(queued);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:true,reason:"payload_size_exceeded",original_bytes:serialized.length}}};const trimmedQueued={client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0};serialized=JSON.stringify(trimmedQueued)}await withQueueMutation(async()=>{await appendLineAtomic(queuePath(globalPmRoot),serialized)})}function parseQueueLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&parsed.event&&typeof parsed.event==="object"&&typeof parsed.attempts==="number"&&(parsed.client_schema_version===void 0||typeof parsed.client_schema_version==="number"&&Number.isFinite(parsed.client_schema_version))){entries.push(parsed)}}catch{}}return entries}function nextRetryIso(attempts){const delay=Math.min(TELEMETRY_RETRY_BASE_DELAY_MS*2**Math.max(attempts-1,0),TELEMETRY_MAX_RETRY_DELAY_MS);return new Date(Date.now()+delay).toISOString()}function isDueForRetryAt(nextAttemptAfter){if(typeof nextAttemptAfter!=="string"||nextAttemptAfter.trim().length===0){return true}const dueAtMs=Date.parse(nextAttemptAfter);if(Number.isNaN(dueAtMs)){return true}return dueAtMs<=Date.now()}function isDueForRetry(entry){return isDueForRetryAt(entry.next_attempt_after)}function retentionCutoffMs(retentionDays){const normalizedDays=Number.isFinite(retentionDays)?Math.max(1,Math.trunc(retentionDays)):1;return Date.now()-normalizedDays*MILLISECONDS_PER_DAY}function isExpiredQueueEntry(entry,cutoffMs){const occurredAt=entry.event?.occurred_at;if(typeof occurredAt!=="string"||occurredAt.trim().length===0){return false}const occurredAtMs=Date.parse(occurredAt);if(Number.isNaN(occurredAtMs)){return false}return occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const serializedSize=JSON.stringify(entry).length;const oversized=serializedSize>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredQueueEntry(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}return{entries:retained,prunedCount}}async function rewriteQueue(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
3
3
|
`:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(queuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}function isRetryableQueueRewriteError(error){if(typeof error!=="object"||error===null||!("code"in error)){return false}const code=error.code;return code==="EACCES"||code==="EBUSY"||code==="EPERM"}function sleep(milliseconds){return new Promise(resolve=>{setTimeout(resolve,milliseconds)})}async function enqueuePendingOtelSpan(globalPmRoot,request){const pending={id:crypto.randomUUID(),endpoint:request.endpoint,payload:request.payload,enqueued_at:nowIso(),attempts:0};const serialized=JSON.stringify(pending);if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){return}await withQueueMutation(async()=>{await appendLineAtomic(otelSpansQueuePath(globalPmRoot),serialized)})}function backfillPendingOtelSpanId(entry){const material=JSON.stringify([entry.endpoint,entry.enqueued_at,entry.payload]);return crypto.createHash("sha256").update(material).digest("hex").slice(0,32)}function parsePendingOtelSpanLines(raw){const entries=[];for(const line of raw.split("\n")){const trimmed=line.trim();if(trimmed.length===0){continue}try{const parsed=JSON.parse(trimmed);if(parsed&&typeof parsed==="object"&&typeof parsed.endpoint==="string"&&parsed.endpoint.trim().length>0&&"payload"in parsed&&typeof parsed.attempts==="number"&&Number.isFinite(parsed.attempts)){if(typeof parsed.id!=="string"||parsed.id.length===0){parsed.id=backfillPendingOtelSpanId(parsed)}entries.push(parsed)}}catch{}}return entries}function isExpiredPendingOtelSpan(entry,cutoffMs){if(typeof entry.enqueued_at!=="string"||entry.enqueued_at.trim().length===0){return false}const enqueuedAtMs=Date.parse(entry.enqueued_at);if(Number.isNaN(enqueuedAtMs)){return false}return enqueuedAtMs<cutoffMs}function prunePendingOtelSpans(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays);const retained=[];let prunedCount=0;for(const entry of entries){const oversized=JSON.stringify(entry).length>TELEMETRY_MAX_EVENT_BYTES;if(oversized||isExpiredPendingOtelSpan(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}if(retained.length>TELEMETRY_OTEL_SPANS_MAX_PENDING){const overflow=retained.length-TELEMETRY_OTEL_SPANS_MAX_PENDING;prunedCount+=overflow;return{entries:retained.slice(overflow),prunedCount}}return{entries:retained,prunedCount}}async function rewritePendingOtelSpans(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join("\n");const contents=serialized.length>0?`${serialized}
|
|
4
4
|
`:"";for(let attempt=0;;attempt+=1){try{await writeFileAtomic(otelSpansQueuePath(globalPmRoot),contents);return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error)){throw error}await sleep(retryDelay)}}}async function reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates){return withQueueMutation(async()=>{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));const current=raw===null?[]:parsePendingOtelSpanLines(raw);const reconciled=[];for(const entry of current){if(succeededIds.has(entry.id)){continue}const failure=failedUpdates.get(entry.id);reconciled.push(failure?{...entry,attempts:failure.attempts,next_attempt_after:failure.next_attempt_after}:entry)}const{entries:retained}=prunePendingOtelSpans(reconciled,retentionDays);await rewritePendingOtelSpans(globalPmRoot,retained);return retained.length})}async function flushPendingOtelSpans(globalPmRoot,retentionDays){const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{pending_otel_spans:0});return}const entries=parsePendingOtelSpanLines(raw);const{entries:retained,prunedCount}=prunePendingOtelSpans(entries,retentionDays);const due=retained.filter(entry=>isDueForRetryAt(entry.next_attempt_after)).slice(0,TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE);if(due.length===0){const remaining2=prunedCount>0?await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,new Set,new Map):retained.length;await writeRuntimeState(globalPmRoot,{pending_otel_spans:remaining2});return}const attemptTime=nowIso();const succeededIds=new Set;const failedUpdates=new Map;let succeededCount=0;let lastError;await Promise.all(due.map(async span=>{try{const status=await postTelemetryJson(span.endpoint,{"content-type":"application/json"},JSON.stringify(span.payload));if(status<200||status>=300){throw new Error(`local_otel_export_http_${status}`)}succeededIds.add(span.id);succeededCount+=1}catch(error){lastError=error instanceof Error?sanitizeString(error.message,"redacted"):"local_otel_export_failed";const nextAttempts=span.attempts+1;failedUpdates.set(span.id,{attempts:nextAttempts,next_attempt_after:nextRetryIso(nextAttempts)})}}));const remaining=await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates);const statePatch={pending_otel_spans:remaining,last_otel_attempt_at:attemptTime};if(succeededCount>0){statePatch.last_otel_success_at=attemptTime}if(lastError!==void 0){statePatch.last_otel_failure_at=attemptTime;statePatch.last_otel_failure_error=lastError}else if(remaining===0){statePatch.last_otel_failure_at=void 0;statePatch.last_otel_failure_error=void 0}await writeRuntimeState(globalPmRoot,statePatch)}async function flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays){try{await flushQueue(globalPmRoot,endpoint,retentionDays)}catch{}try{await flushPendingOtelSpans(globalPmRoot,retentionDays)}catch{}}async function cleanupTelemetryQueueTempOrphans(globalPmRoot,maxAgeMs=TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS){try{const dirPath=telemetryRuntimeDirectory(globalPmRoot);const entries=await readdir(dirPath,{withFileTypes:true});const cutoffMs=Date.now()-Math.max(0,maxAgeMs);await Promise.all(entries.filter(entry=>entry.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(entry.name)).map(async entry=>{const candidate=path.join(dirPath,entry.name);const candidateStats=await stat(candidate);if(candidateStats.mtimeMs<cutoffMs){await rm(candidate,{force:true})}}))}catch{}}async function withQueueMutation(operation){const run=_queueMutationPromise.catch(()=>{}).then(operation);_queueMutationPromise=run.catch(()=>{});return run}async function readCurrentQueueEntries(globalPmRoot){const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){return[]}return parseQueueLines(raw)}async function removeFlushedEntriesFromCurrentQueue(globalPmRoot,flushedIds,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const remaining=retainedEntries.filter(entry=>!flushedIds.has(entry.event.event_id));await rewriteQueue(globalPmRoot,remaining);return remaining})}async function markFailedEntriesInCurrentQueue(globalPmRoot,failedIds,attemptTime,retentionDays){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot);const{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays);const retried=retainedEntries.map(entry=>{if(!failedIds.has(entry.event.event_id)){return entry}const attempts=entry.attempts+1;return{...entry,attempts,last_attempt_at:attemptTime,next_attempt_after:nextRetryIso(attempts)}});await rewriteQueue(globalPmRoot,retried);return retried})}async function flushQueue(globalPmRoot,endpoint,retentionDays){await cleanupTelemetryQueueTempOrphans(globalPmRoot);const normalizedEndpoint=endpoint.trim();if(normalizedEndpoint.length===0){return}const raw=await readFileIfExists(queuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const queueEntries=parseQueueLines(raw);if(queueEntries.length===0){await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const{entries:retainedEntries,prunedCount}=pruneExpiredQueueEntries(queueEntries,retentionDays);if(retainedEntries.length===0){await rewriteQueue(globalPmRoot,[]);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:0});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){if(prunedCount>0){await rewriteQueue(globalPmRoot,retainedEntries)}await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retainedEntries.length});return}const dueIds=new Set(dueEntries.map(entry=>entry.event.event_id));const attemptTime=nowIso();const requestHeaders={"content-type":"application/json"};const ingestKey=process.env.PM_TELEMETRY_INGEST_KEY?.trim();if(ingestKey){requestHeaders["x-pm-telemetry-key"]=ingestKey}try{const status=await postTelemetryJson(normalizedEndpoint,requestHeaders,JSON.stringify({schema_version:TELEMETRY_SCHEMA_VERSION,events:dueEntries.map(entry=>entry.event)}));if(status<200||status>=300){throw new Error(`telemetry_flush_http_${status}`)}}catch(error){const retried=await markFailedEntriesInCurrentQueue(globalPmRoot,dueIds,attemptTime,retentionDays);const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:retried.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage});return}try{const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,dueIds,retentionDays);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:remaining.length,last_attempted_flush_at:attemptTime,last_successful_flush_at:attemptTime,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(error){const errorMessage=(()=>{if(error instanceof Error){return sanitizeString(error.message,"redacted")}return"telemetry_flush_failed"})();const currentEntries=await readCurrentQueueEntries(globalPmRoot).catch(()=>retainedEntries);await writeRuntimeState(globalPmRoot,{endpoint:normalizedEndpoint,queue_entries:currentEntries.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage})}}async function acquireTelemetryFlushLock(globalPmRoot){const lockPath=flushLockPath(globalPmRoot);await mkdir(path.dirname(lockPath),{recursive:true});try{await mkdir(lockPath);return true}catch(error){if(typeof error!=="object"||error===null||!("code"in error)||error.code!=="EEXIST"){throw error}}try{const lockStats=await stat(lockPath);if(Date.now()-lockStats.mtimeMs<TELEMETRY_FLUSH_LOCK_STALE_MS){return false}await rm(lockPath,{recursive:true,force:true});await mkdir(lockPath);return true}catch{return false}}function isFreshDirectoryLock(lockPath,staleMs){try{return Date.now()-statSync(lockPath).mtimeMs<staleMs}catch{return false}}function removeDirectoryLockBestEffort(lockPath){try{rmSync(lockPath,{recursive:true,force:true})}catch{}}function errorCode(error){if(typeof error!=="object"||error===null||!("code"in error)){return void 0}const code=error.code;return typeof code==="string"?code:void 0}function createDirectoryLock(lockPath){try{mkdirSync(lockPath);return true}catch(error){const code=errorCode(error);if(code==="EEXIST"){return false}if(!isFileMissingError(error)){return false}}try{mkdirSync(path.dirname(lockPath),{recursive:true});mkdirSync(lockPath);return true}catch{return false}}function acquireTelemetryFlushSpawnGate(globalPmRoot){if(isFreshDirectoryLock(flushLockPath(globalPmRoot),TELEMETRY_FLUSH_LOCK_STALE_MS)){return false}const lockPath=flushSpawnLockPath(globalPmRoot);try{if(Date.now()-statSync(lockPath).mtimeMs<TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS){return false}removeDirectoryLockBestEffort(lockPath)}catch(error){if(!isFileMissingError(error)){return false}}return createDirectoryLock(lockPath)}function releaseTelemetryFlushSpawnGate(globalPmRoot){removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot))}const _testOnly={acquireTelemetryFlushSpawnGate,acquireTelemetryFlushLock,buildAuthorContextPayloadFields,buildCommandErrorPayload,buildCommandFinishPayload,buildCommandStartPayload,buildOtelSpanRequest,createDirectoryLock,enqueuePendingOtelSpan,enqueueTelemetryEvent,errorCode,flushPendingOtelSpans,flushQueue,flushQueueWithProcessLock,flushTelemetryArtifacts,hashTelemetryErrorFingerprint,hashTelemetryValue,isEmailDomainCharacter,isEmailLocalCharacter,isExpiredPendingOtelSpan,isExpiredQueueEntry,isFreshDirectoryLock,isDueForRetry,isDueForRetryAt,isRetryableQueueRewriteError,looksLikeEmailToken,otelSpansQueuePath,parseBooleanTrueLike,postTelemetryJson,parsePendingOtelSpanLines,prunePendingOtelSpans,reconcilePendingOtelSpansAfterFlush,retentionCutoffMs,resolveOtelTracesEndpoint,resolveTelemetryHttpTimeoutMs,rewritePendingOtelSpans,normalizeForHash,normalizeCaptureLevel,normalizePmVersion,normalizeTelemetryErrorCategory,normalizeTelemetryErrorCode,normalizeTelemetryExitCode,parseQueueLines,pruneExpiredQueueEntries,readRuntimeState,readCurrentQueueEntries,releaseTelemetryFlushSpawnGate,removeFlushedEntriesFromCurrentQueue,removeDirectoryLockBestEffort,resolveTelemetrySourceContext,rewriteQueue,sanitizeCommandArgs,sanitizeStringMax,sanitizeStringRedacted,sanitizeValue,scheduleTelemetryFlush,shouldFlushInline,sleep,summarizeResult,telemetryFlushRunnerPath,withQueueMutation,flushLockPath,flushSpawnLockPath,runtimeStatePath,writeRuntimeState};async function flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays){const acquired=await acquireTelemetryFlushLock(globalPmRoot);releaseTelemetryFlushSpawnGate(globalPmRoot);if(!acquired){return}try{await flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)}finally{try{await rm(flushLockPath(globalPmRoot),{recursive:true,force:true})}catch{}}}function scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays){if(shouldFlushInline()){const previousFlush=_lastFlushPromise;const nextFlush=flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays);_lastFlushPromise=Promise.allSettled([previousFlush,nextFlush]).then(()=>{});return}try{const acquiredSpawnGate=acquireTelemetryFlushSpawnGate(globalPmRoot);if(!acquiredSpawnGate){return}const child=spawn(process.execPath,[telemetryFlushRunnerPath()],{detached:true,stdio:"ignore",cwd:os.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:globalPmRoot,[PM_TELEMETRY_FLUSH_CHILD_ENV]:"1"}});child.on("error",()=>{releaseTelemetryFlushSpawnGate(globalPmRoot)});child.unref()}catch{releaseTelemetryFlushSpawnGate(globalPmRoot)}}async function flushTelemetryQueueNow(globalPmRoot=resolveGlobalPmRoot(process.cwd())){if(telemetryDisabledByEnvironment()){return}try{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const{endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);await flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays)}catch{}}async function startTelemetryCommand(context){if(telemetryDisabledByEnvironment()){return null}if(context.command==="telemetry"&&context.args.some(token=>token.trim().toLowerCase()==="clear")){return null}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return null}const captureLevel=normalizeCaptureLevel(settings.telemetry.capture_level);const{installationId,endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const otelTracesEndpoint=resolveOtelTracesEndpoint();const occurredAt=nowIso();const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_start",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:context.command,payload:buildCommandStartPayload({captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId})};await enqueueTelemetryEvent(globalPmRoot,event);scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays);const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command);return{started_at:occurredAt,started_at_ms:Date.now(),command:context.command,command_taxonomy:commandTaxonomy,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,installation_id:installationId,pm_root_hash:pmRootHash,cwd_hash:cwdHash,endpoint,retention_days:retentionDays,global_pm_root:globalPmRoot,capture_level:captureLevel,otel_traces_endpoint:otelTracesEndpoint??void 0,otel_trace_id:otelTracesEndpoint?crypto.randomBytes(16).toString("hex"):void 0,otel_span_id:otelTracesEndpoint?crypto.randomBytes(8).toString("hex"):void 0}}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!activeCommand){return}try{const finishedAt=nowIso();const durationMs=Math.max(0,Date.now()-activeCommand.started_at_ms);const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:outcome.ok,errorCode:outcome.error_code,errorMessage:outcome.error,exitCode:outcome.exit_code}));const normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category});const normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok);const commandResolution=outcome.command_resolution??deriveTelemetryCommandResolution({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=outcome.resolution_stage??"execute";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_finish",occurred_at:finishedAt,installation_id:activeCommand.installation_id,session_id:PROCESS_SESSION_ID,command:activeCommand.command,payload:buildCommandFinishPayload({captureLevel:activeCommand.capture_level,pmVersion:activeCommand.pm_version,sourceContext:{source_context:activeCommand.source_context,source_context_source:activeCommand.source_context_source},outcome,durationMs,startedAt:activeCommand.started_at,command:activeCommand.command,installationId:activeCommand.installation_id,commandTaxonomy:activeCommand.command_taxonomy,exitCode:normalizedExitCode,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,commandResolution,resolutionStage})};await enqueueTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs);if(otelRequest){await enqueuePendingOtelSpan(activeCommand.global_pm_root,otelRequest)}scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(telemetryDisabledByEnvironment()){return}try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled){return}const captureLevel=normalizeCaptureLevel(settings.telemetry.capture_level);const{installationId,endpoint,retentionDays}=await ensureInstallationId(globalPmRoot);const pmVersion=normalizePmVersion(context.pm_version);const sourceContext=resolveTelemetrySourceContext(context.global);const pmRootHash=hashWithInstallationId(installationId,context.pm_root);const cwdHash=hashWithInstallationId(installationId,process.cwd());const occurredAt=nowIso();const normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:false,errorCode:context.error_code,errorMessage:context.error_message,exitCode:context.exit_code}));const normalizedErrorCategory=context.error_category??resolveTelemetryErrorCategory(normalizedErrorCode);const normalizedExitCode=normalizeTelemetryExitCode(context.exit_code,false);const normalizedCommand=context.command.trim().length>0?context.command:"<unknown>";const commandTaxonomy=deriveTelemetryCommandTaxonomy(normalizedCommand);const commandResolution=context.command_resolution??deriveTelemetryCommandResolution({ok:false,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory});const resolutionStage=context.resolution_stage??"unknown";const event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_error",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:sanitizeString(normalizedCommand,"redacted"),payload:buildCommandErrorPayload({captureLevel,pmVersion,sourceContext,command:normalizedCommand,commandTaxonomy,commandResolution,resolutionStage,args:context.args,options:context.options,pmRootHash,cwdHash,installationId,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,exitCode:normalizedExitCode,errorMessage:context.error_message})};await enqueueTelemetryEvent(globalPmRoot,event);scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush};
|
|
5
5
|
//# sourceMappingURL=runtime.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4f7274c6-547e-5590-b7c9-a4d6418bf860")}catch(e2){}})();import{renderPmCommand}from"../command-line.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";function normalizeMissingFlag(label){const match=label.trim().match(/--[a-z0-9][a-z0-9_-]*/i);return match?.[0]?.replaceAll("_","-").toLowerCase()}function resolveRecoveryCommandName(invocationArgv){if(!Array.isArray(invocationArgv)||invocationArgv.length===0){return void 0}return parseBootstrapCommandName(invocationArgv)}function resolveMissingOptionPlaceholder(commandName,missingLabel){const flag=normalizeMissingFlag(missingLabel);if(!flag)return void 0;const contract=resolveSubcommandFlagContractsForCommand(commandName).find(entry=>entry.flag===flag||entry.aliases?.includes(flag));if(!contract)return"<value>";if(contract.value_type==="boolean"){return null}return`<${contract.value_name??"value"}>`}function renderMissingOptionRetry(invocationArgv,commandName,missingLabels){const retry=[...invocationArgv];const terminatorIndex=retry.indexOf("--");let insertionIndex=terminatorIndex<0?retry.length:terminatorIndex;for(const label of missingLabels){const flag=normalizeMissingFlag(label);if(!flag||retry.slice(0,insertionIndex).some(token=>token===flag||token.startsWith(`${flag}=`))){continue}const placeholder=resolveMissingOptionPlaceholder(commandName,flag);const recoveredOption=placeholder?[flag,placeholder]:[flag];retry.splice(insertionIndex,0,...recoveredOption);insertionIndex+=recoveredOption.length}return retry.length===invocationArgv.length?void 0:renderPmCommand(retry)}export{renderMissingOptionRetry,resolveMissingOptionPlaceholder,resolveRecoveryCommandName};
|
|
2
2
|
//# sourceMappingURL=command-recovery.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3fa186e5-1c33-5761-87c5-3ca7b95ab501")}catch(e2){}})();import{findBootstrapCommandTokenIndex}from"../cli-contracts/bootstrap-command-scanner.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";const ITEM_ID_ALIAS_COMMANDS=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]);const ITEM_ID_ALIAS_SUBCOMMANDS=new Map([["files","discover"],["item","complete"]]);const TRAILING_POSITIONAL_COUNTS=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function supportsItemIdAlias(commandName){const normalized=resolvePmCommandOperation(commandName?.trim().toLowerCase()??"");return ITEM_ID_ALIAS_COMMANDS.has(normalized)||ITEM_ID_ALIAS_SUBCOMMANDS.has(normalized)}function resolveNamespacedItemAddressIndex(argv,commandIndex,commandName){const fallback=ITEM_ID_ALIAS_COMMANDS.has(commandName)?commandIndex+1:void 0;const leafOffset=findBootstrapCommandTokenIndex(argv.slice(commandIndex+1));if(leafOffset===void 0)return fallback;const leafIndex=commandIndex+1+leafOffset;const candidate=`${commandName} ${argv[leafIndex]}`;const operation=resolvePmCommandOperation(candidate);if(operation===candidate)return commandName==="item"&&argv[leafIndex]==="complete"?leafIndex+1:fallback;return supportsItemIdAlias(operation)?leafIndex+1:void 0}function resolveItemAddressIndex(argv,commandIndex,commandName){if(["history","context","ctx","update","close","item"].includes(commandName)){return resolveNamespacedItemAddressIndex(argv,commandIndex,commandName)}const declaredSubcommand=ITEM_ID_ALIAS_SUBCOMMANDS.get(commandName);if(declaredSubcommand===void 0)return commandIndex+1;const usesDeclaredSubcommand=argv[commandIndex+1]?.toLowerCase()===declaredSubcommand;return commandIndex+(usesDeclaredSubcommand?2:1)}function buildFlagContractMap(commandPath){const contractsByFlag=new Map;for(const contract of resolveSubcommandFlagContractsForCommand(commandPath)){for(const flag of[contract.flag,contract.short,...contract.aliases??[]]){if(flag)contractsByFlag.set(flag,contract)}}return contractsByFlag}function collectNamedItemIds(argv){const namedIds=[];for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){namedIds.push({index,consumed:2,value:argv[index+1]});index+=1}else if(token.startsWith("--id=")){namedIds.push({index,consumed:1,value:token.slice("--id=".length)})}}return namedIds}function consumesSeparateFlagValue(token,nextToken,contractsByFlag){const separatorIndex=token.indexOf("=");if(separatorIndex>=0||nextToken===void 0||nextToken.startsWith("-")){return false}const contract=contractsByFlag.get(token);return contract!==void 0&&contract.value_type!=="boolean"}function hasPositionalItemId(argv,addressIndex,commandPath,namedIndex,contractsByFlag){let trailingPositionals=0;for(let index=addressIndex;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){index+=1;continue}if(token.startsWith("--id="))continue;if(!token.startsWith("-")){if(index<namedIndex)return true;trailingPositionals+=1;continue}if(consumesSeparateFlagValue(token,argv[index+1],contractsByFlag)){index+=1}}return trailingPositionals>(TRAILING_POSITIONAL_COUNTS.get(resolvePmCommandOperation(commandPath))??0)}function normalizeItemAddressInvocation(argv){const commandIndex=findBootstrapCommandTokenIndex(argv);const commandName=commandIndex===void 0?void 0:argv[commandIndex]?.toLowerCase();if(commandName!=="context"&&commandName!=="ctx"&&!supportsItemIdAlias(commandName)){return{argv:[...argv],changed:false,conflict:false}}const addressIndex=resolveItemAddressIndex(argv,commandIndex,commandName);if(addressIndex===void 0){return{argv:[...argv],changed:false,conflict:false}}const commandPath=addressIndex>commandIndex+1?`${commandName} ${argv[addressIndex-1]}`:commandName;const contractsByFlag=buildFlagContractMap(commandPath);const namedIds=collectNamedItemIds(argv);const named=namedIds[0];if(!named||!named.value?.trim()){return{argv:[...argv],changed:false,conflict:false}}if(namedIds.length>1||hasPositionalItemId(argv,addressIndex,commandPath,named.index,contractsByFlag)){return{argv:[...argv],changed:false,conflict:true,itemId:named.value}}const withoutNamed=[...argv.slice(0,named.index),...argv.slice(named.index+named.consumed)];const normalizedCommandIndex=findBootstrapCommandTokenIndex(withoutNamed);const normalizedAddressIndex=resolveItemAddressIndex(withoutNamed,normalizedCommandIndex,commandName);withoutNamed.splice(normalizedAddressIndex,0,named.value);return{argv:withoutNamed,changed:true,conflict:false,itemId:named.value}}export{normalizeItemAddressInvocation,supportsItemIdAlias};
|
|
2
2
|
//# sourceMappingURL=item-addressing.js.map
|
|
@@ -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]="
|
|
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]="41d33f0e-f925-54da-a75d-52a73dd76f38")}catch(e2){}})();import{PLAN_SUBCOMMANDS}from"../lifecycle/plan.js";import{PROFILE_SUBCOMMANDS}from"../profile.js";import{SCHEMA_SUBCOMMANDS}from"../schema.js";import{GRAPH_SUBCOMMAND_VALUES,MERGE_SUBCOMMAND_VALUES}from"../cli-contracts/enum-contracts.js";import{PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS}from"../cli-contracts/grammar-contracts.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const REJECTED_ACTION="not-a-declared-action";function positionalPlaceholder(command,slot){if(command.startsWith("assurance ")&&slot.name==="kind"){return"measurement"}switch(slot.value_kind){case"integer":return"1";case"item_id":return"pm-domain";case"action":throw new Error(`Cannot synthesize a preceding action value for positional slot ${slot.name}.`);default:return"example"}}function probeSlug(value){return value.replaceAll(/[^a-z0-9]+/gu,"-").replaceAll(/^-|-$/gu,"")}function listPmRequiredArgumentRefusalContracts(contracts=PM_COMMAND_POSITIONAL_CONTRACTS.filter(contract=>PM_COMMAND_DESTINATION_CONTRACTS.some(destination=>destination.command===contract.command&&destination.disposition!=="package_owned"))){const rootProbeSlugs=new Set(contracts.filter(({command})=>!command.includes(" ")).map(({command})=>probeSlug(command)));return contracts.flatMap(contract=>contract.slots.flatMap((slot,index)=>{if(!slot.required)return[];const commandArguments=contract.command.split(" ");const commandSlug=probeSlug(contract.command);const commandProbeId=commandArguments.length>1&&rootProbeSlugs.has(commandSlug)?commandArguments.map(probeSlug).join("--"):commandSlug;const requiredFlagArguments=resolveSubcommandFlagContractsForCommand(contract.command).flatMap(flagContract=>flagContract.required?[flagContract.flag,...flagContract.value_name?["example"]:[]]:[]);const isVirtualAction=PM_POSITIONAL_ACTION_CONTRACTS.some(actionContract=>actionContract.command===contract.command);return[{probe_id:`required-argument-${commandProbeId}-${probeSlug(slot.name)}`,command:contract.command,refusal_args:[...commandArguments,...contract.slots.slice(0,index).map(priorSlot=>positionalPlaceholder(contract.command,priorSlot)),...requiredFlagArguments],recovery_args:[...commandArguments,"--help"],error_code:isVirtualAction&&!contract.command.startsWith("assurance ")?"invalid_argument_value":/^extension (?:activate|adopt|deactivate|uninstall)$/u.test(contract.command)?"missing_lifecycle_target":"missing_required_argument",missing_argument:slot.name,missing_argument_index:index}]})).sort((left,right)=>left.probe_id.localeCompare(right.probe_id))}function positionalActionValues(command){switch(resolvePmCommandOperation(command)){case"assurance":case"workspace snapshot":return PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent===command).map(({action})=>action);case"graph":return GRAPH_SUBCOMMAND_VALUES;case"merge":return MERGE_SUBCOMMAND_VALUES;case"plan":return PLAN_SUBCOMMANDS;case"profile":return PROFILE_SUBCOMMANDS;case"schema":return SCHEMA_SUBCOMMANDS;default:throw new Error(`Required positional action family ${command} has no authoritative value domain.`)}}function listPmSubcommandRefusalContracts(contracts=PM_COMMAND_POSITIONAL_CONTRACTS){return contracts.filter(({slots})=>slots[0]?.required===true&&slots[0].value_kind==="action").map(({command})=>{const commandArguments=command.split(" ");return{probe_id:`unknown-subcommand-${probeSlug(command)}`,command,refusal_args:[...commandArguments,REJECTED_ACTION],recovery_args:[...commandArguments,"--help"],error_code:"unknown_subcommand",rejected_value:REJECTED_ACTION,allowed_values:[...positionalActionValues(command)].sort()}}).sort((left,right)=>left.probe_id.localeCompare(right.probe_id))}function sameValues(left,right){const sortedRight=[...right].sort();return left.length===right.length&&[...left].sort().every((value,index)=>value===sortedRight[index])}function scoreGrammarRefusalObservation(contract,observation){if(!observation){return[{code:"refusal_probe_missing",probe_id:contract.probe_id,detail:`${contract.probe_id} has no runtime observation.`}]}const findings=[];if(observation.error_code!==contract.error_code){findings.push({code:"refusal_error_code_mismatch",probe_id:contract.probe_id,detail:`${contract.probe_id} emitted ${observation.error_code||"<none>"}; expected ${contract.error_code}.`})}if(observation.exit_code!==2){findings.push({code:"refusal_exit_code_mismatch",probe_id:contract.probe_id,detail:`${contract.probe_id} exited ${observation.exit_code}; expected usage exit 2.`})}if("allowed_values"in contract&&!sameValues(observation.allowed_values,contract.allowed_values)){findings.push({code:"refusal_allowed_values_mismatch",probe_id:contract.probe_id,detail:`${contract.probe_id} did not expose its complete action domain.`})}if(!observation.recovery_succeeded){findings.push({code:"refusal_recovery_failed",probe_id:contract.probe_id,detail:`${contract.probe_id} help recovery did not succeed.`})}if(observation.refusal_mutated_state){findings.push({code:"refusal_mutated_state",probe_id:contract.probe_id,detail:`${contract.probe_id} changed tracker state while refusing input${observation.mutated_paths?.length?`: ${observation.mutated_paths.join(", ")}`:"."}`})}return findings}function scorePmGrammarRefusalClosure(contracts,observations){const contractsById=new Map(contracts.map(contract=>[contract.probe_id,contract]));const observationsById=new Map(observations.map(observation=>[observation.probe_id,observation]));const findings=[...contracts.flatMap(contract=>scoreGrammarRefusalObservation(contract,observationsById.get(contract.probe_id))),...observations.filter(observation=>!contractsById.has(observation.probe_id)).map(observation=>({code:"unexpected_refusal_probe",probe_id:observation.probe_id,detail:`${observation.probe_id} has no declared grammar refusal contract.`}))];findings.sort((left,right)=>left.probe_id.localeCompare(right.probe_id)||left.code.localeCompare(right.code));const failedProbeIds=new Set(findings.map(({probe_id:probeId})=>probeId));return{ok:findings.length===0,probe_count:contracts.length,closed_probe_count:contracts.filter(({probe_id:probeId})=>!failedProbeIds.has(probeId)).length,findings}}export{listPmRequiredArgumentRefusalContracts,listPmSubcommandRefusalContracts,scorePmGrammarRefusalClosure};
|
|
2
2
|
//# sourceMappingURL=refusal-corpus-contracts.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]="498f7dad-b360-5494-ab5e-7ed5cd319207")}catch(e2){}})();import{PM_CORE_COMMAND_NAMES}from"./cli-contracts/enum-contracts.js";import{PM_COMMAND_ALIAS_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";const CORE_COMMANDS=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate"]);const STANDARD_COMMANDS=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]);const COMMANDS_BY_FAMILY=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])});const EXTENSION_COMMANDS=new Set(["extension","install","package","packages","upgrade"]);function resolvePmCommandCapabilityFamily(command){const normalized=resolvePmCommandOperation(command.trim().toLowerCase());if(normalized==="ops")return"quality";for(const[family,commands]of Object.entries(COMMANDS_BY_FAMILY)){if(commands.has(normalized))return family}return EXTENSION_COMMANDS.has(normalized)?"extensions":"internal"}const PM_COMMAND_CAPABILITY_CONTRACTS=Object.freeze([...PM_CORE_COMMAND_NAMES.flatMap(command=>command==="item"?["item-reopen"]:[command,...PM_NAMESPACED_COMMAND_ALIASES.filter(alias=>alias.alias===command).map(alias=>alias.canonical)]).map(command=>({command,tier:CORE_COMMANDS.has(resolvePmCommandOperation(command))?"core":STANDARD_COMMANDS.has(resolvePmCommandOperation(command))?"standard":"full",family:resolvePmCommandCapabilityFamily(command)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"}]);const PM_COMMAND_VISIBILITY_CONTRACTS=PM_COMMAND_CAPABILITY_CONTRACTS;const PM_CORE_HELP_BUDGET=Object.freeze({max_lines:50,max_utf8_bytes:6e3});const PM_CORE_HELP_OPTION_FLAGS=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function measurePmCoreHelp(text){const lines=text===""?0:text.split(/\r?\n/).length;const utf8Bytes=Buffer.byteLength(text,"utf8");return{lines,utf8_bytes:utf8Bytes,within_budget:lines<=PM_CORE_HELP_BUDGET.max_lines&&utf8Bytes<=PM_CORE_HELP_BUDGET.max_utf8_bytes}}const TIER_ORDER={core:0,standard:1,full:2,internal:3};const COMMAND_TIER_BY_NAME=new Map(PM_COMMAND_VISIBILITY_CONTRACTS.map(({command,tier})=>[command,tier]));function resolvePmCommandVisibilityTier(command,extensionTier="standard"){return COMMAND_TIER_BY_NAME.get(command.trim().toLowerCase())??extensionTier}function listPmCommandsForTier(tier){return listPmCommandsForTierFromContracts(tier,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForTierFromContracts(tier,contracts){const maximum=TIER_ORDER[tier];return contracts.filter(entry=>entry.tier!=="internal"&&TIER_ORDER[entry.tier]<=maximum).map(entry=>entry.command)}function listPmCommandsForFamily(family){return listPmCommandsForFamilyFromContracts(family,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForFamilyFromContracts(family,contracts){return contracts.filter(entry=>entry.family===family).map(entry=>entry.command)}const CAPABILITY_FAMILY_ORDER=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"];const CAPABILITY_ROUTING_EXCLUDED_ALIASES=new Set([...PM_COMMAND_ALIAS_CONTRACTS.filter(alias=>alias.hidden).map(alias=>alias.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function listPmCommandCapabilityGroups(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){return CAPABILITY_FAMILY_ORDER.map(family=>({family,commands:listPmCommandsForFamilyFromContracts(family,contracts).filter(command=>contracts.find(entry=>entry.command===command)?.tier!=="internal"&&!CAPABILITY_ROUTING_EXCLUDED_ALIASES.has(command))})).filter(({commands})=>commands.length>0)}const PM_MCP_TOOL_COMMAND_CONTRACTS=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function listPmMcpToolsForProfile(availableTools,profile){return listPmMcpToolsForProfileFromContracts(availableTools,profile,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmMcpToolsForProfileFromContracts(availableTools,profile,contracts){if(profile==="full")return[...availableTools];const visibleCommands=new Set(listPmCommandsForTierFromContracts(profile,contracts));return availableTools.filter(tool=>{const command=PM_MCP_TOOL_COMMAND_CONTRACTS[tool];return command!==void 0&&visibleCommands.has(command)})}const PM_MCP_RESOURCE_CONTRACTS=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]);const PM_MCP_PROMPT_CONTRACTS=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:true},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:false}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:true}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:true},{name:"evidence",description:"Exact verification and outcome evidence.",required:true}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function renderPmCommandVisibilityMarkdown(){return renderPmCommandVisibilityMarkdownFromContracts(PM_COMMAND_CAPABILITY_CONTRACTS)}function renderPmCommandVisibilityMarkdownFromContracts(contracts){const rows=contracts.map(({command,tier,family})=>`| \`${command}\` | ${tier} | ${family} |`);return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...rows,""].join("\n")}function renderPmCapabilityRoutingMarkdown(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){const rows=listPmCommandCapabilityGroups(contracts).map(({family,commands})=>`| ${family} | ${commands.map(command=>`\`${command}\``).join(", ")} |`);return["# Generated agent capability routing","","Tracker: `pm-kxci8x`.","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Capability family | Commands |","| --- | --- |",...rows,""].join("\n")}export{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CORE_HELP_BUDGET,PM_CORE_HELP_OPTION_FLAGS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandCapabilityGroups,listPmCommandsForFamily,listPmCommandsForFamilyFromContracts,listPmCommandsForTier,listPmCommandsForTierFromContracts,listPmMcpToolsForProfile,listPmMcpToolsForProfileFromContracts,measurePmCoreHelp,renderPmCapabilityRoutingMarkdown,renderPmCommandVisibilityMarkdown,renderPmCommandVisibilityMarkdownFromContracts,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier};
|
|
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]="6d931940-2d41-557a-8913-875848774ed0")}catch(e2){}})();import{PM_CORE_COMMAND_NAMES}from"./cli-contracts/enum-contracts.js";import{PM_COMMAND_ALIAS_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";const CORE_COMMANDS=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate"]);const STANDARD_COMMANDS=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]);const COMMANDS_BY_FAMILY=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])});const EXTENSION_COMMANDS=new Set(["extension","install","package","packages","upgrade"]);function resolvePmCommandCapabilityFamily(command){const normalized=resolvePmCommandOperation(command.trim().toLowerCase());if(normalized==="ops")return"quality";for(const[family,commands]of Object.entries(COMMANDS_BY_FAMILY)){if(commands.has(normalized))return family}return EXTENSION_COMMANDS.has(normalized)?"extensions":"internal"}const PM_COMMAND_CAPABILITY_CONTRACTS=Object.freeze([...PM_CORE_COMMAND_NAMES.flatMap(command=>command==="item"?["item-reopen"]:[command,...PM_NAMESPACED_COMMAND_ALIASES.filter(alias=>alias.alias===command).map(alias=>alias.canonical)]).map(command=>({command,tier:CORE_COMMANDS.has(resolvePmCommandOperation(command))?"core":STANDARD_COMMANDS.has(resolvePmCommandOperation(command))?"standard":"full",family:resolvePmCommandCapabilityFamily(command)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"}]);const PM_COMMAND_VISIBILITY_CONTRACTS=PM_COMMAND_CAPABILITY_CONTRACTS;const PM_CORE_HELP_BUDGET=Object.freeze({max_lines:50,max_utf8_bytes:6e3});const PM_CORE_HELP_OPTION_FLAGS=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function measurePmCoreHelp(text){const lines=text===""?0:text.split(/\r?\n/).length;const utf8Bytes=Buffer.byteLength(text,"utf8");return{lines,utf8_bytes:utf8Bytes,within_budget:lines<=PM_CORE_HELP_BUDGET.max_lines&&utf8Bytes<=PM_CORE_HELP_BUDGET.max_utf8_bytes}}const TIER_ORDER={core:0,standard:1,full:2,internal:3};const COMMAND_TIER_BY_NAME=new Map(PM_COMMAND_VISIBILITY_CONTRACTS.map(({command,tier})=>[command,tier]));function resolvePmCommandVisibilityTier(command,extensionTier="standard"){return COMMAND_TIER_BY_NAME.get(command.trim().toLowerCase())??extensionTier}function listPmCommandsForTier(tier){return listPmCommandsForTierFromContracts(tier,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForTierFromContracts(tier,contracts){const maximum=TIER_ORDER[tier];return contracts.filter(entry=>entry.tier!=="internal"&&TIER_ORDER[entry.tier]<=maximum).map(entry=>entry.command)}function listPmCommandsForFamily(family){return listPmCommandsForFamilyFromContracts(family,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForFamilyFromContracts(family,contracts){return contracts.filter(entry=>entry.family===family).map(entry=>entry.command)}const CAPABILITY_FAMILY_ORDER=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"];const CAPABILITY_ROUTING_EXCLUDED_ALIASES=new Set([...PM_COMMAND_ALIAS_CONTRACTS.filter(alias=>alias.hidden).map(alias=>alias.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function listPmCommandCapabilityGroups(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){return CAPABILITY_FAMILY_ORDER.map(family=>({family,commands:listPmCommandsForFamilyFromContracts(family,contracts).filter(command=>contracts.find(entry=>entry.command===command)?.tier!=="internal"&&!CAPABILITY_ROUTING_EXCLUDED_ALIASES.has(command))})).filter(({commands})=>commands.length>0)}const PM_MCP_TOOL_COMMAND_CONTRACTS=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function listPmMcpToolsForProfile(availableTools,profile){return listPmMcpToolsForProfileFromContracts(availableTools,profile,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmMcpToolsForProfileFromContracts(availableTools,profile,contracts){if(profile==="full")return[...availableTools];const visibleCommands=new Set(listPmCommandsForTierFromContracts(profile,contracts));return availableTools.filter(tool=>{const command=PM_MCP_TOOL_COMMAND_CONTRACTS[tool];return command!==void 0&&visibleCommands.has(command)})}const PM_MCP_RESOURCE_CONTRACTS=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]);const PM_MCP_PROMPT_CONTRACTS=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:true},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:false}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:true}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:true},{name:"evidence",description:"Exact verification and outcome evidence.",required:true}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function renderPmCommandVisibilityMarkdown(){return renderPmCommandVisibilityMarkdownFromContracts(PM_COMMAND_CAPABILITY_CONTRACTS)}function renderPmCommandVisibilityMarkdownFromContracts(contracts){const rows=contracts.map(({command,tier,family})=>`| \`${command}\` | ${tier} | ${family} |`);return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...rows,""].join("\n")}function renderPmCapabilityRoutingMarkdown(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){const rows=listPmCommandCapabilityGroups(contracts).map(({family,commands})=>`| ${family} | ${commands.map(command=>`\`${command}\``).join(", ")} |`);return["# Generated agent capability routing","","Tracker: `pm-kxci8x`.","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Capability family | Commands |","| --- | --- |",...rows,""].join("\n")}export{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CORE_HELP_BUDGET,PM_CORE_HELP_OPTION_FLAGS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandCapabilityGroups,listPmCommandsForFamily,listPmCommandsForFamilyFromContracts,listPmCommandsForTier,listPmCommandsForTierFromContracts,listPmMcpToolsForProfile,listPmMcpToolsForProfileFromContracts,measurePmCoreHelp,renderPmCapabilityRoutingMarkdown,renderPmCommandVisibilityMarkdown,renderPmCommandVisibilityMarkdownFromContracts,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier};
|
|
2
2
|
//# sourceMappingURL=agent-capability-contracts.js.map
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Provides public bootstrap argument normalization for embedded CLI hosts.
|
|
5
5
|
*/
|
|
6
|
-
import { EXECUTABLE_COMMAND_ALIASES, PM_COMMAND_ALIAS_CONTRACTS, renderPmCommandAliasMigrationHint, resolvePmCommandAlias, type
|
|
6
|
+
import { EXECUTABLE_COMMAND_ALIASES, PM_COMMAND_ALIAS_CONTRACTS, renderPmCommandAliasMigrationHint, resolvePmCommandAlias, type PmCommandAliasContract, type PmCommandAliasLifecycle, type PmCommandAliasRegistration } from "./cli-contracts/command-aliases.js";
|
|
7
|
+
import { type CliFlagContract } from "./cli-contracts/flag-contracts.js";
|
|
7
8
|
export { EXECUTABLE_COMMAND_ALIASES, PM_COMMAND_ALIAS_CONTRACTS, renderPmCommandAliasMigrationHint, resolvePmCommandAlias, type PmCommandAliasContract, type PmCommandAliasLifecycle, type PmCommandAliasRegistration, };
|
|
8
9
|
/** Documents the bootstrap global options payload exchanged by command, SDK, and package integrations. */
|
|
9
10
|
export interface BootstrapGlobalOptions {
|