@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
|
@@ -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]="4c8b43ab-cada-5adf-8c00-aed8de1a8bc1")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{attachExtensionReadOutputRows}from"./read-output/extension.js";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{unicodeSafePrefix}from"../core/shared/text-normalization.js";const CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING="limit_overridden_by_intent",PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}function applyIntentRowLimit(projected,budgetDerivedLimit){const requestedLimit=parsePositiveIntentTokenBudget(projected.limit),effectiveLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));return(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=effectiveLimit),effectiveLimit}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),derivedLimit=applyIntentRowLimit(projected,budgetDerivedLimit);projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0,projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){return Array.isArray(value)?value.map(compactContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)])):typeof value=="string"&&value.length>240?`${unicodeSafePrefix(value,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowCost(command,intent){return command==="context"?command==="context"&&intent==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:command==="list"?520:480,rowCost:16}}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const{overhead,rowCost}=resolveIntentRowCost(command,intent),calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit,discloseIntentLimitOverride({builtInCommand,intent:contract.intent},receipt,resultWithDiagnostics,options)}let projected={...resultWithDiagnostics,context_intent:receipt};return updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt},updateContextIntentEstimate(projected,receipt)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt)),receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget,receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,receipt.within_budget=!1,projected={budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}),projected}const CONTINUATION_METADATA_KEYS=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0)return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of CONTINUATION_METADATA_KEYS)delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function contextIntentRecoveryPositional(builtInCommand,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0;return recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`}function discloseIntentLimitOverride(identity,receipt,result,options){const requested=parsePositiveIntentTokenBudget(options.limit),effective=receipt.budget_derived_limit;if(requested===void 0||requested<=effective)return;const{overhead,rowCost}=resolveIntentRowCost(identity.builtInCommand,identity.intent),sufficientBudget=Math.max(receipt.token_budget,overhead+rowCost*requested);receipt.limit_reason=`The ${receipt.token_budget}-token ${identity.intent} budget carries ${effective} rows, so it reduced the caller's --limit ${requested}.`,receipt.limit_override={flag:"--limit",requested,effective,...Number.isSafeInteger(sufficientBudget)?{token_budget_for_requested:sufficientBudget,restore_with:`--token-budget ${sufficientBudget}`}:{}};const warning=`${CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING}:--limit ${requested}->${effective}`;result.warnings=Array.isArray(result.warnings)?[...result.warnings,warning]:[warning],isOutputRecord(result.filters)&&(result.filters={...result.filters,requested_limit:String(requested)})}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryPositional=contextIntentRecoveryPositional(builtInCommand,result),boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&updateContextIntentEstimate(finalized,finalized.context_intent),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,attachExtensionReadOutputRows(command??"",result)),projected=typeof disclosedResult=="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",{...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0},collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||typeof projected!="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract"))return projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING,PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
|
|
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]="b9a7ec77-c0da-589a-823e-dc1acae42797")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{attachExtensionReadOutputRows}from"./read-output/extension.js";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,isReadResultOmittedForBudget,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{estimateReadOutputTokens,MAX_ESTIMATE_ITERATIONS,readOutputMeasurementFormat,resolveReadOutputRecoveryBudget}from"./read-output-budget.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{unicodeSafePrefix}from"../core/shared/text-normalization.js";const CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING="limit_overridden_by_intent",PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}function applyIntentRowLimit(projected,budgetDerivedLimit){const requestedLimit=parsePositiveIntentTokenBudget(projected.limit),effectiveLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));return(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=effectiveLimit),effectiveLimit}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget,canonical)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),derivedLimit=applyIntentRowLimit(projected,budgetDerivedLimit);projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget,canonical)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget,canonical)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),canonical=canonicalIntentOutputBudget(options),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0||typeof canonical=="number",projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,typeof canonical=="number"?projected.tokenBudget=String(canonical):projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget,canonical),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){return Array.isArray(value)?value.map(compactContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)])):typeof value=="string"&&value.length>240?`${unicodeSafePrefix(value,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function canonicalIntentOutputBudget(options){const value=options.outputBudget??options.output_budget;return value==="unbounded"?value:parsePositiveIntentTokenBudget(value)}function intentBudgetFlag(options){return canonicalIntentOutputBudget(options)===void 0?"--token-budget":"--output-budget"}function resolveEffectiveIntentTokenBudget(canonical,legacy,declaredBudget){return typeof canonical=="number"?canonical:resolveIntentTokenBudget(legacy,declaredBudget)}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowCost(command,intent){return command==="context"?command==="context"&&intent==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:command==="list"?520:480,rowCost:16}}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const{overhead,rowCost}=resolveIntentRowCost(command,intent),calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt,options){const format=readOutputMeasurementFormat(options),rowContractDelivered=options.outputRowContract===!0||options.output_row_contract===!0;let measuredTokens=receipt.estimated_tokens,largestTokens=measuredTokens;for(let iteration=0;iteration<MAX_ESTIMATE_ITERATIONS;iteration+=1){receipt.estimated_tokens=measuredTokens;const nextMeasurement=estimateReadOutputTokens(rowContractDelivered||!Object.hasOwn(projected,"row_contract")?projected:Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract")),format);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement,largestTokens=Math.max(largestTokens,measuredTokens)}receipt.estimated_tokens=largestTokens}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows,options){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows,options)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt,options),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),canonicalBudget=canonicalIntentOutputBudget(options),effectiveTokenBudget=resolveEffectiveIntentTokenBudget(canonicalBudget,options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0||typeof canonicalBudget=="number");if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit,discloseIntentLimitOverride({builtInCommand,intent:contract.intent},receipt,resultWithDiagnostics,options)}const envelopeOverhead=intentEnvelopeOverheads.get(options)??0,reportedBudget=receipt.token_budget;receipt.token_budget=reportedBudget-envelopeOverhead;const projected=canonicalBudget==="unbounded"?estimatedIntentProjection(resultWithDiagnostics,receipt,options):compactIntentProjection(builtInCommand,resultWithDiagnostics,receipt,options);receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget;const outcome=intentBudgetOutcome(canonicalBudget,receipt,projected,()=>buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,{...receipt,token_budget:reportedBudget,estimated_tokens:receipt.estimated_tokens+envelopeOverhead},resultWithDiagnostics,options));return receipt.result_omitted&&(receipt.estimated_tokens+=envelopeOverhead,receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget),receipt.token_budget=reportedBudget,outcome}function estimatedIntentProjection(result,receipt,options){const projected={...result,context_intent:receipt};return updateContextIntentEstimate(projected,receipt,options),projected}function compactIntentProjection(builtInCommand,result,receipt,options){let projected=estimatedIntentProjection(result,receipt,options);return receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected=estimatedIntentProjection(compactContextIntentValue(result),receipt,options)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt,options)),projected}const intentEnvelopeOverheads=new WeakMap;function intentBudgetOutcome(canonicalBudget,receipt,projected,restoreWith){return receipt.estimated_tokens<=receipt.token_budget||(receipt.within_budget=!1,canonicalBudget==="unbounded")?projected:(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,typeof canonicalBudget=="number"?{output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},context_intent:receipt}:{budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:restoreWith()},context_intent:receipt})}const CONTINUATION_METADATA_KEYS=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0||isReadResultOmittedForBudget(result))return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of CONTINUATION_METADATA_KEYS)delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function contextIntentRecoveryPositional(builtInCommand,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0;return recoveryTarget===void 0?"":` ${shellQuote(recoveryTarget)}`}function shellQuote(value){return`'${value.replaceAll("'",`'"'"'`)}'`}function contextIntentRecoveryProjection(options){return typeof options.fields=="string"&&options.fields.trim()!==""?` --fields ${shellQuote(options.fields)}`:""}function discloseIntentLimitOverride(identity,receipt,result,options){const requested=parsePositiveIntentTokenBudget(options.limit),effective=receipt.budget_derived_limit;if(requested===void 0||requested<=effective)return;const{overhead,rowCost}=resolveIntentRowCost(identity.builtInCommand,identity.intent),sufficientBudget=Math.max(receipt.token_budget,overhead+rowCost*requested);receipt.limit_reason=`The ${receipt.token_budget}-token ${identity.intent} budget carries ${effective} rows, so it reduced the caller's --limit ${requested}.`,receipt.limit_override={flag:"--limit",requested,effective,...Number.isSafeInteger(sufficientBudget)?{token_budget_for_requested:sufficientBudget,restore_with:`${intentBudgetFlag(options)} ${sufficientBudget}`}:{}};const warning=`${CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING}:--limit ${requested}->${effective}`;result.warnings=Array.isArray(result.warnings)?[...result.warnings,warning]:[warning],isOutputRecord(result.filters)&&(result.filters={...result.filters,requested_limit:String(requested)})}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result,options){const recoveryPositional=contextIntentRecoveryPositional(builtInCommand,result),boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`,{output_budget:retryBudget}=resolveReadOutputRecoveryBudget({effective_budget_tokens:receipt.token_budget,measured_result_tokens:receipt.estimated_tokens});return`pm ${command}${recoveryPositional}${contextIntentRecoveryProjection(options)} --for ${intent} --token-budget ${retryBudget}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){reconcileIntentFit(finalized);const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&finalized.context_intent.result_omitted!==!0&&updateContextIntentEstimate(finalized,finalized.context_intent,options),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function reconcileIntentFit(result){const intent=result.context_intent;isOutputRecord(intent)&&Number(intent.estimated_tokens)>Number(intent.token_budget)&&(intent.within_budget=!1)}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,attachExtensionReadOutputRows(command??"",result));if(typeof disclosedResult!="object"||disclosedResult===null||Array.isArray(disclosedResult))return propagateContextUsageServingReceipt(result,disclosedResult),disclosedResult;const surface=command??"",source=disclosedResult,intentProjected=attachContextIntentReceipt(surface,options,source),intentEstimate=receiptEstimate(intentProjected.context_intent,"estimated_tokens"),finalized=finalizeReadOutputEnvelope(surface,options,result,intentProjected),settled=settledIntentOverBudget(options,finalized,intentProjected.context_intent);if(settled===void 0)return finalized;const charged={...options};intentEnvelopeOverheads.set(charged,settled.estimated-Number(intentEstimate));const rechargedIntent=attachContextIntentReceipt(surface,charged,source),recharged=finalizeReadOutputEnvelope(surface,charged,result,rechargedIntent),residual=settledIntentOverBudget(options,recharged,rechargedIntent.context_intent);if(residual===void 0)return recharged;const receipt={...residual.receipt,estimated_tokens:residual.estimated};return finalizeReadOutputEnvelope(surface,options,result,intentBudgetOutcome(canonicalIntentOutputBudget(options),receipt,recharged,()=>buildContextIntentRecoveryCommand(surface,receipt.command,receipt.intent,receipt,source,options)))}function settledIntentOverBudget(options,finalized,intentReceipt){const delivered=isOutputRecord(finalized.context_intent),settled=delivered?finalized.context_intent:intentReceipt;if(!isOutputRecord(settled)||settled.result_omitted===!0||Object.hasOwn(finalized,"output_budget_exceeded"))return;const receipt=settled,estimated=delivered?receipt.estimated_tokens:estimateReadOutputTokens(finalized,readOutputMeasurementFormat(options));return canonicalIntentOutputBudget(options)==="unbounded"||estimated<=receipt.token_budget?void 0:{receipt,estimated}}function finalizeReadOutputEnvelope(command,options,result,intentProjected){const projected=applyReadOutputDimensions(command,{...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0},collapseContinuationMetadata(options,intentProjected));if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||!Object.hasOwn(projected,"row_contract"))return isOutputRecord(projected.context_intent)?stabilizeSuppressedRowContractReceipts(projected,options):projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING,PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
|
|
2
2
|
//# sourceMappingURL=context-intent-contracts.js.map
|
package/dist/sdk/contracts.d.ts
CHANGED
|
@@ -24,3 +24,6 @@ export * from "./agent/refusal-closure.js";
|
|
|
24
24
|
export * from "./agent/closed-domain-contracts.js";
|
|
25
25
|
export * from "./agent/tracker-preflight-contracts.js";
|
|
26
26
|
export type { PmReadOutputSessionReceipt,PmReadOutputSessionReference,PmReadOutputSessionState,} from "./read-output-session.js";
|
|
27
|
+
export type { FlagDefinition } from "../core/extensions/extension-types.js";
|
|
28
|
+
export type { ContextIntentCursorEnvelope } from "./context-intent-contracts.js";
|
|
29
|
+
export type { ReadOutputResultForSession } from "./read-output-contracts.js";
|
package/dist/sdk/contracts.js
CHANGED
|
@@ -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]="b6abd682-bd34-572d-8630-7b24d1b4746b")}catch{}})();export*from"./cli-contracts.js";export*from"./mcp/executable.js";export*from"./graph/query-contracts.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-intent-contracts.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./flag-invocation-contracts.js";import{resolveExtensionFlagValueContract}from"../core/extensions/flag-value-types.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./output-token-accounting.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./read-output-contracts.js";export*from"./history/attestation-contract.js";export*from"../core/history/operation-contract.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/tracker-preflight-contracts.js";export{resolveExtensionFlagValueContract};
|
|
2
2
|
//# sourceMappingURL=contracts.js.map
|
package/dist/sdk/core.d.ts
CHANGED
|
@@ -16,3 +16,17 @@ export type { PmReadOutputSessionReceipt,PmReadOutputSessionReference,PmReadOutp
|
|
|
16
16
|
export type { ItemDocument,ItemMetadata,ItemStatus,ItemType,PmSettings,} from "../types/index.js";
|
|
17
17
|
export type { CloseCompletionReceipt,CloseEvidenceFollowUp } from "./lifecycle-policy.js";
|
|
18
18
|
export { assertWellFormedOutputText,toWellFormedText } from "../core/shared/output-unicode.js";
|
|
19
|
+
export type { ItemDocumentFormatOptions } from "../core/item/item-format.js";
|
|
20
|
+
export type { RuntimeStatusRegistry } from "../core/schema/runtime-schema.js";
|
|
21
|
+
export type { AgentSemanticAttribution } from "../core/session/session-state.js";
|
|
22
|
+
export type { GlobalOptions } from "../core/shared/command-types.js";
|
|
23
|
+
export type { HistoryEntry } from "../types.js";
|
|
24
|
+
export type { GraphSubcommand } from "./cli-contracts/enum-contracts.js";
|
|
25
|
+
export type { PmCreateActionOptions,PmUpdateActionOptions } from "./cli-contracts/typed-action-inputs.js";
|
|
26
|
+
export type { CreatePmCliExpectedErrorOptions,PmCliExpectedError } from "./errors.js";
|
|
27
|
+
export type { GraphCommandOptions,GraphResult } from "./graph/run.js";
|
|
28
|
+
export type { ClaimNextResult } from "./lifecycle/claim.js";
|
|
29
|
+
export type { PmResolvedReadOutputDimensions,ReadOutputResultForSession } from "./read-output-contracts.js";
|
|
30
|
+
export type { CloseTaskResult,PauseTaskResult,PmClientCloseActionOptions,PmClientFullMutationOptions,StartTaskResult } from "./runtime-public-contracts.js";
|
|
31
|
+
export type { InitialReadOptions,ReadOptions,ReadPromise } from "./runtime.js";
|
|
32
|
+
export type { TraceabilityCandidate } from "./traceability/source-traceability.js";
|
package/dist/sdk/core.js
CHANGED
|
@@ -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]="da93cfe5-b451-50d5-b763-a303bf1f19cc")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference}from"./read-output-session.js";import{assertWellFormedOutputText,toWellFormedText}from"../core/shared/output-unicode.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,assertWellFormedOutputText,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,isReadOutputSessionReference,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,toWellFormedText,update,updateLinkedTest,validateReadOutputOptions};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|
|
@@ -124,7 +124,8 @@ add(plan:CorpusShapeItemPlan):void;
|
|
|
124
124
|
/** Finish the measurement and return its conformance profile. */
|
|
125
125
|
finish():CorpusShapeProfile;
|
|
126
126
|
}
|
|
127
|
-
|
|
127
|
+
/** A corpus shape literal with no keys beyond CorpusShape, so misspelled fields fail at compile time. */
|
|
128
|
+
export type ExactCorpusShape<Shape extends CorpusShape> = Shape & Record<Exclude<keyof Shape,keyof CorpusShape>,never>;
|
|
128
129
|
/** Validate, detach, and deeply freeze a portable corpus-shape declaration. */
|
|
129
130
|
export declare function defineCorpusShape<const Shape extends CorpusShape>(shape:ExactCorpusShape<Shape>):Readonly<Shape>;
|
|
130
131
|
/** Canonical built-in corpus shapes used by repository and downstream gates. */
|
|
@@ -139,4 +140,3 @@ export declare function buildCorpusShapeItemPlan(shape:Readonly<CorpusShape>,ind
|
|
|
139
140
|
export declare function createCorpusShapeMeasurement(shape:Readonly<CorpusShape>):CorpusShapeMeasurement;
|
|
140
141
|
/** Measure a generated plan and fail closed when declared invariants drift. */
|
|
141
142
|
export declare function measureCorpusShapePlan(shape:Readonly<CorpusShape>,plans:readonly CorpusShapeItemPlan[]):CorpusShapeProfile;
|
|
142
|
-
export {};
|
package/dist/sdk/corpus-shape.js
CHANGED
|
@@ -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]="14472bc2-ebca-5b9c-9462-bd8694b630a0")}catch{}})();const PM_CORPUS_SHAPE_SCHEMA="https://schema.unbrained.dev/pm/corpus-shape/v1";function positiveInteger(value,field){if(!Number.isSafeInteger(value)||value<=0)throw new TypeError(`Corpus shape ${field} must be a positive safe integer`);return value}function nonNegativeInteger(value,field){if(!Number.isSafeInteger(value)||value<0)throw new TypeError(`Corpus shape ${field} must be a non-negative safe integer`);return value}function deepFreeze(value){if(!(typeof value!="object"||value===null||Object.isFrozen(value))){for(const nested of Object.values(value))deepFreeze(nested);Object.freeze(value)}}function defineCorpusShape(shape){if(shape.schema!==PM_CORPUS_SHAPE_SCHEMA)throw new TypeError(`Unsupported corpus shape schema: ${shape.schema}`);if(shape.name.trim().length===0||shape.description.trim().length===0)throw new TypeError("Corpus shape name and description must be non-empty");if(positiveInteger(shape.hierarchy_depth,"hierarchy_depth"),positiveInteger(shape.hierarchy_fanout,"hierarchy_fanout"),nonNegativeInteger(shape.age_span_days,"age_span_days"),positiveInteger(shape.history_entries_per_item,"history_entries_per_item"),nonNegativeInteger(shape.comments_per_100_items,"comments_per_100_items"),nonNegativeInteger(shape.notes_per_100_items,"notes_per_100_items"),nonNegativeInteger(shape.learnings_per_100_items,"learnings_per_100_items"),positiveInteger(shape.author_cardinality,"author_cardinality"),positiveInteger(shape.component_count,"component_count"),shape.edge_kind_mix.length===0||shape.edge_kind_mix.some(edge=>edge.kind.trim().length===0||edge.weight<=0))throw new TypeError("Corpus shape edge_kind_mix requires non-empty kinds with positive weights");if(shape.terminal_statuses.some(status=>!shape.custom_statuses.includes(status)))throw new TypeError("Corpus shape terminal_statuses must be declared in custom_statuses");const detached=structuredClone(shape);return deepFreeze(detached),detached}const COMMON_EDGE_MIX=[{kind:"implements",weight:5},{kind:"blocked_by",weight:2},{kind:"discovered_from",weight:2},{kind:"verifies",weight:2},{kind:"supersedes",weight:1},{kind:"related",weight:4}],BUILTIN_CORPUS_SHAPES=Object.freeze({scratch:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"scratch",description:"Seconds-old, shallow project with minimal history.",hierarchy_depth:2,hierarchy_fanout:50,age_span_days:0,history_entries_per_item:1,comments_per_100_items:2,notes_per_100_items:1,learnings_per_100_items:1,edge_kind_mix:[{kind:"related",weight:1}],author_cardinality:2,component_count:1,include_cycles:!1,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),representative:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"representative",description:"Medium-lived project with rich evidence and typed lineage.",hierarchy_depth:5,hierarchy_fanout:8,age_span_days:730,history_entries_per_item:12,comments_per_100_items:30,notes_per_100_items:12,learnings_per_100_items:10,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:32,component_count:1,include_cycles:!1,custom_types:["Experiment"],custom_statuses:["review"],terminal_statuses:[],custom_fields:["domain"]}),"deep-graph":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"deep-graph",description:"Deep typed relationship graph with deterministic cycles.",hierarchy_depth:16,hierarchy_fanout:2,age_span_days:3650,history_entries_per_item:6,comments_per_100_items:15,notes_per_100_items:8,learnings_per_100_items:8,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:16,component_count:1,include_cycles:!0,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),"multi-decade":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"multi-decade",description:"Thirty-year event history with dense per-item evolution.",hierarchy_depth:6,hierarchy_fanout:6,age_span_days:10958,history_entries_per_item:24,comments_per_100_items:40,notes_per_100_items:20,learnings_per_100_items:16,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:64,component_count:1,include_cycles:!1,custom_types:["Program"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["portfolio"]}),"disconnected-archive":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"disconnected-archive",description:"Multiple disconnected historical project components.",hierarchy_depth:4,hierarchy_fanout:10,age_span_days:7305,history_entries_per_item:8,comments_per_100_items:10,notes_per_100_items:5,learnings_per_100_items:6,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:24,component_count:5,include_cycles:!1,custom_types:["Archive"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["archive_source"]})});function listBuiltinCorpusShapes(){return Object.keys(BUILTIN_CORPUS_SHAPES).sort().map(name=>BUILTIN_CORPUS_SHAPES[name])}function resolveBuiltinCorpusShape(name){const normalized=name.trim().toLowerCase();if(!Object.hasOwn(BUILTIN_CORPUS_SHAPES,normalized))throw new TypeError(`Unknown corpus shape "${name}". Available: ${Object.keys(BUILTIN_CORPUS_SHAPES).join(", ")}`);return BUILTIN_CORPUS_SHAPES[normalized]}const expandedEdgeKinds=new WeakMap;function selectedEdgeKinds(index,shape){if(index===0)return[];let expanded=expandedEdgeKinds.get(shape);expanded===void 0&&(expanded=shape.edge_kind_mix.flatMap(entry=>Array.from({length:entry.weight},()=>entry.kind)),expandedEdgeKinds.set(shape,expanded));const kinds=[expanded[index%expanded.length]];return shape.include_cycles&&index>2&&index%17===0&&kinds.push("related"),[...new Set(kinds)]}function buildCorpusShapeItemPlan(shape,index,itemCount,seed=42){if(nonNegativeInteger(index,"item index"),positiveInteger(itemCount,"item count"),index>=itemCount)throw new RangeError(`Corpus item index ${index} exceeds ${itemCount}`);const componentCount=Math.min(shape.component_count,itemCount),component=index%componentCount,componentPosition=Math.floor(index/componentCount);let hierarchyCapacity=0,levelWidth=1;for(let depth=0;depth<shape.hierarchy_depth;depth+=1)hierarchyCapacity=Math.min(Number.MAX_SAFE_INTEGER,hierarchyCapacity+levelWidth),levelWidth=Math.min(Number.MAX_SAFE_INTEGER,levelWidth*shape.hierarchy_fanout);const treeOffset=componentPosition%hierarchyCapacity,treeStart=componentPosition-treeOffset,parentIndex=treeOffset===0?void 0:component+(treeStart+Math.floor((treeOffset-1)/shape.hierarchy_fanout))*componentCount,base=Date.UTC(2026,0,1),spanMs=shape.age_span_days*864e5,timestamp=new Date(base+(itemCount===1?0:Math.round(index/(itemCount-1)*spanMs))).toISOString(),annotationBucket=(index*37+seed)%100;return{index,id:`pm-s${index.toString(36).padStart(7,"0")}`,...parentIndex===void 0?{}:{parent:`pm-s${parentIndex.toString(36).padStart(7,"0")}`},component,timestamp,author:`pm-corpus-agent-${(index+seed)%Math.min(shape.author_cardinality,itemCount)}`,history_entry_count:shape.history_entries_per_item,dependency_kinds:selectedEdgeKinds(index,shape),has_comment:annotationBucket<shape.comments_per_100_items,has_note:annotationBucket<shape.notes_per_100_items,has_learning:annotationBucket<shape.learnings_per_100_items,...shape.custom_types.length>0&&index%11===0?{custom_type:shape.custom_types[index%shape.custom_types.length]}:{},...shape.custom_statuses.length>0&&index%13===0?{custom_status:shape.custom_statuses[index%shape.custom_statuses.length]}:{}}}class IncrementalCorpusShapeMeasurement{shape;authors=new Set;components=new Set;depths=new Map;childCounts=new Map;edgeKinds={};expectedEdgeKinds={};annotations={comments:0,notes:0,learnings:0};annotationFields;planMismatches=[];itemCount=0;observedDepth=0;observedFanout=0;historyEntryCount=0;firstTimestamp=null;lastTimestamp=null;constructor(shape){this.shape=shape,this.annotationFields=[["comments","has_comment",shape.comments_per_100_items],["notes","has_note",shape.notes_per_100_items],["learnings","has_learning",shape.learnings_per_100_items]]}recordMismatch(mismatched,message){mismatched&&this.planMismatches.push(message)}recordEdgeKinds(counts,kinds){for(const kind of kinds)counts[kind]=(counts[kind]??0)+1}add(plan){this.itemCount+=1,this.authors.add(plan.author),this.components.add(plan.component),this.recordMismatch(this.depths.has(plan.id),`duplicate_id:${plan.id}`);let depth=1;if(plan.parent!==void 0){const parentDepth=this.depths.get(plan.parent);this.recordMismatch(parentDepth===void 0,`parent_missing:${plan.parent}`),depth=(parentDepth??0)+1;const childCount=(this.childCounts.get(plan.parent)??0)+1;this.childCounts.set(plan.parent,childCount),this.observedFanout=Math.max(this.observedFanout,childCount)}this.depths.set(plan.id,depth),this.observedDepth=Math.max(this.observedDepth,depth),this.historyEntryCount+=plan.history_entry_count,this.recordMismatch(plan.history_entry_count!==this.shape.history_entries_per_item,"history_entries_per_item:drift"),this.firstTimestamp=this.firstTimestamp===null||plan.timestamp<this.firstTimestamp?plan.timestamp:this.firstTimestamp,this.lastTimestamp=this.lastTimestamp===null||plan.timestamp>this.lastTimestamp?plan.timestamp:this.lastTimestamp;for(const[annotation,property]of this.annotationFields)this.annotations[annotation]+=Number(plan[property]);this.recordEdgeKinds(this.edgeKinds,plan.dependency_kinds),this.recordEdgeKinds(this.expectedEdgeKinds,selectedEdgeKinds(plan.index,this.shape))}finish(){const expectedAuthors=Math.min(this.shape.author_cardinality,this.itemCount),expectedComponents=Math.min(this.shape.component_count,this.itemCount),mismatches=[...this.planMismatches,...this.itemCount===0?["item_count:empty"]:[],...this.authors.size===expectedAuthors?[]:[`author_count:${this.authors.size}!=${expectedAuthors}`],...this.components.size===expectedComponents?[]:[`component_count:${this.components.size}!=${expectedComponents}`],...this.observedDepth<=this.shape.hierarchy_depth?[]:[`hierarchy_depth:${this.observedDepth}>${this.shape.hierarchy_depth}`],...this.observedFanout<=this.shape.hierarchy_fanout?[]:[`hierarchy_fanout:${this.observedFanout}>${this.shape.hierarchy_fanout}`]];for(const[annotation,,rate]of this.annotationFields){const completeBuckets=Math.floor(this.itemCount/100),remainder=this.itemCount%100,minimum=completeBuckets*rate+Math.max(0,rate+remainder-100),maximum=completeBuckets*rate+Math.min(rate,remainder),observed=this.annotations[annotation];(observed<minimum||observed>maximum)&&mismatches.push(`${annotation}:${observed}!in[${minimum},${maximum}]`)}const edgeKindNames=new Set([...Object.keys(this.edgeKinds),...Object.keys(this.expectedEdgeKinds)]);for(const kind of[...edgeKindNames].sort()){const observed=this.edgeKinds[kind]??0,expected=this.expectedEdgeKinds[kind]??0;observed!==expected&&mismatches.push(`edge_kind:${kind}:${observed}!=${expected}`)}const uniqueMismatches=[...new Set(mismatches)];return{shape:this.shape.name,item_count:this.itemCount,author_count:this.authors.size,component_count:this.components.size,hierarchy_depth:this.observedDepth,hierarchy_fanout:this.observedFanout,timestamp_range:{first:this.firstTimestamp,last:this.lastTimestamp},history_entry_count:this.historyEntryCount,annotations:{...this.annotations},edge_kinds:{...this.edgeKinds},matches_declaration:uniqueMismatches.length===0,mismatches:uniqueMismatches}}}function createCorpusShapeMeasurement(shape){return new IncrementalCorpusShapeMeasurement(shape)}function measureCorpusShapePlan(shape,plans){const measurement=createCorpusShapeMeasurement(shape);for(const plan of plans)measurement.add(plan);return measurement.finish()}export{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape};
|
|
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]="1202ba19-0bcb-5478-b245-4472e361d4de")}catch{}})();const PM_CORPUS_SHAPE_SCHEMA="https://schema.unbrained.dev/pm/corpus-shape/v1";function positiveInteger(value,field){if(!Number.isSafeInteger(value)||value<=0)throw new TypeError(`Corpus shape ${field} must be a positive safe integer`);return value}function nonNegativeInteger(value,field){if(!Number.isSafeInteger(value)||value<0)throw new TypeError(`Corpus shape ${field} must be a non-negative safe integer`);return value}function deepFreeze(value){if(!(typeof value!="object"||value===null||Object.isFrozen(value))){for(const nested of Object.values(value))deepFreeze(nested);Object.freeze(value)}}function defineCorpusShape(shape){if(shape.schema!==PM_CORPUS_SHAPE_SCHEMA)throw new TypeError(`Unsupported corpus shape schema: ${shape.schema}`);if(shape.name.trim().length===0||shape.description.trim().length===0)throw new TypeError("Corpus shape name and description must be non-empty");if(positiveInteger(shape.hierarchy_depth,"hierarchy_depth"),positiveInteger(shape.hierarchy_fanout,"hierarchy_fanout"),nonNegativeInteger(shape.age_span_days,"age_span_days"),positiveInteger(shape.history_entries_per_item,"history_entries_per_item"),nonNegativeInteger(shape.comments_per_100_items,"comments_per_100_items"),nonNegativeInteger(shape.notes_per_100_items,"notes_per_100_items"),nonNegativeInteger(shape.learnings_per_100_items,"learnings_per_100_items"),positiveInteger(shape.author_cardinality,"author_cardinality"),positiveInteger(shape.component_count,"component_count"),shape.edge_kind_mix.length===0||shape.edge_kind_mix.some(edge=>edge.kind.trim().length===0||edge.weight<=0))throw new TypeError("Corpus shape edge_kind_mix requires non-empty kinds with positive weights");if(shape.terminal_statuses.some(status=>!shape.custom_statuses.includes(status)))throw new TypeError("Corpus shape terminal_statuses must be declared in custom_statuses");const detached=structuredClone(shape);return deepFreeze(detached),detached}const COMMON_EDGE_MIX=[{kind:"implements",weight:5},{kind:"blocked_by",weight:2},{kind:"discovered_from",weight:2},{kind:"verifies",weight:2},{kind:"supersedes",weight:1},{kind:"related",weight:4}],BUILTIN_CORPUS_SHAPES=Object.freeze({scratch:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"scratch",description:"Seconds-old, shallow project with minimal history.",hierarchy_depth:2,hierarchy_fanout:50,age_span_days:0,history_entries_per_item:1,comments_per_100_items:2,notes_per_100_items:1,learnings_per_100_items:1,edge_kind_mix:[{kind:"related",weight:1}],author_cardinality:2,component_count:1,include_cycles:!1,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),representative:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"representative",description:"Medium-lived project with rich evidence and typed lineage.",hierarchy_depth:5,hierarchy_fanout:8,age_span_days:730,history_entries_per_item:12,comments_per_100_items:30,notes_per_100_items:12,learnings_per_100_items:10,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:32,component_count:1,include_cycles:!1,custom_types:["Experiment"],custom_statuses:["review"],terminal_statuses:[],custom_fields:["domain"]}),"deep-graph":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"deep-graph",description:"Deep typed relationship graph with deterministic cycles.",hierarchy_depth:16,hierarchy_fanout:2,age_span_days:3650,history_entries_per_item:6,comments_per_100_items:15,notes_per_100_items:8,learnings_per_100_items:8,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:16,component_count:1,include_cycles:!0,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),"multi-decade":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"multi-decade",description:"Thirty-year event history with dense per-item evolution.",hierarchy_depth:6,hierarchy_fanout:6,age_span_days:10958,history_entries_per_item:24,comments_per_100_items:40,notes_per_100_items:20,learnings_per_100_items:16,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:64,component_count:1,include_cycles:!1,custom_types:["Program"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["portfolio"]}),"disconnected-archive":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"disconnected-archive",description:"Multiple disconnected historical project components.",hierarchy_depth:4,hierarchy_fanout:10,age_span_days:7305,history_entries_per_item:8,comments_per_100_items:10,notes_per_100_items:5,learnings_per_100_items:6,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:24,component_count:5,include_cycles:!1,custom_types:["Archive"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["archive_source"]})});function listBuiltinCorpusShapes(){return Object.keys(BUILTIN_CORPUS_SHAPES).sort().map(name=>BUILTIN_CORPUS_SHAPES[name])}function resolveBuiltinCorpusShape(name){const normalized=name.trim().toLowerCase();if(!Object.hasOwn(BUILTIN_CORPUS_SHAPES,normalized))throw new TypeError(`Unknown corpus shape "${name}". Available: ${Object.keys(BUILTIN_CORPUS_SHAPES).join(", ")}`);return BUILTIN_CORPUS_SHAPES[normalized]}const expandedEdgeKinds=new WeakMap;function selectedEdgeKinds(index,shape){if(index===0)return[];let expanded=expandedEdgeKinds.get(shape);expanded===void 0&&(expanded=shape.edge_kind_mix.flatMap(entry=>Array.from({length:entry.weight},()=>entry.kind)),expandedEdgeKinds.set(shape,expanded));const kinds=[expanded[index%expanded.length]];return shape.include_cycles&&index>2&&index%17===0&&kinds.push("related"),[...new Set(kinds)]}function buildCorpusShapeItemPlan(shape,index,itemCount,seed=42){if(nonNegativeInteger(index,"item index"),positiveInteger(itemCount,"item count"),index>=itemCount)throw new RangeError(`Corpus item index ${index} exceeds ${itemCount}`);const componentCount=Math.min(shape.component_count,itemCount),component=index%componentCount,componentPosition=Math.floor(index/componentCount);let hierarchyCapacity=0,levelWidth=1;for(let depth=0;depth<shape.hierarchy_depth;depth+=1)hierarchyCapacity=Math.min(Number.MAX_SAFE_INTEGER,hierarchyCapacity+levelWidth),levelWidth=Math.min(Number.MAX_SAFE_INTEGER,levelWidth*shape.hierarchy_fanout);const treeOffset=componentPosition%hierarchyCapacity,treeStart=componentPosition-treeOffset,parentIndex=treeOffset===0?void 0:component+(treeStart+Math.floor((treeOffset-1)/shape.hierarchy_fanout))*componentCount,base=Date.UTC(2026,0,1),spanMs=shape.age_span_days*864e5,timestamp=new Date(base+(itemCount===1?0:Math.round(index/(itemCount-1)*spanMs))).toISOString(),annotationBucket=(index*37+seed)%100;return{index,id:`pm-s${index.toString(36).padStart(7,"0")}`,...parentIndex===void 0?{}:{parent:`pm-s${parentIndex.toString(36).padStart(7,"0")}`},component,timestamp,author:`pm-corpus-agent-${(index+seed)%Math.min(shape.author_cardinality,itemCount)}`,history_entry_count:shape.history_entries_per_item,dependency_kinds:selectedEdgeKinds(index,shape),has_comment:annotationBucket<shape.comments_per_100_items,has_note:annotationBucket<shape.notes_per_100_items,has_learning:annotationBucket<shape.learnings_per_100_items,...shape.custom_types.length>0&&index%11===0?{custom_type:shape.custom_types[index%shape.custom_types.length]}:{},...shape.custom_statuses.length>0&&index%13===0?{custom_status:shape.custom_statuses[index%shape.custom_statuses.length]}:{}}}class IncrementalCorpusShapeMeasurement{shape;authors=new Set;components=new Set;depths=new Map;childCounts=new Map;edgeKinds={};expectedEdgeKinds={};annotations={comments:0,notes:0,learnings:0};annotationFields;planMismatches=[];itemCount=0;observedDepth=0;observedFanout=0;historyEntryCount=0;firstTimestamp=null;lastTimestamp=null;constructor(shape){this.shape=shape,this.annotationFields=[["comments","has_comment",shape.comments_per_100_items],["notes","has_note",shape.notes_per_100_items],["learnings","has_learning",shape.learnings_per_100_items]]}recordMismatch(mismatched,message){mismatched&&this.planMismatches.push(message)}recordEdgeKinds(counts,kinds){for(const kind of kinds)counts[kind]=(counts[kind]??0)+1}add(plan){this.itemCount+=1,this.authors.add(plan.author),this.components.add(plan.component),this.recordMismatch(this.depths.has(plan.id),`duplicate_id:${plan.id}`);let depth=1;if(plan.parent!==void 0){const parentDepth=this.depths.get(plan.parent);this.recordMismatch(parentDepth===void 0,`parent_missing:${plan.parent}`),depth=(parentDepth??0)+1;const childCount=(this.childCounts.get(plan.parent)??0)+1;this.childCounts.set(plan.parent,childCount),this.observedFanout=Math.max(this.observedFanout,childCount)}this.depths.set(plan.id,depth),this.observedDepth=Math.max(this.observedDepth,depth),this.historyEntryCount+=plan.history_entry_count,this.recordMismatch(plan.history_entry_count!==this.shape.history_entries_per_item,"history_entries_per_item:drift"),this.firstTimestamp=this.firstTimestamp===null||plan.timestamp<this.firstTimestamp?plan.timestamp:this.firstTimestamp,this.lastTimestamp=this.lastTimestamp===null||plan.timestamp>this.lastTimestamp?plan.timestamp:this.lastTimestamp;for(const[annotation,property]of this.annotationFields)this.annotations[annotation]+=Number(plan[property]);this.recordEdgeKinds(this.edgeKinds,plan.dependency_kinds),this.recordEdgeKinds(this.expectedEdgeKinds,selectedEdgeKinds(plan.index,this.shape))}finish(){const expectedAuthors=Math.min(this.shape.author_cardinality,this.itemCount),expectedComponents=Math.min(this.shape.component_count,this.itemCount),mismatches=[...this.planMismatches,...this.itemCount===0?["item_count:empty"]:[],...this.authors.size===expectedAuthors?[]:[`author_count:${this.authors.size}!=${expectedAuthors}`],...this.components.size===expectedComponents?[]:[`component_count:${this.components.size}!=${expectedComponents}`],...this.observedDepth<=this.shape.hierarchy_depth?[]:[`hierarchy_depth:${this.observedDepth}>${this.shape.hierarchy_depth}`],...this.observedFanout<=this.shape.hierarchy_fanout?[]:[`hierarchy_fanout:${this.observedFanout}>${this.shape.hierarchy_fanout}`]];for(const[annotation,,rate]of this.annotationFields){const completeBuckets=Math.floor(this.itemCount/100),remainder=this.itemCount%100,minimum=completeBuckets*rate+Math.max(0,rate+remainder-100),maximum=completeBuckets*rate+Math.min(rate,remainder),observed=this.annotations[annotation];(observed<minimum||observed>maximum)&&mismatches.push(`${annotation}:${observed}!in[${minimum},${maximum}]`)}const edgeKindNames=new Set([...Object.keys(this.edgeKinds),...Object.keys(this.expectedEdgeKinds)]);for(const kind of[...edgeKindNames].sort()){const observed=this.edgeKinds[kind]??0,expected=this.expectedEdgeKinds[kind]??0;observed!==expected&&mismatches.push(`edge_kind:${kind}:${observed}!=${expected}`)}const uniqueMismatches=[...new Set(mismatches)];return{shape:this.shape.name,item_count:this.itemCount,author_count:this.authors.size,component_count:this.components.size,hierarchy_depth:this.observedDepth,hierarchy_fanout:this.observedFanout,timestamp_range:{first:this.firstTimestamp,last:this.lastTimestamp},history_entry_count:this.historyEntryCount,annotations:{...this.annotations},edge_kinds:{...this.edgeKinds},matches_declaration:uniqueMismatches.length===0,mismatches:uniqueMismatches}}}function createCorpusShapeMeasurement(shape){return new IncrementalCorpusShapeMeasurement(shape)}function measureCorpusShapePlan(shape,plans){const measurement=createCorpusShapeMeasurement(shape);for(const plan of plans)measurement.add(plan);return measurement.finish()}export{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape};
|
|
2
2
|
//# sourceMappingURL=corpus-shape.js.map
|
package/dist/sdk/define.d.ts
CHANGED
|
@@ -34,13 +34,20 @@
|
|
|
34
34
|
*/
|
|
35
35
|
import type { AfterCommandHook,BeforeCommandHook,BeforeMutationHook,CommandDefinition,CommandOverride,Exporter,ExtensionManifest,FlagDefinition,Importer,OnIndexHook,OnReadHook,OnWriteHook,ParserOverride,PreflightOverride,ScopedPreflightOverrideDefinition,RendererOverride,ScopedRendererOverrideDefinition,SchemaFieldDefinition,SchemaItemTypeDefinition,SchemaMigrationDefinition,SearchProviderDefinition,ServiceOverride,ServiceOverrideDecision,VectorStoreAdapterDefinition } from "../core/extensions/loader.js";
|
|
36
36
|
import type { ProjectProfileDefinition } from "../core/profile/profile-presets.js";
|
|
37
|
-
|
|
38
|
-
type
|
|
39
|
-
|
|
40
|
-
type
|
|
41
|
-
|
|
42
|
-
type
|
|
43
|
-
type
|
|
37
|
+
/** A definition literal with no keys beyond its contract, so misspelled fields fail at compile time. */
|
|
38
|
+
export type ExactDefinition<TDefinition,TContract> = TDefinition & Record<Exclude<keyof TDefinition,keyof TContract>,never>;
|
|
39
|
+
/** Flag declaration fields a package author may set with defineFlags. */
|
|
40
|
+
export type FlagAuthoringDefinition = Pick<FlagDefinition,"long" | "short" | "value_name" | "description" | "required" | "enabled" | "visible" | "value_type" | "type" | "list" | "repeatable" | "default" | "value_validation">;
|
|
41
|
+
/** Custom item field declaration fields a package author may set with defineItemFields. */
|
|
42
|
+
export type ItemFieldAuthoringDefinition = Pick<SchemaFieldDefinition,"name" | "type" | "optional" | "default" | "values">;
|
|
43
|
+
/** Custom item type declaration fields a package author may set with defineItemTypes. */
|
|
44
|
+
export type ItemTypeAuthoringDefinition = Pick<SchemaItemTypeDefinition,"name" | "folder" | "aliases" | "required_create_fields" | "required_create_repeatables" | "command_option_policies" | "options" | "description" | "default_status" | "execution_role">;
|
|
45
|
+
/** Schema migration declaration fields a package author may set with defineMigration. */
|
|
46
|
+
export type MigrationAuthoringDefinition = Pick<SchemaMigrationDefinition,"id" | "description" | "status" | "mandatory" | "run">;
|
|
47
|
+
/** Search provider declaration fields a package author may set with defineSearchProvider. */
|
|
48
|
+
export type SearchProviderAuthoringDefinition = Pick<SearchProviderDefinition,"name" | "query" | "queryExpansion" | "query_expansion" | "rerank" | "embedBatch" | "embed_batch" | "embed">;
|
|
49
|
+
/** Vector store adapter declaration fields a package author may set with defineVectorStoreAdapter. */
|
|
50
|
+
export type VectorStoreAdapterAuthoringDefinition = Pick<VectorStoreAdapterDefinition,"name" | "query" | "upsert" | "delete">;
|
|
44
51
|
/**
|
|
45
52
|
* Type an extension's in-module manifest mirror (the `manifest` export / field).
|
|
46
53
|
*
|
|
@@ -229,4 +236,3 @@ export declare function defineOnReadHook(hook:OnReadHook):OnReadHook;
|
|
|
229
236
|
* annotations.
|
|
230
237
|
*/
|
|
231
238
|
export declare function defineOnIndexHook(hook:OnIndexHook):OnIndexHook;
|
|
232
|
-
export {};
|
package/dist/sdk/define.js
CHANGED
|
@@ -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]="3f3a5dca-8370-52d7-b279-dc6f9f0aeadf")}catch{}})();function defineExtensionManifest(manifest){return manifest}function defineProjectProfile(profile){return profile}function defineCommand(definition){return definition}function defineFlag(flag){return flag}function defineItemType(type){return type}function defineItemField(field){return field}function defineMigration(migration){return migration}function defineSearchProvider(provider){return provider}function defineVectorStoreAdapter(adapter){return adapter}function defineCommandOverride(override){return override}function defineParserOverride(override){return override}function definePreflightOverride(override){return override}function defineServiceOverride(override){return override}function handleServiceOverride(result){return{handled:!0,result}}function declineServiceOverride(){return{handled:!1}}function defineRendererOverride(renderer){return renderer}function defineImporter(importer){return importer}function defineExporter(exporter){return exporter}function defineBeforeCommandHook(hook){return hook}function defineBeforeMutationHook(hook){return hook}function defineAfterCommandHook(hook){return hook}function defineOnWriteHook(hook){return hook}function defineOnReadHook(hook){return hook}function defineOnIndexHook(hook){return hook}export{declineServiceOverride,defineAfterCommandHook,defineBeforeCommandHook,defineBeforeMutationHook,defineCommand,defineCommandOverride,defineExporter,defineExtensionManifest,defineFlag,defineImporter,defineItemField,defineItemType,defineMigration,defineOnIndexHook,defineOnReadHook,defineOnWriteHook,defineParserOverride,definePreflightOverride,defineProjectProfile,defineRendererOverride,defineSearchProvider,defineServiceOverride,defineVectorStoreAdapter,handleServiceOverride};
|
|
2
2
|
//# sourceMappingURL=define.js.map
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { type FlagDefinition } from "../runtime-primitives.js";
|
|
2
|
+
/** Flag metadata consumed by loose-option parsing across core and extension commands. */
|
|
3
|
+
export interface LooseCommandFlagDefinition {
|
|
4
|
+
/** Canonical long option token. */
|
|
5
|
+
long?:string;
|
|
6
|
+
/** Optional short option token. */
|
|
7
|
+
short?:string;
|
|
8
|
+
/** Backward-compatible aliases emitted by core command contracts. */
|
|
9
|
+
aliases?:string[];
|
|
10
|
+
/** Canonical runtime value kind. */
|
|
11
|
+
value_type?:string;
|
|
12
|
+
/** Backward-compatible runtime value kind alias. */
|
|
13
|
+
type?:string;
|
|
14
|
+
/** Whether the option can be supplied to the command. */
|
|
15
|
+
enabled?:boolean;
|
|
16
|
+
/** Whether callers must provide the option. */
|
|
17
|
+
required?:boolean;
|
|
18
|
+
/** Whether repeated or comma-delimited values accumulate. */
|
|
19
|
+
list?:boolean;
|
|
20
|
+
/** Whether repeated occurrences accumulate without splitting commas. */
|
|
21
|
+
repeatable?:boolean;
|
|
22
|
+
/** Value used when callers omit the option. */
|
|
23
|
+
default?:unknown;
|
|
24
|
+
/** `strict` refuses malformed number/boolean tokens before dispatch; `coerce` (default) forwards them. */
|
|
25
|
+
value_validation?:string;
|
|
26
|
+
}
|
|
27
|
+
/** Collect every option key the declared flags answer to: each long flag's camel-case key and each short letter. */
|
|
28
|
+
export declare function collectLooseCommandOptionKeysForDefinitions(definitions:ReadonlyArray<LooseCommandFlagDefinition>):Set<string>;
|
|
29
|
+
/**
|
|
30
|
+
* The flags an unknown-option refusal lists (pm-4of199). By default every
|
|
31
|
+
* validated definition is listed; an extension-created command lists only
|
|
32
|
+
* its declared flags and the host flags it inherits, because the host
|
|
33
|
+
* definitions it is also validated against include controls it refuses.
|
|
34
|
+
*/
|
|
35
|
+
export interface LooseOptionRefusalListing {
|
|
36
|
+
/** Definitions whose labels are listed, in place of every validated definition. */
|
|
37
|
+
definitions?:ReadonlyArray<LooseCommandFlagDefinition>;
|
|
38
|
+
/** Host flags listed after the definitions' labels. */
|
|
39
|
+
inheritedFlags?:readonly string[];
|
|
40
|
+
}
|
|
41
|
+
/** Refuse an option no declaration owns, a disabled flag that was supplied, or a required flag that is missing, naming the command and its accepted flags. */
|
|
42
|
+
export declare function validateLooseCommandOptionsWithFlagDefinitions(options:Record<string,unknown>,definitions:ReadonlyArray<LooseCommandFlagDefinition>,commandPath:string,listing?:LooseOptionRefusalListing):void;
|
|
43
|
+
/** Fold each declared flag's spellings into its handler key, apply declared defaults, and coerce values by declared type, refusing malformed strict scalars. */
|
|
44
|
+
export declare function coerceLooseCommandOptionsWithFlagDefinitions(options:Record<string,unknown>,definitions:ReadonlyArray<LooseCommandFlagDefinition>,occurrenceSource?:Record<string,unknown>,commandPath?:string):Record<string,unknown>;
|
|
45
|
+
/** Parse option tokens from argv into camel-case keys, accumulating repeats and recording each occurrence in order for list and switch handling. */
|
|
46
|
+
export declare function parseLooseCommandOptions(args:string[]):Record<string,unknown>;
|
|
47
|
+
/** Returns the positional operands in `args`, skipping option tokens and the values they consume (`--flag value`, `--flag=value`, `-f value`, and boolean flags). Tokens after a bare `--` separator are all positional. Used to count genuinely unexpected positionals for extension commands that declare no arguments without miscounting leaked/undeclared option tokens as operands. */
|
|
48
|
+
export declare function collectLoosePositionalArgs(args:string[]):string[];
|
|
49
|
+
/** Remove the tokens of declared flags (and the values they consume) from argv, leaving positional operands and undeclared tokens. */
|
|
50
|
+
export declare function stripLooseCommandOptionTokens(args:string[],definitions:ReadonlyArray<LooseCommandFlagDefinition>):string[];
|
|
51
|
+
/**
|
|
52
|
+
* Handler option key a declared extension flag is delivered under in
|
|
53
|
+
* `context.options` — the key `pm contracts` publishes as `sdk_option` and the
|
|
54
|
+
* key direct callers pass to `PmClient.run` or the test harness.
|
|
55
|
+
*/
|
|
56
|
+
export declare function resolveExtensionFlagOptionKey(definition:LooseCommandFlagDefinition):string | null;
|
|
57
|
+
/** Join contributed flags by stable operation identity so canonical and compatibility command paths share one schema. */
|
|
58
|
+
export declare function collectExtensionFlagDefinitionsForCommand(registrations:{
|
|
59
|
+
readonly flags:ReadonlyArray<{
|
|
60
|
+
readonly target_command:string;
|
|
61
|
+
readonly flags:readonly FlagDefinition[];
|
|
62
|
+
}>;
|
|
63
|
+
},commandPath:string):FlagDefinition[];
|
|
64
|
+
/**
|
|
65
|
+
* Normalize the options a direct caller — `PmClient.run`, an MCP tool call, or
|
|
66
|
+
* the extension test harness — passes to an extension command, exactly as CLI
|
|
67
|
+
* dispatch normalizes argv. Each declared spelling of a flag (`statusFilter`,
|
|
68
|
+
* `status-filter`, `--status-filter`, or its short letter) folds into the
|
|
69
|
+
* handler key, then declared defaults, value coercion, and strict validation
|
|
70
|
+
* apply through {@link coerceLooseCommandOptionsWithFlagDefinitions}. An
|
|
71
|
+
* `undefined` value counts as omitted. Undeclared keys pass through unchanged.
|
|
72
|
+
* Two spellings of one flag with different values are refused with
|
|
73
|
+
* `extension_option_spelling_conflict`.
|
|
74
|
+
*/
|
|
75
|
+
export declare function normalizeDirectExtensionCommandOptions(options:Record<string,unknown>,definitions:ReadonlyArray<LooseCommandFlagDefinition>,commandPath:string):Record<string,unknown>;
|
|
76
|
+
/** How an argv option token takes its value, as Commander parses it: `<value>`, `[value]`, or a switch. */
|
|
77
|
+
export type ArgvOptionArity = "required" | "optional" | "none";
|
|
78
|
+
/** An option a command registered with Commander: how it takes its value and the attribute it sets. */
|
|
79
|
+
export interface ArgvCommandOption {
|
|
80
|
+
/** Value arity Commander applies to the option. */
|
|
81
|
+
arity:ArgvOptionArity;
|
|
82
|
+
/** Commander attribute the option sets, compared with a declaration's handler key. */
|
|
83
|
+
key:string;
|
|
84
|
+
/** Whether the option is variadic, so it keeps consuming following operands. */
|
|
85
|
+
variadic?:boolean;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* One command's captured option tokens and the options its own parser
|
|
89
|
+
* recognizes. Commander lets an ancestor consume its own options anywhere in
|
|
90
|
+
* the argv after its name, so every command on the dispatch path is a scope.
|
|
91
|
+
*/
|
|
92
|
+
export interface ArgvOptionScope {
|
|
93
|
+
/** Tokens the command's option parser received. */
|
|
94
|
+
tokens:readonly string[];
|
|
95
|
+
/** The Commander option that owns a spelling on this command, if any. */
|
|
96
|
+
optionOf:(spelling:string) => ArgvCommandOption | undefined;
|
|
97
|
+
/** Whether declared flags the command did not register with Commander are read too (the dispatched leaf). */
|
|
98
|
+
includesLooseFlags:boolean;
|
|
99
|
+
/** Whether a negative number is a value, which Commander allows when no numeric short option exists on the path. */
|
|
100
|
+
negativeNumbersAreValues:boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Where the command stops reading its own options, as Commander does for a
|
|
103
|
+
* command with positional options (at a subcommand name before any other
|
|
104
|
+
* unrecognized token) or pass-through options (at the first unrecognized
|
|
105
|
+
* token). Absent: the command reads its options anywhere.
|
|
106
|
+
*/
|
|
107
|
+
stop?:{
|
|
108
|
+
atSubcommand:(token:string) => boolean;
|
|
109
|
+
atFirstUnrecognized:boolean;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Refuse CLI argv that sets one declared scalar flag through two spellings
|
|
114
|
+
* with different values (pm-wlxf8f), as direct callers are refused through
|
|
115
|
+
* {@link normalizeDirectExtensionCommandOptions}. Commander keeps the last
|
|
116
|
+
* value of an option whatever spelling supplied it, so `--status-filter open
|
|
117
|
+
* -s closed` would otherwise run with one value and drop the other silently.
|
|
118
|
+
* `scopes` are the commands on the dispatch path, each with the tokens its
|
|
119
|
+
* own parser received, so an occurrence an ancestor consumed is still seen.
|
|
120
|
+
* Values compare after the declared coercion, so `--count 1 -c 1` is
|
|
121
|
+
* accepted; repeats of one spelling and list flags are not checked.
|
|
122
|
+
*/
|
|
123
|
+
export declare function refuseConflictingArgvOptionSpellings(scopes:readonly ArgvOptionScope[],definitions:ReadonlyArray<LooseCommandFlagDefinition>,commandPath:string):void;
|
|
@@ -0,0 +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]="90fdc6f3-29d4-5266-a142-d9d14fbb12e7")}catch{}})();import{isDeepStrictEqual}from"node:util";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";import{describeFlagScalarValueFailure,resolveExtensionFlagValueContract,resolveExtensionLongFlagName,EXIT_CODE,PmCliError,flattenFlagListValue,resolveFlagValueKind}from"../runtime-primitives.js";const UNSAFE_LOOSE_OPTION_KEYS=new Set(["__proto__","prototype","constructor"]),LOOSE_OPTION_OCCURRENCES=Symbol("looseOptionOccurrences");function toLooseOptionKey(rawKey){return rawKey.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(_match,group)=>group.toUpperCase())}function setLooseOptionValue(options,key,value){const existing=options[key];if(existing===void 0){options[key]=value;return}if(Array.isArray(existing)){existing.push(value),options[key]=existing;return}options[key]=[existing,value]}function parseLooseOptionToken(args,index){const token=args[index];if(!token.startsWith("-")||token==="-"||token==="--")return null;if(!token.startsWith("--")){const equalsIndex2=token.indexOf("=");if(equalsIndex2>=0)return{consumed:1,key:token.slice(1,equalsIndex2).trim(),value:token.slice(equalsIndex2+1),attached:!0};const key2=token.slice(1).trim(),next2=args[index+1];return typeof next2=="string"&&!next2.startsWith("-")?{consumed:2,key:key2,value:next2}:{consumed:1,key:key2,value:!0}}const equalsIndex=token.indexOf("=");if(equalsIndex>=0)return{consumed:1,key:token.slice(2,equalsIndex).trim(),value:token.slice(equalsIndex+1),attached:!0};if(token.startsWith("--no-"))return{consumed:1,key:token.slice(5).trim(),value:!1};const key=token.slice(2).trim(),next=args[index+1];return typeof next=="string"&&!next.startsWith("-")?{consumed:2,key,value:next}:{consumed:1,key,value:!0}}function isUnsafeLooseOptionKey(key){return UNSAFE_LOOSE_OPTION_KEYS.has(key)}function resolveLooseOptionCoercionKind(definition){const raw=(typeof definition.value_type=="string"?definition.value_type:void 0)??(typeof definition.type=="string"?definition.type:void 0);return resolveFlagValueKind(raw)}function collectLooseOptionKeys(definition){const keys=[],long=resolveExtensionLongFlagName(definition.long)??"",short=typeof definition.short=="string"?definition.short.trim():"";if(long.startsWith("--")){const normalized=toLooseOptionKey(long.slice(2));normalized.length>0&&!isUnsafeLooseOptionKey(normalized)&&keys.push(normalized)}if(short.startsWith("-")&&!short.startsWith("--")){const normalized=toLooseOptionKey(short.slice(1));normalized.length>0&&!isUnsafeLooseOptionKey(normalized)&&keys.push(normalized)}return[...new Set(keys)]}function collectLooseCommandOptionKeysForDefinitions(definitions){const keys=new Set;for(const definition of definitions)for(const key of collectLooseOptionKeys(definition))keys.add(key);return keys}function resolveCanonicalLooseOptionKey(definition){const long=resolveExtensionLongFlagName(definition.long)??"";if(long.startsWith("--")){const normalized=toLooseOptionKey(long.slice(2));if(normalized.length>0&&!isUnsafeLooseOptionKey(normalized))return normalized}return collectLooseOptionKeys(definition)[0]??null}function formatLooseOptionLabel(definition){const long=typeof definition.long=="string"?definition.long.trim():"";if(long.startsWith("--")&&long.length>2)return long;const short=typeof definition.short=="string"?definition.short.trim():"";return short.startsWith("-")&&!short.startsWith("--")&&short.length>1?short:null}function collectRefusalListingLabels(definitions,listing){return[...(listing.definitions??definitions).map(definition=>formatLooseOptionLabel(definition)).filter(label=>label!==null),...listing.inheritedFlags??[]]}function validateLooseCommandOptionsWithFlagDefinitions(options,definitions,commandPath,listing={}){if(definitions.length===0)return;const allowed=new Set,disabled=new Map,required=[],labels=collectRefusalListingLabels(definitions,listing);for(const definition of definitions){const keys=collectLooseOptionKeys(definition),normalizedLabel=formatLooseOptionLabel(definition);for(const key of keys)allowed.add(key),definition.enabled===!1&&disabled.set(key,normalizedLabel);definition.required===!0&&definition.enabled!==!1&&keys.length>0&&required.push({keys,label:normalizedLabel})}for(const key of Object.keys(options)){if(!allowed.has(key)){const expected=labels.length>0?` Expected one of: ${[...new Set(labels)].join(", ")}.`:"";throw new PmCliError(`Unknown option '--${key}' for extension command '${commandPath}'.${expected}`,EXIT_CODE.USAGE,{code:"unknown_option",flag:`--${key}`,required:`Use a flag the command accepts; run pm contracts --command ${commandPath} --flags-only --json to list them.`})}const disabledLabel=disabled.get(key);if(disabledLabel)throw new PmCliError(`Option '${disabledLabel}' is disabled for extension command '${commandPath}'.`,EXIT_CODE.USAGE)}for(const entry of required)if(!entry.keys.some(key=>Object.hasOwn(options,key)))throw new PmCliError(`Missing required option '${entry.label}' for extension command '${commandPath}'.`,EXIT_CODE.USAGE)}function coerceLooseStringOptionValue(value){return typeof value=="string"||value==null?value:String(value)}function coerceLooseNumberOptionValue(value){if(typeof value=="number")return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);return Number.isFinite(parsed)?parsed:value}return value}function coerceLooseBooleanOptionValue(value){if(typeof value=="boolean")return value;if(typeof value=="string"){const normalized=value.trim().toLowerCase();if(normalized==="true"||normalized==="1")return!0;if(normalized==="false"||normalized==="0")return!1}return value}const LOOSE_OPTION_VALUE_COERCERS={string:coerceLooseStringOptionValue,number:coerceLooseNumberOptionValue,boolean:coerceLooseBooleanOptionValue};function coerceLooseOptionValue(value,kind){return Array.isArray(value)?value.map(entry=>coerceLooseOptionValue(entry,kind)):LOOSE_OPTION_VALUE_COERCERS[kind](value)}function normalizeAccumulatedFlagValue(value,kind,preserveOccurrenceCommas){const entries=preserveOccurrenceCommas?(Array.isArray(value)?value.flat(1/0):[value]).filter(entry=>entry!=null&&entry!==""):flattenFlagListValue(value);return kind?entries.map(entry=>coerceLooseOptionValue(entry,kind)):entries}function applyFlagDefault(defaultValue,kind,isListFlag,preserveOccurrenceCommas){return isListFlag?normalizeAccumulatedFlagValue(defaultValue,kind,preserveOccurrenceCommas):kind?coerceLooseOptionValue(defaultValue,kind):defaultValue}function readOrderedLooseListValues(occurrenceSource,optionKeys,fallback){const occurrences=occurrenceSource[LOOSE_OPTION_OCCURRENCES];if(!occurrences||occurrences.length===0)return fallback;const acceptedKeys=new Set(optionKeys);return occurrences.filter(occurrence=>acceptedKeys.has(occurrence.key)).map(occurrence=>occurrence.value)}function isBooleanSwitchDefinition(definition){return resolveExtensionFlagValueContract(definition).value_arity==="none"}function refuseStrictScalarValue(definition,kind,entry,expected,commandPath){const label=formatLooseOptionLabel(definition),scope=commandPath?` for extension command '${commandPath}'`:"",received=entry===!0?"no value":JSON.stringify(entry);throw new PmCliError(`Option '${label}'${scope} expects ${expected}; received ${received}.`,EXIT_CODE.USAGE,{code:"extension_flag_value_invalid",required:`Pass ${label} ${kind==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${kind} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${kind} value for ${label}.`,`Run pm ${commandPath??"<command>"} --help to review the declared flag contract.`]})}function isStrictTypedDefinition(definition,kind){return definition.value_validation==="strict"&&kind!=="string"}function readLooseOccurrences(occurrenceSource,optionKeys){const occurrences=occurrenceSource[LOOSE_OPTION_OCCURRENCES];if(!occurrences)return[];const acceptedKeys=new Set(optionKeys);return occurrences.filter(occurrence=>acceptedKeys.has(occurrence.key))}function refuseMalformedAttachedSwitchValues(definition,optionKeys,occurrenceSource,commandPath){if(isBooleanSwitchDefinition(definition))for(const occurrence of readLooseOccurrences(occurrenceSource,optionKeys)){if(occurrence.attached!==!0)continue;const values=definition.list===!0&&definition.repeatable!==!0?flattenFlagListValue(occurrence.value):[occurrence.value];for(const value of values){const failure=describeFlagScalarValueFailure(coerceLooseOptionValue(value,"boolean"),"boolean");failure!==null&&refuseStrictScalarValue(definition,"boolean",value,failure.expected,commandPath)}}}function refuseEmptyStrictListEntries(definition,kind,rawValue,preserveOccurrenceCommas,commandPath){const occurrences=Array.isArray(rawValue)?rawValue.flat(1/0):[rawValue],entries=preserveOccurrenceCommas?occurrences:occurrences.flatMap(entry=>typeof entry=="string"?entry.split(","):[entry]);for(const entry of entries)if(typeof entry=="string"&&entry.trim().length===0){const failure=describeFlagScalarValueFailure(entry,kind);refuseStrictScalarValue(definition,kind,entry,failure.expected,commandPath)}}function validateStrictScalarOptionValue(definition,value,kind,commandPath){if(!isStrictTypedDefinition(definition,kind))return value;const isSwitch=kind==="boolean"&&isBooleanSwitchDefinition(definition),normalizeEntry=entry=>{const failure=describeFlagScalarValueFailure(entry,kind);return failure===null?entry:isSwitch&&typeof entry=="string"?!0:refuseStrictScalarValue(definition,kind,entry,failure.expected,commandPath)};return Array.isArray(value)?value.map(normalizeEntry):normalizeEntry(value)}function mergeAliasOptionKeys(coerced,canonical,optionKeys,isListFlag){for(const key of optionKeys)if(!(key===canonical||!Object.hasOwn(coerced,key))){if(Object.hasOwn(coerced,canonical)){if(isListFlag){const canonicalValue=coerced[canonical],aliasValue=coerced[key];coerced[canonical]=[...Array.isArray(canonicalValue)?canonicalValue:[canonicalValue],...Array.isArray(aliasValue)?aliasValue:[aliasValue]].filter(value=>value!=null)}delete coerced[key];continue}coerced[canonical]=coerced[key],delete coerced[key]}}function coerceLooseCommandOptionsWithFlagDefinitions(options,definitions,occurrenceSource=options,commandPath){if(definitions.length===0)return options;const coerced=Object.create(null);for(const[key,value]of Object.entries(options))coerced[key]=value;const canonicalKeys=new Set(definitions.map(definition=>resolveCanonicalLooseOptionKey(definition)).filter(key=>key!==null));for(const definition of definitions){const canonical=resolveCanonicalLooseOptionKey(definition);if(canonical){const optionKeys=collectLooseOptionKeys(definition).filter(key=>key===canonical||!canonicalKeys.has(key));coerceDefinedLooseOption(coerced,definition,canonical,optionKeys,occurrenceSource,commandPath)}}return coerced}function coerceDefinedLooseOption(coerced,definition,canonical,optionKeys,occurrenceSource,commandPath){const isListFlag=definition.list===!0,kind=resolveLooseOptionCoercionKind(definition);kind&&!isListFlag&&refuseMalformedScalarAliasValues(coerced,definition,canonical,optionKeys,kind,commandPath),mergeAliasOptionKeys(coerced,canonical,optionKeys,isListFlag);const preserveOccurrenceCommas=definition.repeatable===!0;if(!Object.hasOwn(coerced,canonical)){definition.default!==void 0&&(coerced[canonical]=applyFlagDefault(definition.default,kind,isListFlag,preserveOccurrenceCommas));return}if(kind==="boolean"&&isStrictTypedDefinition(definition,kind)&&refuseMalformedAttachedSwitchValues(definition,optionKeys,occurrenceSource,commandPath),isListFlag){coerced[canonical]=coerceAccumulatedLooseOption(definition,optionKeys,occurrenceSource,coerced[canonical],kind,preserveOccurrenceCommas,commandPath);return}kind&&(coerced[canonical]=validateStrictScalarOptionValue(definition,coerceLooseOptionValue(coerced[canonical],kind),kind,commandPath))}function refuseMalformedScalarAliasValues(coerced,definition,canonical,optionKeys,kind,commandPath){for(const key of optionKeys)key!==canonical&&Object.hasOwn(coerced,key)&&validateStrictScalarOptionValue(definition,coerceLooseOptionValue(coerced[key],kind),kind,commandPath)}function coerceAccumulatedLooseOption(definition,optionKeys,occurrenceSource,current,kind,preserveOccurrenceCommas,commandPath){const ordered=readOrderedLooseListValues(occurrenceSource,optionKeys,current);kind&&isStrictTypedDefinition(definition,kind)&&refuseEmptyStrictListEntries(definition,kind,ordered,preserveOccurrenceCommas,commandPath);const normalized=normalizeAccumulatedFlagValue(ordered,kind,preserveOccurrenceCommas);return kind?validateStrictScalarOptionValue(definition,normalized,kind,commandPath):normalized}function parseLooseCommandOptions(args){const options=Object.create(null),occurrences=[];Object.defineProperty(options,LOOSE_OPTION_OCCURRENCES,{value:occurrences});let index=0;for(;index<args.length;){const parsed=parseLooseOptionToken(args,index);if(!parsed){index+=1;continue}const normalizedKey=toLooseOptionKey(parsed.key);if(normalizedKey.length===0||isUnsafeLooseOptionKey(normalizedKey)){index+=parsed.consumed;continue}setLooseOptionValue(options,normalizedKey,parsed.value),occurrences.push({...parsed,key:normalizedKey}),index+=parsed.consumed}return options}function collectLoosePositionalArgs(args){const positionals=[];let index=0;for(;index<args.length;){if(args[index]==="--"){positionals.push(...args.slice(index+1));break}const parsed=parseLooseOptionToken(args,index);if(parsed){index+=Math.max(1,parsed.consumed);continue}positionals.push(args[index]),index+=1}return positionals}function stripLooseCommandOptionTokens(args,definitions){if(definitions.length===0)return[...args];const knownKeys=new Set,booleanKeys=new Set;for(const definition of definitions){const valueKind=resolveLooseOptionCoercionKind(definition);for(const key of collectLooseOptionKeys(definition))knownKeys.add(key),valueKind==="boolean"&&booleanKeys.add(key)}if(knownKeys.size===0)return[...args];const stripped=[];let index=0;for(;index<args.length;){if(args[index]==="--"){stripped.push(...args.slice(index+1));break}const parsed=parseLooseOptionToken(args,index);if(parsed){const normalizedKey=toLooseOptionKey(parsed.key);if(knownKeys.has(normalizedKey)){const token=args[index],consumed=booleanKeys.has(normalizedKey)&&!token.includes("=")?1:parsed.consumed;index+=consumed;continue}}stripped.push(args[index]),index+=1}return stripped}function resolveExtensionFlagOptionKey(definition){return resolveCanonicalLooseOptionKey(definition)}function normalizeFlagTargetCommandPath(commandPath){return commandPath.trim().toLowerCase().split(/\s+/u).filter(part=>part.length>0).join(" ")}function collectExtensionFlagDefinitionsForCommand(registrations,commandPath){const normalizedCommandPath=normalizeFlagTargetCommandPath(commandPath);if(normalizedCommandPath.length===0)return[];const operation=resolvePmCommandOperation(normalizedCommandPath);return registrations.flags.filter(entry=>resolvePmCommandOperation(normalizeFlagTargetCommandPath(entry.target_command))===operation).flatMap(entry=>[...entry.flags])}function refuseConflictingOptionSpellings(definition,handlerKey,spellings,commandPath){const label=formatLooseOptionLabel(definition),[first,second]=spellings;throw new PmCliError(`Options '${first}' and '${second}' both set ${label} for extension command '${commandPath}' with different values.`,EXIT_CODE.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${label} once, under the handler key '${handlerKey}'.`,why:`'${first}' and '${second}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${first}' or '${second}' and pass one value as '${handlerKey}'.`,`Run pm contracts --command ${commandPath} --flags-only --json to read each flag's sdk_option key.`]})}function normalizeDirectExtensionCommandOptions(options,definitions,commandPath){if(definitions.length===0)return options;const index=indexDeclaredOptionSpellings(definitions),folded=foldDirectOptionSpellings(options,index,commandPath),handlerKeys=new Set([...index.long.values()].map(({handlerKey})=>handlerKey)),declared=Object.create(null),passthrough=Object.create(null);for(const[key,value]of Object.entries(folded))(handlerKeys.has(key)?declared:passthrough)[key]=value;return refuseDirectDeclarationViolations(declared,definitions,commandPath),Object.assign(passthrough,coerceLooseCommandOptionsWithFlagDefinitions(declared,definitions,recordDirectOptionOccurrences(declared,index),commandPath))}function recordDirectOptionOccurrences(folded,index){const handlerKeys=new Set([...index.long.values()].map(({handlerKey})=>handlerKey)),occurrences=Object.entries(folded).filter(([key])=>handlerKeys.has(key)).flatMap(([key,value])=>(Array.isArray(value)?value.flat(1/0):[value]).map(entry=>({consumed:1,key,value:entry,attached:!0}))),occurrenceSource=Object.create(null);return Object.defineProperty(occurrenceSource,LOOSE_OPTION_OCCURRENCES,{value:occurrences}),occurrenceSource}function refuseDirectDeclarationViolations(declared,definitions,commandPath){for(const definition of definitions){const handlerKey=resolveCanonicalLooseOptionKey(definition);if(handlerKey===null)continue;const label=formatLooseOptionLabel(definition),supplied=Object.hasOwn(declared,handlerKey);if(definition.enabled===!1&&supplied)throw new PmCliError(`Option '${label}' is disabled for extension command '${commandPath}'.`,EXIT_CODE.USAGE);if(definition.required===!0&&definition.enabled!==!1&&!supplied)throw new PmCliError(`Missing required option '${label}' for extension command '${commandPath}'.`,EXIT_CODE.USAGE)}}function indexDeclaredOptionSpellings(definitions){const index={long:new Map,short:new Map},claim=(map,spelling,entry)=>{spelling.length>0&&!map.has(spelling)&&map.set(spelling,entry)};for(const definition of definitions){const handlerKey=resolveCanonicalLooseOptionKey(definition);if(handlerKey===null)continue;const entry={handlerKey,definition};claim(index.long,handlerKey,entry);const short=typeof definition.short=="string"?definition.short.trim():"";short.startsWith("-")&&!short.startsWith("--")&&claim(index.short,short.slice(1),entry)}return index}function resolveDeclaredOptionSpelling(index,spelling){return index.long.get(spelling)??index.short.get(spelling.replace(/^-(?!-)/u,""))??index.long.get(toLooseOptionKey(spelling.replace(/^-{1,2}/u,"")))}function resolveNegatedBooleanSpelling(index,spelling,value){const negated=/^(?:--)?no-(.+)$/u.exec(spelling)?.[1];if(negated===void 0||resolveDeclaredOptionSpelling(index,spelling)!==void 0)return{spelling,value};const declared=resolveDeclaredOptionSpelling(index,negated),flag=coerceLooseBooleanOptionValue(value);return declared!==void 0&&resolveLooseOptionCoercionKind(declared.definition)==="boolean"&&typeof flag=="boolean"?{spelling:negated,value:!flag}:{spelling,value}}function foldDirectOptionSpellings(options,index,commandPath){const folded=Object.create(null),suppliedBy=new Map;for(const[rawSpelling,rawValue]of Object.entries(options)){const{spelling,value}=resolveNegatedBooleanSpelling(index,rawSpelling,rawValue),declared=resolveDeclaredOptionSpelling(index,spelling);if(declared===void 0)folded[spelling]=value;else if(value!==void 0){const prior=suppliedBy.get(declared.handlerKey);prior===void 0?(suppliedBy.set(declared.handlerKey,spelling),folded[declared.handlerKey]=value):isDeepStrictEqual(folded[declared.handlerKey],value)||refuseConflictingOptionSpellings(declared.definition,declared.handlerKey,[prior,spelling],commandPath)}}return folded}function indexDeclaredArgvSpellings(definitions){const index=new Map;for(const definition of definitions){const handlerKey=resolveCanonicalLooseOptionKey(definition);if(handlerKey===null)continue;const entry={definition,handlerKey,kind:resolveLooseOptionCoercionKind(definition),arity:resolveExtensionFlagValueContract(definition).value_arity,scalar:definition.list!==!0},spellings=[resolveExtensionLongFlagName(definition.long),typeof definition.short=="string"?definition.short.trim():""];for(const spelling of spellings.filter(candidate=>candidate?.startsWith("-")===!0))index.has(spelling)||index.set(spelling,entry)}return index}function resolveArgvSpelling(scope,index,spelling){const registered=scope.optionOf(spelling),declared=index.get(spelling),settable=declared?.scalar===!0?declared:void 0;if(registered!==void 0){const base={arity:registered.arity,...registered.variadic===!0?{variadic:!0}:{}};if(settable?.handlerKey===registered.key)return{...base,declared:settable};const positive=declared===void 0&&spelling.startsWith("--no-")?index.get(`--${spelling.slice(5)}`):void 0;return positive?.scalar===!0&&positive.kind==="boolean"&&positive.handlerKey===registered.key?{...base,declared:positive,negates:!0}:base}if(!(!scope.includesLooseFlags||declared===void 0))return settable===void 0?{arity:declared.arity,loose:!0}:{arity:declared.arity,declared:settable,loose:!0}}function isArgvOptionToken(token){return token.length>1&&token.startsWith("-")}const NEGATIVE_NUMBER_ARGV_TOKEN=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function scanArgvScope(scope,resolve,record){const{tokens}=scope;let position=0,group,unrecognizedSeen=!1,variadic=!1;for(;position<tokens.length||group!==void 0;){const token=group??tokens[position++];if(token==="--")return;if(variadic&&group===void 0&&isArgvVariadicValue(scope,token))continue;const step=isArgvOptionToken(token)?scanArgvOptionToken(scope,token,tokens[position],resolve,record):{consumedByCommander:!1,consumed:0};if(position+=step.consumed,group=step.group,variadic=step.variadic===!0,!step.consumedByCommander){if(stopsArgvScope(scope.stop,token,unrecognizedSeen))return;unrecognizedSeen=!0}}}function isArgvVariadicValue(scope,token){return!isArgvOptionToken(token)||scope.negativeNumbersAreValues&&NEGATIVE_NUMBER_ARGV_TOKEN.test(token)}function stopsArgvScope(stop,token,unrecognizedSeen){return stop!==void 0&&(stop.atFirstUnrecognized||!unrecognizedSeen&&stop.atSubcommand(token))}function scanArgvOptionToken(scope,token,next,resolve,record){const loose=readLooseArgvOccurrence(token,next,resolve);if(loose!==void 0)return record(loose.spelling,loose.entry,loose.value),{consumedByCommander:!1,consumed:loose.consumed};const exact=resolve(token);if(exact!==void 0){const takesNext=exact.arity==="required"||exact.arity==="optional"&&next!==void 0&&(!isArgvOptionToken(next)||scope.negativeNumbersAreValues&&NEGATIVE_NUMBER_ARGV_TOKEN.test(next));return record(token,exact,exact.negates===!0?!1:takesNext?next:!0),{consumedByCommander:!0,consumed:takesNext?1:0,variadic:exact.variadic===!0}}return token[1]!=="-"?{consumed:0,...scanShortGroup(token,resolve,record)}:{consumedByCommander:scanLongToken(token,resolve,record,scope.includesLooseFlags?record:()=>{}),consumed:0}}function readLooseArgvOccurrence(token,next,resolve){const equals=token.indexOf("="),spelling=equals>1?token.slice(0,equals):token,entry=resolve(spelling);if(entry?.loose===!0)return equals>1?{spelling,entry,value:token.slice(equals+1),consumed:0}:next!==void 0&&!next.startsWith("-")?{spelling,entry,value:next,consumed:1}:{spelling,entry,value:!0,consumed:0};const negated=equals<0&&token.startsWith("--no-")?resolve(`--${token.slice(5)}`):void 0;return negated?.loose===!0&&negated.declared?.kind==="boolean"?{spelling:token,entry:negated,value:!1,consumed:0}:void 0}function scanShortGroup(token,resolve,record){const spelling=token.slice(0,2),entry=token.length>2?resolve(spelling):void 0;return entry===void 0||entry.loose===!0?{consumedByCommander:!1}:entry.arity!=="none"?(record(spelling,entry,token.slice(2)),{consumedByCommander:!0}):(record(spelling,entry,!0),{consumedByCommander:!0,group:`-${token.slice(2)}`})}function scanLongToken(token,resolve,record,recordUnparsed){const equals=token.indexOf("=");if(equals>2){const spelling=token.slice(0,equals),entry=resolve(spelling);return entry!==void 0&&entry.arity!=="none"?(record(spelling,entry,token.slice(equals+1)),!0):(entry?.declared?.kind==="boolean"&&recordUnparsed(spelling,entry,token.slice(equals+1)),!1)}const negated=token.startsWith("--no-")?resolve(`--${token.slice(5)}`):void 0;return negated?.declared?.kind==="boolean"&&recordUnparsed(token,negated,!1),!1}function refuseConflictingArgvOptionSpellings(scopes,definitions,commandPath){const index=indexDeclaredArgvSpellings(definitions),latest=new Map;for(const scope of scopes)scanArgvScope(scope,spelling=>resolveArgvSpelling(scope,index,spelling),(spelling,entry,value)=>{entry.declared!==void 0&&recordArgvSpellingValue(latest,entry.declared,spelling,value,commandPath)})}function recordArgvSpellingValue(latest,declared,spelling,value,commandPath){const{definition,handlerKey,kind}=declared,coerced=kind?coerceLooseOptionValue(value,kind):value,spellings=latest.get(handlerKey)??new Map,conflicting=[...spellings].find(([other,otherValue])=>other!==spelling&&!isDeepStrictEqual(otherValue,coerced));conflicting!==void 0&&refuseConflictingOptionSpellings(definition,handlerKey,[conflicting[0],spelling],commandPath),spellings.set(spelling,coerced),latest.set(handlerKey,spellings)}export{coerceLooseCommandOptionsWithFlagDefinitions,collectExtensionFlagDefinitionsForCommand,collectLooseCommandOptionKeysForDefinitions,collectLoosePositionalArgs,normalizeDirectExtensionCommandOptions,parseLooseCommandOptions,refuseConflictingArgvOptionSpellings,resolveExtensionFlagOptionKey,stripLooseCommandOptionTokens,validateLooseCommandOptionsWithFlagDefinitions};
|
|
2
|
+
//# sourceMappingURL=command-options.js.map
|
|
@@ -14,8 +14,7 @@ import { type CliFlagContract } from "./cli-contracts/flag-contracts.js";
|
|
|
14
14
|
* `capabilities`.
|
|
15
15
|
*/
|
|
16
16
|
export declare const EXTENSION_CAPABILITIES:readonly ["commands","renderers","hooks","schema","importers","search","parser","preflight","services"];
|
|
17
|
-
|
|
18
|
-
export type ExtensionCapability = (typeof EXTENSION_CAPABILITIES)[number];
|
|
17
|
+
export type { ExtensionCapability } from "../core/extensions/extension-types.js";
|
|
19
18
|
/** Canonical extension governance policy modes. */
|
|
20
19
|
export declare const EXTENSION_POLICY_MODES:readonly ["off","warn","enforce"];
|
|
21
20
|
/** Canonical extension registration surfaces governed by policy. */
|
|
@@ -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]="d449d43b-5192-58dc-bdc0-0ec5e8922353")}catch{}})();import{EXTENSION_CAPABILITY_CONTRACT,EXTENSION_CAPABILITY_CONTRACT_VERSION,EXTENSION_CAPABILITY_LEGACY_ALIASES,KNOWN_EXTENSION_CAPABILITIES,KNOWN_EXTENSION_POLICY_MODES,KNOWN_EXTENSION_POLICY_SURFACES,KNOWN_EXTENSION_SANDBOX_PROFILES,KNOWN_EXTENSION_TRUST_MODES}from"../core/extensions/loader.js";import{LIST_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS}from"./cli-contracts/commander-types.js";import{compactFlagAliasContracts,LIST_FILTER_FLAG_CONTRACTS,SEARCH_FLAG_CONTRACTS}from"./cli-contracts/flag-contracts.js";const EXTENSION_CAPABILITIES=KNOWN_EXTENSION_CAPABILITIES,EXTENSION_POLICY_MODES=KNOWN_EXTENSION_POLICY_MODES,EXTENSION_POLICY_SURFACES=KNOWN_EXTENSION_POLICY_SURFACES,EXTENSION_TRUST_MODES=KNOWN_EXTENSION_TRUST_MODES,EXTENSION_SANDBOX_PROFILES=KNOWN_EXTENSION_SANDBOX_PROFILES;function toExtensionFlagDefinition(contract,long,stringOptionKeys,short){const normalizedKey=contract.flag.slice(2).replace(/[-_]([a-z])/gu,(_match,letter)=>letter.toUpperCase()),stringValued=stringOptionKeys.has(normalizedKey);return{long,...short?{short}:{},description:contract.description??`Standard pm ${contract.flag} option.`,...contract.required===!0?{required:!0}:{},...contract.list===!0?{list:!0}:{},...contract.repeatable===!0?{repeatable:!0}:{},value_type:stringValued?"string":"boolean",...stringValued?{value_name:contract.value_name??"value"}:{}}}function toExtensionFlagDefinitions(contracts,stringOptions=[]){const stringOptionKeys=new Set(stringOptions.flatMap(contract=>contract.keys)),definitions=[];for(const contract of compactFlagAliasContracts(contracts.map(entry=>({...entry})))){definitions.push(toExtensionFlagDefinition(contract,contract.flag,stringOptionKeys,contract.short));for(const alias of contract.aliases??[])definitions.push(toExtensionFlagDefinition(contract,alias,stringOptionKeys))}return definitions}const LIST_FILTER_EXTENSION_FLAG_DEFINITIONS=toExtensionFlagDefinitions(LIST_FILTER_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS),SEARCH_EXTENSION_FLAG_DEFINITIONS=toExtensionFlagDefinitions(SEARCH_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS);export{EXTENSION_CAPABILITIES,EXTENSION_CAPABILITY_CONTRACT,EXTENSION_CAPABILITY_CONTRACT_VERSION,EXTENSION_CAPABILITY_LEGACY_ALIASES,EXTENSION_POLICY_MODES,EXTENSION_POLICY_SURFACES,EXTENSION_SANDBOX_PROFILES,EXTENSION_TRUST_MODES,LIST_FILTER_EXTENSION_FLAG_DEFINITIONS,SEARCH_EXTENSION_FLAG_DEFINITIONS,toExtensionFlagDefinitions};
|
|
2
2
|
//# sourceMappingURL=extension-contracts.js.map
|