@unbrained/pm-cli 2026.9.29 → 2026.9.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +9 -0
  3. package/dist/cli/main.js +1 -1
  4. package/dist/cli-bundle/bundle-manifest.json +156 -156
  5. package/dist/cli-bundle/chunks/{chunk-4DOL43PF.js → chunk-6XTJLOKW.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-S5A2UIRV.js → chunk-6YEET7XI.js} +22 -22
  7. package/dist/cli-bundle/chunks/{chunk-U3QJGJYN.js → chunk-A6NDNRCK.js} +3 -3
  8. package/dist/cli-bundle/chunks/{chunk-5KEPG36D.js → chunk-BNAT4EYR.js} +9 -9
  9. package/dist/cli-bundle/chunks/{chunk-OTLIM22J.js → chunk-BTCE36JS.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-SJI55O65.js → chunk-BX4LEJX4.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-GP6QTYSD.js → chunk-EGAIIWI3.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-FYTXVVZG.js +2 -0
  13. package/dist/cli-bundle/chunks/{chunk-SC6JHXFT.js → chunk-O23CQ5T4.js} +27 -27
  14. package/dist/cli-bundle/chunks/{chunk-SEJ53XDN.js → chunk-UIAH7UFK.js} +65 -65
  15. package/dist/cli-bundle/chunks/{chunk-2AQKVJMW.js → chunk-USTAFHIM.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-PJSQAWWQ.js → chunk-XRN3JYNN.js} +73 -73
  17. package/dist/cli-bundle/chunks/{chunk-P75SO5HO.js → chunk-YM342ELM.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-list-query-R3ELWWPY.js → register-list-query-SYNBVMNG.js} +2 -2
  19. package/dist/cli-bundle/chunks/{register-mutation-WHXJXIHJ.js → register-mutation-4GSUK23D.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-operations-7ASWBYQG.js → register-operations-7FCJUC4Z.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-setup-FDRTUG54.js → register-setup-YTWW2KL5.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/{chunk-MRH4A542.js → chunk-3CAZ7Z4R.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-5MC57KRC.js → chunk-4AORVUT4.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-FBIRNSYP.js → chunk-AKB3JN57.js} +33 -33
  25. package/dist/cli-bundle/focused-chunks/{chunk-T4H6Q44B.js → chunk-EFD4ATS7.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-NXQZMKW5.js → chunk-EVMH4SKN.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-6OXJVE74.js → chunk-IDB6E3ZV.js} +27 -27
  28. package/dist/cli-bundle/focused-chunks/{chunk-2O3QFI3G.js → chunk-IQBFYQF2.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-NY6FLQTN.js → chunk-KZULQIAG.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-KLKKCHWM.js → chunk-MOUCTR72.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-7URX7FMY.js → chunk-OMBDUJWZ.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-AZE7KUHG.js → chunk-RIJQQOEZ.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-IFBA3ZAT.js → chunk-T4PZJQG4.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-DZVOCJFY.js → chunk-UPOMLSW7.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-AVP5C674.js → chunk-XB5Q2P7Z.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-K3AIMRIK.js → chunk-XUCXRZZZ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-4A4DO5ZT.js → chunk-ZJ3CLTV4.js} +2 -2
  38. package/dist/cli-bundle/main.js +2 -2
  39. package/dist/cli-bundle/sdk-authoring.js +1 -1
  40. package/dist/cli-bundle/sdk-contracts.js +1 -1
  41. package/dist/cli-bundle/sdk-core.js +22 -22
  42. package/dist/cli-bundle/sdk-governance.js +1 -1
  43. package/dist/cli-bundle/sdk-graph.js +1 -1
  44. package/dist/cli-bundle/sdk-merge.js +32 -32
  45. package/dist/cli-bundle/sdk-query.js +1 -1
  46. package/dist/cli-bundle/sdk-runtime.js +1 -1
  47. package/dist/cli-bundle/sdk-testing.js +1 -1
  48. package/dist/cli-bundle/sdk.js +2 -2
  49. package/dist/core/extensions/extension-types.d.ts +13 -0
  50. package/dist/core/extensions/extension-types.js +1 -1
  51. package/dist/core/history/workspace-history.d.ts +17 -0
  52. package/dist/core/history/workspace-history.js +1 -1
  53. package/dist/sdk/extension-command-context.d.ts +1 -7
  54. package/dist/sdk/extension-command-context.js +1 -1
  55. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  56. package/dist/sdk/lifecycle/update.d.ts +2 -0
  57. package/dist/sdk/lifecycle/update.js +1 -1
  58. package/dist/sdk/merge/install.js +1 -1
  59. package/dist/sdk/public-surface.json +1 -1
  60. package/dist/sdk/runtime.js +1 -1
  61. package/dist/sdk/structured-mutations.js +1 -1
  62. package/dist/sdk/testing.js +1 -1
  63. package/docs/MERGE_SAFETY.md +11 -6
  64. package/docs/README.md +1 -0
  65. package/docs/RELEASE_RELIABILITY.md +26 -4
  66. package/docs/SDK_AUDITED_MUTATIONS.md +52 -0
  67. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  68. package/marketplace.json +2 -2
  69. package/package.json +1 -1
  70. package/packages/pm-beads/package.json +1 -1
  71. package/packages/pm-calendar/package.json +1 -1
  72. package/packages/pm-command-kit/package.json +1 -1
  73. package/packages/pm-digital-twin/package.json +1 -1
  74. package/packages/pm-governance-audit/package.json +1 -1
  75. package/packages/pm-guide-shell/package.json +1 -1
  76. package/packages/pm-kanban/package.json +1 -1
  77. package/packages/pm-lifecycle-hooks/package.json +1 -1
  78. package/packages/pm-linked-test-adapters/package.json +1 -1
  79. package/packages/pm-search-advanced/package.json +1 -1
  80. package/packages/pm-templates/package.json +1 -1
  81. package/packages/pm-todos/package.json +1 -1
  82. package/packages/pm-vcs/package.json +1 -1
  83. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  84. package/plugins/pm-claude/package.json +2 -2
  85. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  86. package/plugins/pm-codex/package.json +2 -2
  87. package/plugins/pm-codex/plugin.json +1 -1
  88. package/dist/cli-bundle/chunks/chunk-D32HVIB2.js +0 -2
@@ -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]="196dc906-149b-5280-b054-81d1e178100f")}catch(e2){}})();import{AsyncLocalStorage}from"node:async_hooks";import{createEmptyExtensionCommandRegistry,createEmptyExtensionHookRegistry,createEmptyExtensionParserRegistry,createEmptyExtensionPreflightRegistry,createEmptyExtensionRegistrationRegistry,createEmptyExtensionRendererRegistry,createEmptyExtensionServiceRegistry}from"../core/extensions/extension-registries.js";import{activateExtensions,deactivateExtensions,loadExtensions,runActiveCommandHandler,runWithIsolatedExtensionRuntime,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices}from"../core/extensions/index.js";import{pathExists}from"../core/fs/fs-utils.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{createAsyncReadWriteGate}from"../core/shared/serial-queue.js";import{getSettingsPath,resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{PM_TOOL_ACTIONS}from"./cli-contracts/enum-contracts.js";import{runContracts}from"./cli-contracts/runtime-contracts.js";import{attachReadOutputContracts}from"./context-intent-contracts.js";import{runWithDiscoveredContextIntentContracts}from"./context-intent-runtime.js";import{finalizeContextUsageEgress}from"./context/usage-egress.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{INIT_INVOCATION_CWD}from"./init.js";import{certifyCompleteListResult,createCompleteListOptions}from"./query/complete-list.js";import{listClientItemMetadataLight}from"./query/light-metadata.js";import{normalizeReadOutputIncludeModeOptions,validateReadOutputOptions}from"./read-output-contracts.js";import{SDK_ACTION_ALIASES}from"./runtime-action-aliases.js";import{closeManyOptionsFromFlat,extensionOptionsFromArgs,actionGlobalOptions as globalOptions,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,readRuntimeScalarString as readScalarString,readRuntimeScalarStringAllowBlank as readScalarStringAllowBlank,readRuntimeString as readString,readRuntimeStringArray as readStringArray,shouldInvalidateWorkspaceContractsCacheAfterAction,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction}from"./runtime-input.js";import{SDK_ACTION_HANDLERS}from"./runtime/actions.js";import{getOwnHandler,readRequiredString}from"./runtime/context.js";import{clearWorkspaceContractsCache}from"./workspace-contracts-cache.js";import{PM_GITIGNORE_END,PM_GITIGNORE_START,ensurePmGitignore,getPmGitignoreBlock}from"./workspace.js";import{SEARCH_EXTENSION_FLAG_DEFINITIONS}from"./extension-contracts.js";export*from"./cli-contracts/agent-output-contracts.js";import{PmCompleteListValidationError,assertCompleteListResult,certifyCompleteListResult as certifyCompleteListResult2,createCompleteListOptions as createCompleteListOptions2,inspectCompleteListResult}from"./query/complete-list.js";import{getWorkspaceContracts}from"./query/workspace-contracts.js";import{clearWorkspaceContractsCache as clearWorkspaceContractsCache2}from"./workspace-contracts-cache.js";export*from"./governance/workflow-policy.js";import{runCloseTask,runPauseTask,runStartTask}from"./lifecycle/task-composition.js";import{getActiveExtensionRegistrations,runActiveOnReadHooks,runActiveOnWriteHooks}from"../core/extensions/index.js";import{pathExists as pathExists2,readFileIfExists,removeFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{appendHistoryEntry,createHistoryEntry}from"../core/history/history.js";import{HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS,classifyHistoryEvent}from"../core/history/event-classification.js";import{generateItemId,normalizeItemId,normalizeRawItemId}from"../core/item/id.js";import{readBooleanOption,readCsvListOption,readStringOption}from"./package-runtime-options.js";import{PM_CLI_EXPECTED_ERROR_NAME,createPmCliExpectedError,isPmCliExpectedError}from"./errors.js";import{commitImportedItem,emptyImportedDocument,ensureTrackerInitialized,selectImportAuthor,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString}from"./package-import-adapters.js";import{canonicalDocument,normalizeItemMetadata,serializeItemDocument,splitFrontMatter}from"../core/item/item-format.js";import{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,classifyItemFormatVersion,effectiveItemFormatVersion,normalizeItemFormatVersion,scanItemFormatVersions}from"../core/item/item-format-version.js";import{parseTags}from"../core/item/parse.js";import{isTerminalStatus,normalizeStatusInput}from"../core/item/status.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{acquireLock}from"../core/lock/lock.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{PmCliError as PmCliError2}from"../core/shared/errors.js";import{isTimestampLiteral,nowIso}from"../core/shared/time.js";import{jaccardSimilarity,normalizeSimilarityText,scoreItemSimilarity,tokenizeSimilarityText}from"./similarity-scoring.js";import{listAllItemMetadata,listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{getHistoryPath,getItemPath,getSettingsPath as getSettingsPath2,resolveImplicitPmRoot,resolvePmRoot as resolvePmRoot2}from"../core/store/paths.js";import{readSettings as readSettings2}from"../core/store/settings.js";import{runAggregate}from"./query/aggregate.js";import{CONTEXT_OUTPUT_VALUES,runContext}from"./query/context.js";import{runGet}from"./query/get.js";import{runList}from"./query/list.js";import{closeItem,runClose}from"./lifecycle/close.js";import{runCopy}from"./lifecycle/copy.js";import{runDelete}from"./lifecycle/delete.js";import{runFocus}from"./lifecycle/focus.js";import{runRestore}from"./lifecycle/restore.js";import{DEFAULT_TERMINAL_TRANSITION_POLICY,applyTerminalOrderingPolicy,requireTerminalReason,resolveTerminalReason}from"./lifecycle-policy.js";import{runUpdate}from"./lifecycle/update.js";import{runReopen}from"./lifecycle/reopen.js";import{NEXT_OUTPUT_VALUES,runNext}from"./query/next.js";import{runSearch}from"./query/search.js";import{runStats}from"./stats.js";import{runDuplicates}from"./duplicates.js";import{renderCalendarMarkdown,renderCalendarToon,resolveCalendarOutputFormat,runCalendar}from"./query/calendar.js";import{renderGuideMarkdown,resolveGuideOutputFormat,runGuide}from"./guide.js";import{runCompletion}from"./completion.js";import{runReindex}from"./governance/reindex.js";import{loadCreateTemplateOptions,runTemplatesList,runTemplatesSave,runTemplatesShow}from"./templates.js";import{runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop}from"./test/runs.js";import{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,DEPENDENCY_KIND_VALUES,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,RISK_VALUES,STATUS_VALUES}from"../types/index.js";const ACTIVE_EXTENSION_HOST_CONTEXT=Symbol("pm.active-extension-host-context");function splitFullClientMutationOptions(options){return{fullChangedFields:true,options}}class PmClient{defaults;constructor(options={}){this.defaults={...options.pmRoot===void 0?{}:{path:options.pmRoot},...options.cwd===void 0?{}:{cwd:options.cwd},...options.author===void 0?{}:{author:options.author},...options.noExtensions===void 0?{}:{noExtensions:options.noExtensions}}}static forActiveExtensionHost(options){const client=new PmClient({...options,noExtensions:true});client.defaults[ACTIVE_EXTENSION_HOST_CONTEXT]=true;return client}run(action,args={}){return runAction({...this.defaults,...args,action})}runTyped(action,args={}){return this.run(action,args)}context(options={}){return this.runTyped("context",{options})}listAllItemMetadataLight(){return listClientItemMetadataLight(this.defaults.path,this.defaults.cwd)}list(options={}){return this.runTyped("list",{options})}async listAllComplete(options={}){return certifyCompleteListResult(await this.list(createCompleteListOptions(options)))}search(query,options={}){return this.runTyped("search",{query,options})}get(id,options={}){return this.runTyped("get",{id,options})}next(options={}){return this.runTyped("next",{options})}aggregate(options={}){return this.runTyped("aggregate",{options})}stats(options={}){return this.runTyped("stats",{options})}duplicates(options={}){return this.runTyped("duplicates",{options})}comments(id,options={}){return this.runTyped("comments",{id,options})}notes(id,options={}){return this.runTyped("notes",{id,options})}learnings(id,options={}){return this.runTyped("learnings",{id,options})}files(id,options={}){return this.runTyped("files",{id,options})}filesDiscover(id,options={}){return this.runTyped("files-discover",{id,options})}filesLookup(options){return this.runTyped("files-lookup",{options})}docs(id,options={}){return this.runTyped("docs",{id,options})}deps(id,options={}){return this.runTyped("deps",{id,options})}graph(subcommand,ids={},options={}){return this.runTyped("graph",{subcommand,...ids,options})}append(id,body,options={}){return this.runTyped("append",{id,...splitFullClientMutationOptions(mutationOptionsWithOverrides(options,{body}))})}init(prefix,options={}){return this.runTyped("init",{...prefix===void 0?{}:{prefix},options})}config(scope,configAction,key,value,options={}){return this.runTyped("config",{scope,configAction,...key===void 0?{}:{key},...value===void 0?{}:{value},options})}schema(subcommand,options={}){return this.runTyped("schema",{options:{...options,subcommand}})}workflowPolicy(action,name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:action}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(name){return this.runTyped("schema",{name,options:{subcommand:"show"}})}schemaAddType(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-type"}})}schemaRemoveType(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-type"}})}schemaAddStatus(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-status"}})}schemaRemoveStatus(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-status"}})}schemaAddField(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-field"}})}schemaRemoveField(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(name){return this.runTyped("schema",{name,options:{subcommand:"show-field"}})}schemaApplyPreset(typePreset,options={}){return this.runTyped("schema",{typePreset,options:{...options,subcommand:"apply-preset"}})}schemaInferTypes(options={}){return this.runTyped("schema",{options:{...options,subcommand:"add-type",infer:true}})}schemaRenameType(from,to,options){return this.runTyped("schema",{name:from,options:{...options,subcommand:"rename-type",to}})}schemaRenameField(from,to,options,type){return this.runTyped("schema",{name:from,options:{...options,subcommand:"rename-field",to,...type?{fieldTypeScope:type}:{}}})}schemaRemapStatus(from,to,options){return this.runTyped("schema",{name:from,options:{...options,subcommand:"remap-status",to}})}schemaShowStatus(name){return this.runTyped("schema",{name,options:{subcommand:"show-status"}})}profile(subcommand,options={}){return this.runTyped("profile",{options:{...options,subcommand}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(name){return this.runTyped("profile",{name,options:{subcommand:"show"}})}profileApply(name,options={}){return this.runTyped("profile",{name,options:{...options,subcommand:"apply"}})}profileLint(name){return this.runTyped("profile",{name,options:{subcommand:"lint"}})}validate(options={}){return this.runTyped("validate",{options})}health(options={}){return this.runTyped("health",{options})}gc(options={}){return this.runTyped("gc",{options})}assurance(input){return this.runTyped("assurance",{options:{...input,subcommand:input.action}})}historyRedact(id,options){return this.runTyped("history-redact",{id,options})}historyRepair(id,options={}){return this.runTyped("history-repair",{id,options})}historyRepairAll(options={}){return this.runTyped("history-repair",{options:{...options,all:true}})}historyAttest(options={}){return this.runTyped("history-attest",{options})}historyCompact(id,options={}){return this.runTyped("history-compact",{id,options})}historyCompactBulk(options){return this.runTyped("history-compact",{options})}historyAuthorAcknowledge(options){return this.runTyped("history-author-acknowledge",{historyEvent:(options.events??[]).map(event=>`${event.item_id}:${String(event.line)}`),allActionable:options.all_actionable===true,dryRun:options.dry_run===true,planFingerprint:options.plan_fingerprint,limit:options.coordinate_limit,attributedAuthor:options.attributed_author,reviewer:options.reviewer,reason:options.reason})}plan(subcommand,id,options={},stepRef,reorderTo){return this.runTyped("plan",{fullChangedFields:true,...id===void 0?{}:{id},...stepRef===void 0?{}:{stepRef},...reorderTo===void 0?{}:{reorderTo},options:mutationOptionsWithOverrides(options,{subcommand})})}planCreate(options){return this.plan("create",void 0,options)}planShow(id,options={}){return this.plan("show",id,options)}planAddStep(id,options){return this.plan("add-step",id,options)}planUpdateStep(id,stepRef,options){return this.plan("update-step",id,options,stepRef)}planCompleteStep(id,stepRef,options={}){return this.plan("complete-step",id,options,stepRef)}planBlockStep(id,stepRef,options){return this.plan("block-step",id,options,stepRef)}planReorderStep(id,stepRef,reorderTo,options={}){return this.plan("reorder-step",id,options,stepRef,reorderTo)}planRemoveStep(id,stepRef,options={}){return this.plan("remove-step",id,options,stepRef)}planLink(id,stepRef,options){return this.plan("link",id,options,stepRef)}planUnlink(id,stepRef,options){return this.plan("unlink",id,options,stepRef)}planDecision(id,options){return this.plan("decision",id,options)}planDiscovery(id,options){return this.plan("discovery",id,options)}planValidation(id,options){return this.plan("validation",id,options)}planResume(id,options){return this.plan("resume",id,options)}planApprove(id,options={}){return this.plan("approve",id,options)}planMaterialize(id,options){return this.plan("materialize",id,options)}create(options={}){return this.runTyped("create",splitFullClientMutationOptions(options))}update(id,options={}){return this.runTyped("update",{id,...splitFullClientMutationOptions(options)})}reopen(id,reason,options={}){return this.runTyped("item-reopen",{id,reason,fullChangedFields:true,options})}close(id,reason,options={}){return this.runTyped("close",{id,reason,...splitFullClientMutationOptions(options)})}claim(id,options={}){return this.runTyped("claim",{id,...splitFullClientMutationOptions(options)})}claimNext(options={}){return this.runTyped("claim",{next:true,...splitFullClientMutationOptions(options)})}release(id,options={}){return this.runTyped("release",{id,...splitFullClientMutationOptions(options)})}copy(id,options={}){return this.runTyped("copy",{id,...splitFullClientMutationOptions(options)})}delete(id,options={}){return this.runTyped("delete",{id,...splitFullClientMutationOptions(options)})}restore(id,target,options={}){return this.runTyped("restore",{fullChangedFields:true,id,options:{...options,target}})}focus(id,options={}){return this.runTyped("focus",{...id===void 0?{}:{id},...splitFullClientMutationOptions(options)})}startTask(id,options={}){return this.runTyped("start-task",{id,...splitFullClientMutationOptions(options)})}pauseTask(id,options={}){return this.runTyped("pause-task",{id,...splitFullClientMutationOptions(options)})}closeTask(id,reason,options={}){return this.runTyped("close-task",{id,reason,...splitFullClientMutationOptions(options)})}extension(target,options={}){return this.runTyped("extension",{...target===void 0?{}:{target},options})}extensionList(options={}){return this.extension("list",options)}extensionActivate(target,options={}){return this.runTyped("extension-activate",{target,options})}extensionDeactivate(target,options={}){return this.runTyped("extension-deactivate",{target,options})}package(target,options={}){return this.runTyped("package",{...target===void 0?{}:{target},options:{...options,vocabulary:"package"}})}packageList(options={}){return this.package("list",options)}packageInstall(target,options={}){return this.runTyped("package-install",{target,options})}packageUninstall(target,options={}){return this.runTyped("package-uninstall",{target,options})}packageDoctor(options={}){return this.runTyped("package-doctor",{options})}packageManage(target,options={}){return this.runTyped("package-manage",{...target===void 0?{}:{target},options})}packageDescribe(target,options={}){return this.runTyped("package-describe",{...target===void 0?{}:{target},options})}packageReload(options={}){return this.runTyped("package-reload",{options})}packageCatalog(options={}){return this.runTyped("package-catalog",{options})}packageActivate(target,options={}){return this.runTyped("package-activate",{target,options})}packageDeactivate(target,options={}){return this.runTyped("package-deactivate",{target,options})}packageMigrate(options={}){return this.package(void 0,{...options,migrate:true})}upgrade(target,options={}){return this.runTyped("upgrade",{...target===void 0?{}:{target},options})}}function context(options={},clientOptions={}){return new PmClient(clientOptions).context(options)}function list(options={},clientOptions={}){return new PmClient(clientOptions).list(options)}function listAllComplete(options={},clientOptions={}){return new PmClient(clientOptions).listAllComplete(options)}function search(query,options={},clientOptions={}){return new PmClient(clientOptions).search(query,options)}function get(id,options={},clientOptions={}){return new PmClient(clientOptions).get(id,options)}function next(options={},clientOptions={}){return new PmClient(clientOptions).next(options)}function aggregate(options={},clientOptions={}){return new PmClient(clientOptions).aggregate(options)}function stats(options={},clientOptions={}){return new PmClient(clientOptions).stats(options)}function duplicates(options={},clientOptions={}){return new PmClient(clientOptions).duplicates(options)}function comments(id,options={},clientOptions={}){return new PmClient(clientOptions).comments(id,options)}function notes(id,options={},clientOptions={}){return new PmClient(clientOptions).notes(id,options)}function learnings(id,options={},clientOptions={}){return new PmClient(clientOptions).learnings(id,options)}function files(id,options={},clientOptions={}){return new PmClient(clientOptions).files(id,options)}function filesDiscover(id,options={},clientOptions={}){return new PmClient(clientOptions).filesDiscover(id,options)}function filesLookup(options,clientOptions={}){return new PmClient(clientOptions).filesLookup(options)}function docs(id,options={},clientOptions={}){return new PmClient(clientOptions).docs(id,options)}function deps(id,options={},clientOptions={}){return new PmClient(clientOptions).deps(id,options)}function graph(subcommand,ids={},options={},clientOptions={}){return new PmClient(clientOptions).graph(subcommand,ids,options)}function append(id,body,options={},clientOptions={}){return new PmClient(clientOptions).append(id,body,options)}function init(prefix,options={},clientOptions={}){return new PmClient(clientOptions).init(prefix,options)}function config(scope,configAction,key,value,options={},clientOptions={}){return new PmClient(clientOptions).config(scope,configAction,key,value,options)}function schema(subcommand,options={},clientOptions={}){return new PmClient(clientOptions).schema(subcommand,options)}function schemaList(clientOptions={}){return new PmClient(clientOptions).schemaList()}function schemaShow(name,clientOptions={}){return new PmClient(clientOptions).schemaShow(name)}function schemaAddType(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddType(name,options)}function schemaRemoveType(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveType(name,options)}function schemaAddStatus(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddStatus(name,options)}function schemaRemoveStatus(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveStatus(name,options)}function schemaAddField(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddField(name,options)}function schemaRemoveField(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveField(name,options)}function schemaListFields(clientOptions={}){return new PmClient(clientOptions).schemaListFields()}function schemaShowField(name,clientOptions={}){return new PmClient(clientOptions).schemaShowField(name)}function schemaApplyPreset(typePreset,options={},clientOptions={}){return new PmClient(clientOptions).schemaApplyPreset(typePreset,options)}function schemaInferTypes(options={},clientOptions={}){return new PmClient(clientOptions).schemaInferTypes(options)}function schemaRenameType(from,to,options,clientOptions={}){return new PmClient(clientOptions).schemaRenameType(from,to,options)}function schemaRenameField(from,to,options,type,clientOptions={}){return new PmClient(clientOptions).schemaRenameField(from,to,options,type)}function schemaRemapStatus(from,to,options,clientOptions={}){return new PmClient(clientOptions).schemaRemapStatus(from,to,options)}function schemaShowStatus(name,clientOptions={}){return new PmClient(clientOptions).schemaShowStatus(name)}function profile(subcommand,options={},clientOptions={}){return new PmClient(clientOptions).profile(subcommand,options)}function profileList(clientOptions={}){return new PmClient(clientOptions).profileList()}function profileShow(name,clientOptions={}){return new PmClient(clientOptions).profileShow(name)}function profileApply(name,options={},clientOptions={}){return new PmClient(clientOptions).profileApply(name,options)}function profileLint(name,clientOptions={}){return new PmClient(clientOptions).profileLint(name)}function validate(options={},clientOptions={}){return new PmClient(clientOptions).validate(options)}function health(options={},clientOptions={}){return new PmClient(clientOptions).health(options)}function gc(options={},clientOptions={}){return new PmClient(clientOptions).gc(options)}function historyRedact(id,options,clientOptions={}){return new PmClient(clientOptions).historyRedact(id,options)}function historyRepair(id,options={},clientOptions={}){return new PmClient(clientOptions).historyRepair(id,options)}function historyRepairAll(options={},clientOptions={}){return new PmClient(clientOptions).historyRepairAll(options)}function historyCompact(id,options={},clientOptions={}){return new PmClient(clientOptions).historyCompact(id,options)}function historyCompactBulk(options,clientOptions={}){return new PmClient(clientOptions).historyCompactBulk(options)}function create(options={},clientOptions={}){return new PmClient(clientOptions).create(options)}function update(id,options={},clientOptions={}){return new PmClient(clientOptions).update(id,options)}function reopen(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).reopen(id,reason,options)}function close(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).close(id,reason,options)}function claim(id,options={},clientOptions={}){return new PmClient(clientOptions).claim(id,options)}function claimNext(options={},clientOptions={}){return new PmClient(clientOptions).claimNext(options)}function release(id,options={},clientOptions={}){return new PmClient(clientOptions).release(id,options)}function copy(id,options={},clientOptions={}){return new PmClient(clientOptions).copy(id,options)}function deleteItem(id,options={},clientOptions={}){return new PmClient(clientOptions).delete(id,options)}function restore(id,target,options={},clientOptions={}){return new PmClient(clientOptions).restore(id,target,options)}function focus(id,options={},clientOptions={}){return new PmClient(clientOptions).focus(id,options)}function startTask(id,options={},clientOptions={}){return new PmClient(clientOptions).startTask(id,options)}function pauseTask(id,options={},clientOptions={}){return new PmClient(clientOptions).pauseTask(id,options)}function closeTask(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).closeTask(id,reason,options)}function extension(target,options={},clientOptions={}){return new PmClient(clientOptions).extension(target,options)}function extensionList(options={},clientOptions={}){return new PmClient(clientOptions).extensionList(options)}function extensionActivate(target,options={},clientOptions={}){return new PmClient(clientOptions).extensionActivate(target,options)}function extensionDeactivate(target,options={},clientOptions={}){return new PmClient(clientOptions).extensionDeactivate(target,options)}function packageLifecycle(target,options={},clientOptions={}){return new PmClient(clientOptions).package(target,options)}function packageList(options={},clientOptions={}){return new PmClient(clientOptions).packageList(options)}function packageInstall(target,options={},clientOptions={}){return new PmClient(clientOptions).packageInstall(target,options)}function packageUninstall(target,options={},clientOptions={}){return new PmClient(clientOptions).packageUninstall(target,options)}function packageDoctor(options={},clientOptions={}){return new PmClient(clientOptions).packageDoctor(options)}function packageManage(target,options={},clientOptions={}){return new PmClient(clientOptions).packageManage(target,options)}function packageDescribe(target,options={},clientOptions={}){return new PmClient(clientOptions).packageDescribe(target,options)}function packageReload(options={},clientOptions={}){return new PmClient(clientOptions).packageReload(options)}function packageCatalog(options={},clientOptions={}){return new PmClient(clientOptions).packageCatalog(options)}function packageActivate(target,options={},clientOptions={}){return new PmClient(clientOptions).packageActivate(target,options)}function packageDeactivate(target,options={},clientOptions={}){return new PmClient(clientOptions).packageDeactivate(target,options)}function upgrade(target,options={},clientOptions={}){return new PmClient(clientOptions).upgrade(target,options)}async function getContracts(pmRootOrOptions,options={}){const resolvedOptions=typeof pmRootOrOptions==="string"?{...options,pmRoot:pmRootOrOptions}:pmRootOrOptions??options;const global2={json:true,quiet:resolvedOptions.quiet??true,noExtensions:resolvedOptions.noExtensions??false,noPager:true,profile:resolvedOptions.profile??false,path:resolvedOptions.pmRoot};return runContracts(resolvedOptions,global2)}const extensionActivationGate=createAsyncReadWriteGate();const activeExtensionScope=new AsyncLocalStorage;function resetActiveExtensionRegistries(){setActiveExtensionHooks(createEmptyExtensionHookRegistry());setActiveExtensionCommands(createEmptyExtensionCommandRegistry());setActiveExtensionParsers(createEmptyExtensionParserRegistry());setActiveExtensionPreflight(createEmptyExtensionPreflightRegistry());setActiveExtensionServices(createEmptyExtensionServiceRegistry());setActiveExtensionRenderers(createEmptyExtensionRendererRegistry());setActiveExtensionRegistrations(createEmptyExtensionRegistrationRegistry())}async function withActiveExtensions(global2,explicitCwd,resolutionCwd,run){return runWithIsolatedExtensionRuntime(()=>explicitCwd===void 0?extensionActivationGate.read(()=>withActiveExtensionsExclusively(global2,resolutionCwd,run)):extensionActivationGate.write(()=>withCwd(explicitCwd,()=>withActiveExtensionsExclusively(global2,resolutionCwd,run))))}async function runWithActiveExtensions(options,run){const explicitCwd=options.cwd;const resolutionCwd=explicitCwd??process.cwd();return withActiveExtensions(globalOptions({path:options.path,noExtensions:options.noExtensions}),explicitCwd,resolutionCwd,()=>activeExtensionScope.run(true,run))}async function withActiveExtensionsExclusively(global2,cwd,run){const pmRoot=resolvePmRoot(cwd,global2.path);if(global2.noExtensions){resetActiveExtensionRegistries();return runWithDiscoveredContextIntentContracts({pmRoot},()=>run(null))}if(!await pathExists(getSettingsPath(pmRoot))){resetActiveExtensionRegistries();return run(null)}let active=null;let activated;try{const settings=await readSettings(pmRoot);const loadResult=await loadExtensions({pmRoot,settings,cwd,noExtensions:false});const activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});activated={loadResult,activationResult};setActiveExtensionHooks(activationResult.hooks);setActiveExtensionCommands(activationResult.commands);setActiveExtensionParsers(activationResult.parsers);setActiveExtensionPreflight(activationResult.preflight);setActiveExtensionServices(activationResult.services);setActiveExtensionRenderers(activationResult.renderers);setActiveExtensionRegistrations(activationResult.registrations);active={registrations:activationResult.registrations,commands:activationResult.commands,pmRoot,packages:loadResult.loaded}}catch(error){resetActiveExtensionRegistries();console.error("[pm-sdk] extension activation failed; continuing without active extensions:",error)}try{return await runWithDiscoveredContextIntentContracts({pmRoot,packages:active?.packages},()=>run(active))}finally{resetActiveExtensionRegistries();if(activated){await deactivateExtensions(activated.loadResult,activated.activationResult).catch(()=>void 0)}}}async function dispatchActiveExtensionAction(action,args,options,global2,active){if(!active){throw new PmCliError(`Unsupported native pm action: ${action}`,EXIT_CODE.USAGE)}const normalizedAction=normalizeActionName(action);const definition=active.registrations.commands.find(entry=>normalizeActionName(entry.action)===normalizedAction);const command=definition?.command??active.commands.handlers.find(entry=>normalizeActionName(entry.command)===normalizedAction)?.command;if(!command){throw new PmCliError(`Unsupported native pm action: ${action}`,EXIT_CODE.USAGE)}const handlerResult=await runActiveCommandHandler({command:normalizeCommandPath(command),args:readStringArray(options.args??args.args),options:extensionOptionsFromArgs(args,options),global:global2,pm_root:active.pmRoot,sdk:createExtensionCommandSdk(active.pmRoot,PmClient.forActiveExtensionHost({pmRoot:active.pmRoot,author:typeof global2.author==="string"&&global2.author.trim()?global2.author.trim():"pm-extension"}))});if(!handlerResult.handled){const suffix=handlerResult.warnings.length>0?` (${handlerResult.warnings.join(", ")})`:"";throw new PmCliError(`Unsupported native pm action: ${action}${suffix}`,EXIT_CODE.USAGE)}return handlerResult.result}async function withCwd(cwd,run){const previous=process.cwd();process.chdir(cwd);try{return await run()}finally{process.chdir(previous)}}function resolveSdkActionInput(args){const rawAction=readRequiredString(args,"action");const normalizedAction=normalizeActionName(rawAction);const alias=getOwnHandler(SDK_ACTION_ALIASES,normalizedAction);const action=alias?.action??normalizedAction;const resolvedArgs={...args,action};if(alias?.options!==void 0){resolvedArgs.options={...alias.options,...asRecordClone(args.options)}}if(action==="package"){resolvedArgs.options={...asRecordClone(resolvedArgs.options),vocabulary:"package"}}return{action,args:resolvedArgs}}async function runAction(args){const resolved=resolveSdkActionInput(args);const global2=globalOptions(resolved.args);const invalidateWorkspaceContractsCache=shouldInvalidateWorkspaceContractsCacheAfterAction(resolved.action);const explicitCwd=readString(resolved.args,"cwd");const resolutionCwd=explicitCwd??process.cwd();if(resolved.action==="init"){global2[INIT_INVOCATION_CWD]=resolutionCwd}if(resolved.action!=="init"||global2.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0){global2.path=resolvePmRoot(resolutionCwd,global2.path)}try{if(resolved.action==="history-attest"){return await dispatchAction(resolved.action,resolved.args,global2,null)}if(args[ACTIVE_EXTENSION_HOST_CONTEXT]===true||activeExtensionScope.getStore()===true){return await dispatchAction(resolved.action,resolved.args,global2,null)}return await withActiveExtensions(global2,explicitCwd,resolutionCwd,activeExtensions=>dispatchAction(resolved.action,resolved.args,global2,activeExtensions))}finally{if(invalidateWorkspaceContractsCache){clearWorkspaceContractsCache()}}}function analyzeSdkActionCoverage(actions=PM_TOOL_ACTIONS){return actions.map(action=>{const normalized=normalizeActionName(action);const alias=getOwnHandler(SDK_ACTION_ALIASES,normalized);const resolvedAction=alias?.action??normalized;const covered=getOwnHandler(SDK_ACTION_HANDLERS,resolvedAction)!==void 0;return{action,resolved_action:resolvedAction,covered,route:covered?alias?"alias":"native":"missing"}})}async function dispatchAction(action,args,global2,activeExtensions){const options=optionsWithAuthor(args,action);validateReadOutputOptions(action,options);normalizeReadOutputIncludeModeOptions(action,options);const ctx={action,args,options,id:readString(args,"id"),force:args.force===true||options.force===true,global:global2,activeExtensions};const handler=getOwnHandler(SDK_ACTION_HANDLERS,action);const result=handler?await handler(ctx):await dispatchActiveExtensionAction(action,args,options,global2,activeExtensions);if(action==="history-attest"){return result}else{options.resolvedOutputFormat="json";const projected=attachReadOutputContracts(action,options,result);await finalizeContextUsageEgress(resolvePmRoot(process.cwd(),global2.path),projected);return projected}}const actionRunnerTestHooks={closeManyOptionsFromFlat,extensionOptionsFromArgs,globalOptions,mutationListOptions,normalizeActionName,normalizeCommandPath,normalizeMcpUpdateOptions,normalizeMcpOptionsArrays,optionsWithAuthor,readRequiredString,readScalarString,readScalarStringAllowBlank,readStringArray,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};if(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0){globalThis.__pmCliActionRunnerTestHooks=actionRunnerTestHooks}import{readRequiredString as readRequiredString2}from"./runtime/context.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_OUTPUT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_TERMINAL_TRANSITION_POLICY,DEPENDENCY_KIND_VALUES,EXIT_CODE,HISTORY_EVENT_CLASSIFICATION_VERSION,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,MAINTENANCE_HISTORY_OPERATIONS,NEXT_OUTPUT_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_GITIGNORE_END,PM_GITIGNORE_START,PmCliError2 as PmCliError,PmClient,PmCompleteListValidationError,RISK_VALUES,SEARCH_EXTENSION_FLAG_DEFINITIONS,STATUS_VALUES,SUBSTANTIVE_HISTORY_OPERATIONS,acquireLock,aggregate,analyzeSdkActionCoverage,append,appendHistoryEntry,applyTerminalOrderingPolicy,assertCompleteListResult,canonicalDocument,certifyCompleteListResult2 as certifyCompleteListResult,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,clearWorkspaceContractsCache2 as clearWorkspaceContractsCache,close,closeItem,closeTask,comments,commitImportedItem,config,context,copy,create,createCompleteListOptions2 as createCompleteListOptions,createHistoryEntry,createPmCliExpectedError,deleteItem,deps,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureTrackerInitialized,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getPmGitignoreBlock,getSettingsPath2 as getSettingsPath,getWorkspaceContracts,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,inspectCompleteListResult,isPmCliExpectedError,isTerminalStatus,isTimestampLiteral,jaccardSimilarity,learnings,list,listAllComplete,listAllItemMetadata,listAllItemMetadataLight,loadCreateTemplateOptions,locateItem,next,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,parseTags,pathExists2 as pathExists,pauseTask,profile,profileApply,profileLint,profileList,profileShow,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString2 as readRequiredString,readSettings2 as readSettings,readStringOption,release,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,reopen,requireTerminalReason,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemTypeRegistry,resolvePmRoot2 as resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveTerminalReason,restore,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runCalendar,runClose,runCloseTask,runCompletion,runContext,runCopy,runDelete,runDuplicates,runFocus,runGet,runGuide,runList,runNext,runPauseTask,runReindex,runReopen,runRestore,runSearch,runStartTask,runStats,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runUpdate,runWithActiveExtensions,scanItemFormatVersions,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,search,selectImportAuthor,serializeItemDocument,splitFrontMatter,startTask,stats,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,upgrade,validate,writeFileAtomic};
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]="f42d8a66-b4c0-5281-b5ef-fdc0ea503f58")}catch(e2){}})();import{AsyncLocalStorage}from"node:async_hooks";import{createEmptyExtensionCommandRegistry,createEmptyExtensionHookRegistry,createEmptyExtensionParserRegistry,createEmptyExtensionPreflightRegistry,createEmptyExtensionRegistrationRegistry,createEmptyExtensionRendererRegistry,createEmptyExtensionServiceRegistry}from"../core/extensions/extension-registries.js";import{activateExtensions,deactivateExtensions,loadExtensions,runActiveCommandHandler,runWithIsolatedExtensionRuntime,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices}from"../core/extensions/index.js";import{pathExists}from"../core/fs/fs-utils.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{createAsyncReadWriteGate}from"../core/shared/serial-queue.js";import{getSettingsPath,resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{PM_TOOL_ACTIONS}from"./cli-contracts/enum-contracts.js";import{runContracts}from"./cli-contracts/runtime-contracts.js";import{attachReadOutputContracts}from"./context-intent-contracts.js";import{runWithDiscoveredContextIntentContracts}from"./context-intent-runtime.js";import{finalizeContextUsageEgress}from"./context/usage-egress.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{INIT_INVOCATION_CWD}from"./init.js";import{certifyCompleteListResult,createCompleteListOptions}from"./query/complete-list.js";import{listClientItemMetadataLight}from"./query/light-metadata.js";import{normalizeReadOutputIncludeModeOptions,validateReadOutputOptions}from"./read-output-contracts.js";import{SDK_ACTION_ALIASES}from"./runtime-action-aliases.js";import{closeManyOptionsFromFlat,extensionOptionsFromArgs,actionGlobalOptions as globalOptions,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,readRuntimeScalarString as readScalarString,readRuntimeScalarStringAllowBlank as readScalarStringAllowBlank,readRuntimeString as readString,readRuntimeStringArray as readStringArray,shouldInvalidateWorkspaceContractsCacheAfterAction,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction}from"./runtime-input.js";import{SDK_ACTION_HANDLERS}from"./runtime/actions.js";import{getOwnHandler,readRequiredString}from"./runtime/context.js";import{clearWorkspaceContractsCache}from"./workspace-contracts-cache.js";import{PM_GITIGNORE_END,PM_GITIGNORE_START,ensurePmGitignore,getPmGitignoreBlock}from"./workspace.js";import{SEARCH_EXTENSION_FLAG_DEFINITIONS}from"./extension-contracts.js";export*from"./cli-contracts/agent-output-contracts.js";import{PmCompleteListValidationError,assertCompleteListResult,certifyCompleteListResult as certifyCompleteListResult2,createCompleteListOptions as createCompleteListOptions2,inspectCompleteListResult}from"./query/complete-list.js";import{getWorkspaceContracts}from"./query/workspace-contracts.js";import{clearWorkspaceContractsCache as clearWorkspaceContractsCache2}from"./workspace-contracts-cache.js";export*from"./governance/workflow-policy.js";import{runCloseTask,runPauseTask,runStartTask}from"./lifecycle/task-composition.js";import{getActiveExtensionRegistrations,runActiveOnReadHooks,runActiveOnWriteHooks}from"../core/extensions/index.js";import{pathExists as pathExists2,readFileIfExists,removeFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{appendHistoryEntry,createHistoryEntry}from"../core/history/history.js";import{HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS,classifyHistoryEvent}from"../core/history/event-classification.js";import{generateItemId,normalizeItemId,normalizeRawItemId}from"../core/item/id.js";import{readBooleanOption,readCsvListOption,readStringOption}from"./package-runtime-options.js";import{PM_CLI_EXPECTED_ERROR_NAME,createPmCliExpectedError,isPmCliExpectedError}from"./errors.js";import{commitImportedItem,emptyImportedDocument,ensureTrackerInitialized,selectImportAuthor,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString}from"./package-import-adapters.js";import{canonicalDocument,normalizeItemMetadata,serializeItemDocument,splitFrontMatter}from"../core/item/item-format.js";import{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,classifyItemFormatVersion,effectiveItemFormatVersion,normalizeItemFormatVersion,scanItemFormatVersions}from"../core/item/item-format-version.js";import{parseTags}from"../core/item/parse.js";import{isTerminalStatus,normalizeStatusInput}from"../core/item/status.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{acquireLock}from"../core/lock/lock.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{PmCliError as PmCliError2}from"../core/shared/errors.js";import{isTimestampLiteral,nowIso}from"../core/shared/time.js";import{jaccardSimilarity,normalizeSimilarityText,scoreItemSimilarity,tokenizeSimilarityText}from"./similarity-scoring.js";import{listAllItemMetadata,listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{getHistoryPath,getItemPath,getSettingsPath as getSettingsPath2,resolveImplicitPmRoot,resolvePmRoot as resolvePmRoot2}from"../core/store/paths.js";import{readSettings as readSettings2}from"../core/store/settings.js";import{runAggregate}from"./query/aggregate.js";import{CONTEXT_OUTPUT_VALUES,runContext}from"./query/context.js";import{runGet}from"./query/get.js";import{runList}from"./query/list.js";import{closeItem,runClose}from"./lifecycle/close.js";import{runCopy}from"./lifecycle/copy.js";import{runDelete}from"./lifecycle/delete.js";import{runFocus}from"./lifecycle/focus.js";import{runRestore}from"./lifecycle/restore.js";import{DEFAULT_TERMINAL_TRANSITION_POLICY,applyTerminalOrderingPolicy,requireTerminalReason,resolveTerminalReason}from"./lifecycle-policy.js";import{runUpdate}from"./lifecycle/update.js";import{runReopen}from"./lifecycle/reopen.js";import{NEXT_OUTPUT_VALUES,runNext}from"./query/next.js";import{runSearch}from"./query/search.js";import{runStats}from"./stats.js";import{runDuplicates}from"./duplicates.js";import{renderCalendarMarkdown,renderCalendarToon,resolveCalendarOutputFormat,runCalendar}from"./query/calendar.js";import{renderGuideMarkdown,resolveGuideOutputFormat,runGuide}from"./guide.js";import{runCompletion}from"./completion.js";import{runReindex}from"./governance/reindex.js";import{loadCreateTemplateOptions,runTemplatesList,runTemplatesSave,runTemplatesShow}from"./templates.js";import{runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop}from"./test/runs.js";import{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,DEPENDENCY_KIND_VALUES,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,RISK_VALUES,STATUS_VALUES}from"../types/index.js";const ACTIVE_EXTENSION_HOST_CONTEXT=Symbol("pm.active-extension-host-context");function splitFullClientMutationOptions(options){return{fullChangedFields:true,options}}class PmClient{defaults;constructor(options={}){this.defaults={...options.pmRoot===void 0?{}:{path:options.pmRoot},...options.cwd===void 0?{}:{cwd:options.cwd},...options.author===void 0?{}:{author:options.author},...options.noExtensions===void 0?{}:{noExtensions:options.noExtensions}}}static forActiveExtensionHost(options){const client=new PmClient({...options,noExtensions:true});client.defaults[ACTIVE_EXTENSION_HOST_CONTEXT]=true;return client}run(action,args={}){return runAction({...this.defaults,...args,action})}runTyped(action,args={}){return this.run(action,args)}context(options={}){return this.runTyped("context",{options})}listAllItemMetadataLight(){return listClientItemMetadataLight(this.defaults.path,this.defaults.cwd)}list(options={}){return this.runTyped("list",{options})}async listAllComplete(options={}){return certifyCompleteListResult(await this.list(createCompleteListOptions(options)))}search(query,options={}){return this.runTyped("search",{query,options})}get(id,options={}){return this.runTyped("get",{id,options})}next(options={}){return this.runTyped("next",{options})}aggregate(options={}){return this.runTyped("aggregate",{options})}stats(options={}){return this.runTyped("stats",{options})}duplicates(options={}){return this.runTyped("duplicates",{options})}comments(id,options={}){return this.runTyped("comments",{id,options})}notes(id,options={}){return this.runTyped("notes",{id,options})}learnings(id,options={}){return this.runTyped("learnings",{id,options})}files(id,options={}){return this.runTyped("files",{id,options})}filesDiscover(id,options={}){return this.runTyped("files-discover",{id,options})}filesLookup(options){return this.runTyped("files-lookup",{options})}docs(id,options={}){return this.runTyped("docs",{id,options})}deps(id,options={}){return this.runTyped("deps",{id,options})}graph(subcommand,ids={},options={}){return this.runTyped("graph",{subcommand,...ids,options})}append(id,body,options={}){return this.runTyped("append",{id,...splitFullClientMutationOptions(mutationOptionsWithOverrides(options,{body}))})}init(prefix,options={}){return this.runTyped("init",{...prefix===void 0?{}:{prefix},options})}config(scope,configAction,key,value,options={}){return this.runTyped("config",{scope,configAction,...key===void 0?{}:{key},...value===void 0?{}:{value},options})}schema(subcommand,options={}){return this.runTyped("schema",{options:{...options,subcommand}})}workflowPolicy(action,name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:action}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(name){return this.runTyped("schema",{name,options:{subcommand:"show"}})}schemaAddType(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-type"}})}schemaRemoveType(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-type"}})}schemaAddStatus(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-status"}})}schemaRemoveStatus(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-status"}})}schemaAddField(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-field"}})}schemaRemoveField(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(name){return this.runTyped("schema",{name,options:{subcommand:"show-field"}})}schemaApplyPreset(typePreset,options={}){return this.runTyped("schema",{typePreset,options:{...options,subcommand:"apply-preset"}})}schemaInferTypes(options={}){return this.runTyped("schema",{options:{...options,subcommand:"add-type",infer:true}})}schemaRenameType(from,to,options){return this.runTyped("schema",{name:from,options:{...options,subcommand:"rename-type",to}})}schemaRenameField(from,to,options,type){return this.runTyped("schema",{name:from,options:{...options,subcommand:"rename-field",to,...type?{fieldTypeScope:type}:{}}})}schemaRemapStatus(from,to,options){return this.runTyped("schema",{name:from,options:{...options,subcommand:"remap-status",to}})}schemaShowStatus(name){return this.runTyped("schema",{name,options:{subcommand:"show-status"}})}profile(subcommand,options={}){return this.runTyped("profile",{options:{...options,subcommand}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(name){return this.runTyped("profile",{name,options:{subcommand:"show"}})}profileApply(name,options={}){return this.runTyped("profile",{name,options:{...options,subcommand:"apply"}})}profileLint(name){return this.runTyped("profile",{name,options:{subcommand:"lint"}})}validate(options={}){return this.runTyped("validate",{options})}health(options={}){return this.runTyped("health",{options})}gc(options={}){return this.runTyped("gc",{options})}assurance(input){return this.runTyped("assurance",{options:{...input,subcommand:input.action}})}historyRedact(id,options){return this.runTyped("history-redact",{id,options})}historyRepair(id,options={}){return this.runTyped("history-repair",{id,options})}historyRepairAll(options={}){return this.runTyped("history-repair",{options:{...options,all:true}})}historyAttest(options={}){return this.runTyped("history-attest",{options})}historyCompact(id,options={}){return this.runTyped("history-compact",{id,options})}historyCompactBulk(options){return this.runTyped("history-compact",{options})}historyAuthorAcknowledge(options){return this.runTyped("history-author-acknowledge",{historyEvent:(options.events??[]).map(event=>`${event.item_id}:${String(event.line)}`),allActionable:options.all_actionable===true,dryRun:options.dry_run===true,planFingerprint:options.plan_fingerprint,limit:options.coordinate_limit,attributedAuthor:options.attributed_author,reviewer:options.reviewer,reason:options.reason})}plan(subcommand,id,options={},stepRef,reorderTo){return this.runTyped("plan",{fullChangedFields:true,...id===void 0?{}:{id},...stepRef===void 0?{}:{stepRef},...reorderTo===void 0?{}:{reorderTo},options:mutationOptionsWithOverrides(options,{subcommand})})}planCreate(options){return this.plan("create",void 0,options)}planShow(id,options={}){return this.plan("show",id,options)}planAddStep(id,options){return this.plan("add-step",id,options)}planUpdateStep(id,stepRef,options){return this.plan("update-step",id,options,stepRef)}planCompleteStep(id,stepRef,options={}){return this.plan("complete-step",id,options,stepRef)}planBlockStep(id,stepRef,options){return this.plan("block-step",id,options,stepRef)}planReorderStep(id,stepRef,reorderTo,options={}){return this.plan("reorder-step",id,options,stepRef,reorderTo)}planRemoveStep(id,stepRef,options={}){return this.plan("remove-step",id,options,stepRef)}planLink(id,stepRef,options){return this.plan("link",id,options,stepRef)}planUnlink(id,stepRef,options){return this.plan("unlink",id,options,stepRef)}planDecision(id,options){return this.plan("decision",id,options)}planDiscovery(id,options){return this.plan("discovery",id,options)}planValidation(id,options){return this.plan("validation",id,options)}planResume(id,options){return this.plan("resume",id,options)}planApprove(id,options={}){return this.plan("approve",id,options)}planMaterialize(id,options){return this.plan("materialize",id,options)}create(options={}){return this.runTyped("create",splitFullClientMutationOptions(options))}update(id,options={}){return this.runTyped("update",{id,...splitFullClientMutationOptions(options)})}reopen(id,reason,options={}){return this.runTyped("item-reopen",{id,reason,fullChangedFields:true,options})}close(id,reason,options={}){return this.runTyped("close",{id,reason,...splitFullClientMutationOptions(options)})}claim(id,options={}){return this.runTyped("claim",{id,...splitFullClientMutationOptions(options)})}claimNext(options={}){return this.runTyped("claim",{next:true,...splitFullClientMutationOptions(options)})}release(id,options={}){return this.runTyped("release",{id,...splitFullClientMutationOptions(options)})}copy(id,options={}){return this.runTyped("copy",{id,...splitFullClientMutationOptions(options)})}delete(id,options={}){return this.runTyped("delete",{id,...splitFullClientMutationOptions(options)})}restore(id,target,options={}){return this.runTyped("restore",{fullChangedFields:true,id,options:{...options,target}})}focus(id,options={}){return this.runTyped("focus",{...id===void 0?{}:{id},...splitFullClientMutationOptions(options)})}startTask(id,options={}){return this.runTyped("start-task",{id,...splitFullClientMutationOptions(options)})}pauseTask(id,options={}){return this.runTyped("pause-task",{id,...splitFullClientMutationOptions(options)})}closeTask(id,reason,options={}){return this.runTyped("close-task",{id,reason,...splitFullClientMutationOptions(options)})}extension(target,options={}){return this.runTyped("extension",{...target===void 0?{}:{target},options})}extensionList(options={}){return this.extension("list",options)}extensionActivate(target,options={}){return this.runTyped("extension-activate",{target,options})}extensionDeactivate(target,options={}){return this.runTyped("extension-deactivate",{target,options})}package(target,options={}){return this.runTyped("package",{...target===void 0?{}:{target},options:{...options,vocabulary:"package"}})}packageList(options={}){return this.package("list",options)}packageInstall(target,options={}){return this.runTyped("package-install",{target,options})}packageUninstall(target,options={}){return this.runTyped("package-uninstall",{target,options})}packageDoctor(options={}){return this.runTyped("package-doctor",{options})}packageManage(target,options={}){return this.runTyped("package-manage",{...target===void 0?{}:{target},options})}packageDescribe(target,options={}){return this.runTyped("package-describe",{...target===void 0?{}:{target},options})}packageReload(options={}){return this.runTyped("package-reload",{options})}packageCatalog(options={}){return this.runTyped("package-catalog",{options})}packageActivate(target,options={}){return this.runTyped("package-activate",{target,options})}packageDeactivate(target,options={}){return this.runTyped("package-deactivate",{target,options})}packageMigrate(options={}){return this.package(void 0,{...options,migrate:true})}upgrade(target,options={}){return this.runTyped("upgrade",{...target===void 0?{}:{target},options})}}function context(options={},clientOptions={}){return new PmClient(clientOptions).context(options)}function list(options={},clientOptions={}){return new PmClient(clientOptions).list(options)}function listAllComplete(options={},clientOptions={}){return new PmClient(clientOptions).listAllComplete(options)}function search(query,options={},clientOptions={}){return new PmClient(clientOptions).search(query,options)}function get(id,options={},clientOptions={}){return new PmClient(clientOptions).get(id,options)}function next(options={},clientOptions={}){return new PmClient(clientOptions).next(options)}function aggregate(options={},clientOptions={}){return new PmClient(clientOptions).aggregate(options)}function stats(options={},clientOptions={}){return new PmClient(clientOptions).stats(options)}function duplicates(options={},clientOptions={}){return new PmClient(clientOptions).duplicates(options)}function comments(id,options={},clientOptions={}){return new PmClient(clientOptions).comments(id,options)}function notes(id,options={},clientOptions={}){return new PmClient(clientOptions).notes(id,options)}function learnings(id,options={},clientOptions={}){return new PmClient(clientOptions).learnings(id,options)}function files(id,options={},clientOptions={}){return new PmClient(clientOptions).files(id,options)}function filesDiscover(id,options={},clientOptions={}){return new PmClient(clientOptions).filesDiscover(id,options)}function filesLookup(options,clientOptions={}){return new PmClient(clientOptions).filesLookup(options)}function docs(id,options={},clientOptions={}){return new PmClient(clientOptions).docs(id,options)}function deps(id,options={},clientOptions={}){return new PmClient(clientOptions).deps(id,options)}function graph(subcommand,ids={},options={},clientOptions={}){return new PmClient(clientOptions).graph(subcommand,ids,options)}function append(id,body,options={},clientOptions={}){return new PmClient(clientOptions).append(id,body,options)}function init(prefix,options={},clientOptions={}){return new PmClient(clientOptions).init(prefix,options)}function config(scope,configAction,key,value,options={},clientOptions={}){return new PmClient(clientOptions).config(scope,configAction,key,value,options)}function schema(subcommand,options={},clientOptions={}){return new PmClient(clientOptions).schema(subcommand,options)}function schemaList(clientOptions={}){return new PmClient(clientOptions).schemaList()}function schemaShow(name,clientOptions={}){return new PmClient(clientOptions).schemaShow(name)}function schemaAddType(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddType(name,options)}function schemaRemoveType(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveType(name,options)}function schemaAddStatus(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddStatus(name,options)}function schemaRemoveStatus(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveStatus(name,options)}function schemaAddField(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddField(name,options)}function schemaRemoveField(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveField(name,options)}function schemaListFields(clientOptions={}){return new PmClient(clientOptions).schemaListFields()}function schemaShowField(name,clientOptions={}){return new PmClient(clientOptions).schemaShowField(name)}function schemaApplyPreset(typePreset,options={},clientOptions={}){return new PmClient(clientOptions).schemaApplyPreset(typePreset,options)}function schemaInferTypes(options={},clientOptions={}){return new PmClient(clientOptions).schemaInferTypes(options)}function schemaRenameType(from,to,options,clientOptions={}){return new PmClient(clientOptions).schemaRenameType(from,to,options)}function schemaRenameField(from,to,options,type,clientOptions={}){return new PmClient(clientOptions).schemaRenameField(from,to,options,type)}function schemaRemapStatus(from,to,options,clientOptions={}){return new PmClient(clientOptions).schemaRemapStatus(from,to,options)}function schemaShowStatus(name,clientOptions={}){return new PmClient(clientOptions).schemaShowStatus(name)}function profile(subcommand,options={},clientOptions={}){return new PmClient(clientOptions).profile(subcommand,options)}function profileList(clientOptions={}){return new PmClient(clientOptions).profileList()}function profileShow(name,clientOptions={}){return new PmClient(clientOptions).profileShow(name)}function profileApply(name,options={},clientOptions={}){return new PmClient(clientOptions).profileApply(name,options)}function profileLint(name,clientOptions={}){return new PmClient(clientOptions).profileLint(name)}function validate(options={},clientOptions={}){return new PmClient(clientOptions).validate(options)}function health(options={},clientOptions={}){return new PmClient(clientOptions).health(options)}function gc(options={},clientOptions={}){return new PmClient(clientOptions).gc(options)}function historyRedact(id,options,clientOptions={}){return new PmClient(clientOptions).historyRedact(id,options)}function historyRepair(id,options={},clientOptions={}){return new PmClient(clientOptions).historyRepair(id,options)}function historyRepairAll(options={},clientOptions={}){return new PmClient(clientOptions).historyRepairAll(options)}function historyCompact(id,options={},clientOptions={}){return new PmClient(clientOptions).historyCompact(id,options)}function historyCompactBulk(options,clientOptions={}){return new PmClient(clientOptions).historyCompactBulk(options)}function create(options={},clientOptions={}){return new PmClient(clientOptions).create(options)}function update(id,options={},clientOptions={}){return new PmClient(clientOptions).update(id,options)}function reopen(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).reopen(id,reason,options)}function close(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).close(id,reason,options)}function claim(id,options={},clientOptions={}){return new PmClient(clientOptions).claim(id,options)}function claimNext(options={},clientOptions={}){return new PmClient(clientOptions).claimNext(options)}function release(id,options={},clientOptions={}){return new PmClient(clientOptions).release(id,options)}function copy(id,options={},clientOptions={}){return new PmClient(clientOptions).copy(id,options)}function deleteItem(id,options={},clientOptions={}){return new PmClient(clientOptions).delete(id,options)}function restore(id,target,options={},clientOptions={}){return new PmClient(clientOptions).restore(id,target,options)}function focus(id,options={},clientOptions={}){return new PmClient(clientOptions).focus(id,options)}function startTask(id,options={},clientOptions={}){return new PmClient(clientOptions).startTask(id,options)}function pauseTask(id,options={},clientOptions={}){return new PmClient(clientOptions).pauseTask(id,options)}function closeTask(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).closeTask(id,reason,options)}function extension(target,options={},clientOptions={}){return new PmClient(clientOptions).extension(target,options)}function extensionList(options={},clientOptions={}){return new PmClient(clientOptions).extensionList(options)}function extensionActivate(target,options={},clientOptions={}){return new PmClient(clientOptions).extensionActivate(target,options)}function extensionDeactivate(target,options={},clientOptions={}){return new PmClient(clientOptions).extensionDeactivate(target,options)}function packageLifecycle(target,options={},clientOptions={}){return new PmClient(clientOptions).package(target,options)}function packageList(options={},clientOptions={}){return new PmClient(clientOptions).packageList(options)}function packageInstall(target,options={},clientOptions={}){return new PmClient(clientOptions).packageInstall(target,options)}function packageUninstall(target,options={},clientOptions={}){return new PmClient(clientOptions).packageUninstall(target,options)}function packageDoctor(options={},clientOptions={}){return new PmClient(clientOptions).packageDoctor(options)}function packageManage(target,options={},clientOptions={}){return new PmClient(clientOptions).packageManage(target,options)}function packageDescribe(target,options={},clientOptions={}){return new PmClient(clientOptions).packageDescribe(target,options)}function packageReload(options={},clientOptions={}){return new PmClient(clientOptions).packageReload(options)}function packageCatalog(options={},clientOptions={}){return new PmClient(clientOptions).packageCatalog(options)}function packageActivate(target,options={},clientOptions={}){return new PmClient(clientOptions).packageActivate(target,options)}function packageDeactivate(target,options={},clientOptions={}){return new PmClient(clientOptions).packageDeactivate(target,options)}function upgrade(target,options={},clientOptions={}){return new PmClient(clientOptions).upgrade(target,options)}async function getContracts(pmRootOrOptions,options={}){const resolvedOptions=typeof pmRootOrOptions==="string"?{...options,pmRoot:pmRootOrOptions}:pmRootOrOptions??options;const global2={json:true,quiet:resolvedOptions.quiet??true,noExtensions:resolvedOptions.noExtensions??false,noPager:true,profile:resolvedOptions.profile??false,path:resolvedOptions.pmRoot};return runContracts(resolvedOptions,global2)}const extensionActivationGate=createAsyncReadWriteGate();const activeExtensionScope=new AsyncLocalStorage;function resetActiveExtensionRegistries(){setActiveExtensionHooks(createEmptyExtensionHookRegistry());setActiveExtensionCommands(createEmptyExtensionCommandRegistry());setActiveExtensionParsers(createEmptyExtensionParserRegistry());setActiveExtensionPreflight(createEmptyExtensionPreflightRegistry());setActiveExtensionServices(createEmptyExtensionServiceRegistry());setActiveExtensionRenderers(createEmptyExtensionRendererRegistry());setActiveExtensionRegistrations(createEmptyExtensionRegistrationRegistry())}async function withActiveExtensions(global2,explicitCwd,resolutionCwd,run){return runWithIsolatedExtensionRuntime(()=>explicitCwd===void 0?extensionActivationGate.read(()=>withActiveExtensionsExclusively(global2,resolutionCwd,run)):extensionActivationGate.write(()=>withCwd(explicitCwd,()=>withActiveExtensionsExclusively(global2,resolutionCwd,run))))}async function runWithActiveExtensions(options,run){const explicitCwd=options.cwd;const resolutionCwd=explicitCwd??process.cwd();return withActiveExtensions(globalOptions({path:options.path,noExtensions:options.noExtensions}),explicitCwd,resolutionCwd,()=>activeExtensionScope.run(true,run))}async function withActiveExtensionsExclusively(global2,cwd,run){const pmRoot=resolvePmRoot(cwd,global2.path);if(global2.noExtensions){resetActiveExtensionRegistries();return runWithDiscoveredContextIntentContracts({pmRoot},()=>run(null))}if(!await pathExists(getSettingsPath(pmRoot))){resetActiveExtensionRegistries();return run(null)}let active=null;let activated;try{const settings=await readSettings(pmRoot);const loadResult=await loadExtensions({pmRoot,settings,cwd,noExtensions:false});const activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});activated={loadResult,activationResult};setActiveExtensionHooks(activationResult.hooks);setActiveExtensionCommands(activationResult.commands);setActiveExtensionParsers(activationResult.parsers);setActiveExtensionPreflight(activationResult.preflight);setActiveExtensionServices(activationResult.services);setActiveExtensionRenderers(activationResult.renderers);setActiveExtensionRegistrations(activationResult.registrations);active={registrations:activationResult.registrations,commands:activationResult.commands,pmRoot,packages:loadResult.loaded}}catch(error){resetActiveExtensionRegistries();console.error("[pm-sdk] extension activation failed; continuing without active extensions:",error)}try{return await runWithDiscoveredContextIntentContracts({pmRoot,packages:active?.packages},()=>run(active))}finally{resetActiveExtensionRegistries();if(activated){await deactivateExtensions(activated.loadResult,activated.activationResult).catch(()=>void 0)}}}async function dispatchActiveExtensionAction(action,args,options,global2,active){if(!active){throw new PmCliError(`Unsupported native pm action: ${action}`,EXIT_CODE.USAGE)}const normalizedAction=normalizeActionName(action);const definition=active.registrations.commands.find(entry=>normalizeActionName(entry.action)===normalizedAction);const command=definition?.command??active.commands.handlers.find(entry=>normalizeActionName(entry.command)===normalizedAction)?.command;if(!command){throw new PmCliError(`Unsupported native pm action: ${action}`,EXIT_CODE.USAGE)}const extensionAuthor=typeof global2.author==="string"&&global2.author.trim()?global2.author.trim():"pm-extension";const handlerResult=await runActiveCommandHandler({command:normalizeCommandPath(command),args:readStringArray(options.args??args.args),options:extensionOptionsFromArgs(args,options),global:global2,pm_root:active.pmRoot,sdk:createExtensionCommandSdk(active.pmRoot,PmClient.forActiveExtensionHost({pmRoot:active.pmRoot,author:extensionAuthor}),extensionAuthor,normalizeCommandPath(command))});if(!handlerResult.handled){const suffix=handlerResult.warnings.length>0?` (${handlerResult.warnings.join(", ")})`:"";throw new PmCliError(`Unsupported native pm action: ${action}${suffix}`,EXIT_CODE.USAGE)}return handlerResult.result}async function withCwd(cwd,run){const previous=process.cwd();process.chdir(cwd);try{return await run()}finally{process.chdir(previous)}}function resolveSdkActionInput(args){const rawAction=readRequiredString(args,"action");const normalizedAction=normalizeActionName(rawAction);const alias=getOwnHandler(SDK_ACTION_ALIASES,normalizedAction);const action=alias?.action??normalizedAction;const resolvedArgs={...args,action};if(alias?.options!==void 0){resolvedArgs.options={...alias.options,...asRecordClone(args.options)}}if(action==="package"){resolvedArgs.options={...asRecordClone(resolvedArgs.options),vocabulary:"package"}}return{action,args:resolvedArgs}}async function runAction(args){const resolved=resolveSdkActionInput(args);const global2=globalOptions(resolved.args);const invalidateWorkspaceContractsCache=shouldInvalidateWorkspaceContractsCacheAfterAction(resolved.action);const explicitCwd=readString(resolved.args,"cwd");const resolutionCwd=explicitCwd??process.cwd();if(resolved.action==="init"){global2[INIT_INVOCATION_CWD]=resolutionCwd}if(resolved.action!=="init"||global2.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0){global2.path=resolvePmRoot(resolutionCwd,global2.path)}try{if(resolved.action==="history-attest"){return await dispatchAction(resolved.action,resolved.args,global2,null)}if(args[ACTIVE_EXTENSION_HOST_CONTEXT]===true||activeExtensionScope.getStore()===true){return await dispatchAction(resolved.action,resolved.args,global2,null)}return await withActiveExtensions(global2,explicitCwd,resolutionCwd,activeExtensions=>dispatchAction(resolved.action,resolved.args,global2,activeExtensions))}finally{if(invalidateWorkspaceContractsCache){clearWorkspaceContractsCache()}}}function analyzeSdkActionCoverage(actions=PM_TOOL_ACTIONS){return actions.map(action=>{const normalized=normalizeActionName(action);const alias=getOwnHandler(SDK_ACTION_ALIASES,normalized);const resolvedAction=alias?.action??normalized;const covered=getOwnHandler(SDK_ACTION_HANDLERS,resolvedAction)!==void 0;return{action,resolved_action:resolvedAction,covered,route:covered?alias?"alias":"native":"missing"}})}async function dispatchAction(action,args,global2,activeExtensions){const options=optionsWithAuthor(args,action);validateReadOutputOptions(action,options);normalizeReadOutputIncludeModeOptions(action,options);const ctx={action,args,options,id:readString(args,"id"),force:args.force===true||options.force===true,global:global2,activeExtensions};const handler=getOwnHandler(SDK_ACTION_HANDLERS,action);const result=handler?await handler(ctx):await dispatchActiveExtensionAction(action,args,options,global2,activeExtensions);if(action==="history-attest"){return result}else{options.resolvedOutputFormat="json";const projected=attachReadOutputContracts(action,options,result);await finalizeContextUsageEgress(resolvePmRoot(process.cwd(),global2.path),projected);return projected}}const actionRunnerTestHooks={closeManyOptionsFromFlat,extensionOptionsFromArgs,globalOptions,mutationListOptions,normalizeActionName,normalizeCommandPath,normalizeMcpUpdateOptions,normalizeMcpOptionsArrays,optionsWithAuthor,readRequiredString,readScalarString,readScalarStringAllowBlank,readStringArray,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};if(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0){globalThis.__pmCliActionRunnerTestHooks=actionRunnerTestHooks}import{readRequiredString as readRequiredString2}from"./runtime/context.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_OUTPUT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_TERMINAL_TRANSITION_POLICY,DEPENDENCY_KIND_VALUES,EXIT_CODE,HISTORY_EVENT_CLASSIFICATION_VERSION,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,MAINTENANCE_HISTORY_OPERATIONS,NEXT_OUTPUT_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_GITIGNORE_END,PM_GITIGNORE_START,PmCliError2 as PmCliError,PmClient,PmCompleteListValidationError,RISK_VALUES,SEARCH_EXTENSION_FLAG_DEFINITIONS,STATUS_VALUES,SUBSTANTIVE_HISTORY_OPERATIONS,acquireLock,aggregate,analyzeSdkActionCoverage,append,appendHistoryEntry,applyTerminalOrderingPolicy,assertCompleteListResult,canonicalDocument,certifyCompleteListResult2 as certifyCompleteListResult,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,clearWorkspaceContractsCache2 as clearWorkspaceContractsCache,close,closeItem,closeTask,comments,commitImportedItem,config,context,copy,create,createCompleteListOptions2 as createCompleteListOptions,createHistoryEntry,createPmCliExpectedError,deleteItem,deps,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureTrackerInitialized,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getPmGitignoreBlock,getSettingsPath2 as getSettingsPath,getWorkspaceContracts,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,inspectCompleteListResult,isPmCliExpectedError,isTerminalStatus,isTimestampLiteral,jaccardSimilarity,learnings,list,listAllComplete,listAllItemMetadata,listAllItemMetadataLight,loadCreateTemplateOptions,locateItem,next,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,parseTags,pathExists2 as pathExists,pauseTask,profile,profileApply,profileLint,profileList,profileShow,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString2 as readRequiredString,readSettings2 as readSettings,readStringOption,release,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,reopen,requireTerminalReason,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemTypeRegistry,resolvePmRoot2 as resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveTerminalReason,restore,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runCalendar,runClose,runCloseTask,runCompletion,runContext,runCopy,runDelete,runDuplicates,runFocus,runGet,runGuide,runList,runNext,runPauseTask,runReindex,runReopen,runRestore,runSearch,runStartTask,runStats,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runUpdate,runWithActiveExtensions,scanItemFormatVersions,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,search,selectImportAuthor,serializeItemDocument,splitFrontMatter,startTask,stats,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,upgrade,validate,writeFileAtomic};
2
2
  //# 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]="d6ceb51a-6085-5d65-aebe-31d09ea4d1d6")}catch(e2){}})();import crypto from"node:crypto";import{normalizeItemId,normalizePrefix}from"../core/item/id.js";import{preserveMutationStdinTokenLiterals}from"../core/item/parse.js";import{EXIT_CODE,ITEM_PROJECT_CONTEXT_KEYS}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{CLOSE_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS}from"./cli-contracts/flag-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";const MUTATION_ROW_KEYS=["op","id","reason","options"];const REFERENCED_MUTATION_ROW_KEYS=[...MUTATION_ROW_KEYS,"ref"];const MUTATION_DOCUMENT_KEYS=["schema_version","mutations"];const MUTATION_REFERENCE_SOURCE="[a-z][a-z0-9._-]{0,63}";const MUTATION_REFERENCE_PATTERN=new RegExp(`^${MUTATION_REFERENCE_SOURCE}$`,"u");const MUTATION_DEPENDENCY_REFERENCE_PATTERN=new RegExp(`(^|,)id=@(${MUTATION_REFERENCE_SOURCE})(?=,|$)`,"gu");const flagToOptionKey=flag=>flag.slice(2).replaceAll(/-([a-z])/gu,(_match,letter)=>letter.toUpperCase());const ITEM_ENVELOPE_KEYS=["item","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"];const READ_ONLY_ITEM_KEYS=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count"]);const UPDATE_READ_ONLY_ITEM_KEYS=new Set([...READ_ONLY_ITEM_KEYS,"completed_at","id"]);const ITEM_FIELD_KEYS=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...ITEM_PROJECT_CONTEXT_KEYS,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);const MUTATION_OPTION_KEYS={create:CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS.map(contract=>contract.target),update:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS.map(contract=>contract.target),close:CLOSE_FLAG_CONTRACTS.map(contract=>flagToOptionKey(contract.flag)).filter(key=>key!=="reason"),release:RELEASE_FLAG_CONTRACTS.map(contract=>flagToOptionKey(contract.flag))};function parseAtomicMutationControls(value){const controls={};const compensation=value.createCompensation;if(compensation!==void 0){if(compensation!=="close"&&compensation!=="delete"){throw new PmCliError("createCompensation must be close or delete.",EXIT_CODE.USAGE)}controls.createCompensation=compensation}for(const key of["lockTtlSeconds","lockWaitMs"]){const raw=value[key];if(raw===void 0)continue;const parsed=typeof raw==="number"||typeof raw==="string"&&raw.trim().length>0?Number(raw):Number.NaN;if(!Number.isSafeInteger(parsed)||parsed<=0){throw new PmCliError(`${key} must be a positive safe integer.`,EXIT_CODE.USAGE)}controls[key]=parsed}return controls}function isPlainObject(value){if(typeof value!=="object"||value===null||Array.isArray(value)){return false}const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function nearestKey(key,candidates){const limit=Math.max(1,Math.min(3,Math.floor(key.length/4)+1));let best;for(const candidate of candidates){const distance=levenshteinDistanceWithinLimit(key,candidate,limit);if(distance!==null&&(best===void 0||distance<best.distance)){best={key:candidate,distance}}}return best?.key}function unknownKeyError(scope,key,candidates){const suggestion=nearestKey(key,candidates);return new PmCliError(suggestion===void 0?`${scope} does not recognize key "${key}". Allowed keys: ${candidates.join(", ")}.`:`${scope} does not recognize key "${key}". Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"stdin_json_unknown_key",required:`Use documented ${scope} keys only.`,why:"Strict structured input prevents silent typos from creating incomplete or unintended mutations.",nextSteps:[suggestion===void 0?`Remove or correct "${key}".`:`Replace "${key}" with "${suggestion}".`]})}function parseJsonValue(input,label){try{return JSON.parse(input)}catch(error){const detail=error instanceof Error?error.message:String(error);throw new PmCliError(`${label} must be valid JSON: ${detail}`,EXIT_CODE.USAGE,{code:"stdin_json_invalid",required:`Pipe one valid JSON ${label.toLowerCase()} into stdin.`,why:"Structured mutation input must parse deterministically before any tracker write begins."})}}function validateMutationObject(value,index){if(!isPlainObject(value)){throw new PmCliError(`Mutation ${index+1} must be an object.`,EXIT_CODE.USAGE)}for(const key of Object.keys(value)){if(!MUTATION_ROW_KEYS.includes(key)){throw unknownKeyError(`mutation ${index+1}`,key,MUTATION_ROW_KEYS)}}return value}function validateMutationOptions(options,op,index){if(options===void 0)return void 0;if(!isPlainObject(options)){throw new PmCliError(`Mutation ${index+1} options must be an object.`,EXIT_CODE.USAGE)}for(const key of Object.keys(options)){if(!MUTATION_OPTION_KEYS[op].includes(key)){throw unknownKeyError(`mutation ${index+1} ${op} options`,key,MUTATION_OPTION_KEYS[op])}}return options}function validateMutationRow(value,index){const mutation=validateMutationObject(value,index);const{op,id,reason}=mutation;if(op!=="create"&&op!=="update"&&op!=="close"&&op!=="release"){throw new PmCliError(`Mutation ${index+1} op must be create, update, close, or release.`,EXIT_CODE.USAGE)}const options=validateMutationOptions(mutation.options,op,index);if(typeof id!=="string"||id.trim().length===0){throw new PmCliError(`Mutation ${index+1} requires a non-empty id.`,EXIT_CODE.USAGE)}const normalizedId=id.trim();if(op==="close"){if(typeof reason!=="string"||reason.trim().length===0){throw new PmCliError(`Mutation ${index+1} close requires a non-empty reason.`,EXIT_CODE.USAGE)}return{op,id:normalizedId,reason:reason.trim(),...options===void 0?{}:{options}}}if(op==="release"){return{op,id:normalizedId,...options===void 0?{}:{options}}}if(!isPlainObject(options)){throw new PmCliError(`Mutation ${index+1} ${op} requires an options object.`,EXIT_CODE.USAGE)}return{op,id:normalizedId,options}}function parseItemMutationBatch(input){const parsed=parseJsonValue(input,"Mutation batch");const rows=Array.isArray(parsed)?parsed:isPlainObject(parsed)&&Array.isArray(parsed.mutations)?parsed.mutations:void 0;if(rows===void 0||rows.length===0){throw new PmCliError("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",EXIT_CODE.USAGE)}return rows.map((row,index)=>{const mutation=validateMutationRow(row,index);if(mutation.options!==void 0){preserveMutationStdinTokenLiterals(mutation.options)}return mutation})}function deriveReferencedItemId(transactionId,reference,idPrefix){const digest=crypto.createHash("sha256").update(transactionId).update("\0").update(reference).digest("hex");const token=BigInt(`0x${digest.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${normalizePrefix(idPrefix)}${token}`}function replaceExactMutationReference(value,references){if(typeof value!=="string"||!value.startsWith("@")){return value}const reference=value.slice(1);const resolved=references[reference];if(resolved===void 0){throw new PmCliError(`Unknown mutation reference "${value}".`,EXIT_CODE.USAGE)}return resolved}function replaceDependencyReference(value,references){if(typeof value!=="string")return value;const resolvedValue=value.replace(MUTATION_DEPENDENCY_REFERENCE_PATTERN,(_match,prefix,reference)=>{const resolved=references[reference];if(resolved===void 0){throw new PmCliError(`Unknown mutation reference "@${reference}".`,EXIT_CODE.USAGE)}return`${prefix}id=${resolved}`});if(/(^|,)id=@/u.test(resolvedValue)){throw new PmCliError(`Malformed mutation reference in dependency "${value}".`,EXIT_CODE.USAGE)}return resolvedValue}function referencedAliases(value){if(typeof value!=="string")return[];if(value.startsWith("@"))return[value.slice(1)];return[...value.matchAll(MUTATION_DEPENDENCY_REFERENCE_PATTERN)].map(match=>match[1]).filter(reference=>reference!==void 0)}function assertAcyclicCreateReferences(rows){const graph=new Map;for(const row of rows){if(row.op!=="create"||typeof row.ref!=="string")continue;const mutationOptions=isPlainObject(row.options)?row.options:{};const dependencies=Array.isArray(mutationOptions.dep)?mutationOptions.dep:mutationOptions.dep===void 0?[]:[mutationOptions.dep];graph.set(row.ref,[mutationOptions.parent,mutationOptions.blockedBy,...dependencies].flatMap(referencedAliases))}const visiting=new Set;const visited=new Set;const visit=reference=>{if(visiting.has(reference)){throw new PmCliError(`Mutation reference cycle includes "@${reference}".`,EXIT_CODE.USAGE)}if(visited.has(reference))return;visiting.add(reference);for(const dependency of graph.get(reference)){if(graph.has(dependency))visit(dependency)}visiting.delete(reference);visited.add(reference)};for(const reference of graph.keys())visit(reference)}function parseMutationDocumentRows(input){const parsed=parseJsonValue(input,"Mutation document");const envelope=Array.isArray(parsed)?{schema_version:1,mutations:parsed}:parsed;if(!isPlainObject(envelope)){throw new PmCliError("Mutation document must be a JSON array or object.",EXIT_CODE.USAGE)}for(const key of Object.keys(envelope)){if(!MUTATION_DOCUMENT_KEYS.includes(key)){throw unknownKeyError("mutation document",key,MUTATION_DOCUMENT_KEYS)}}if(envelope.schema_version!==void 0&&envelope.schema_version!==1){throw new PmCliError("Mutation document schema_version must be 1.",EXIT_CODE.USAGE)}if(!Array.isArray(envelope.mutations)||envelope.mutations.length===0){throw new PmCliError("Mutation document requires a non-empty mutations array.",EXIT_CODE.USAGE)}return envelope.mutations.map((row,index)=>{if(!isPlainObject(row)){throw new PmCliError(`Mutation ${index+1} must be an object.`,EXIT_CODE.USAGE)}for(const key of Object.keys(row)){if(!REFERENCED_MUTATION_ROW_KEYS.includes(key)){throw unknownKeyError(`mutation ${index+1}`,key,REFERENCED_MUTATION_ROW_KEYS)}}return{...row}})}function collectMutationReferences(rows,options){const references=Object.create(null);for(const[index,row]of rows.entries()){if(row.ref===void 0)continue;if(row.op!=="create"){throw new PmCliError(`Mutation ${index+1} ref is only valid for create operations.`,EXIT_CODE.USAGE)}if(typeof row.ref!=="string"||!MUTATION_REFERENCE_PATTERN.test(row.ref)){throw new PmCliError(`Mutation ${index+1} ref must match ${MUTATION_REFERENCE_PATTERN.source}.`,EXIT_CODE.USAGE)}if(references[row.ref]!==void 0){throw new PmCliError(`Duplicate mutation ref "${row.ref}".`,EXIT_CODE.USAGE)}references[row.ref]=typeof row.id==="string"&&row.id.trim().length>0?normalizeItemId(row.id,options.idPrefix):deriveReferencedItemId(options.transactionId,row.ref,options.idPrefix)}return references}function resolveItemMutationDocument(input,options){const rows=parseMutationDocumentRows(input);const references=collectMutationReferences(rows,options);assertAcyclicCreateReferences(rows);const resolvedRows=rows.map(row=>{const resolved={...row};const reference=typeof resolved.ref==="string"?resolved.ref:void 0;delete resolved.ref;if(reference!==void 0){resolved.id=references[reference]}else{resolved.id=replaceExactMutationReference(resolved.id,references)}if(isPlainObject(resolved.options)){const mutationOptions={...resolved.options};for(const key of["parent","blockedBy"]){if(mutationOptions[key]!==void 0){mutationOptions[key]=replaceExactMutationReference(mutationOptions[key],references)}}if(Array.isArray(mutationOptions.dep)){mutationOptions.dep=mutationOptions.dep.map(entry=>replaceDependencyReference(entry,references))}else if(mutationOptions.dep!==void 0){mutationOptions.dep=replaceDependencyReference(mutationOptions.dep,references)}resolved.options=mutationOptions}return resolved});const mutations=parseItemMutationBatch(JSON.stringify(resolvedRows));const createIds=mutations.filter(mutation=>mutation.op==="create").map(mutation=>mutation.id);if(new Set(createIds).size!==createIds.length){throw new PmCliError("Duplicate resolved create id in mutation document.",EXIT_CODE.USAGE)}return{schema_version:1,mutations,references}}function serializePairs(value,keys){return keys.filter(key=>value[key]!==void 0&&value[key]!==null).map(key=>{const rendered=String(value[key]);return`${key}=${/[",\n\r\\]/u.test(rendered)?JSON.stringify(rendered):rendered}`}).join(",")}function serializeObjectArray(value,keys,label){if(value===void 0)return void 0;if(!Array.isArray(value)||!value.every(isPlainObject)){throw new PmCliError(`${label} must be an array of objects.`,EXIT_CODE.USAGE)}return value.map(entry=>serializePairs(entry,keys))}function scalarItemOption(key,value){if(key==="tags"&&Array.isArray(value)&&value.every(entry=>typeof entry==="string")){return JSON.stringify(value)}if(typeof value==="number"||typeof value==="boolean"){return String(value)}return value}function appendFacetOptions(target,source,skipPersistedAnnotations=false){const mappings=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];for(const[sourceKey,targetKey,keys]of mappings){const sourceValue=source[sourceKey];const serialized=serializeObjectArray(skipPersistedAnnotations&&["comments","notes","learnings"].includes(sourceKey)&&Array.isArray(sourceValue)?sourceValue.filter(entry=>!isPlainObject(entry)||entry.created_at===void 0):sourceValue,keys,sourceKey);if(serialized!==void 0&&serialized.length>0)target[targetKey]=serialized}}function validateItemDocumentKeys(parsed,envelope){for(const key of Object.keys(parsed)){if(envelope){if(!ITEM_ENVELOPE_KEYS.includes(key))throw unknownKeyError("item envelope",key,ITEM_ENVELOPE_KEYS);continue}if(!ITEM_FIELD_KEYS.has(key)&&nearestKey(key,[...ITEM_FIELD_KEYS])===void 0&&nearestKey(key,ITEM_ENVELOPE_KEYS)==="item")throw unknownKeyError("item envelope",key,ITEM_ENVELOPE_KEYS)}}function resolveItemDocument(parsed){const envelope=Object.hasOwn(parsed,"item");validateItemDocumentKeys(parsed,envelope);const item=envelope?parsed.item:parsed;if(!isPlainObject(item)){throw new PmCliError("Item document item must be an object.",EXIT_CODE.USAGE)}return{item,...envelope&&isPlainObject(parsed.linked)?{linked:parsed.linked}:{}}}function appendItemDocumentEntry(documentOptions,key,value,mode){const readOnlyKeys=mode==="update"?UPDATE_READ_ONLY_ITEM_KEYS:READ_ONLY_ITEM_KEYS;if(readOnlyKeys.has(key))return;if(!ITEM_FIELD_KEYS.has(key)){const suggestion=nearestKey(key,[...ITEM_FIELD_KEYS]);if(suggestion!==void 0)throw unknownKeyError("item document",key,[...ITEM_FIELD_KEYS]);const fields=Array.isArray(documentOptions.field)?documentOptions.field:[];fields.push(serializePairs({key,value:typeof value==="string"?value:JSON.stringify(value)},["key","value"]));documentOptions.field=fields;return}if(["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(key))return;documentOptions[key.replaceAll(/_([a-z])/gu,(_match,letter)=>letter.toUpperCase())]=scalarItemOption(key,value)}function itemDocumentToMutationOptions(input,mode,explicitOptions={}){const parsed=parseJsonValue(input,"Item document");if(!isPlainObject(parsed)){throw new PmCliError("Item document must be a JSON object.",EXIT_CODE.USAGE)}const{item,linked}=resolveItemDocument(parsed);const documentOptions={};for(const[key,value]of Object.entries(item)){appendItemDocumentEntry(documentOptions,key,value,mode)}appendFacetOptions(documentOptions,item,mode==="update");if(linked!==void 0)appendFacetOptions(documentOptions,linked);return{...documentOptions,...Object.fromEntries(Object.entries(explicitOptions).filter(([,value])=>value!==void 0)),stdinJson:void 0}}function validateItemMutationRows(value){return parseItemMutationBatch(JSON.stringify(value))}export{itemDocumentToMutationOptions,parseAtomicMutationControls,parseItemMutationBatch,resolveItemMutationDocument,validateItemMutationRows};
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]="2b75ffc0-8175-58fc-8d63-98081a68dcb8")}catch(e2){}})();import crypto from"node:crypto";import{normalizeItemId,normalizePrefix}from"../core/item/id.js";import{preserveMutationStdinTokenLiterals}from"../core/item/parse.js";import{EXIT_CODE,ITEM_PROJECT_CONTEXT_KEYS}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{CLOSE_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS}from"./cli-contracts/flag-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";const MUTATION_ROW_KEYS=["op","id","reason","options"];const REFERENCED_MUTATION_ROW_KEYS=[...MUTATION_ROW_KEYS,"ref"];const MUTATION_DOCUMENT_KEYS=["schema_version","mutations"];const MUTATION_REFERENCE_SOURCE="[a-z][a-z0-9._-]{0,63}";const MUTATION_REFERENCE_PATTERN=new RegExp(`^${MUTATION_REFERENCE_SOURCE}$`,"u");const MUTATION_DEPENDENCY_REFERENCE_PATTERN=new RegExp(`(^|,)id=@(${MUTATION_REFERENCE_SOURCE})(?=,|$)`,"gu");const flagToOptionKey=flag=>flag.slice(2).replaceAll(/-([a-z])/gu,(_match,letter)=>letter.toUpperCase());const ITEM_ENVELOPE_KEYS=["item","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"];const READ_ONLY_ITEM_KEYS=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count"]);const UPDATE_READ_ONLY_ITEM_KEYS=new Set([...READ_ONLY_ITEM_KEYS,"completed_at","id"]);const ITEM_FIELD_KEYS=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...ITEM_PROJECT_CONTEXT_KEYS,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);const MUTATION_OPTION_KEYS={create:CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS.map(contract=>contract.target),update:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS.map(contract=>contract.target),close:CLOSE_FLAG_CONTRACTS.map(contract=>flagToOptionKey(contract.flag)).filter(key=>key!=="reason"),release:RELEASE_FLAG_CONTRACTS.map(contract=>flagToOptionKey(contract.flag))};function parseAtomicMutationControls(value){const controls={};const compensation=value.createCompensation;if(compensation!==void 0){if(compensation!=="close"&&compensation!=="delete"){throw new PmCliError("createCompensation must be close or delete.",EXIT_CODE.USAGE)}controls.createCompensation=compensation}for(const key of["lockTtlSeconds","lockWaitMs"]){const raw=value[key];if(raw===void 0)continue;const parsed=typeof raw==="number"||typeof raw==="string"&&raw.trim().length>0?Number(raw):Number.NaN;if(!Number.isSafeInteger(parsed)||parsed<=0){throw new PmCliError(`${key} must be a positive safe integer.`,EXIT_CODE.USAGE)}controls[key]=parsed}return controls}function isPlainObject(value){if(typeof value!=="object"||value===null||Array.isArray(value)){return false}const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function nearestKey(key,candidates){const limit=Math.max(1,Math.min(3,Math.floor(key.length/4)+1));let best;for(const candidate of candidates){const distance=levenshteinDistanceWithinLimit(key,candidate,limit);if(distance!==null&&(best===void 0||distance<best.distance)){best={key:candidate,distance}}}return best?.key}function unknownKeyError(scope,key,candidates){const suggestion=nearestKey(key,candidates);return new PmCliError(suggestion===void 0?`${scope} does not recognize key "${key}". Allowed keys: ${candidates.join(", ")}.`:`${scope} does not recognize key "${key}". Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"stdin_json_unknown_key",required:`Use documented ${scope} keys only.`,why:"Strict structured input prevents silent typos from creating incomplete or unintended mutations.",nextSteps:[suggestion===void 0?`Remove or correct "${key}".`:`Replace "${key}" with "${suggestion}".`]})}function parseJsonValue(input,label){try{return JSON.parse(input)}catch(error){const detail=error instanceof Error?error.message:String(error);throw new PmCliError(`${label} must be valid JSON: ${detail}`,EXIT_CODE.USAGE,{code:"stdin_json_invalid",required:`Pipe one valid JSON ${label.toLowerCase()} into stdin.`,why:"Structured mutation input must parse deterministically before any tracker write begins."})}}function validateMutationObject(value,index){if(!isPlainObject(value)){throw new PmCliError(`Mutation ${index+1} must be an object.`,EXIT_CODE.USAGE)}for(const key of Object.keys(value)){if(!MUTATION_ROW_KEYS.includes(key)){throw unknownKeyError(`mutation ${index+1}`,key,MUTATION_ROW_KEYS)}}return value}function validateMutationOptions(options,op,index){if(options===void 0)return void 0;if(!isPlainObject(options)){throw new PmCliError(`Mutation ${index+1} options must be an object.`,EXIT_CODE.USAGE)}for(const key of Object.keys(options)){if(!MUTATION_OPTION_KEYS[op].includes(key)){throw unknownKeyError(`mutation ${index+1} ${op} options`,key,MUTATION_OPTION_KEYS[op])}}return options}function validateMutationRow(value,index){const mutation=validateMutationObject(value,index);const{op,id,reason}=mutation;if(op!=="create"&&op!=="update"&&op!=="close"&&op!=="release"){throw new PmCliError(`Mutation ${index+1} op must be create, update, close, or release.`,EXIT_CODE.USAGE)}const options=validateMutationOptions(mutation.options,op,index);if(typeof id!=="string"||id.trim().length===0){throw new PmCliError(`Mutation ${index+1} requires a non-empty id.`,EXIT_CODE.USAGE)}const normalizedId=id.trim();if(op==="close"){if(typeof reason!=="string"||reason.trim().length===0){throw new PmCliError(`Mutation ${index+1} close requires a non-empty reason.`,EXIT_CODE.USAGE)}return{op,id:normalizedId,reason:reason.trim(),...options===void 0?{}:{options}}}if(op==="release"){return{op,id:normalizedId,...options===void 0?{}:{options}}}if(!isPlainObject(options)){throw new PmCliError(`Mutation ${index+1} ${op} requires an options object.`,EXIT_CODE.USAGE)}return{op,id:normalizedId,options}}function parseItemMutationBatch(input){const parsed=parseJsonValue(input,"Mutation batch");const rows=Array.isArray(parsed)?parsed:isPlainObject(parsed)&&Array.isArray(parsed.mutations)?parsed.mutations:void 0;if(rows===void 0||rows.length===0){throw new PmCliError("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",EXIT_CODE.USAGE)}return rows.map((row,index)=>{const mutation=validateMutationRow(row,index);if(mutation.options!==void 0){preserveMutationStdinTokenLiterals(mutation.options)}return mutation})}function deriveReferencedItemId(transactionId,reference,idPrefix){const digest=crypto.createHash("sha256").update(transactionId).update("\0").update(reference).digest("hex");const token=BigInt(`0x${digest.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${normalizePrefix(idPrefix)}${token}`}function replaceExactMutationReference(value,references){if(typeof value!=="string"||!value.startsWith("@")){return value}const reference=value.slice(1);const resolved=references[reference];if(resolved===void 0){throw new PmCliError(`Unknown mutation reference "${value}".`,EXIT_CODE.USAGE)}return resolved}function replaceDependencyReference(value,references){if(typeof value!=="string")return value;const resolvedValue=value.replace(MUTATION_DEPENDENCY_REFERENCE_PATTERN,(_match,prefix,reference)=>{const resolved=references[reference];if(resolved===void 0){throw new PmCliError(`Unknown mutation reference "@${reference}".`,EXIT_CODE.USAGE)}return`${prefix}id=${resolved}`});if(/(^|,)id=@/u.test(resolvedValue)){throw new PmCliError(`Malformed mutation reference in dependency "${value}".`,EXIT_CODE.USAGE)}return resolvedValue}function referencedAliases(value){if(typeof value!=="string")return[];if(value.startsWith("@"))return[value.slice(1)];return[...value.matchAll(MUTATION_DEPENDENCY_REFERENCE_PATTERN)].map(match=>match[1]).filter(reference=>reference!==void 0)}function assertAcyclicCreateReferences(rows){const graph=new Map;for(const row of rows){if(row.op!=="create"||typeof row.ref!=="string")continue;const mutationOptions=isPlainObject(row.options)?row.options:{};const dependencies=Array.isArray(mutationOptions.dep)?mutationOptions.dep:mutationOptions.dep===void 0?[]:[mutationOptions.dep];graph.set(row.ref,[mutationOptions.parent,mutationOptions.blockedBy,...dependencies].flatMap(referencedAliases))}const visiting=new Set;const visited=new Set;const visit=reference=>{if(visiting.has(reference)){throw new PmCliError(`Mutation reference cycle includes "@${reference}".`,EXIT_CODE.USAGE)}if(visited.has(reference))return;visiting.add(reference);for(const dependency of graph.get(reference)){if(graph.has(dependency))visit(dependency)}visiting.delete(reference);visited.add(reference)};for(const reference of graph.keys())visit(reference)}function parseMutationDocumentRows(input){const parsed=parseJsonValue(input,"Mutation document");const envelope=Array.isArray(parsed)?{schema_version:1,mutations:parsed}:parsed;if(!isPlainObject(envelope)){throw new PmCliError("Mutation document must be a JSON array or object.",EXIT_CODE.USAGE)}for(const key of Object.keys(envelope)){if(!MUTATION_DOCUMENT_KEYS.includes(key)){throw unknownKeyError("mutation document",key,MUTATION_DOCUMENT_KEYS)}}if(envelope.schema_version!==void 0&&envelope.schema_version!==1){throw new PmCliError("Mutation document schema_version must be 1.",EXIT_CODE.USAGE)}if(!Array.isArray(envelope.mutations)||envelope.mutations.length===0){throw new PmCliError("Mutation document requires a non-empty mutations array.",EXIT_CODE.USAGE)}return envelope.mutations.map((row,index)=>{if(!isPlainObject(row)){throw new PmCliError(`Mutation ${index+1} must be an object.`,EXIT_CODE.USAGE)}for(const key of Object.keys(row)){if(!REFERENCED_MUTATION_ROW_KEYS.includes(key)){throw unknownKeyError(`mutation ${index+1}`,key,REFERENCED_MUTATION_ROW_KEYS)}}return{...row}})}function collectMutationReferences(rows,options){const references=Object.create(null);for(const[index,row]of rows.entries()){if(row.ref===void 0)continue;if(row.op!=="create"){throw new PmCliError(`Mutation ${index+1} ref is only valid for create operations.`,EXIT_CODE.USAGE)}if(typeof row.ref!=="string"||!MUTATION_REFERENCE_PATTERN.test(row.ref)){throw new PmCliError(`Mutation ${index+1} ref must match ${MUTATION_REFERENCE_PATTERN.source}.`,EXIT_CODE.USAGE)}if(references[row.ref]!==void 0){throw new PmCliError(`Duplicate mutation ref "${row.ref}".`,EXIT_CODE.USAGE)}references[row.ref]=typeof row.id==="string"&&row.id.trim().length>0?normalizeItemId(row.id,options.idPrefix):deriveReferencedItemId(options.transactionId,row.ref,options.idPrefix)}return references}function resolveItemMutationDocument(input,options){const rows=parseMutationDocumentRows(input);const references=collectMutationReferences(rows,options);assertAcyclicCreateReferences(rows);const resolvedRows=rows.map(row=>{const resolved={...row};const reference=typeof resolved.ref==="string"?resolved.ref:void 0;delete resolved.ref;if(reference!==void 0){resolved.id=references[reference]}else{resolved.id=replaceExactMutationReference(resolved.id,references)}if(isPlainObject(resolved.options)){const mutationOptions={...resolved.options};for(const key of["parent","blockedBy"]){if(mutationOptions[key]!==void 0){mutationOptions[key]=replaceExactMutationReference(mutationOptions[key],references)}}if(Array.isArray(mutationOptions.dep)){mutationOptions.dep=mutationOptions.dep.map(entry=>replaceDependencyReference(entry,references))}else if(mutationOptions.dep!==void 0){mutationOptions.dep=replaceDependencyReference(mutationOptions.dep,references)}resolved.options=mutationOptions}return resolved});const mutations=parseItemMutationBatch(JSON.stringify(resolvedRows));const createIds=mutations.filter(mutation=>mutation.op==="create").map(mutation=>mutation.id);if(new Set(createIds).size!==createIds.length){throw new PmCliError("Duplicate resolved create id in mutation document.",EXIT_CODE.USAGE)}return{schema_version:1,mutations,references}}function serializePairs(value,keys){return keys.filter(key=>value[key]!==void 0&&value[key]!==null).map(key=>{const rendered=String(value[key]);return`${key}=${/[",\n\r\\]/u.test(rendered)?JSON.stringify(rendered):rendered}`}).join(",")}function serializeObjectArray(value,keys,label){if(value===void 0)return void 0;if(!Array.isArray(value)||!value.every(isPlainObject)){throw new PmCliError(`${label} must be an array of objects.`,EXIT_CODE.USAGE)}return value.map(entry=>serializePairs(entry,keys))}function scalarItemOption(key,value){if(key==="tags"&&Array.isArray(value)&&value.every(entry=>typeof entry==="string")){return JSON.stringify(value)}if(typeof value==="number"||typeof value==="boolean"){return String(value)}return value}function appendFacetOptions(target,source,skipPersistedAnnotations=false){const mappings=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];for(const[sourceKey,targetKey,keys]of mappings){const sourceValue=source[sourceKey];const serialized=serializeObjectArray(skipPersistedAnnotations&&["comments","notes","learnings"].includes(sourceKey)&&Array.isArray(sourceValue)?sourceValue.filter(entry=>!isPlainObject(entry)||entry.created_at===void 0):sourceValue,keys,sourceKey);if(serialized!==void 0&&serialized.length>0)target[targetKey]=serialized}}function validateItemDocumentKeys(parsed,envelope){for(const key of Object.keys(parsed)){if(envelope){if(!ITEM_ENVELOPE_KEYS.includes(key))throw unknownKeyError("item envelope",key,ITEM_ENVELOPE_KEYS);continue}if(!ITEM_FIELD_KEYS.has(key)&&nearestKey(key,[...ITEM_FIELD_KEYS])===void 0&&nearestKey(key,ITEM_ENVELOPE_KEYS)==="item")throw unknownKeyError("item envelope",key,ITEM_ENVELOPE_KEYS)}}function resolveItemDocument(parsed){const envelope=Object.hasOwn(parsed,"item");validateItemDocumentKeys(parsed,envelope);const item=envelope?parsed.item:parsed;if(!isPlainObject(item)){throw new PmCliError("Item document item must be an object.",EXIT_CODE.USAGE)}return{item,...envelope&&isPlainObject(parsed.linked)?{linked:parsed.linked}:{}}}function appendItemDocumentEntry(documentOptions,key,value,mode){const readOnlyKeys=mode==="update"?UPDATE_READ_ONLY_ITEM_KEYS:READ_ONLY_ITEM_KEYS;if(readOnlyKeys.has(key))return;if(!ITEM_FIELD_KEYS.has(key)){const suggestion=nearestKey(key,[...ITEM_FIELD_KEYS]);if(suggestion!==void 0)throw unknownKeyError("item document",key,[...ITEM_FIELD_KEYS]);const fields=Array.isArray(documentOptions.field)?documentOptions.field:[];fields.push(serializePairs({key,value:typeof value==="string"?value:JSON.stringify(value)},["key","value"]));documentOptions.field=fields;return}if(["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(key))return;documentOptions[key.replaceAll(/_([a-z])/gu,(_match,letter)=>letter.toUpperCase())]=scalarItemOption(key,value)}function itemDocumentToMutationOptions(input,mode,explicitOptions={}){const parsed=parseJsonValue(input,"Item document");if(!isPlainObject(parsed)){throw new PmCliError("Item document must be a JSON object.",EXIT_CODE.USAGE)}const{item,linked}=resolveItemDocument(parsed);const documentOptions={};for(const[key,value]of Object.entries(item)){appendItemDocumentEntry(documentOptions,key,value,mode)}appendFacetOptions(documentOptions,item,mode==="update");if(linked!==void 0)appendFacetOptions(documentOptions,linked);if(mode==="update"){const annotations=Object.fromEntries(["comments","notes","learnings"].filter(key=>Object.hasOwn(item,key)).map(key=>[key,item[key].filter(entry=>isPlainObject(entry)&&entry.created_at!==void 0)]));if(Object.keys(annotations).length>0){documentOptions.documentAnnotationSnapshot=annotations}}return{...documentOptions,...Object.fromEntries(Object.entries(explicitOptions).filter(([,value])=>value!==void 0)),stdinJson:void 0}}function validateItemMutationRows(value){return parseItemMutationBatch(JSON.stringify(value))}export{itemDocumentToMutationOptions,parseAtomicMutationControls,parseItemMutationBatch,resolveItemMutationDocument,validateItemMutationRows};
2
2
  //# sourceMappingURL=structured-mutations.js.map
@@ -1,4 +1,4 @@
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]="fa9e95e5-7782-509d-96af-093a47daaed7")}catch(e2){}})();import{activateExtensions,deactivateExtensions,runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride}from"../core/extensions/loader.js";import{createDefaultExtensionGovernancePolicy}from"../core/extensions/extension-types.js";import{getMigrationRuntimeDefinition,resolveRegisteredSearchProvider,resolveRegisteredVectorStoreAdapter}from"../core/extensions/runtime-registrations.js";import{collectUsedExtensionCapabilities}from"../core/extensions/capability-usage.js";import{normalizeKnownExtensionCapability}from"../core/extensions/extension-capability-aliases.js";import{checkExtensionManifestCompatibility,describeExtensionBlueprint,lintExtensionBlueprint,preflightExtension}from"./compose.js";import{describeExtensionActivation}from"../core/extensions/activation-summary.js";import{lintProjectProfile}from"../core/profile/profile-lint.js";import{renderExtensionSurfaceMarkdown}from"../core/extensions/activation-summary-markdown.js";import{asPropertyRecord,resolveActivatablePropertyRecord}from"../core/shared/primitives.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{PmClient}from"./runtime.js";function registeredExpectationName(expectation,legacyValue){return expectation.name??legacyValue??""}const HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};const RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function normalizeSdkIdentifier(value){return value.trim().toLowerCase()}function normalizeSdkProfileMatchKey(value){return normalizeSdkIdentifier(value).replaceAll("-","_")}function extensionNameSuffix(extensionName){return extensionName?` from extension "${extensionName}"`:""}function sortedUnique(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function normalizeSdkCommandName(command){if(typeof command!=="string"){throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.')}return command.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function formatAvailable(values){return values.length>0?values.join(", "):"(none)"}function assertStringSetIncludes(actual,expected,label){const actualValues=new Set(actual??[]);const missing=sortedUnique(expected.filter(value=>!actualValues.has(value)));if(missing.length>0){throw new Error(`Expected package manifest ${label} to include ${missing.join(", ")}; available: ${formatAvailable(sortedUnique(actual??[]))}`)}}function collectFlagLabels(flags){const labels=new Set;for(const flag of flags){if(typeof flag.long==="string"&&flag.long.trim().length>0){labels.add(flag.long.trim())}if(typeof flag.short==="string"&&flag.short.trim().length>0){labels.add(flag.short.trim())}}return labels}function readTestExtensionManifest(module){const moduleRecord=asPropertyRecord(module);if(!moduleRecord){return{}}const manifest=asPropertyRecord(moduleRecord.manifest);if(manifest){return manifest}const defaultExport=asPropertyRecord(moduleRecord.default);const defaultManifest=asPropertyRecord(defaultExport?.manifest);if(defaultManifest){return defaultManifest}if(defaultExport&&typeof moduleRecord.default!=="function"&&("name"in defaultExport||"capabilities"in defaultExport)){return defaultExport}if(typeof module!=="function"&&("name"in moduleRecord||"capabilities"in moduleRecord)){return moduleRecord}return{}}function resolveTestExtensionName(manifest,explicitName){return explicitName??(typeof manifest.name==="string"&&manifest.name.trim().length>0?manifest.name.trim():"test-extension")}function readTestExtensionCapabilities(manifest,options){if(Array.isArray(options.capabilities)){return[...options.capabilities]}if(Array.isArray(manifest.capabilities)){return manifest.capabilities.filter(capability=>typeof capability==="string")}return[]}function buildSingleExtensionLoadResult(module,manifest,identity){return{disabled_by_flag:false,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:identity.policy,failed:[],loaded:[{layer:identity.layer,directory:"",manifest_path:"",name:identity.name,version:typeof manifest.version==="string"?manifest.version:"0.0.0",entry:typeof manifest.entry==="string"?manifest.entry:"./index.js",priority:typeof manifest.priority==="number"?manifest.priority:0,entry_path:"",capabilities:identity.capabilities,manifest_version:typeof manifest.manifest_version==="number"?manifest.manifest_version:void 0,pm_min_version:typeof manifest.pm_min_version==="string"?manifest.pm_min_version:void 0,pm_max_version:typeof manifest.pm_max_version==="string"?manifest.pm_max_version:void 0,engines:manifest.engines,trusted:manifest.trusted,provenance:manifest.provenance,sandbox_profile:manifest.sandbox_profile,permissions:manifest.permissions,activation:manifest.activation,module}]}}async function activateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return activateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,options),policy:options.policy??createDefaultExtensionGovernancePolicy()}))}async function deactivateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return deactivateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,{}),policy:createDefaultExtensionGovernancePolicy()}),options.activation,options.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:options.deactivateTimeoutMs})}async function runRegisteredCommandForTest(commands,options){const command=normalizeSdkCommandName(options.command);if(command.length===0){throw new Error("Expected command name must be a non-empty string")}const hasHandler=commands.handlers.some(entry=>entry.command===command);if(!hasHandler){const available=sortedUnique(commands.handlers.map(entry=>entry.command));throw new Error(`Expected a registered command handler for "${command}" to invoke. Available command handlers: ${formatAvailable(available)}`)}if(options.sdk!==void 0&&options.sdkFactory!==void 0){throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both")}const pmRoot=options.pmRoot??"";const global2={json:true,quiet:true,noPager:true,...options.global};const sdk=options.sdk??options.sdkFactory?.({pmRoot,global:global2})??(pmRoot.length>0?createExtensionCommandSdk(pmRoot,new PmClient({pmRoot})):void 0);return runCommandHandler(commands,{command,args:options.args?[...options.args]:[],options:options.options?{...options.options}:{},global:global2,pm_root:pmRoot,...sdk===void 0?{}:{sdk}})}async function runRegisteredMutationGuardForTest(hooks,options){if((hooks.beforeMutation?.length??0)===0){throw new Error("Expected a registered before_mutation hook to invoke")}await runBeforeMutationHooks(hooks,options.context)}async function runRegisteredHookForTest(hooks,options){const kind=options.kind;if(kind==="before_mutation"){throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.")}if((hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[kind]]?.length??0)===0){const populatedKinds=sortedUnique(Object.keys(RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD).filter(candidateKind=>(hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[candidateKind]]?.length??0)>0));throw new Error(`Expected a registered "${kind}" hook to invoke. Hook kinds with registrations: ${formatAvailable(populatedKinds)}`)}switch(options.kind){case"before_command":return runBeforeCommandHooks(hooks,options.context);case"after_command":return runAfterCommandHooks(hooks,options.context);case"on_read":return runOnReadHooks(hooks,options.context);case"on_write":return runOnWriteHooks(hooks,options.context);case"on_index":return runOnIndexHooks(hooks,options.context)}}async function runRegisteredParserOverrideForTest(parsers,context){const command=normalizeSdkCommandName(context.command);if(!parsers.overrides.some(entry=>entry.command===command)){throw new Error(`Expected a registered parser override for command "${command}" to invoke. Available parser override commands: ${formatAvailable(sortedUnique(parsers.overrides.map(entry=>entry.command)))}`)}return runParserOverride(parsers,context)}async function runRegisteredPreflightOverrideForTest(preflight,context){if(preflight.overrides.length===0){throw new Error("Expected a registered preflight override to invoke, but none are registered.")}return runPreflightOverride(preflight,context)}async function runRegisteredCommandOverrideForTest(commands,context){const command=normalizeSdkCommandName(context.command);if(!commands.overrides.some(entry=>entry.command===command)){throw new Error(`Expected a registered command override for command "${command}" to invoke. Available command override commands: ${formatAvailable(sortedUnique(commands.overrides.map(entry=>entry.command)))}`)}return runCommandOverride(commands,context)}async function runRegisteredRendererOverrideForTest(renderers,context){if(!renderers.overrides.some(entry=>entry.format===context.format)){throw new Error(`Expected a registered renderer override for format "${context.format}" to invoke. Available renderer override formats: ${formatAvailable(sortedUnique(renderers.overrides.map(entry=>entry.format)))}`)}return runRendererOverride(renderers,context)}async function runRegisteredServiceOverrideForTest(services,context){if(!services.overrides.some(entry=>entry.service===context.service)){throw new Error(`Expected a registered service override for service "${context.service}" to invoke. Available service override services: ${formatAvailable(sortedUnique(services.overrides.map(entry=>entry.service)))}`)}return runServiceOverride(services,context)}const SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function runRegisteredSearchProviderForTest(registrations,options){const registration=resolveRegisteredSearchProvider(registrations,options.provider);if(!registration){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected a registered search provider "${options.provider}" to invoke. Available search providers: ${formatAvailable(available)}`)}const runtimeDefinition=registration.runtime_definition;const operationFn=SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS[options.operation].map(key=>runtimeDefinition[key]).find(value=>typeof value==="function");if(typeof operationFn!=="function"){throw new Error(`Registered search provider "${options.provider}" does not implement the "${options.operation}" operation.`)}return await operationFn(options.context)}async function runRegisteredVectorStoreAdapterForTest(registrations,options){const registration=resolveRegisteredVectorStoreAdapter(registrations,options.adapter);if(!registration){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected a registered vector store adapter "${options.adapter}" to invoke. Available vector store adapters: ${formatAvailable(available)}`)}const operationFn=registration.runtime_definition[options.operation];if(typeof operationFn!=="function"){throw new Error(`Registered vector store adapter "${options.adapter}" does not implement the "${options.operation}" operation.`)}return await operationFn(options.context)}async function runRegisteredMigrationForTest(registrations,options){const migration=assertRegisteredMigration(registrations,{migration:options.migration,extensionName:options.extensionName});const run=getMigrationRuntimeDefinition(migration).run;if(typeof run!=="function"){throw new Error(`Registered migration "${options.migration}" does not implement a run function to invoke.`)}const declaredStatus=migration.definition.status;const context={id:migration.definition.id,command:"migration",layer:migration.layer,extension:migration.name,pm_root:options.pmRoot??"",status:(typeof declaredStatus==="string"?declaredStatus.trim().toLowerCase():"")||"pending"};return await run(context)}async function runRegisteredImporterForTest(activation,options){const importer=assertRegisteredImporter(activation.registrations,{importer:options.importer,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${importer.importer} import`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}async function runRegisteredExporterForTest(activation,options){const exporter=assertRegisteredExporter(activation.registrations,{exporter:options.exporter,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${exporter.exporter} export`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}function assertExtensionDeactivated(result,expectation={}){const expectedDeactivated=expectation.deactivated??1;if(result.deactivated!==expectedDeactivated){throw new Error(`Expected ${expectedDeactivated} extension${expectedDeactivated===1?"":"s"} to deactivate cleanly, but ${result.deactivated} did.`)}const expectedFailed=expectation.failed??0;if(result.failed.length!==expectedFailed){const detail=result.failed.map(failure=>`${failure.layer}:${failure.name} (${failure.error})`).join(", ");throw new Error(`Expected ${expectedFailed} teardown failure${expectedFailed===1?"":"s"}, but observed ${result.failed.length}${detail.length>0?`: ${detail}`:""}.`)}return result}function assertPackageManifest(manifest,expectation){if(expectation.packageName!==void 0&&manifest.package_name!==expectation.packageName){throw new Error(`Expected package manifest package_name to be "${expectation.packageName}"; received "${manifest.package_name??"(none)"}"`)}if(expectation.aliases!==void 0){assertStringSetIncludes(manifest.aliases,expectation.aliases,"aliases")}if(expectation.resources!==void 0){for(const[kind,expectedPaths]of Object.entries(expectation.resources)){assertStringSetIncludes(manifest.resources[kind],expectedPaths,`pm.${kind}`)}}return manifest}function assertRegisteredCommandContract(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0){throw new Error("Expected command name must be a non-empty string")}const commandCandidates=registrations.commands.filter(entry=>entry.command===expectedCommand);const command=expectation.extensionName?commandCandidates.find(entry=>entry.name===expectation.extensionName):commandCandidates[0];if(!command){const available=registrations.commands.map(entry=>entry.command).sort((left,right)=>left.localeCompare(right));const extensionSuffix=expectation.extensionName?` from extension "${expectation.extensionName}"`:"";throw new Error(`Expected extension command "${expectedCommand}"${extensionSuffix} to be registered. Available commands: ${formatAvailable(available)}`)}if(expectation.action!==void 0&&command.action!==expectation.action){throw new Error(`Expected extension command "${expectedCommand}" action "${expectation.action}", received "${command.action}"`)}if(expectation.arguments!==void 0){const actualArguments=(command.arguments??[]).map(argument=>argument.name);const missingArguments=expectation.arguments.filter(argument=>!actualArguments.includes(argument));if(missingArguments.length>0){throw new Error(`Expected extension command "${expectedCommand}" arguments ${formatAvailable(expectation.arguments)}; missing ${formatAvailable(missingArguments)}; available ${formatAvailable(actualArguments)}`)}}const flags=registrations.flags.filter(entry=>entry.target_command===expectedCommand&&(expectation.extensionName===void 0||entry.name===expectation.extensionName)).flatMap(entry=>entry.flags);if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(flags);const missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0){throw new Error(`Expected extension command "${expectedCommand}" flags ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}}return{command,flags}}function assertRegisteredFlags(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.targetCommand));if(expectedCommand.length===0){throw new Error("Expected target command name must be a non-empty string")}const candidates=registrations.flags.filter(entry=>entry.target_command===expectedCommand);let registration;if(expectation.extensionName){registration=candidates.find(entry=>entry.name===expectation.extensionName)}else if(candidates.length===1){registration=candidates[0]}else if(candidates.length>1){const availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}" matched multiple extensions: ${formatAvailable(availableExtensions)}. Specify extensionName to choose one registration.`)}if(!registration){const available=sortedUnique(registrations.flags.map(entry=>entry.target_command));const availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available flag target commands: ${formatAvailable(available)}; matching extensions: ${formatAvailable(availableExtensions)}`)}if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(registration.flags);const missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0){throw new Error(`Expected flags for target command "${expectedCommand}" to include ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}}return registration}function assertRegisteredHook(hooks,expectation){const field=HOOK_KIND_TO_REGISTRY_FIELD[expectation.kind];const candidates=hooks[field]??[];const hook=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!hook){const available=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected a "${expectation.kind}" hook${extensionNameSuffix(expectation.extensionName)} to be registered. Available "${expectation.kind}" hooks: ${formatAvailable(available)}`)}return hook}function assertRegisteredSearchProvider(registrations,expectation){const expectedProvider=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.provider));if(expectedProvider.length===0){throw new Error("Expected search provider name must be a non-empty string")}const candidates=registrations.search_providers.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedProvider);const provider=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!provider){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected search provider "${expectedProvider}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available search providers: ${formatAvailable(available)}`)}return provider}function assertRegisteredVectorStoreAdapter(registrations,expectation){const expectedAdapter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.adapter));if(expectedAdapter.length===0){throw new Error("Expected vector store adapter name must be a non-empty string")}const candidates=registrations.vector_store_adapters.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedAdapter);const adapter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!adapter){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected vector store adapter "${expectedAdapter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available vector store adapters: ${formatAvailable(available)}`)}return adapter}function assertRegisteredImporter(registrations,expectation){const expectedImporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.importer));if(expectedImporter.length===0){throw new Error("Expected importer name must be a non-empty string")}const candidates=registrations.importers.filter(entry=>normalizeSdkIdentifier(entry.importer)===expectedImporter);const importer=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!importer){const available=sortedUnique(registrations.importers.map(entry=>entry.importer));throw new Error(`Expected importer "${expectedImporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available importers: ${formatAvailable(available)}`)}return importer}function assertRegisteredExporter(registrations,expectation){const expectedExporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.exporter));if(expectedExporter.length===0){throw new Error("Expected exporter name must be a non-empty string")}const candidates=registrations.exporters.filter(entry=>normalizeSdkIdentifier(entry.exporter)===expectedExporter);const exporter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!exporter){const available=sortedUnique(registrations.exporters.map(entry=>entry.exporter));throw new Error(`Expected exporter "${expectedExporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available exporters: ${formatAvailable(available)}`)}return exporter}function assertRegisteredItemField(registrations,expectation){const expectedField=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.field));if(expectedField.length===0){throw new Error("Expected item field name must be a non-empty string")}const candidates=registrations.item_fields.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,field:registration.fields.find(field=>normalizeSdkIdentifier(field.name)===expectedField)})).filter(entry=>entry.field!==void 0);const match=candidates.find(entry=>expectation.type===void 0||entry.field.type===expectation.type);if(!match){const available=sortedUnique(registrations.item_fields.flatMap(entry=>entry.fields.map(field=>`${field.name}:${field.type}`)));throw new Error(`Expected item field "${expectedField}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item fields: ${formatAvailable(available)}`)}return match}function assertRegisteredItemType(registrations,expectation){const expectedType=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.itemType));if(expectedType.length===0){throw new Error("Expected item type name must be a non-empty string")}const candidates=registrations.item_types.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,itemType:registration.types.find(itemType=>normalizeSdkIdentifier(itemType.name)===expectedType)})).filter(entry=>entry.itemType!==void 0);const match=candidates.find(entry=>expectation.folder===void 0||entry.itemType.folder===expectation.folder);if(!match){const available=sortedUnique(registrations.item_types.flatMap(entry=>entry.types.map(itemType=>`${itemType.name}:${itemType.folder}`)));throw new Error(`Expected item type "${expectedType}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item types: ${formatAvailable(available)}`)}return match}function assertRegisteredProfile(registrations,expectation){const expectedProfile=normalizeSdkProfileMatchKey(registeredExpectationName(expectation,expectation.profile));if(expectedProfile.length===0){throw new Error("Expected profile name must be a non-empty string")}const match=registrations.profiles.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).find(entry=>normalizeSdkProfileMatchKey(entry.profile.name)===expectedProfile);if(!match){const available=sortedUnique(registrations.profiles.map(entry=>entry.profile.name));throw new Error(`Expected profile "${expectedProfile}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available profiles: ${formatAvailable(available)}`)}return{registration:match,profile:match.profile}}function assertRegisteredCommandOverride(commands,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0){throw new Error("Expected command name must be a non-empty string")}const candidates=commands.overrides.filter(entry=>entry.command===expectedCommand);const override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(commands.overrides.map(entry=>entry.command));throw new Error(`Expected command override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available command overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredParserOverride(parsers,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0){throw new Error("Expected command name must be a non-empty string")}const candidates=parsers.overrides.filter(entry=>entry.command===expectedCommand);const override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(parsers.overrides.map(entry=>entry.command));throw new Error(`Expected parser override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available parser overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredPreflightOverride(preflight,expectation={}){const override=expectation.extensionName?preflight.overrides.find(entry=>entry.name===expectation.extensionName):preflight.overrides[0];if(!override){const available=sortedUnique(preflight.overrides.map(entry=>entry.name));throw new Error(`Expected a preflight override${extensionNameSuffix(expectation.extensionName)} to be registered. Available preflight overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredRendererOverride(renderers,expectation){const expectedFormat=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.format));if(expectedFormat.length===0){throw new Error("Expected renderer format must be a non-empty string")}const candidates=renderers.overrides.filter(entry=>entry.format===expectedFormat);const override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(renderers.overrides.map(entry=>entry.format));throw new Error(`Expected renderer override "${expectedFormat}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available renderer overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredServiceOverride(services,expectation){const expectedService=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.service));if(expectedService.length===0){throw new Error("Expected service name must be a non-empty string")}const candidates=services.overrides.filter(entry=>normalizeSdkIdentifier(entry.service)===expectedService);const override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(services.overrides.map(entry=>entry.service));throw new Error(`Expected service override "${expectedService}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available service overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredMigration(registrations,expectation){const expectedMigration=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.migration));if(expectedMigration.length===0){throw new Error("Expected migration id must be a non-empty string")}const candidates=registrations.migrations.filter(entry=>(expectation.extensionName===void 0||entry.name===expectation.extensionName)&&typeof entry.definition.id==="string"&&normalizeSdkIdentifier(entry.definition.id)===expectedMigration);const match=candidates.find(entry=>expectation.mandatory===void 0||(entry.definition.mandatory??false)===expectation.mandatory);if(match){return match}const idMatch=candidates[0];if(idMatch!==void 0){throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to have mandatory=${expectation.mandatory}, but it is mandatory=${idMatch.definition.mandatory??false}.`)}const available=sortedUnique(registrations.migrations.map(entry=>{const id=typeof entry.definition.id==="string"&&entry.definition.id.trim().length>0?entry.definition.id.trim():"(unnamed)";return`${id}:${entry.definition.mandatory===true}`}));throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available migrations: ${formatAvailable(available)}`)}function assertExtensionCapabilityUsage(activation,expectation){const toKnownCapabilitySet=(capabilities,field)=>{const known=new Set;for(const capability of capabilities){const normalized=normalizeKnownExtensionCapability(capability);if(normalized===null){throw new Error(`Expected ${field} capability "${capability}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`)}known.add(normalized)}return known};const declared=[...toKnownCapabilitySet(expectation.declared,"declared")].sort((left,right)=>left.localeCompare(right));const allowUnused=toKnownCapabilitySet(expectation.allowUnused??[],"allowUnused");const used=collectUsedExtensionCapabilities(activation,{extensionName:expectation.extensionName});const usedSet=new Set(used);const unused=declared.filter(capability=>!usedSet.has(capability)&&!allowUnused.has(capability));if(unused.length>0){const scopeSuffix=extensionNameSuffix(expectation.extensionName);throw new Error(`Expected every declared capability${scopeSuffix} to be exercised, but [${unused.join(", ")}] ${unused.length===1?"is":"are"} declared yet never registered against. Remove ${unused.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared,used,unused}}function assertExtensionBlueprint(blueprint,options={}){const result=lintExtensionBlueprint(blueprint,options);if(!result.ok){const errors=result.findings.filter(finding=>finding.severity==="error");throw new Error(`Extension blueprint failed preflight with ${errors.length} ${errors.length===1?"error":"errors"}:
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]="52ee6b9f-9465-52ec-9164-c5b21360d078")}catch(e2){}})();import{activateExtensions,deactivateExtensions,runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride}from"../core/extensions/loader.js";import{createDefaultExtensionGovernancePolicy}from"../core/extensions/extension-types.js";import{getMigrationRuntimeDefinition,resolveRegisteredSearchProvider,resolveRegisteredVectorStoreAdapter}from"../core/extensions/runtime-registrations.js";import{collectUsedExtensionCapabilities}from"../core/extensions/capability-usage.js";import{normalizeKnownExtensionCapability}from"../core/extensions/extension-capability-aliases.js";import{checkExtensionManifestCompatibility,describeExtensionBlueprint,lintExtensionBlueprint,preflightExtension}from"./compose.js";import{describeExtensionActivation}from"../core/extensions/activation-summary.js";import{lintProjectProfile}from"../core/profile/profile-lint.js";import{renderExtensionSurfaceMarkdown}from"../core/extensions/activation-summary-markdown.js";import{asPropertyRecord,resolveActivatablePropertyRecord}from"../core/shared/primitives.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{PmClient}from"./runtime.js";function registeredExpectationName(expectation,legacyValue){return expectation.name??legacyValue??""}const HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};const RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function normalizeSdkIdentifier(value){return value.trim().toLowerCase()}function normalizeSdkProfileMatchKey(value){return normalizeSdkIdentifier(value).replaceAll("-","_")}function extensionNameSuffix(extensionName){return extensionName?` from extension "${extensionName}"`:""}function sortedUnique(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function normalizeSdkCommandName(command){if(typeof command!=="string"){throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.')}return command.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function formatAvailable(values){return values.length>0?values.join(", "):"(none)"}function assertStringSetIncludes(actual,expected,label){const actualValues=new Set(actual??[]);const missing=sortedUnique(expected.filter(value=>!actualValues.has(value)));if(missing.length>0){throw new Error(`Expected package manifest ${label} to include ${missing.join(", ")}; available: ${formatAvailable(sortedUnique(actual??[]))}`)}}function collectFlagLabels(flags){const labels=new Set;for(const flag of flags){if(typeof flag.long==="string"&&flag.long.trim().length>0){labels.add(flag.long.trim())}if(typeof flag.short==="string"&&flag.short.trim().length>0){labels.add(flag.short.trim())}}return labels}function readTestExtensionManifest(module){const moduleRecord=asPropertyRecord(module);if(!moduleRecord){return{}}const manifest=asPropertyRecord(moduleRecord.manifest);if(manifest){return manifest}const defaultExport=asPropertyRecord(moduleRecord.default);const defaultManifest=asPropertyRecord(defaultExport?.manifest);if(defaultManifest){return defaultManifest}if(defaultExport&&typeof moduleRecord.default!=="function"&&("name"in defaultExport||"capabilities"in defaultExport)){return defaultExport}if(typeof module!=="function"&&("name"in moduleRecord||"capabilities"in moduleRecord)){return moduleRecord}return{}}function resolveTestExtensionName(manifest,explicitName){return explicitName??(typeof manifest.name==="string"&&manifest.name.trim().length>0?manifest.name.trim():"test-extension")}function readTestExtensionCapabilities(manifest,options){if(Array.isArray(options.capabilities)){return[...options.capabilities]}if(Array.isArray(manifest.capabilities)){return manifest.capabilities.filter(capability=>typeof capability==="string")}return[]}function buildSingleExtensionLoadResult(module,manifest,identity){return{disabled_by_flag:false,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:identity.policy,failed:[],loaded:[{layer:identity.layer,directory:"",manifest_path:"",name:identity.name,version:typeof manifest.version==="string"?manifest.version:"0.0.0",entry:typeof manifest.entry==="string"?manifest.entry:"./index.js",priority:typeof manifest.priority==="number"?manifest.priority:0,entry_path:"",capabilities:identity.capabilities,manifest_version:typeof manifest.manifest_version==="number"?manifest.manifest_version:void 0,pm_min_version:typeof manifest.pm_min_version==="string"?manifest.pm_min_version:void 0,pm_max_version:typeof manifest.pm_max_version==="string"?manifest.pm_max_version:void 0,engines:manifest.engines,trusted:manifest.trusted,provenance:manifest.provenance,sandbox_profile:manifest.sandbox_profile,permissions:manifest.permissions,activation:manifest.activation,module}]}}async function activateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return activateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,options),policy:options.policy??createDefaultExtensionGovernancePolicy()}))}async function deactivateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return deactivateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,{}),policy:createDefaultExtensionGovernancePolicy()}),options.activation,options.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:options.deactivateTimeoutMs})}async function runRegisteredCommandForTest(commands,options){const command=normalizeSdkCommandName(options.command);if(command.length===0){throw new Error("Expected command name must be a non-empty string")}const hasHandler=commands.handlers.some(entry=>entry.command===command);if(!hasHandler){const available=sortedUnique(commands.handlers.map(entry=>entry.command));throw new Error(`Expected a registered command handler for "${command}" to invoke. Available command handlers: ${formatAvailable(available)}`)}if(options.sdk!==void 0&&options.sdkFactory!==void 0){throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both")}const pmRoot=options.pmRoot??"";const global2={json:true,quiet:true,noPager:true,...options.global};const sdk=options.sdk??options.sdkFactory?.({pmRoot,global:global2})??(pmRoot.length>0?createExtensionCommandSdk(pmRoot,new PmClient({pmRoot}),void 0,command):void 0);return runCommandHandler(commands,{command,args:options.args?[...options.args]:[],options:options.options?{...options.options}:{},global:global2,pm_root:pmRoot,...sdk===void 0?{}:{sdk}})}async function runRegisteredMutationGuardForTest(hooks,options){if((hooks.beforeMutation?.length??0)===0){throw new Error("Expected a registered before_mutation hook to invoke")}await runBeforeMutationHooks(hooks,options.context)}async function runRegisteredHookForTest(hooks,options){const kind=options.kind;if(kind==="before_mutation"){throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.")}if((hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[kind]]?.length??0)===0){const populatedKinds=sortedUnique(Object.keys(RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD).filter(candidateKind=>(hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[candidateKind]]?.length??0)>0));throw new Error(`Expected a registered "${kind}" hook to invoke. Hook kinds with registrations: ${formatAvailable(populatedKinds)}`)}switch(options.kind){case"before_command":return runBeforeCommandHooks(hooks,options.context);case"after_command":return runAfterCommandHooks(hooks,options.context);case"on_read":return runOnReadHooks(hooks,options.context);case"on_write":return runOnWriteHooks(hooks,options.context);case"on_index":return runOnIndexHooks(hooks,options.context)}}async function runRegisteredParserOverrideForTest(parsers,context){const command=normalizeSdkCommandName(context.command);if(!parsers.overrides.some(entry=>entry.command===command)){throw new Error(`Expected a registered parser override for command "${command}" to invoke. Available parser override commands: ${formatAvailable(sortedUnique(parsers.overrides.map(entry=>entry.command)))}`)}return runParserOverride(parsers,context)}async function runRegisteredPreflightOverrideForTest(preflight,context){if(preflight.overrides.length===0){throw new Error("Expected a registered preflight override to invoke, but none are registered.")}return runPreflightOverride(preflight,context)}async function runRegisteredCommandOverrideForTest(commands,context){const command=normalizeSdkCommandName(context.command);if(!commands.overrides.some(entry=>entry.command===command)){throw new Error(`Expected a registered command override for command "${command}" to invoke. Available command override commands: ${formatAvailable(sortedUnique(commands.overrides.map(entry=>entry.command)))}`)}return runCommandOverride(commands,context)}async function runRegisteredRendererOverrideForTest(renderers,context){if(!renderers.overrides.some(entry=>entry.format===context.format)){throw new Error(`Expected a registered renderer override for format "${context.format}" to invoke. Available renderer override formats: ${formatAvailable(sortedUnique(renderers.overrides.map(entry=>entry.format)))}`)}return runRendererOverride(renderers,context)}async function runRegisteredServiceOverrideForTest(services,context){if(!services.overrides.some(entry=>entry.service===context.service)){throw new Error(`Expected a registered service override for service "${context.service}" to invoke. Available service override services: ${formatAvailable(sortedUnique(services.overrides.map(entry=>entry.service)))}`)}return runServiceOverride(services,context)}const SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function runRegisteredSearchProviderForTest(registrations,options){const registration=resolveRegisteredSearchProvider(registrations,options.provider);if(!registration){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected a registered search provider "${options.provider}" to invoke. Available search providers: ${formatAvailable(available)}`)}const runtimeDefinition=registration.runtime_definition;const operationFn=SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS[options.operation].map(key=>runtimeDefinition[key]).find(value=>typeof value==="function");if(typeof operationFn!=="function"){throw new Error(`Registered search provider "${options.provider}" does not implement the "${options.operation}" operation.`)}return await operationFn(options.context)}async function runRegisteredVectorStoreAdapterForTest(registrations,options){const registration=resolveRegisteredVectorStoreAdapter(registrations,options.adapter);if(!registration){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected a registered vector store adapter "${options.adapter}" to invoke. Available vector store adapters: ${formatAvailable(available)}`)}const operationFn=registration.runtime_definition[options.operation];if(typeof operationFn!=="function"){throw new Error(`Registered vector store adapter "${options.adapter}" does not implement the "${options.operation}" operation.`)}return await operationFn(options.context)}async function runRegisteredMigrationForTest(registrations,options){const migration=assertRegisteredMigration(registrations,{migration:options.migration,extensionName:options.extensionName});const run=getMigrationRuntimeDefinition(migration).run;if(typeof run!=="function"){throw new Error(`Registered migration "${options.migration}" does not implement a run function to invoke.`)}const declaredStatus=migration.definition.status;const context={id:migration.definition.id,command:"migration",layer:migration.layer,extension:migration.name,pm_root:options.pmRoot??"",status:(typeof declaredStatus==="string"?declaredStatus.trim().toLowerCase():"")||"pending"};return await run(context)}async function runRegisteredImporterForTest(activation,options){const importer=assertRegisteredImporter(activation.registrations,{importer:options.importer,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${importer.importer} import`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}async function runRegisteredExporterForTest(activation,options){const exporter=assertRegisteredExporter(activation.registrations,{exporter:options.exporter,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${exporter.exporter} export`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}function assertExtensionDeactivated(result,expectation={}){const expectedDeactivated=expectation.deactivated??1;if(result.deactivated!==expectedDeactivated){throw new Error(`Expected ${expectedDeactivated} extension${expectedDeactivated===1?"":"s"} to deactivate cleanly, but ${result.deactivated} did.`)}const expectedFailed=expectation.failed??0;if(result.failed.length!==expectedFailed){const detail=result.failed.map(failure=>`${failure.layer}:${failure.name} (${failure.error})`).join(", ");throw new Error(`Expected ${expectedFailed} teardown failure${expectedFailed===1?"":"s"}, but observed ${result.failed.length}${detail.length>0?`: ${detail}`:""}.`)}return result}function assertPackageManifest(manifest,expectation){if(expectation.packageName!==void 0&&manifest.package_name!==expectation.packageName){throw new Error(`Expected package manifest package_name to be "${expectation.packageName}"; received "${manifest.package_name??"(none)"}"`)}if(expectation.aliases!==void 0){assertStringSetIncludes(manifest.aliases,expectation.aliases,"aliases")}if(expectation.resources!==void 0){for(const[kind,expectedPaths]of Object.entries(expectation.resources)){assertStringSetIncludes(manifest.resources[kind],expectedPaths,`pm.${kind}`)}}return manifest}function assertRegisteredCommandContract(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0){throw new Error("Expected command name must be a non-empty string")}const commandCandidates=registrations.commands.filter(entry=>entry.command===expectedCommand);const command=expectation.extensionName?commandCandidates.find(entry=>entry.name===expectation.extensionName):commandCandidates[0];if(!command){const available=registrations.commands.map(entry=>entry.command).sort((left,right)=>left.localeCompare(right));const extensionSuffix=expectation.extensionName?` from extension "${expectation.extensionName}"`:"";throw new Error(`Expected extension command "${expectedCommand}"${extensionSuffix} to be registered. Available commands: ${formatAvailable(available)}`)}if(expectation.action!==void 0&&command.action!==expectation.action){throw new Error(`Expected extension command "${expectedCommand}" action "${expectation.action}", received "${command.action}"`)}if(expectation.arguments!==void 0){const actualArguments=(command.arguments??[]).map(argument=>argument.name);const missingArguments=expectation.arguments.filter(argument=>!actualArguments.includes(argument));if(missingArguments.length>0){throw new Error(`Expected extension command "${expectedCommand}" arguments ${formatAvailable(expectation.arguments)}; missing ${formatAvailable(missingArguments)}; available ${formatAvailable(actualArguments)}`)}}const flags=registrations.flags.filter(entry=>entry.target_command===expectedCommand&&(expectation.extensionName===void 0||entry.name===expectation.extensionName)).flatMap(entry=>entry.flags);if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(flags);const missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0){throw new Error(`Expected extension command "${expectedCommand}" flags ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}}return{command,flags}}function assertRegisteredFlags(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.targetCommand));if(expectedCommand.length===0){throw new Error("Expected target command name must be a non-empty string")}const candidates=registrations.flags.filter(entry=>entry.target_command===expectedCommand);let registration;if(expectation.extensionName){registration=candidates.find(entry=>entry.name===expectation.extensionName)}else if(candidates.length===1){registration=candidates[0]}else if(candidates.length>1){const availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}" matched multiple extensions: ${formatAvailable(availableExtensions)}. Specify extensionName to choose one registration.`)}if(!registration){const available=sortedUnique(registrations.flags.map(entry=>entry.target_command));const availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available flag target commands: ${formatAvailable(available)}; matching extensions: ${formatAvailable(availableExtensions)}`)}if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(registration.flags);const missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0){throw new Error(`Expected flags for target command "${expectedCommand}" to include ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}}return registration}function assertRegisteredHook(hooks,expectation){const field=HOOK_KIND_TO_REGISTRY_FIELD[expectation.kind];const candidates=hooks[field]??[];const hook=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!hook){const available=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected a "${expectation.kind}" hook${extensionNameSuffix(expectation.extensionName)} to be registered. Available "${expectation.kind}" hooks: ${formatAvailable(available)}`)}return hook}function assertRegisteredSearchProvider(registrations,expectation){const expectedProvider=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.provider));if(expectedProvider.length===0){throw new Error("Expected search provider name must be a non-empty string")}const candidates=registrations.search_providers.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedProvider);const provider=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!provider){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected search provider "${expectedProvider}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available search providers: ${formatAvailable(available)}`)}return provider}function assertRegisteredVectorStoreAdapter(registrations,expectation){const expectedAdapter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.adapter));if(expectedAdapter.length===0){throw new Error("Expected vector store adapter name must be a non-empty string")}const candidates=registrations.vector_store_adapters.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedAdapter);const adapter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!adapter){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected vector store adapter "${expectedAdapter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available vector store adapters: ${formatAvailable(available)}`)}return adapter}function assertRegisteredImporter(registrations,expectation){const expectedImporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.importer));if(expectedImporter.length===0){throw new Error("Expected importer name must be a non-empty string")}const candidates=registrations.importers.filter(entry=>normalizeSdkIdentifier(entry.importer)===expectedImporter);const importer=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!importer){const available=sortedUnique(registrations.importers.map(entry=>entry.importer));throw new Error(`Expected importer "${expectedImporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available importers: ${formatAvailable(available)}`)}return importer}function assertRegisteredExporter(registrations,expectation){const expectedExporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.exporter));if(expectedExporter.length===0){throw new Error("Expected exporter name must be a non-empty string")}const candidates=registrations.exporters.filter(entry=>normalizeSdkIdentifier(entry.exporter)===expectedExporter);const exporter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!exporter){const available=sortedUnique(registrations.exporters.map(entry=>entry.exporter));throw new Error(`Expected exporter "${expectedExporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available exporters: ${formatAvailable(available)}`)}return exporter}function assertRegisteredItemField(registrations,expectation){const expectedField=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.field));if(expectedField.length===0){throw new Error("Expected item field name must be a non-empty string")}const candidates=registrations.item_fields.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,field:registration.fields.find(field=>normalizeSdkIdentifier(field.name)===expectedField)})).filter(entry=>entry.field!==void 0);const match=candidates.find(entry=>expectation.type===void 0||entry.field.type===expectation.type);if(!match){const available=sortedUnique(registrations.item_fields.flatMap(entry=>entry.fields.map(field=>`${field.name}:${field.type}`)));throw new Error(`Expected item field "${expectedField}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item fields: ${formatAvailable(available)}`)}return match}function assertRegisteredItemType(registrations,expectation){const expectedType=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.itemType));if(expectedType.length===0){throw new Error("Expected item type name must be a non-empty string")}const candidates=registrations.item_types.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,itemType:registration.types.find(itemType=>normalizeSdkIdentifier(itemType.name)===expectedType)})).filter(entry=>entry.itemType!==void 0);const match=candidates.find(entry=>expectation.folder===void 0||entry.itemType.folder===expectation.folder);if(!match){const available=sortedUnique(registrations.item_types.flatMap(entry=>entry.types.map(itemType=>`${itemType.name}:${itemType.folder}`)));throw new Error(`Expected item type "${expectedType}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item types: ${formatAvailable(available)}`)}return match}function assertRegisteredProfile(registrations,expectation){const expectedProfile=normalizeSdkProfileMatchKey(registeredExpectationName(expectation,expectation.profile));if(expectedProfile.length===0){throw new Error("Expected profile name must be a non-empty string")}const match=registrations.profiles.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).find(entry=>normalizeSdkProfileMatchKey(entry.profile.name)===expectedProfile);if(!match){const available=sortedUnique(registrations.profiles.map(entry=>entry.profile.name));throw new Error(`Expected profile "${expectedProfile}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available profiles: ${formatAvailable(available)}`)}return{registration:match,profile:match.profile}}function assertRegisteredCommandOverride(commands,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0){throw new Error("Expected command name must be a non-empty string")}const candidates=commands.overrides.filter(entry=>entry.command===expectedCommand);const override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(commands.overrides.map(entry=>entry.command));throw new Error(`Expected command override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available command overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredParserOverride(parsers,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0){throw new Error("Expected command name must be a non-empty string")}const candidates=parsers.overrides.filter(entry=>entry.command===expectedCommand);const override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(parsers.overrides.map(entry=>entry.command));throw new Error(`Expected parser override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available parser overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredPreflightOverride(preflight,expectation={}){const override=expectation.extensionName?preflight.overrides.find(entry=>entry.name===expectation.extensionName):preflight.overrides[0];if(!override){const available=sortedUnique(preflight.overrides.map(entry=>entry.name));throw new Error(`Expected a preflight override${extensionNameSuffix(expectation.extensionName)} to be registered. Available preflight overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredRendererOverride(renderers,expectation){const expectedFormat=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.format));if(expectedFormat.length===0){throw new Error("Expected renderer format must be a non-empty string")}const candidates=renderers.overrides.filter(entry=>entry.format===expectedFormat);const override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(renderers.overrides.map(entry=>entry.format));throw new Error(`Expected renderer override "${expectedFormat}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available renderer overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredServiceOverride(services,expectation){const expectedService=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.service));if(expectedService.length===0){throw new Error("Expected service name must be a non-empty string")}const candidates=services.overrides.filter(entry=>normalizeSdkIdentifier(entry.service)===expectedService);const override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(services.overrides.map(entry=>entry.service));throw new Error(`Expected service override "${expectedService}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available service overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredMigration(registrations,expectation){const expectedMigration=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.migration));if(expectedMigration.length===0){throw new Error("Expected migration id must be a non-empty string")}const candidates=registrations.migrations.filter(entry=>(expectation.extensionName===void 0||entry.name===expectation.extensionName)&&typeof entry.definition.id==="string"&&normalizeSdkIdentifier(entry.definition.id)===expectedMigration);const match=candidates.find(entry=>expectation.mandatory===void 0||(entry.definition.mandatory??false)===expectation.mandatory);if(match){return match}const idMatch=candidates[0];if(idMatch!==void 0){throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to have mandatory=${expectation.mandatory}, but it is mandatory=${idMatch.definition.mandatory??false}.`)}const available=sortedUnique(registrations.migrations.map(entry=>{const id=typeof entry.definition.id==="string"&&entry.definition.id.trim().length>0?entry.definition.id.trim():"(unnamed)";return`${id}:${entry.definition.mandatory===true}`}));throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available migrations: ${formatAvailable(available)}`)}function assertExtensionCapabilityUsage(activation,expectation){const toKnownCapabilitySet=(capabilities,field)=>{const known=new Set;for(const capability of capabilities){const normalized=normalizeKnownExtensionCapability(capability);if(normalized===null){throw new Error(`Expected ${field} capability "${capability}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`)}known.add(normalized)}return known};const declared=[...toKnownCapabilitySet(expectation.declared,"declared")].sort((left,right)=>left.localeCompare(right));const allowUnused=toKnownCapabilitySet(expectation.allowUnused??[],"allowUnused");const used=collectUsedExtensionCapabilities(activation,{extensionName:expectation.extensionName});const usedSet=new Set(used);const unused=declared.filter(capability=>!usedSet.has(capability)&&!allowUnused.has(capability));if(unused.length>0){const scopeSuffix=extensionNameSuffix(expectation.extensionName);throw new Error(`Expected every declared capability${scopeSuffix} to be exercised, but [${unused.join(", ")}] ${unused.length===1?"is":"are"} declared yet never registered against. Remove ${unused.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared,used,unused}}function assertExtensionBlueprint(blueprint,options={}){const result=lintExtensionBlueprint(blueprint,options);if(!result.ok){const errors=result.findings.filter(finding=>finding.severity==="error");throw new Error(`Extension blueprint failed preflight with ${errors.length} ${errors.length===1?"error":"errors"}:
2
2
  `+errors.map(finding=>` - [${finding.code}] ${finding.message}`).join("\n"))}return result}function assertProjectProfile(profile,options={}){const report=lintProjectProfile(profile);const blocking=report.findings.filter(finding=>finding.severity==="error"||options.strict===true&&finding.severity==="warning");if(blocking.length>0){throw new Error(`Project profile "${report.profile}" failed lint with ${blocking.length} ${blocking.length===1?"issue":"issues"}:
3
3
  `+blocking.map(finding=>` - ${finding.severity} [${finding.code}] ${finding.message}`).join("\n"))}return report}function assertExtensionManifestMatchesBlueprint(manifest,blueprint){const declaredCapabilities=Array.isArray(manifest.capabilities)?manifest.capabilities:[];const result=lintExtensionBlueprint(blueprint,{declaredCapabilities});const declared=result.declared;const declaredSet=new Set(declared);const usedSet=new Set(result.used);const missing=result.used.filter(capability=>!declaredSet.has(capability));const unused=declared.filter(capability=>!usedSet.has(capability));if(missing.length>0||unused.length>0){const parts=[];if(missing.length>0){parts.push(`missing [${missing.join(", ")}] (the blueprint registers ${missing.length===1?"a surface":"surfaces"} requiring ${missing.length===1?"it":"them"}; activation throws extension_capability_missing)`)}if(unused.length>0){parts.push(`unused [${unused.join(", ")}] (declared but no surface exercises ${unused.length===1?"it":"them"}; drop for least privilege)`)}throw new Error(`Manifest capabilities do not match the blueprint: ${parts.join("; ")}. Set capabilities to synthesizeExtensionManifest(blueprint, identity).capabilities to stay in sync.`)}return{used:result.used,declared,missing,unused,findings:result.findings}}function assertExtensionManifestCompatible(manifest,target){const result=checkExtensionManifestCompatibility(manifest,target);const blocking=result.findings.filter(finding=>finding.severity==="error");if(blocking.length>0){throw new Error(`Extension manifest is not compatible with pm ${result.pmVersion}: ${blocking.map(finding=>finding.message).join("; ")}`)}return result}function assertExtensionPreflight(blueprint,options={}){const report=preflightExtension(blueprint,options);if(!report.ok){const errors=report.findings.filter(finding=>finding.severity==="error");throw new Error(`Extension failed preflight with ${errors.length} ${errors.length===1?"error":"errors"}:
4
4
  `+errors.map(finding=>` - [${finding.source}:${finding.code}] ${finding.message}`).join("\n"))}return report}function assertTestModuleHasActivateExport(module){if(resolveActivatablePropertyRecord(module)){return}throw new Error("createExtensionTestHarness received a module with no activate export. Pass the extension module (with an activate(api) function on the module or its default export) as the first argument, and options second.")}async function createExtensionTestHarness(module,options={}){assertTestModuleHasActivateExport(module);const manifest=readTestExtensionManifest(module);const name=resolveTestExtensionName(manifest,options.name);const layer=options.layer??"project";const activation=await activateExtensionForTest(module,options);if(activation.failed.length>0){const detail=activation.failed.map(failure=>{const missingCapability=failure.trace?.missing_capability;const reason=missingCapability?`${failure.error}; missing capability "${missingCapability}"`:failure.error;return`${failure.layer}:${failure.name} (${reason})`}).join(", ");throw new Error(`createExtensionTestHarness could not activate the extension cleanly: ${detail}. Declare the required capability in the manifest (or pass it via options.capabilities), or use activateExtensionForTest directly to inspect a failed activation.`)}return{module,name,layer,activation,activationSummary(describeOptions){return describeExtensionActivation(activation,describeOptions)},renderMarkdown(markdownOptions={}){const{extensionName,...renderOptions}=markdownOptions??{};return renderExtensionSurfaceMarkdown(describeExtensionActivation(activation,{extensionName}),renderOptions)},assertCommandContract(expectation){return assertRegisteredCommandContract(activation.registrations,expectation)},assertFlags(expectation){return assertRegisteredFlags(activation.registrations,expectation)},assertItemField(expectation){return assertRegisteredItemField(activation.registrations,expectation)},assertItemType(expectation){return assertRegisteredItemType(activation.registrations,expectation)},assertProfile(expectation){return assertRegisteredProfile(activation.registrations,expectation)},assertHook(expectation){return assertRegisteredHook(activation.hooks,expectation)},assertCommandOverride(expectation){return assertRegisteredCommandOverride(activation.commands,expectation)},assertParserOverride(expectation){return assertRegisteredParserOverride(activation.parsers,expectation)},assertPreflightOverride(expectation){return assertRegisteredPreflightOverride(activation.preflight,expectation)},assertRendererOverride(expectation){return assertRegisteredRendererOverride(activation.renderers,expectation)},assertServiceOverride(expectation){return assertRegisteredServiceOverride(activation.services,expectation)},assertSearchProvider(expectation){return assertRegisteredSearchProvider(activation.registrations,expectation)},assertVectorStoreAdapter(expectation){return assertRegisteredVectorStoreAdapter(activation.registrations,expectation)},assertImporter(expectation){return assertRegisteredImporter(activation.registrations,expectation)},assertExporter(expectation){return assertRegisteredExporter(activation.registrations,expectation)},assertMigration(expectation){return assertRegisteredMigration(activation.registrations,expectation)},assertCapabilityUsage(expectation){return assertExtensionCapabilityUsage(activation,expectation)},runCommand(runOptions){return runRegisteredCommandForTest(activation.commands,runOptions)},runHook(runOptions){return runRegisteredHookForTest(activation.hooks,runOptions)},runMutationGuard(runOptions){return runRegisteredMutationGuardForTest(activation.hooks,runOptions)},runCommandOverride(context){return runRegisteredCommandOverrideForTest(activation.commands,context)},runParserOverride(context){return runRegisteredParserOverrideForTest(activation.parsers,context)},runPreflightOverride(context){return runRegisteredPreflightOverrideForTest(activation.preflight,context)},runRendererOverride(context){return runRegisteredRendererOverrideForTest(activation.renderers,context)},runServiceOverride(context){return runRegisteredServiceOverrideForTest(activation.services,context)},runSearchProvider(runOptions){return runRegisteredSearchProviderForTest(activation.registrations,runOptions)},runVectorStoreAdapter(runOptions){return runRegisteredVectorStoreAdapterForTest(activation.registrations,runOptions)},runMigration(runOptions){return runRegisteredMigrationForTest(activation.registrations,runOptions)},runImporter(runOptions){return runRegisteredImporterForTest(activation,runOptions)},runExporter(runOptions){return runRegisteredExporterForTest(activation,runOptions)},deactivate(deactivateOptions={}){return deactivateExtensionForTest(module,{name,layer,activation,deactivateTimeoutMs:deactivateOptions.deactivateTimeoutMs})}}}export{activateExtensionForTest,assertExtensionBlueprint,assertExtensionCapabilityUsage,assertExtensionDeactivated,assertExtensionManifestCompatible,assertExtensionManifestMatchesBlueprint,assertExtensionPreflight,assertPackageManifest,assertProjectProfile,assertRegisteredCommandContract,assertRegisteredCommandOverride,assertRegisteredExporter,assertRegisteredFlags,assertRegisteredHook,assertRegisteredImporter,assertRegisteredItemField,assertRegisteredItemType,assertRegisteredMigration,assertRegisteredParserOverride,assertRegisteredPreflightOverride,assertRegisteredProfile,assertRegisteredRendererOverride,assertRegisteredSearchProvider,assertRegisteredServiceOverride,assertRegisteredVectorStoreAdapter,createExtensionTestHarness,deactivateExtensionForTest,describeExtensionActivation,describeExtensionBlueprint,lintExtensionBlueprint,renderExtensionSurfaceMarkdown,runRegisteredCommandForTest,runRegisteredCommandOverrideForTest,runRegisteredExporterForTest,runRegisteredHookForTest,runRegisteredImporterForTest,runRegisteredMigrationForTest,runRegisteredMutationGuardForTest,runRegisteredParserOverrideForTest,runRegisteredPreflightOverrideForTest,runRegisteredRendererOverrideForTest,runRegisteredSearchProviderForTest,runRegisteredServiceOverrideForTest,runRegisteredVectorStoreAdapterForTest};
@@ -13,6 +13,8 @@ compatibility is tracked by
13
13
  [pm-wn3ee5](../.agents/pm/issues/pm-wn3ee5.toon).
14
14
  Lossless concurrent acceptance-criteria composition is tracked by
15
15
  [pm-inn5y5](../.agents/pm/issues/pm-inn5y5.toon).
16
+ The Bun launcher and strict-health repair are tracked by
17
+ [pm-vks66s](../.agents/pm/issues/pm-vks66s.toon).
16
18
  Recency-aware scalar convergence, bounded fresh-clone decision evidence, and
17
19
  audited pre-durable receipt dispositions are tracked by
18
20
  [pm-7wzb6d](../.agents/pm/issues/pm-7wzb6d.toon),
@@ -39,11 +41,14 @@ git commit -m "chore(pm): install tracker merge drivers"
39
41
  `pm merge install` writes an idempotent, fenced `.gitattributes` block and repository-local `git config` entries. The attributes are committed; the driver commands are clone-local, so every collaborator and fresh CI clone that performs merges must run the install command.
40
42
 
41
43
  The clone-local driver values record the absolute runtime launcher and bundled
42
- `dist/cli.js` path resolved by the installing SDK. The installer preserves an
43
- absolute PATH symlink when it resolves to the executing runtime, so a runtime
44
- manager can retarget that launcher during upgrades without breaking every clone.
45
- Relative PATH entries, inaccessible launchers, and different runtimes are ignored;
46
- without a matching launcher, the installer retains the executing binary path.
44
+ `dist/cli.js` path resolved by the installing SDK. With Node, the installer
45
+ preserves an absolute PATH symlink when it resolves to the executing runtime, so
46
+ a runtime manager can retarget that launcher during upgrades without breaking
47
+ every clone. With Bun, it resolves an executable `bun` on an absolute PATH entry,
48
+ checks that its version matches the running Bun version, and records its stable
49
+ absolute target. Relative PATH entries, inaccessible launchers, and different
50
+ runtimes are ignored; without a matching launcher, the installer retains the
51
+ executing binary path.
47
52
  Git therefore does not depend
48
53
  on a bare `pm` command or the caller's later `PATH` when it merges tracker data.
49
54
  The item-path placeholder is stored as bare `%P`: Git performs the required
@@ -53,7 +58,7 @@ remain reconcilable.
53
58
  `pm validate --check-storage-integrity` and `pm health` also compare every
54
59
  effective driver definition with the installed SDK. A command installed by
55
60
  another valid `@unbrained/pm-cli` package is
56
- also accepted when its Node and `dist/cli.js` paths exist, its manifest owns the
61
+ also accepted when its Node or Bun launcher and `dist/cli.js` paths exist, its manifest owns the
57
62
  `pm` bin, the driver arguments are semantically identical, and its version
58
63
  matches any exact project runtime pins. A driver inside a sibling worktree of
59
64
  the same repository is rejected, even when that package is otherwise valid.
package/docs/README.md CHANGED
@@ -95,6 +95,7 @@ pm guide release --json
95
95
  - [Extension Lifecycle Contracts](EXTENSION_LIFECYCLE.md) - source identity, durable migrations, and scoped preflight ownership.
96
96
  - [Extension Author Contracts](EXTENSION_AUTHOR_CONTRACTS.md) - the stability guarantees and contract surface package authors build against.
97
97
  - [SDK](SDK.md) - public import surfaces and typed authoring examples.
98
+ - [Audited SDK Settings and Item Updates](SDK_AUDITED_MUTATIONS.md) - extension-owned settings changes, replay-safe previews, and full-item JSON annotation integrity.
98
99
  - [SDK execution and recovery contracts](SDK_EXECUTION_CONTRACTS.md): schema-driven scheduling, handoff, and command recovery.
99
100
  - [Multi-Branch Merge Safety](MERGE_SAFETY.md) - semantic tracker merge drivers, post-merge integrity gates, delete/modify policy, and recovery-receipt retention.
100
101
  - [Codex Plugin](CODEX_PLUGIN.md) - native MCP plugin install, tools, skills, and safety notes.
@@ -1,7 +1,10 @@
1
1
  # Scheduled release reliability
2
2
 
3
3
  Tracked by [pm-e70zh5](../.agents/pm/issues/pm-e70zh5.toon) and
4
- [pm-44u3wt](../.agents/pm/issues/pm-44u3wt.toon).
4
+ [pm-44u3wt](../.agents/pm/issues/pm-44u3wt.toon). Trigger provenance and
5
+ installed-package diagnostics are tracked by
6
+ [pm-prrlce](../.agents/pm/issues/pm-prrlce.toon) and
7
+ [pm-q7c36n](../.agents/pm/issues/pm-q7c36n.toon).
5
8
 
6
9
  The **Release Reliability** workflow evaluates the preceding 30 days after a
7
10
  scheduled Auto Release completes, daily at nominal 04:35 UTC, and on manual
@@ -33,16 +36,27 @@ The unchanged [release recovery rules](RELEASING.md#failure-handling) apply.
33
36
 
34
37
  ## Evidence and denominator
35
38
 
36
- The collector paginates the schedule-only runs API over an explicit half-open
37
- UTC window and checks returned counts and unique IDs. It retrieves attempt 1
39
+ The collector paginates Auto Release runs over an explicit half-open UTC window
40
+ and checks returned counts and unique IDs. It retrieves attempt 1
38
41
  when a run was rerun. A later successful attempt, manual dispatch, issue recovery,
39
42
  or closed blocker cannot change the original scheduled failure. Pending runs
40
43
  are listed separately; all completed non-success conclusions count as failures.
44
+ The native scheduled denominator and policy remain separate from the morning
45
+ dispatcher series. Each new dispatch declares `trigger_origin`; the workflow
46
+ run name and attempt receipt preserve it. If setup fails before the receipt can
47
+ be uploaded, the collector reads the declared run name. Historical dispatches
48
+ without either declaration appear in `pre_attribution_gap`; the failed
49
+ 2026-09-28 morning dispatch cannot be attributed from its old run record.
50
+ Dispatcher rows retain creation time, queue delay, outcome, and failure stage.
51
+ They omit nominal occurrence and dispatch delay because the native 02:35 UTC
52
+ cron is not the dispatcher's clock; the scheduled timing policy does not apply
53
+ to those rows.
41
54
  API errors, truncated pages, ambiguous artifacts, and mismatched run identities
42
55
  fail collection rather than silently reducing the denominator.
43
56
 
44
57
  Auto Release saves `release-observation-<attempt>` artifacts for 90 days. Each
45
- contains only run/attempt identity, event, outcome and failure-stage name. Gate
58
+ contains only run/attempt identity, event, trigger origin, outcome and
59
+ failure-stage name. Gate
46
60
  stdout, stderr, credentials and environment values are not archived. A confirmed
47
61
  publication, verified existing same-day release, unchanged source, tracker-only
48
62
  changes, and an empty changelog are distinct outcomes. Failed gates retain their
@@ -61,6 +75,14 @@ downloads only data, never executable source. The reporting workflow checks out
61
75
  the default branch rather than the triggering run's code and has read-only token
62
76
  permissions.
63
77
 
78
+ Registry acceptance records every exact-package install attempt. A timeout,
79
+ signal, missing executable, other spawn error, and nonzero exit each keep their
80
+ own classification, exit status, signal, error code, and a bounded redacted
81
+ stderr excerpt. Only an explicit registry 404 is retried as possible metadata
82
+ propagation; successful recovery retains the earlier failure receipts. The
83
+ control and candidate sessions share a 13-minute deadline under the 15-minute
84
+ hosted acceptance job limit.
85
+
64
86
  The report is a rolling observation, not a permanent archive of all releases.
65
87
  Retain exported receipts externally if a longer historical window is needed.
66
88
  It does not implement the separate nightly per-leg reliability programme or