@unbrained/pm-cli 2026.11.7 → 2026.11.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +69 -48
- package/dist/cli/extension-command-help.js +4 -3
- package/dist/cli/help-json-payload.js +1 -1
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/register-list-query.js +5 -5
- package/dist/cli/runtime/annotation-option-retry.js +2 -0
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3A5DJZCC.js +116 -0
- package/dist/cli-bundle/chunks/chunk-4BMPGUTG.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-RFI4O6NU.js → chunk-7GC6WIDR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VM6OGNQC.js → chunk-7V6I6X4G.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MQOZNGPS.js → chunk-AFZS6WFV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OIBSKKCO.js → chunk-C4MQFWCM.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-CP43BHX3.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-WS2N4TQW.js → chunk-DOHZKPPC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ETHAZC3F.js → chunk-HESIRIVX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JZWFZH2K.js → chunk-JAE5MWLX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KPAVZILX.js → chunk-L5BU5FYN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3DI6CEF3.js → chunk-LI2HP5OX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D53G3NOE.js → chunk-LLTRUVKK.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-BQ5O3CBF.js → chunk-MKW5LGVQ.js} +69 -65
- package/dist/cli-bundle/chunks/chunk-NH7QX2M2.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-OJZG7Y6S.js → chunk-NKO42JMT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XSEDESNW.js → chunk-PE6CZ3PE.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-RC6SSFOF.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TGQPCNAD.js → chunk-S4IZIMAO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WXVMPLBY.js → chunk-XBUZENP4.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YGUUJHSR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-F3B2ULHB.js → chunk-YUTFMHSG.js} +6 -6
- package/dist/cli-bundle/chunks/{chunk-QG6FLDM4.js → chunk-Z3LWNF7C.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-SPEKTFBB.js → item-revision-TUGZYYXX.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-2RRBAQN3.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-LUXUKISJ.js → mutation-admission-FJ3D66PV.js} +2 -2
- package/dist/cli-bundle/chunks/register-list-query-GXP77CX7.js +11 -0
- package/dist/cli-bundle/chunks/register-mutation-XJ2DROUM.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-AHDWE2G3.js → register-operations-O5LERXM7.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-7BGG3CI3.js → register-setup-4VOTYLL2.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-S5BYWLGY.js → stage-ZDJL3FGL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2A3QZELL.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JRJOFMI7.js → chunk-3HFENALW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4UOXVFJZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LW4TN5ZM.js → chunk-5YPX3QKU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4EXRRSDS.js → chunk-6U5HP6L3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DIEBSC76.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BIDF4KO7.js → chunk-I4YUZW3J.js} +8 -8
- package/dist/cli-bundle/focused-chunks/{chunk-AJ2I377F.js → chunk-KBRSA4OK.js} +26 -26
- package/dist/cli-bundle/focused-chunks/{chunk-IYJRFJHT.js → chunk-KNF2QTEZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-LTPT5TE7.js +24 -0
- package/dist/cli-bundle/focused-chunks/chunk-O7K3X4LH.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-P4EHEH4C.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-P6TG33FV.js +82 -0
- package/dist/cli-bundle/focused-chunks/chunk-PL6EO4GJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LTTMERPN.js → chunk-PSLDGAEY.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-SZ2BKK3M.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-TSHRBPTI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ULTSMJYF.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-UNNLBJRI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-UUVRYIKA.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-G2VIY6XA.js → chunk-WPXMPGTY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-Z2QWZRSL.js +26 -0
- package/dist/cli-bundle/focused-chunks/item-revision-XNSRDTFB.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-Q2Z7DDCR.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-QWC6MLTZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/stage-NKH5SKSZ.js +2 -0
- package/dist/cli-bundle/main.js +32 -31
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +12 -12
- package/dist/core/extensions/flag-definition-validation.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/history/history-stream-policy.d.ts +12 -3
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/projection.d.ts +7 -2
- package/dist/core/history/projection.js +1 -1
- package/dist/core/item/item-format.d.ts +5 -1
- package/dist/core/item/item-format.js +2 -2
- package/dist/core/lock/lock.d.ts +1 -1
- package/dist/core/lock/lock.js +1 -1
- package/dist/core/output/output.d.ts +10 -1
- package/dist/core/output/output.js +7 -7
- package/dist/core/search/providers.d.ts +3 -2
- package/dist/core/search/providers.js +1 -1
- package/dist/core/search/vector-stores.d.ts +3 -2
- package/dist/core/search/vector-stores.js +1 -1
- package/dist/core/sentry/instrument.d.ts +2 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/annotations.d.ts +44 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/authoring.d.ts +6 -0
- package/dist/sdk/authoring.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +15 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/command-line.d.ts +2 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.d.ts +4 -2
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/completion/bash.js +1 -1
- package/dist/sdk/completion/fish.js +2 -1
- package/dist/sdk/completion/zsh.js +4 -1
- package/dist/sdk/context-intent-contracts.d.ts +5 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/contracts.d.ts +3 -0
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core.d.ts +14 -0
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/corpus-shape.d.ts +2 -2
- package/dist/sdk/corpus-shape.js +1 -1
- package/dist/sdk/define.d.ts +14 -8
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/extension/command-options.d.ts +123 -0
- package/dist/sdk/extension/command-options.js +2 -0
- package/dist/sdk/extension-contracts.d.ts +1 -2
- package/dist/sdk/extension-contracts.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance.d.ts +8 -0
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/graph.d.ts +5 -0
- package/dist/sdk/graph.js +1 -1
- package/dist/sdk/index.d.ts +61 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/learnings.d.ts +4 -2
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/restore.d.ts +1 -1
- package/dist/sdk/merge.d.ts +3 -0
- package/dist/sdk/merge.js +1 -1
- package/dist/sdk/notes.d.ts +4 -2
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/list.d.ts +5 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/search/semantic.d.ts +11 -3
- package/dist/sdk/query/search/semantic.js +1 -1
- package/dist/sdk/query/search-rendering.d.ts +9 -3
- package/dist/sdk/query/search-rendering.js +1 -1
- package/dist/sdk/query.d.ts +11 -0
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output/continuation.d.ts +8 -0
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output/options.d.ts +1 -1
- package/dist/sdk/read-output/options.js +1 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output/tail-retention.d.ts +34 -0
- package/dist/sdk/read-output/tail-retention.js +2 -0
- package/dist/sdk/read-output-budget.d.ts +14 -2
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +20 -4
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.d.ts +7 -3
- package/dist/sdk/read-output-rows.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.d.ts +26 -3
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution.d.ts +29 -2
- package/dist/sdk/test/execution.js +1 -1
- package/dist/sdk/testing.d.ts +14 -1
- package/dist/sdk/testing.js +1 -1
- package/dist/sdk/traceability/source-traceability.d.ts +4 -1
- package/dist/sdk/traceability/source-traceability.js +1 -1
- package/dist/sdk/workspace-recipe.d.ts +2 -2
- package/dist/sdk/workspace-recipe.js +1 -1
- package/docs/ARCHITECTURE.md +2 -1
- package/docs/COMMANDS.md +4 -1
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +1 -1
- package/docs/EXTENSIONS.md +1 -1
- package/docs/MCP_OPTION_CONFORMANCE.md +13 -0
- package/docs/README.md +1 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +78 -0
- package/docs/SDK.md +100 -2
- package/docs/SDK_CONTEXT_INTEGRITY.md +2 -0
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +6 -6
- package/marketplace.json +1 -1
- package/package.json +2 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli/extension-command-options.js +0 -2
- package/dist/cli-bundle/chunks/chunk-4PPWVIIT.js +0 -2
- package/dist/cli-bundle/chunks/chunk-5KHLV7JU.js +0 -116
- package/dist/cli-bundle/chunks/chunk-COKKWMSC.js +0 -8
- package/dist/cli-bundle/chunks/chunk-O6TIOKCM.js +0 -9
- package/dist/cli-bundle/chunks/chunk-WYIDX67P.js +0 -31
- package/dist/cli-bundle/chunks/item-transaction-BT55TQXE.js +0 -2
- package/dist/cli-bundle/chunks/register-list-query-DU4W7VJU.js +0 -11
- package/dist/cli-bundle/chunks/register-mutation-IC2C53QK.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-4LDOL6U7.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-4PW5XWVI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-A46YSPRF.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AI2PYNFI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CWFNQQZE.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-D3U7FOZR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GFF6BITP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IIBWXNW3.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-J5N42SKC.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-KL33JMPC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LH4C7BLB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LTQEYE2L.js +0 -81
- package/dist/cli-bundle/focused-chunks/chunk-MESFDQ3H.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-MWTBAI3V.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TWULNB3N.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-XAC6NP7U.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-XG3TBYQK.js +0 -23
- package/dist/cli-bundle/focused-chunks/chunk-XMZAFKVP.js +0 -91
- package/dist/cli-bundle/focused-chunks/item-revision-ELI6NGMY.js +0 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-GUGAUY77.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-54FI37AA.js +0 -2
- package/dist/cli-bundle/focused-chunks/stage-OHDJ43T2.js +0 -2
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +0 -472
package/dist/sdk/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0b5eab16-4305-5dfd-902c-fefc7ee0de2b")}catch{}})();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";import{decode,encode}from"@toon-format/toon";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"},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??[]),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)typeof flag.long=="string"&&flag.long.trim().length>0&&labels.add(flag.long.trim()),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);return asPropertyRecord(defaultExport?.manifest)||(defaultExport&&typeof moduleRecord.default!="function"&&("name"in defaultExport||"capabilities"in defaultExport)?defaultExport:typeof module!="function"&&("name"in moduleRecord||"capabilities"in moduleRecord)?moduleRecord:{})}function resolveTestExtensionName(manifest,explicitName){return explicitName??(typeof manifest.name=="string"&&manifest.name.trim().length>0?manifest.name.trim():"test-extension")}function readTestExtensionCapabilities(manifest,options){return Array.isArray(options.capabilities)?[...options.capabilities]:Array.isArray(manifest.capabilities)?manifest.capabilities.filter(capability=>typeof capability=="string"):[]}function buildSingleExtensionLoadResult(module,manifest,identity){return{disabled_by_flag:!1,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");if(!commands.handlers.some(entry=>entry.command===command)){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??"",global2={json:!0,quiet:!0,noPager:!0,...options.global},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,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}),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,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"),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),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)),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),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),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)),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),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],candidates=hooks[field]??[],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),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),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),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),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 match=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).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 match=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).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),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),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),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),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),match=candidates.find(entry=>expectation.mandatory===void 0||(entry.definition.mandatory??!1)===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??!1}.`);const available=sortedUnique(registrations.migrations.map(entry=>`${typeof entry.definition.id=="string"&&entry.definition.id.trim().length>0?entry.definition.id.trim():"(unnamed)"}:${entry.definition.mandatory===!0}`));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},declared=[...toKnownCapabilitySet(expectation.declared,"declared")].sort((left,right)=>left.localeCompare(right)),allowUnused=toKnownCapabilitySet(expectation.allowUnused??[],"allowUnused"),used=collectUsedExtensionCapabilities(activation,{extensionName:expectation.extensionName}),usedSet=new Set(used),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=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="65a4dbbe-c9a7-5092-a325-3ba73c0fc026")}catch{}})();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{collectExtensionFlagDefinitionsForCommand,normalizeDirectExtensionCommandOptions}from"./extension/command-options.js";import{PmClient}from"./runtime.js";import{decode,encode}from"@toon-format/toon";const ACTIVATED_COMMAND_FLAG_REGISTRATIONS=Symbol.for("pm.sdk.testing.activatedFlagRegistrations");function readActivatedFlagRegistrations(commands){return commands[ACTIVATED_COMMAND_FLAG_REGISTRATIONS]}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"},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??[]),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)typeof flag.long=="string"&&flag.long.trim().length>0&&labels.add(flag.long.trim()),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);return asPropertyRecord(defaultExport?.manifest)||(defaultExport&&typeof moduleRecord.default!="function"&&("name"in defaultExport||"capabilities"in defaultExport)?defaultExport:typeof module!="function"&&("name"in moduleRecord||"capabilities"in moduleRecord)?moduleRecord:{})}function resolveTestExtensionName(manifest,explicitName){return explicitName??(typeof manifest.name=="string"&&manifest.name.trim().length>0?manifest.name.trim():"test-extension")}function readTestExtensionCapabilities(manifest,options){return Array.isArray(options.capabilities)?[...options.capabilities]:Array.isArray(manifest.capabilities)?manifest.capabilities.filter(capability=>typeof capability=="string"):[]}function buildSingleExtensionLoadResult(module,manifest,identity){return{disabled_by_flag:!1,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),activation=await activateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,options),policy:options.policy??createDefaultExtensionGovernancePolicy()}));return Object.defineProperty(activation.commands,ACTIVATED_COMMAND_FLAG_REGISTRATIONS,{value:activation.registrations,enumerable:!1}),activation}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");if(!commands.handlers.some(entry=>entry.command===command)){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??"",global2={json:!0,quiet:!0,noPager:!0,...options.global},sdk=options.sdk??options.sdkFactory?.({pmRoot,global:global2})??(pmRoot.length>0?createExtensionCommandSdk(pmRoot,new PmClient({pmRoot}),void 0,command):void 0),registrations=readActivatedFlagRegistrations(commands),handlerOptions=options.options?{...options.options}:{};return runCommandHandler(commands,{command,args:options.args?[...options.args]:[],options:registrations===void 0?handlerOptions:normalizeDirectExtensionCommandOptions(handlerOptions,collectExtensionFlagDefinitionsForCommand(registrations,command),command),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,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}),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,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"),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),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)),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),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),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)),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),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],candidates=hooks[field]??[],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),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),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),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),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 match=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).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 match=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).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),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),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),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),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),match=candidates.find(entry=>expectation.mandatory===void 0||(entry.definition.mandatory??!1)===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??!1}.`);const available=sortedUnique(registrations.migrations.map(entry=>`${typeof entry.definition.id=="string"&&entry.definition.id.trim().length>0?entry.definition.id.trim():"(unnamed)"}:${entry.definition.mandatory===!0}`));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},declared=[...toKnownCapabilitySet(expectation.declared,"declared")].sort((left,right)=>left.localeCompare(right)),allowUnused=toKnownCapabilitySet(expectation.allowUnused??[],"allowUnused"),used=collectUsedExtensionCapabilities(activation,{extensionName:expectation.extensionName}),usedSet=new Set(used),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(`
|
|
3
3
|
`))}return result}function assertProjectProfile(profile,options={}){const report=lintProjectProfile(profile),blocking=report.findings.filter(finding=>finding.severity==="error"||options.strict===!0&&finding.severity==="warning");if(blocking.length>0)throw new Error(`Project profile "${report.profile}" failed lint with ${blocking.length} ${blocking.length===1?"issue":"issues"}:
|
|
4
4
|
`+blocking.map(finding=>` - ${finding.severity} [${finding.code}] ${finding.message}`).join(`
|
|
@@ -65,8 +65,11 @@ unmapped_commit_count:number;
|
|
|
65
65
|
/** Maximum relationship depth searched for a governing decision. */
|
|
66
66
|
decision_depth:number;
|
|
67
67
|
}
|
|
68
|
-
|
|
68
|
+
/** An item that may explain a source file, with the linked files that tie it to the source. */
|
|
69
|
+
export interface TraceabilityCandidate {
|
|
70
|
+
/** Candidate item metadata. */
|
|
69
71
|
item:ItemMetadata;
|
|
72
|
+
/** Linked files of the item that match the source under explanation. */
|
|
70
73
|
files:LinkedFile[];
|
|
71
74
|
}
|
|
72
75
|
interface GitAttribution {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="15749905-177d-5ae0-b475-668733f41e8a")}catch{}})();import{execFile}from"node:child_process";import path from"node:path";import{assembleWorkspaceRelationshipGraph}from"../graph/assembly.js";function runGit(workspaceRoot,args){return new Promise((resolve,reject)=>{execFile("git",[...args],{cwd:workspaceRoot,encoding:"utf8",maxBuffer:4*1024*1024},(error,stdout)=>{error?reject(error):resolve(stdout)})})}function validateLineRange(range){if(range&&(!Number.isSafeInteger(range.start)||!Number.isSafeInteger(range.end)||range.start<1||range.end<range.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function parseSourceLineRange(value){const match=/^(\d+):(\d+)$/u.exec(value.trim()),range=match?{start:Number(match[1]),end:Number(match[2])}:void 0;if(validateLineRange(range),!range)throw new RangeError("Source line range must use start:end.");return range}function parseBlameCommits(output){const lines=new Map;for(const row of output.split(`
|
|
2
2
|
`)){const commit=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(row)?.[1];commit&&lines.set(commit,(lines.get(commit)??0)+1)}return lines}function parseCommitItemReferences(output){const fields=output.split("\0"),references=new Map;for(let index=0;index+1<fields.length;index+=2){const commit=fields[index]?.trim();if(!commit)continue;const ids=[...new Set(fields[index+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((left,right)=>left.localeCompare(right));references.set(commit,ids)}return references}async function readGitAttribution(params){const relativePath=path.relative(params.workspaceRoot,path.resolve(params.workspaceRoot,params.sourcePath)),blame=await runGit(params.workspaceRoot,["blame","--line-porcelain","-L",`${params.lineRange.start},${params.lineRange.end}`,"--",relativePath]),log=await runGit(params.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",relativePath]);return{commitLines:parseBlameCommits(blame),commitItems:parseCommitItemReferences(log),available:!0}}function expandDecisionPath(params){const tail=params.current.nodes.at(-1),nextDepth=params.current.kinds.length+1;let foundDepth;for(const edge of params.graph.incidentEdges(tail)){const outgoing=edge.source===tail,next=outgoing?edge.target:edge.source;if((params.visitedDepth.get(next)??Number.POSITIVE_INFINITY)<nextDepth)continue;params.visitedDepth.set(next,nextDepth);const definition=params.graph.registry().require(edge.kind),nextPath={nodes:[...params.current.nodes,next],kinds:[...params.current.kinds,outgoing?edge.kind:definition.inverse??edge.kind]};params.details.get(next)?.type?.toLowerCase()==="decision"?(foundDepth=nextDepth,params.found.push(nextPath)):params.queue.push(nextPath)}return foundDepth}function collectDecisionPaths(params){const queue=[{nodes:[params.itemId],kinds:[]}],visitedDepth=new Map([[params.itemId,0]]),found=[];let foundDepth;for(;queue.length>0;){const current=queue.shift(),depth=current.kinds.length;foundDepth!==void 0&&depth>=foundDepth||depth>=params.maxDepth||(foundDepth=expandDecisionPath({current,graph:params.graph,details:params.details,visitedDepth,queue,found})??foundDepth)}return found.sort((left,right)=>left.nodes.join("\0").localeCompare(right.nodes.join("\0"))),found}function shortestDecisionPath(itemId,corpus,maxDepth){const assembly=assembleWorkspaceRelationshipGraph(corpus);if(!assembly.graph.hasNode(itemId))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};const found=collectDecisionPaths({itemId,maxDepth,graph:assembly.graph,details:new Map(assembly.details.map(detail=>[detail.id,detail]))}),selected=found[0];if(!selected)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};const decisionIds=[...new Set(found.map(entry=>entry.nodes.at(-1)))];return{status:decisionIds.length===1?"found":"ambiguous",nodes:selected.nodes,kinds:selected.kinds,alternative_decision_ids:decisionIds.slice(1)}}async function resolveGitAttribution(params){if(!params.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await readGitAttribution({workspaceRoot:params.workspaceRoot,sourcePath:params.paths[0],lineRange:params.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function sourceAmbiguities(params){const ambiguities=[];return params.hasLineRange&&!params.attributionAvailable&&ambiguities.push("git_attribution_unavailable"),params.hasLineRange&¶ms.contributionLines===0&&ambiguities.push("line_attribution_unmapped"),params.decisionStatus==="ambiguous"&&ambiguities.push("multiple_governing_decisions"),params.decisionStatus==="not_found"&&ambiguities.push("governing_decision_not_found"),ambiguities}function mappedBlamedCommits(attribution){return[...attribution.commitLines.keys()].filter(commit=>(attribution.commitItems.get(commit)?.length??0)>0)}async function explainSourceTraceability(params){validateLineRange(params.lineRange);const decisionDepth=params.decisionDepth??8;if(!Number.isSafeInteger(decisionDepth)||decisionDepth<1||decisionDepth>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");const attribution=await resolveGitAttribution(params),mappedCommits=mappedBlamedCommits(attribution),explanations=new Map;for(const candidate of params.candidates){const attributedCommits=[...attribution.commitLines.entries()].filter(([commit])=>attribution.commitItems.get(commit)?.includes(candidate.item.id)),contributionLines=attributedCommits.reduce((total,[,lines])=>total+lines,0),decisionPath=shortestDecisionPath(candidate.item.id,params.corpus,decisionDepth),ambiguities=sourceAmbiguities({hasLineRange:params.lineRange!==void 0,attributionAvailable:attribution.available,contributionLines,decisionStatus:decisionPath.status});explanations.set(candidate.item.id,{score:contributionLines*100+candidate.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(candidate.item.updated_at))/(720*60*60*1e3))),contribution_lines:contributionLines,evidence:[...candidate.files.map(file=>({kind:"linked_file",reference:file.path})),...attributedCommits.map(([commit,lines])=>({kind:"git_commit",reference:commit.slice(0,12),contribution_lines:lines}))],rationale:{value:candidate.item.value?.trim()||null,why_now:candidate.item.why_now?.trim()||null,outcome:candidate.item.outcome?.trim()||null,objective:candidate.item.objective?.trim()||null},decision_path:decisionPath,ambiguities})}return{explanations,receipt:{line_range:params.lineRange??null,blamed_commit_count:attribution.commitLines.size,mapped_commit_count:mappedCommits.length,unmapped_commit_count:attribution.commitLines.size-mappedCommits.length,decision_depth:decisionDepth}}}const _testOnlySourceTraceability={mappedBlamedCommits,parseBlameCommits,parseCommitItemReferences,shortestDecisionPath};export{_testOnlySourceTraceability,explainSourceTraceability,parseSourceLineRange};
|
|
3
3
|
//# sourceMappingURL=source-traceability.js.map
|
|
@@ -25,11 +25,11 @@ schema:typeof PM_WORKSPACE_RECIPE_SCHEMA;
|
|
|
25
25
|
/** Ordered operations executed inside the deterministic context. */
|
|
26
26
|
operations:readonly WorkspaceRecipeOperation[];
|
|
27
27
|
}
|
|
28
|
-
|
|
28
|
+
/** A workspace recipe literal with no keys beyond WorkspaceRecipe, so misspelled fields fail at compile time. */
|
|
29
|
+
export type ExactWorkspaceRecipe<TRecipe extends WorkspaceRecipe> = TRecipe & Record<Exclude<keyof TRecipe,keyof WorkspaceRecipe>,never>;
|
|
29
30
|
/** Validate and freeze a caller-authored reproducible workspace recipe. */
|
|
30
31
|
export declare function defineWorkspaceRecipe<const TRecipe extends WorkspaceRecipe>(recipe:ExactWorkspaceRecipe<TRecipe>):Readonly<TRecipe>;
|
|
31
32
|
/** Run arbitrary SDK work under the recipe's deterministic clock and entropy. */
|
|
32
33
|
export declare function runWithWorkspaceRecipe<T>(recipe:WorkspaceRecipe,operation:() => Promise<T>):Promise<T>;
|
|
33
34
|
/** Replay every declared recipe operation with a caller-provided dispatcher. */
|
|
34
35
|
export declare function executeWorkspaceRecipe<T>(recipe:WorkspaceRecipe,execute:(operation:WorkspaceRecipeOperation,index:number) => Promise<T>):Promise<T[]>;
|
|
35
|
-
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="619dbd55-b854-5e69-b5a5-c0bcada81629")}catch{}})();import{runWithReproducibleExecution,validateReproducibleExecutionSettings}from"../core/reproducibility/context.js";const PM_WORKSPACE_RECIPE_SCHEMA="https://schema.unbrained.dev/pm/workspace-recipe/v1";function cloneAndFreezeRecipeJson(value,location){if(value===null||typeof value=="boolean"||typeof value=="string")return value;if(typeof value=="number"){if(!Number.isFinite(value))throw new Error(`Workspace recipe JSON number must be finite at ${location}`);return value}if(Array.isArray(value))return Object.freeze(value.map((entry,index)=>cloneAndFreezeRecipeJson(entry,`${location}[${index}]`)));if(typeof value!="object"||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)throw new Error(`Workspace recipe input must contain JSON values at ${location}`);return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,cloneAndFreezeRecipeJson(entry,`${location}.${key}`)])))}function defineWorkspaceRecipe(recipe){if(recipe.schema!==PM_WORKSPACE_RECIPE_SCHEMA)throw new Error(`Unsupported workspace recipe schema: ${recipe.schema}`);const normalized=validateReproducibleExecutionSettings(recipe);if(recipe.operations.some(operation=>operation.action.trim().length===0||operation.input===null||Array.isArray(operation.input)))throw new Error("Workspace recipe operations require an action and object input");return Object.freeze({...normalized,operations:Object.freeze(recipe.operations.map((operation,index)=>Object.freeze({action:operation.action,input:cloneAndFreezeRecipeJson(operation.input,`operations[${index}].input`)})))})}async function runWithWorkspaceRecipe(recipe,operation){const defined=defineWorkspaceRecipe(recipe);return runWithReproducibleExecution(defined,operation)}async function executeWorkspaceRecipe(recipe,execute){return runWithWorkspaceRecipe(recipe,async()=>{const results=[];for(const[index,operation]of recipe.operations.entries())results.push(await execute(operation,index));return results})}export{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe};
|
|
2
2
|
//# sourceMappingURL=workspace-recipe.js.map
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -56,7 +56,6 @@ src/
|
|
|
56
56
|
extension/
|
|
57
57
|
help-content.ts
|
|
58
58
|
error-guidance.ts
|
|
59
|
-
extension-command-options.ts
|
|
60
59
|
core/
|
|
61
60
|
extensions/
|
|
62
61
|
loader.ts
|
|
@@ -101,6 +100,8 @@ src/
|
|
|
101
100
|
semantic.ts
|
|
102
101
|
response.ts
|
|
103
102
|
types.ts
|
|
103
|
+
extension/
|
|
104
|
+
command-options.ts
|
|
104
105
|
mcp/
|
|
105
106
|
discovery.ts
|
|
106
107
|
types/
|
package/docs/COMMANDS.md
CHANGED
|
@@ -1093,11 +1093,14 @@ printf '%s\n' '## Verification summary' '- Linux pass' '- macOS pass' | pm comme
|
|
|
1093
1093
|
pm comments <id> --file docs/release-evidence.md
|
|
1094
1094
|
pm comments <id> --edit 2 "Corrected: the regression was in the parser, not the renderer."
|
|
1095
1095
|
pm comments <id> --delete 3
|
|
1096
|
+
pm comments <id> --edit 263 --expect-at 2026-11-06T06:02:01.768Z "Corrected the newest comment."
|
|
1096
1097
|
pm notes <id> --add "Keep renderer changes isolated to TOON output." --if-absent
|
|
1097
1098
|
pm learnings <id> --add "Use runtime contracts instead of duplicating flag lists." --if-absent
|
|
1098
1099
|
```
|
|
1099
1100
|
|
|
1100
|
-
Use comments for progress and evidence, notes for implementation context, and learnings for durable future guidance. All three accept `--text` as a hidden compatibility alias for canonical `--add`; comments also retain `--body`/`--comment`, and notes retain `--note`. Choose exactly one input source (`[text]`, an add alias, `--stdin`, or `--file`) per invocation. Conflicting alias values fail before mutation. For retrying agents, `--if-absent` makes any annotation append idempotent by the resolved author plus exact normalized stored text: the first call returns `changed: true` and `mutation_receipt.changed_count: 1`; an exact retry returns `changed: false`, the existing entry position, and `changed_count: 0` without writing item or history state. Different authors remain distinct, and omitting `--if-absent` deliberately preserves duplicate-appending compatibility. The flag is append-only and is rejected for list, edit, and delete operations. To clean up obsolete orchestration notes, `--edit <index>` rewrites the comment at a 1-based index and `--delete <index>` removes it; both record history and honor ownership rules.
|
|
1101
|
+
Use comments for progress and evidence, notes for implementation context, and learnings for durable future guidance. All three accept `--text` as a hidden compatibility alias for canonical `--add`; comments also retain `--body`/`--comment`, and notes retain `--note`. Choose exactly one input source (`[text]`, an add alias, `--stdin`, or `--file`) per invocation. Conflicting alias values fail before mutation. An add alias that took an option as its value (`pm comments <id> --add --file note.md`) refuses with `annotation_flag_like_value` before any source conflict is reported: the refusal names the option's own form (`--file <path>` or `--stdin` works without `--add`) and, when dropping `--add` leaves exactly one source, `recovery.suggested_retry_args` holds your command without it. Use `--add text=--file` for literal dash-leading text. For retrying agents, `--if-absent` makes any annotation append idempotent by the resolved author plus exact normalized stored text: the first call returns `changed: true` and `mutation_receipt.changed_count: 1`; an exact retry returns `changed: false`, the existing entry position, and `changed_count: 0` without writing item or history state. Different authors remain distinct, and omitting `--if-absent` deliberately preserves duplicate-appending compatibility. The flag is append-only and is rejected for list, edit, and delete operations. To clean up obsolete orchestration notes, `--edit <index>` rewrites the comment at a 1-based index and `--delete <index>` removes it; both record history and honor ownership rules.
|
|
1102
|
+
|
|
1103
|
+
Reading annotations (tracked by [pm-8s53lj](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8s53lj.toon) and [pm-hka7ep](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-hka7ep.toon); tracker records excluded from npm): rows stay in stored order, oldest first. Every row leads with `index`, its absolute 1-based position in the stored collection, so the index a row reports is the one `--edit` and `--delete` accept on any page, limit or `pm notes` event filter. When a bare `pm comments`, `pm notes` or `pm learnings` read must be bounded by its output budget, it keeps the newest entries, the same tail `--limit <n>` and `--output-limit <n>` select, so `.comments[-1]` is always the newest comment. The page then carries `count` (rows delivered) beside `total_count` (entries stored), and `next_cursor` continues backwards: `--output-cursor <cursor>` returns the next older page until no older rows remain. A page's `count` is not an entry address. To check that an index still holds an entry with the timestamp you read, pass that row's `created_at` as `--expect-at <ts>` with `--edit` or `--delete` (MCP and SDK: `expectAt`). An entry at that index with a different `created_at` is refused with exit 4 and `annotation_entry_mismatch` before anything is written. On that refusal, `details.matching_indexes` lists every index whose entry has the expected `created_at`. The flag is refused without `--edit` or `--delete` (`annotation_expectation_without_target`). Without `--expect-at`, `--edit <index>` and `--delete <index>` behave as before and address the absolute index unguarded. `created_at` is a timestamp, not a unique identity: entries imported or written in the same millisecond can share one, and when such entries shift, the guard accepts any entry with that timestamp at the index without a refusal. A stable per-entry identity is owned by [pm-gh1381](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-gh1381.toon) (tracker record excluded from npm).
|
|
1101
1104
|
|
|
1102
1105
|
## Linked Artifacts
|
|
1103
1106
|
|
|
@@ -139,7 +139,7 @@ catalog rows across 17 canonical groups. Two of those rows are author-manifest
|
|
|
139
139
|
schema findings reached through a real `pm health --full --strict-exit --json`
|
|
140
140
|
process: an unknown top-level key and omitted canonical pm version bounds. The
|
|
141
141
|
remaining rows stay explicit `uncovered` obligations in
|
|
142
|
-
[the generated census](generated/REFUSAL_CLOSURE_CENSUS.md); the ratchet does not
|
|
142
|
+
[the generated census](https://github.com/unbraind/pm-cli/blob/main/docs/generated/REFUSAL_CLOSURE_CENSUS.md) (current `main`, repository-only gate evidence excluded from npm; for an installed release, open the same path at its `v<version>` tag); the ratchet does not
|
|
143
143
|
turn partial catalog closure into an approval claim.
|
|
144
144
|
|
|
145
145
|
Run the focused proof with:
|
package/docs/EXTENSIONS.md
CHANGED
|
@@ -305,7 +305,7 @@ Use the public SDK barrel. Do not deep-import from `src/core` or `dist/core`.
|
|
|
305
305
|
|
|
306
306
|
- `api.extension` is a read-only identity (`name`, `layer`, `version`, `capabilities`, `pm_min_version?`, `pm_max_version?`, `source_package?`) for self-identifying logs and version gating without re-reading the manifest.
|
|
307
307
|
- `api.registerCommand(definition)` adds package-owned commands; `read_output` opts readers into the [SDK output contract](SDK.md#minimal-command-extension).
|
|
308
|
-
- `api.registerFlags(command, flags)` adds runtime command flags. A flag may declare `value_type` (canonical; the legacy `type` alias is honored only when `value_type` is absent), `list: true` to accumulate repeated/comma-joined values like core `--tags`, a `default` applied when the flag is omitted, and `value_validation: "strict"` to refuse malformed `number`/`boolean` tokens before the handler runs (the default `"coerce"` forwards the raw token). See [
|
|
308
|
+
- `api.registerFlags(command, flags)` adds runtime command flags. A flag may declare `value_type` (canonical; the legacy `type` alias is honored only when `value_type` is absent), `list: true` to accumulate repeated/comma-joined values like core `--tags`, a `default` applied when the flag is omitted, and `value_validation: "strict"` to refuse malformed `number`/`boolean` tokens before the handler runs (the default `"coerce"` forwards the raw token). The handler reads each flag from `context.options` under its camel-case handler key (`--status-filter` → `statusFilter`), published as `sdk_option` by `pm contracts --command <command> --flags-only --json`; CLI, `PmClient.run`, MCP, and `runRegisteredCommandForTest` all deliver that key with the same defaults and coercion, and host flags such as `--json`, `--author`, and `--pm-path` arrive in `context.global` and are listed as `inherited_flags`. On the CLI, a command that declares flags refuses any other option with `unknown_option` before the handler runs (a command that declares none still receives undeclared options for now, see pm-4of199 in the SDK guide), and two spellings of one flag with different values (`--status-filter open -s closed`) are refused with `extension_option_spelling_conflict`, so declare every option a handler reads. See [Handler keys and ownership](SDK.md#handler-keys-and-ownership).
|
|
309
309
|
- `api.registerItemFields(fields)` adds custom metadata fields. Agents can set declared fields with repeatable `pm create --field name=value` and `pm update <id> --field name=value`; undeclared names are rejected. Extension declarations are matched first; a name that no active extension declares but the project schema does (for example `gate_evidence`) is refused with `project_schema_field_requires_declared_flag`, which names a CLI flag and an SDK option that each set only that field (each is omitted when every spelling is shared with another declared field or with an option of the command itself) and, on the CLI, an executable `suggested_retry_args` that rewrites only that assignment. The guidance follows the invoking scope (a bulk `update-many` row is routed under `update_many`, not `update`), and when the same invocation already sets that field through a declared flag, alias or option, no route or retry is offered, because the retry would carry two values for one field ([pm-wftvem](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wftvem.toon); tracker record excluded from npm); reserved core keys keep `core_item_field_requires_dedicated_flag`. `SchemaFieldDefinition.type` is the same closed union used by `pm schema add-field`: `string | number | boolean | string_array | array | object`. Unsupported values fail at compile time for TypeScript authors and at activation for JavaScript packages, with a did-you-mean hint on typos. `string_array` is the repeatable string collection; `array` and `object` require JSON containers. Active fields support `get`, `list` and `search` projections with `--fields name` or `--fields item.name`, preserving declared value types through `PmClient` and CLI reads. Disabled packages do not contribute selectors. Tracked by [pm-gh1571](../.agents/pm/issues/pm-gh1571.toon).
|
|
310
310
|
- Custom fields whose camel-case option name is already owned by a canonical MCP input remain usable through `options.<name>`, but authoring surfaces report the collision instead of allowing silent top-level shadowing. `pm schema add-field`, `pm profile lint`, and `pm package doctor` name the field, canonical `mcp_tool_input` owner, and nested recovery path. SDK authors can preflight the same rule with `resolvePmToolCustomFieldCollision`.
|
|
311
311
|
- `api.registerItemTypes(types)` adds custom item types.
|
|
@@ -27,6 +27,19 @@ Array values that become CLI CSV inputs, such as `tags`, must contain only
|
|
|
27
27
|
strings and are checked before conversion. Validation follows nested precedence:
|
|
28
28
|
an explicit valid nested value replaces a flat value before either is normalized.
|
|
29
29
|
|
|
30
|
+
The read tools (`context`, `get`, `list`, `next`, `search`) and the annotation,
|
|
31
|
+
linked-artifact and linked-test tools (`comments`, `notes`, `learnings`,
|
|
32
|
+
`files`, `docs`, `test`) hoist every optional parameter their strict action contract declares, derived
|
|
33
|
+
from `PM_TOOL_ACTION_PARAMETER_CONTRACTS` rather than a hand list
|
|
34
|
+
([pm-wsqxwb](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wsqxwb.toon);
|
|
35
|
+
tracker record excluded from npm). A flat `add` therefore writes instead of
|
|
36
|
+
falling through to a listing read. The annotation `text` operand (flat or
|
|
37
|
+
nested) is bound to `add` the way the CLI binds positional text. Equal values
|
|
38
|
+
are accepted, and different `text` and `add` values are refused with
|
|
39
|
+
`annotation_text_source_conflict` before anything is written. A nested snake_case
|
|
40
|
+
spelling of a declared annotation parameter (`expect_at`, `if_absent`) is renamed
|
|
41
|
+
to the camelCase key the SDK reads, so it cannot silently drop a guard.
|
|
42
|
+
|
|
30
43
|
For example, `{ "id": "pm-one", "options": {}, "priority": 4 }` changes priority;
|
|
31
44
|
with `"options": { "priority": 2 }`, priority becomes `2`. Create also honors its
|
|
32
45
|
advertised explicit `id`, `deadline`, and other metadata. Regressions check the
|
package/docs/README.md
CHANGED
|
@@ -70,7 +70,7 @@ pm guide release --json
|
|
|
70
70
|
- [SDK Context Platform](SDK_CONTEXT.md) - task-oriented entry point for authoritative reads, ranking, package workflows, diagnostics, recovery, and verification.
|
|
71
71
|
- [Self-Describing Context Contracts](SELF_DESCRIBING_CONTEXT_CONTRACTS.md) - intent-scoped reads, semantic flag invocation metadata, visibility parity, and generated error vocabulary.
|
|
72
72
|
- [Generated Agent Capability Routing](generated/AGENT_CAPABILITY_ROUTING.md) - contract-derived command families shared by help, guide, skills, completion, MCP, and extensions.
|
|
73
|
-
- [Generated Refusal Closure Census](generated/REFUSAL_CLOSURE_CENSUS.md) - complete error-catalog join to executable refusal evidence and explicit uncovered obligations.
|
|
73
|
+
- [Generated Refusal Closure Census](https://github.com/unbraind/pm-cli/blob/main/docs/generated/REFUSAL_CLOSURE_CENSUS.md) - complete error-catalog join to executable refusal evidence and explicit uncovered obligations (repository-only gate evidence on upstream `main`, excluded from npm; in a fork or another checkout, open `docs/generated/REFUSAL_CLOSURE_CENSUS.md` there).
|
|
74
74
|
- [Universal Read Output Contracts](READ_OUTPUT_CONTRACTS.md) - cross-command include, amount, cost, and encoding controls for CLI, SDK, MCP, and packages.
|
|
75
75
|
- [Diagnostic Output Contracts](DIAGNOSTIC_OUTPUT_CONTRACTS.md) - action-first error budgets, deterministic degradation, SDK projection, and executable refusal assurance.
|
|
76
76
|
- [History Algorithms and Detached Attestations](HISTORY_ATTESTATION.md) - named record digests, portable exact-byte proofs, and read-only verification.
|
|
@@ -385,6 +385,20 @@ an unbounded multi-megabyte response;
|
|
|
385
385
|
`recovery_budget_multiplier: 1` declares that each next page retains the same
|
|
386
386
|
useful-result ceiling.
|
|
387
387
|
|
|
388
|
+
Chronological annotation collections keep their newest rows instead
|
|
389
|
+
([pm-8s53lj](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8s53lj.toon);
|
|
390
|
+
tracker record excluded from npm). `PM_READ_OUTPUT_TAIL_RETENTION_POLICIES`
|
|
391
|
+
declares the `comments`, `notes` and `learnings` row paths, and
|
|
392
|
+
`readOutputRetainsTail(command, path)` answers for one path. Budget compaction
|
|
393
|
+
and `--output-limit` retain the tail of those paths, matching the producer's own
|
|
394
|
+
latest-N `--limit`. Their continuation cursor carries `direction: "backward"`:
|
|
395
|
+
`offset` counts the older rows still withheld, `remaining_rows` equals it, and
|
|
396
|
+
replaying the cursor delivers the newest rows before that offset. A cursor whose
|
|
397
|
+
direction disagrees with the path's declared retention is refused as
|
|
398
|
+
`read_output_cursor_stale`. A withheld tail also sets the policy's `total_key`
|
|
399
|
+
(`total_count`) beside `count`, and a producer `returned_count` is refreshed to
|
|
400
|
+
the delivered page.
|
|
401
|
+
|
|
388
402
|
Health continuation fingerprints use a versioned nonvolatile-snapshot policy
|
|
389
403
|
for the `checks` row. Command-lifecycle telemetry may refresh timestamps, queue
|
|
390
404
|
counters, and pending spans between pages, so the policy excludes only those
|
|
@@ -407,6 +421,10 @@ uses `unbounded` explicitly. `resolveReadOutputRecoveryBudget()` exposes the
|
|
|
407
421
|
versioned pure calculation to package authors; there is no hard-coded smaller
|
|
408
422
|
retry and no recovery cycle.
|
|
409
423
|
|
|
424
|
+
Comments, notes and learnings declare `budget_retention_policy: ordered_suffix`:
|
|
425
|
+
budget compaction keeps their newest rows and their continuation pages
|
|
426
|
+
backwards (see the tail retention policy above). Every other surface except
|
|
427
|
+
assurance declares `ordered_prefix`.
|
|
410
428
|
Assurance declares `budget_retention_policy: verdict_priority`: failing block,
|
|
411
429
|
warn, and observe rows precede retired and passing rows while preserving order
|
|
412
430
|
within each class. `assertions_total` remains the pre-projection denominator,
|
|
@@ -429,6 +447,66 @@ from successful command results. Corrective actions precede explanation and
|
|
|
429
447
|
survive every degradation stage, while untruncated JSON avoids a per-call
|
|
430
448
|
receipt tax.
|
|
431
449
|
|
|
450
|
+
### Delivered bytes, intent budgets and complete receipts
|
|
451
|
+
|
|
452
|
+
Tracked by [pm-gh1678](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1678.toon),
|
|
453
|
+
[pm-gh1662](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1662.toon) and
|
|
454
|
+
[pm-sj66lm](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-sj66lm.toon)
|
|
455
|
+
(repository-only tracker records excluded from npm).
|
|
456
|
+
|
|
457
|
+
The CLI measures what it writes. When a scoped `registerRenderer` replacement,
|
|
458
|
+
an `output_format` service override, or a markdown default renders a declared
|
|
459
|
+
read, every estimate, compaction step and omission decision uses that
|
|
460
|
+
delivered string, so `read_output.estimated_tokens` describes the bytes the
|
|
461
|
+
caller receives. A string that cannot fit returns the bounded native
|
|
462
|
+
`output_budget_exceeded` refusal with exit 2; a refusal is always rendered
|
|
463
|
+
natively and never passed back through an expanding renderer. Commands that
|
|
464
|
+
declare no read output keep their renderer untouched, and
|
|
465
|
+
`--output-budget unbounded` keeps unbounded custom rendering.
|
|
466
|
+
|
|
467
|
+
A renderer whose output depends on its own receipts need not converge, so the
|
|
468
|
+
receipt estimates stop after a bounded number of passes. That bound is never
|
|
469
|
+
taken as proof of fit. The CLI checks the final custom rendering against its
|
|
470
|
+
receipts. If any receipt reports fewer tokens than the rendering costs, or the
|
|
471
|
+
intent receipt claims a fit that the rendering exceeds, the read is measured
|
|
472
|
+
and rendered natively instead. No byte that a receipt did not measure is
|
|
473
|
+
delivered. A renderer's own nested SDK contract calls measure their own
|
|
474
|
+
representation, never the outer delivery.
|
|
475
|
+
|
|
476
|
+
Read intents (`--for <intent>`) accept one budget under both spellings: a
|
|
477
|
+
numeric `--output-budget` binds the intent's token budget exactly as the legacy
|
|
478
|
+
`--token-budget` does, including its budget-derived row limit. Both spellings
|
|
479
|
+
apply one rule to the bytes they deliver. The legacy spelling's receipt also
|
|
480
|
+
carries its migration hint, so at the exact boundary it can omit where the
|
|
481
|
+
canonical spelling still fits. The intent estimate covers the delivered
|
|
482
|
+
encoding (pretty JSON or TOON, without a `row_contract` the caller did not
|
|
483
|
+
request). It is settled over the complete envelope, including the
|
|
484
|
+
`read_output` receipt and any requested row contract. A delivery whose settled
|
|
485
|
+
envelope exceeds the intent budget is decided again, with the measured overhead
|
|
486
|
+
charged against the budget, so row compaction leaves room for the receipts. A
|
|
487
|
+
re-settled envelope that still exceeds the budget is omitted, so a read never
|
|
488
|
+
delivers more than its budget allows. `--output-include` never shapes an
|
|
489
|
+
omission: a refused read keeps its refusal under every include selection. A
|
|
490
|
+
successful include projection that drops the intent receipt still answers to
|
|
491
|
+
the intent budget over the bytes it delivers. A refused continuation page keeps
|
|
492
|
+
its receipts whole, and every receipt agrees that it omitted. The retry that a
|
|
493
|
+
legacy refusal names keeps the caller's `--fields` projection, because its
|
|
494
|
+
budget was sized against that projection. An omitted intent result is
|
|
495
|
+
unsuccessful everywhere: the CLI exits 2, and `context_intent`, `read_output`
|
|
496
|
+
and the omission branch all report `result_omitted: true` and
|
|
497
|
+
`within_budget: false`. The canonical spelling keeps the shared
|
|
498
|
+
`output_budget_exceeded` branch; the legacy spelling keeps `budget_exceeded`,
|
|
499
|
+
whose `restore_with` carries the universal 25% recovery margin so the retry it
|
|
500
|
+
names returns the result. SDK consumers detect either branch with
|
|
501
|
+
`isReadResultOmittedForBudget`. `--output-budget unbounded` on an intent read
|
|
502
|
+
never omits the result; its receipt reports `within_budget: false` when the
|
|
503
|
+
result exceeds the declared intent ceiling.
|
|
504
|
+
|
|
505
|
+
In TOON, an omission receipt that reports nothing omitted costs one line,
|
|
506
|
+
`omission_receipt: complete`, and an explicit `get --fields` selection renders
|
|
507
|
+
each requested empty collection as `key: []`. JSON, SDK and MCP keep the typed
|
|
508
|
+
receipt, and receipts that report omissions are unchanged.
|
|
509
|
+
|
|
432
510
|
## SDK and Package Usage
|
|
433
511
|
|
|
434
512
|
Typed `PmClient` read methods accept `PmReadOutputOptions` directly:
|
package/docs/SDK.md
CHANGED
|
@@ -216,6 +216,18 @@ from every non-testing SDK subpath must be available from
|
|
|
216
216
|
Consumers and release tooling can read the exact shipped artifact from
|
|
217
217
|
`@unbrained/pm-cli/sdk/public-surface.json` without locating repository files.
|
|
218
218
|
|
|
219
|
+
The snapshot also records a signature-type census
|
|
220
|
+
(`signature_type_reachability`). Every package type named by an exported
|
|
221
|
+
function's parameters, return type, or type-parameter constraints must be
|
|
222
|
+
importable from the same entrypoint, so `import type { ProjectedGraphResult }
|
|
223
|
+
from "@unbrained/pm-cli/sdk/graph"` works beside `runGraph` instead of forcing
|
|
224
|
+
`Awaited<ReturnType<typeof runGraph>>`. Identity is by declaration, so a
|
|
225
|
+
same-named but different type does not count. `pnpm sdk:surface:check` refuses
|
|
226
|
+
a gap and names the type, where it is declared, and the functions that name it
|
|
227
|
+
([pm-gh1667](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1667.toon),
|
|
228
|
+
tracker record excluded from npm). The merge receipt's `conflict_resolution`
|
|
229
|
+
field is typed by the exported `ItemScalarConflictResolution`.
|
|
230
|
+
|
|
219
231
|
The denominator is the package export map itself, not a list inside the
|
|
220
232
|
generator. Every `exports` entry that declares a `types` path must carry a
|
|
221
233
|
classification, and `pnpm sdk:surface:check` refuses to run while any published
|
|
@@ -909,7 +921,13 @@ is the "invoke" verb that completes the package-author testing loop —
|
|
|
909
921
|
pm's real engine and returns the `CommandHandlerResult`, so a test can assert
|
|
910
922
|
_behavior_ (`result.result`) rather than only that the command is wired. The
|
|
911
923
|
`CommandHandlerContext` is built with agent-safe global defaults
|
|
912
|
-
(`{ json: true, quiet: true, noPager: true }`) that callers may override.
|
|
924
|
+
(`{ json: true, quiet: true, noPager: true }`) that callers may override. When
|
|
925
|
+
`commands` comes from `activateExtensionForTest`, `options` pass through the
|
|
926
|
+
same normalizer as CLI dispatch and `PmClient.run`: `"status-filter"` reaches
|
|
927
|
+
the handler as `statusFilter`, declared defaults and coercion apply, and two
|
|
928
|
+
spellings with different values are refused (see
|
|
929
|
+
[Handler keys and ownership](#handler-keys-and-ownership)). A hand-built
|
|
930
|
+
registry has no declared flags, so its options pass through verbatim. A clean
|
|
913
931
|
run yields `{ handled: true, result, warnings: [] }`; a handler that throws a
|
|
914
932
|
non-exit error yields `{ handled: false, warnings: [code], errorMessage }` so the
|
|
915
933
|
failure can be asserted. Returned objects may declare `exit_code` from `1`
|
|
@@ -2821,7 +2839,19 @@ shared `output_budget_exceeded` branch, and CLI exits 2. SDK consumers should
|
|
|
2821
2839
|
check `isReadOutputBudgetExceeded` before treating the payload as their result.
|
|
2822
2840
|
Packages can describe their own omitted groups with the existing
|
|
2823
2841
|
`OutputProjectionDeclaration`; the host also discloses reductions caused by
|
|
2824
|
-
its output controls. JSON and TOON estimates include their receipts.
|
|
2842
|
+
its output controls. JSON and TOON estimates include their receipts. A scoped
|
|
2843
|
+
`registerRenderer` replacement or `output_format` service is measured too: the
|
|
2844
|
+
estimate, compaction and omission describe the string it returns, and an
|
|
2845
|
+
infeasible budget returns the native refusal rather than the renderer's output
|
|
2846
|
+
(see [Read Output Contracts](READ_OUTPUT_CONTRACTS.md#delivered-bytes-intent-budgets-and-complete-receipts)).
|
|
2847
|
+
For a read that declares read output, the host calls a scoped renderer once
|
|
2848
|
+
for every estimate it measures. That includes each compaction candidate as
|
|
2849
|
+
well as the final delivery, so such a renderer must be pure, idempotent and
|
|
2850
|
+
cheap: no counters, file writes or timestamps in its output, and no expensive
|
|
2851
|
+
work per call. If the final rendering costs more than its receipts measured,
|
|
2852
|
+
the host re-measures the read and delivers it natively instead.
|
|
2853
|
+
Read intents report an omitted result either through `output_budget_exceeded`
|
|
2854
|
+
or through `budget_exceeded`; `isReadResultOmittedForBudget` recognizes both.
|
|
2825
2855
|
|
|
2826
2856
|
```ts
|
|
2827
2857
|
import { defineExtension } from "@unbrained/pm-cli/sdk";
|
|
@@ -3074,6 +3104,74 @@ commands. Put `--` before variadic content that begins with a dash or resembles
|
|
|
3074
3104
|
pm flag: `pm query run -- RETURN -h --json`. Everything after the separator is
|
|
3075
3105
|
delivered to the registered positional arguments unchanged.
|
|
3076
3106
|
|
|
3107
|
+
### Handler keys and ownership
|
|
3108
|
+
|
|
3109
|
+
A declared flag reaches the handler in `context.options` under one **handler
|
|
3110
|
+
key**: the long flag in camel case (`--status-filter` becomes `statusFilter`;
|
|
3111
|
+
a legacy underscore spelling such as `--include_history` keeps it). Every caller
|
|
3112
|
+
gets the same key, defaults, and coercion, because CLI argv dispatch,
|
|
3113
|
+
`PmClient.run`, MCP tool calls, and `runRegisteredCommandForTest` share one
|
|
3114
|
+
definition-driven normalizer
|
|
3115
|
+
([pm-gh1665](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1665.toon),
|
|
3116
|
+
tracker record excluded from npm). A direct caller should pass the handler key.
|
|
3117
|
+
The flag's own spellings (`status-filter`, `--status-filter`, or its short
|
|
3118
|
+
letter) fold into the same key, and undeclared keys pass through unchanged. Two
|
|
3119
|
+
spellings of one flag with different values are refused with
|
|
3120
|
+
`extension_option_spelling_conflict` (exit 2) instead of silently picking one.
|
|
3121
|
+
CLI argv gets the same refusal: `pm demo-brief --status-filter open -s closed`
|
|
3122
|
+
exits 2 instead of running with whichever value Commander kept last. Equal
|
|
3123
|
+
values after the declared coercion (`--count 1 -c 1.0`), repeats of one
|
|
3124
|
+
spelling, and `list` flags keep their accumulation
|
|
3125
|
+
([pm-wlxf8f](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wlxf8f.toon),
|
|
3126
|
+
tracker record excluded from npm):
|
|
3127
|
+
|
|
3128
|
+
```ts
|
|
3129
|
+
const client = new PmClient({ pmRoot });
|
|
3130
|
+
await client.run("demo-brief", { options: { statusFilter: "closed" } }); // handler key
|
|
3131
|
+
await client.run("demo-brief", { options: { "status-filter": "closed" } }); // same result
|
|
3132
|
+
```
|
|
3133
|
+
|
|
3134
|
+
`pm contracts --command <command> --flags-only --json` publishes the key as
|
|
3135
|
+
`sdk_option` on every extension-declared row, and marks the row `owner:
|
|
3136
|
+
"extension"`. The same entry lists the host flags the command inherits under
|
|
3137
|
+
`inherited_flags`, each marked `owner: "host"` because it arrives in
|
|
3138
|
+
`context.global`, not in `context.options`
|
|
3139
|
+
([pm-gh1666](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1666.toon),
|
|
3140
|
+
tracker record excluded from npm):
|
|
3141
|
+
|
|
3142
|
+
```json
|
|
3143
|
+
{
|
|
3144
|
+
"command": "demo-brief",
|
|
3145
|
+
"flags": [{ "flag": "--status-filter", "owner": "extension", "sdk_option": "statusFilter", "default": "open" }],
|
|
3146
|
+
"inherited_flags": [
|
|
3147
|
+
{ "flag": "--json", "owner": "host", "reservation_scope": "inherited", "value_arity": "none" },
|
|
3148
|
+
{ "flag": "--pm-path", "aliases": ["--path"], "owner": "host", "reservation_scope": "inherited", "value_arity": "required", "value_name": "path" }
|
|
3149
|
+
]
|
|
3150
|
+
}
|
|
3151
|
+
```
|
|
3152
|
+
|
|
3153
|
+
`pm help <command> --json` carries the same split as `options` and
|
|
3154
|
+
`inherited_options`, and text help prints an "Inherited host flags" section.
|
|
3155
|
+
The inherited set is derived from the reserved host-flag table: read-output
|
|
3156
|
+
controls (`--output-include`, `--output-limit`, `--output-budget`,
|
|
3157
|
+
`--output-session`, `--output-cursor`, `--output-row-contract`) appear only on
|
|
3158
|
+
commands that declare `read_output`, `--no-extensions` never appears because it
|
|
3159
|
+
removes the command itself, and root-only flags (`--version`, `--all`,
|
|
3160
|
+
`--explain`) are refused as unknown unless the command declares them.
|
|
3161
|
+
|
|
3162
|
+
On the CLI, a command with declared flags refuses any other option with
|
|
3163
|
+
`unknown_option` (exit 2), and the refusal lists exactly what the command
|
|
3164
|
+
accepts: its declared flags, then its inherited host flags, never
|
|
3165
|
+
`--no-extensions` or, on a command without `read_output`, the read-output
|
|
3166
|
+
controls
|
|
3167
|
+
([pm-4of199](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-4of199.toon),
|
|
3168
|
+
tracker record excluded from npm). A command that declares no flags still
|
|
3169
|
+
receives undeclared options in `context.options`, because released packages
|
|
3170
|
+
read options they never declared; pm-4of199 tracks refusing them once those
|
|
3171
|
+
packages declare their flags. Declare every option a handler reads with
|
|
3172
|
+
`api.registerFlags` or inline `flags`, so the command keeps working when that
|
|
3173
|
+
refusal lands.
|
|
3174
|
+
|
|
3077
3175
|
## Output Ownership
|
|
3078
3176
|
|
|
3079
3177
|
Unicode output policy ([pm-gh1624](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1624.toon), tracker record excluded from npm):
|
|
@@ -193,6 +193,8 @@ pm notes pm-a1b2 --delete 2 --full-history
|
|
|
193
193
|
|
|
194
194
|
SDK callers use `fullHistory: true`; MCP callers use `full: true`. The default stays bounded on every transport. An omission receipt identifies the semantic `full_history` selector and includes its CLI (`--full-history`), SDK (`fullHistory`), and MCP (`full`) spellings, so non-CLI consumers never need to interpret shell-only guidance.
|
|
195
195
|
|
|
196
|
+
Every returned row, in a receipt or a listing, leads with `index`, the entry's absolute 1-based position, so `mutation_receipt.entry_index` and the row's `index` agree ([pm-hka7ep](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-hka7ep.toon); tracker record excluded from npm). To make an edit or delete check that the addressed entry still carries the timestamp the caller read, pass that row's `created_at` as `--expect-at <ts>` (SDK and MCP `expectAt`). An entry at the index with a different `created_at` is refused with `annotation_entry_mismatch` before anything is written. The guard compares timestamps, not entry identities: when entries share a `created_at`, an index shift can still address a different entry with the same timestamp without a refusal, and `details.matching_indexes` lists every candidate. Stable per-entry identity is tracked separately.
|
|
197
|
+
|
|
196
198
|
## Author acknowledgment coordinates
|
|
197
199
|
|
|
198
200
|
CLI, SDK, and MCP use the same selector and coordinate parser for `history-author-acknowledge`. A coordinate is `<item-id>:<line>` or `_workspace:<line>`, with a positive one-based line number. Exactly one of explicit events or `all_actionable` is required. Applying is a two-step operation: dry-run returns a deterministic SHA-256 over the complete, ordered coordinate set and every exact source-line hash; apply requires that fingerprint and refuses stale source or selection drift with `CONFLICT` exit 4 before writing history.
|