@unbrained/pm-cli 2026.10.20 → 2026.10.22
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 +142 -77
- package/dist/cli/error-guidance.d.ts +8 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-QMZ73FCW.js → chunk-2B5HAZFK.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-35ISFIPC.js +113 -0
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5LSN7K4N.js +2 -0
- package/dist/cli-bundle/chunks/chunk-7OTYULIJ.js +30 -0
- package/dist/cli-bundle/chunks/{chunk-GHJOMRSF.js → chunk-AOAQDCXX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZA3XXHEE.js → chunk-BAIVTLJM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LS55VKRK.js → chunk-C37RDYZI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YT2Z3JPC.js → chunk-E3JC3WQL.js} +47 -47
- package/dist/cli-bundle/chunks/{chunk-YECCKB4E.js → chunk-GWIGZDRS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YTHI5DTH.js → chunk-HC2DCGFA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +2 -0
- package/dist/cli-bundle/chunks/chunk-J444ZX23.js +126 -0
- package/dist/cli-bundle/chunks/{chunk-VLJLWZBO.js → chunk-LIC5EUQS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KU4Q3MSI.js → chunk-MV3KYY2A.js} +6 -6
- package/dist/cli-bundle/chunks/chunk-O67N62DT.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TZU6U5ZE.js → chunk-PCPOTFJP.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-TNU3XVPC.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-7ZOIZ2AZ.js → chunk-URV4VHQ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YW6SIKYP.js → chunk-UYYTV2TX.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +9 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-U7VGKIYC.js → indexed-receipt-blobs-L3BOTMZN.js} +2 -2
- package/dist/cli-bundle/chunks/mutation-admission-TATOFEXF.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-NNDV6F6I.js → register-list-query-GULR2IYO.js} +5 -5
- package/dist/cli-bundle/chunks/{register-mutation-3GCBSNQS.js → register-mutation-HLSQ4WVW.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-FE3GGA7O.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-XUIKAIZA.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-CLRGA6O7.js → settlement-hook-UVFYSBMU.js} +2 -2
- package/dist/cli-bundle/chunks/stage-QCPZBZRC.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-25L3L2PF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-25NQRZ7J.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-2GFTVXKZ.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HUZAXSIJ.js → chunk-3LWH2RJC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-46HBJC6J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-A52W6GLA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-CB7TSZ7P.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VLSER3XW.js → chunk-CX5FNEFC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LJPUJ2KK.js → chunk-EHPRSWJE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GC4VMLXL.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KKRFSI2N.js → chunk-GVKYTDOH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NI6NS44Q.js → chunk-KM77WU5U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QGDKWULS.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QWKCQ5PW.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SXVJRLLP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E4II2D2B.js → chunk-TMN3RAXZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-F7FD25TG.js → chunk-UQ5JPBY2.js} +11 -11
- package/dist/cli-bundle/focused-chunks/chunk-UUPJ6OZL.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-VYAZND5Q.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-W2CND3BD.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZGEK57KD.js → chunk-XX5JQCLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-H2G6CCGO.js → indexed-receipt-blobs-AAQOKO5B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-TBKR4KRM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-5SNBBT7C.js → settlement-hook-MNCHFCAX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-RM6MJIMT.js +2 -0
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +23 -23
- 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 +58 -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 +7 -7
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/lock/lock-gc.d.ts +12 -5
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.d.ts +33 -0
- package/dist/core/lock/lock-owner.js +2 -0
- package/dist/core/lock/lock.d.ts +11 -22
- package/dist/core/lock/lock.js +4 -3
- package/dist/core/output/output.js +3 -3
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/mcp/server.d.ts +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/agent/command-recovery.d.ts +2 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/context-intent-contracts.d.ts +13 -0
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/contracts.d.ts +1 -1
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core.d.ts +2 -2
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/define.d.ts +15 -16
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/pagination.d.ts +3 -3
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +5 -0
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/session-result.d.ts +39 -0
- package/dist/sdk/read-output/session-result.js +2 -0
- package/dist/sdk/read-output-contracts.d.ts +18 -5
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-session.d.ts +2 -0
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.d.ts +2 -0
- package/dist/sdk/runtime/mutation-admission.js +2 -0
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +6 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +10 -8
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution.d.ts +1 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/workspace.d.ts +3 -1
- package/dist/sdk/workspace.js +8 -5
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +9 -0
- package/docs/ASSURANCE.md +17 -2
- package/docs/COMMANDS.md +17 -3
- package/docs/CONFIGURATION.md +38 -0
- package/docs/CONTEXT_RELEVANCE.md +15 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +56 -3
- package/docs/MCP_OPTION_CONFORMANCE.md +27 -1
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +79 -0
- package/docs/RELATIONSHIP_GRAPH.md +15 -0
- package/docs/RELEASING.md +8 -0
- package/docs/SDK.md +104 -7
- package/docs/TESTING.md +23 -0
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -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-bundle/chunks/chunk-2GGGOD7P.js +0 -30
- package/dist/cli-bundle/chunks/chunk-7NHA5K77.js +0 -126
- package/dist/cli-bundle/chunks/chunk-PNPE2OVJ.js +0 -112
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QETMESEB.js +0 -6
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +0 -2
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-37SU7BZI.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-6IU7BESB.js +0 -65
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +0 -25
- package/dist/cli-bundle/focused-chunks/chunk-AW35RDKA.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-GYHZ7W6O.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-H5Q2HUU6.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-J6EYUGAR.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-KDGUIIRU.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VAYS754X.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VS6VTWTZ.js +0 -8
- package/dist/cli-bundle/focused-chunks/stage-EMTISXR7.js +0 -2
|
@@ -10,6 +10,10 @@ export type { PmReadOutputRecoveryBudget,PmReadOutputRecoveryBudgetInput,} from
|
|
|
10
10
|
export { decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint,} from "./read-output/continuation.js";
|
|
11
11
|
export type { PmReadOutputContinuationFingerprintPolicy } from "./read-output/continuation.js";
|
|
12
12
|
import { type PmReadOutputSessionReceipt,type PmReadOutputSessionState } from "./read-output-session.js";
|
|
13
|
+
import type { PmReadOutputProducerContinuation } from "./context-intent-contracts.js";
|
|
14
|
+
import type { PmReadOutputSessionResult } from "./read-output/session-result.js";
|
|
15
|
+
export type { PmReadOutputSessionResult } from "./read-output/session-result.js";
|
|
16
|
+
export type { PmReadOutputProducerContinuation } from "./context-intent-contracts.js";
|
|
13
17
|
/** Stable output dimensions shared by every read surface. */
|
|
14
18
|
export declare const PM_READ_OUTPUT_DIMENSIONS:readonly ["include","amount","cost","encoding"];
|
|
15
19
|
/** One member of the universal read-output dimension set. */
|
|
@@ -228,16 +232,25 @@ outputBudget:"unbounded";
|
|
|
228
232
|
/** Exact receipt for the bounded omission envelope. */
|
|
229
233
|
read_output:PmReadOutputReceipt;
|
|
230
234
|
}
|
|
231
|
-
|
|
232
|
-
export type PmReadOutputResult<Result> = (Result & {
|
|
235
|
+
type ReadOutputEnvelope<Result> = (Result & {
|
|
233
236
|
read_output?:PmReadOutputReceipt;
|
|
234
237
|
read_session?:PmReadOutputSessionReceipt;
|
|
235
238
|
output_budget_truncation?:PmReadOutputTruncationDisclosure;
|
|
236
239
|
}) | (PmReadOutputBudgetExceeded & {
|
|
237
240
|
read_session?:PmReadOutputSessionReceipt;
|
|
238
241
|
});
|
|
239
|
-
/**
|
|
240
|
-
export type
|
|
242
|
+
/** Read result admitting session reference rows and a discriminated budget omission. */
|
|
243
|
+
export type PmReadOutputResult<Result> = ReadOutputEnvelope<Result | PmReadOutputSessionResult<Result>>;
|
|
244
|
+
/** Preserve first-page results while admitting sparse pages for a possible producer cursor. */
|
|
245
|
+
type ProducerResultFor<Result,Options> = "after" extends keyof Options ? [Options["after"]] extends [undefined] ? Result :Result | PmReadOutputProducerContinuation<Result> :Result;
|
|
246
|
+
/** Distribute over option variants so every possible budget omission and sparse page remains visible. */
|
|
247
|
+
export type PmReadOutputResultFor<Result,Options> = Options extends unknown ? "outputSession" extends keyof Options ? [Options["outputSession"]] extends [undefined] ? ReadOutputEnvelope<ProducerResultFor<Result,Options>> :PmReadOutputResult<ProducerResultFor<Result,Options>> :"outputBudget" extends keyof Options ? ReadOutputEnvelope<ProducerResultFor<Result,Options>> :"outputCursor" extends keyof Options ? ReadOutputEnvelope<ProducerResultFor<Result,Options>> :ProducerResultFor<Result,Options> :never;
|
|
248
|
+
/** Infer possible session values from either spelling accepted by the direct helper. */
|
|
249
|
+
type ReadOutputSessionOption<Options> = ("outputSession" extends keyof Options ? Options["outputSession"] :never) | ("output_session" extends keyof Options ? Options["output_session"] :never);
|
|
250
|
+
/** Keep universal budget omissions while adding references only for possible sessions. */
|
|
251
|
+
type ReadOutputResultForSession<Result,Options> = Options extends unknown ? PmReadOutputResultFor<Result,{
|
|
252
|
+
outputSession:ReadOutputSessionOption<Options>;
|
|
253
|
+
}> :never;
|
|
241
254
|
/** Canonical CLI flags that opt a read invocation into universal output shaping. */
|
|
242
255
|
export declare const PM_READ_OUTPUT_OPTION_FLAGS:readonly string[];
|
|
243
256
|
/** Canonical control that composes the four per-call dimensions across reads. */
|
|
@@ -283,7 +296,7 @@ export declare function resolveReadOutputDimensions(command:string,options:Recor
|
|
|
283
296
|
/** Recompute read and optional session receipts after a final envelope projection. */
|
|
284
297
|
export declare function stabilizeReadOutputReceiptEstimates(result:Record<string,unknown>,options:Record<string,unknown>):Record<string,unknown>;
|
|
285
298
|
/** Apply universal field, row, and token bounds and attach an exact receipt. */
|
|
286
|
-
export declare function applyReadOutputDimensions<Result extends Record<string,unknown>>(command:string,options:
|
|
299
|
+
export declare function applyReadOutputDimensions<Result extends Record<string,unknown>,Options extends Record<string,unknown> = Record<string,unknown>>(command:string,options:Options,result:Result):ReadOutputResultForSession<Result,Options>;
|
|
287
300
|
/** Narrow a universal read result to its budget-omission branch. */
|
|
288
301
|
export declare function isReadOutputBudgetExceeded(result:unknown):result is PmReadOutputBudgetExceeded;
|
|
289
302
|
/** Resolve only the canonical renderer override for shared CLI output code. */
|
|
@@ -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]="d8782989-f417-515e-892a-17ae8ff2b5fa")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS,PM_READ_OUTPUT_SURFACES}from"./read-output/options.js";import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand}from"./read-output/extension.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections,refreshReadOutputDeliveredCounts}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint}from"./read-output/continuation.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as PM_READ_OUTPUT_SURFACES2}from"./read-output/options.js";const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS,LEGACY_FLAGS_BY_COMMAND={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]),BEHAVIOR_PRESERVING_MIGRATION_HINTS=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded --output-budget unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function flagSelector(flag){return flag.slice(2).replaceAll("-","_")}function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command]??{},dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptionsForSurface(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract)),SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase()),extension=resolveExtensionOutputCommand(normalizedCommand);return extension!==void 0?extension.read_output===void 0?void 0:`extension:${extension.command}`:resolveNativeReadOutputSurface(normalizedCommand,options)}function resolveNativeReadOutputSurface(normalizedCommand,options){const root=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===!0||options.target==="catalog"||options.action==="catalog")?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0],normalized=root.startsWith("list-")?"list":root==="ctx"?"context":root;return PM_READ_OUTPUT_SURFACES.includes(normalized)?normalized:void 0}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],HYBRID_READ_MUTATION_KEYS={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>(parseReadOutputSession(value),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value=="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){const encoding=options.outputFormat??options.output_format;if(encoding!==void 0&&encoding!=="json"&&encoding!=="toon")throw new PmCliError("--output-format must be toon or json.",EXIT_CODE.USAGE);if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE);if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==!1))throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE);for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value))throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);return surface?readOutputIncludeModeOptionsForSurface(surface):new Map}function readOutputIncludeModeOptionsForSurface(surface){return new Map((LEGACY_FLAGS_BY_COMMAND[surface]?.include??[]).filter(flag=>!VALUE_BEARING_INCLUDE_ALIASES.has(flag)&&BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0).map(flag=>[flagSelector(flag),optionKey(flag)]))}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual,Object.hasOwn(options,"output_include")&&(options.output_include=residual)}function optionKey(flag){return flag.slice(2).replace(/-([a-z])/gu,(_,character)=>character.toUpperCase())}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).flatMap(entry=>typeof entry=="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(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 resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0)return{source:"canonical",value:canonicalLimit};if(!legacy)return;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0)return{source:"canonical",value:canonicalBudget};if(!legacy)return;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon")return{source:"canonical",value:canonical};if(legacy)return legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)return!explicitLegacyAliases.has(flag);const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance,options){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||isRequestedOption(readOption(options,"--no-truncate"))&&!shouldIgnoreReadOutputLegacyAlias(provenance,"amount","--no-truncate")||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand)??buildSurfaceContract(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)},legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance,options),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result),unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0)throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE);const fullItem=selectors.includes("item"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0)throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE);const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item:itemSelectors.length>0&&(projected.item=projectRecordFields(vocabulary.item,itemSelectors));const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get")return applyGetIncludeProjection(result,selectors);const rows=readOutputRowPaths(result),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount);if(!truncated)return bounded;if(bounded.has_more=!0,bounded.truncated=!0,typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens,previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format),preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate)return withSession}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).some(group=>isRecord(group)&&group.name==="diagnostic_rows"))return result;const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))],diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector=="string"?existingContract.jq_selector:".checks[].details"}}}function projectReadOutputRows(result,resolved,session,cursor,options){let projected={...result};if(resolved.include?.source==="canonical"&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,result,resolved.command,cursor,options);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value),continuationState.cursorContinuesExistingPage&&rebaseCompactedProducerCursor(projected,continuationState.originalItems,continuationState.cursorSource,!0,continuationState.originalItemOffset)),refreshReadOutputDeliveredCounts(projected,continuationSource),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default"||resolved.command==="context"&&resolved.cost.source==="legacy")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]].sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function hasContextIntentBudgetReceipt(result,tokens){return isRecord(result.context_intent)&&result.context_intent.command==="context"&&result.context_intent.token_budget===tokens&&result.context_intent.within_budget===!0}function readOutputBudgetReceiptFields(budget,result={}){return budget?.source==="default"||budget?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,budget.tokens)?{budget_source:budget.source,budget_tokens:budget.tokens}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens)throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE);return boundedOmission}function requiresReadOutputAudit(resolved,options,result){return resolved.command==="context"&&resolved.cost?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,resolved.cost.value)||options.outputRowContract===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options,result))return!1;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"&&resolved.command!=="context"||estimateReadOutputTokens(options.outputRowContract===!1?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);if(retainedRows>=before.rows)return[];const offset=before.baseOffset+retainedRows;return[{path,cursor:encodeReadOutputContinuationCursor({command:resolved.command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint}),retained_rows:retainedRows,remaining_rows:before.totalRows-offset,total_rows:before.totalRows}]}),primary=continuations[0],continuationHint=primary?"; page --output-cursor":"",budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});primary&&!continuationCursorRebased&&(typeof projected.next_cursor!="string"||projected.continuation_kind==="output_cursor")&&(projected.next_cursor=primary.cursor),projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none",projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseCompactedProducerCursor(projected,originalItems,cursorSource,cursorContinuesExistingPage,originalItemOffset){if(typeof cursorSource!="string"||!Array.isArray(projected.items))return!1;const retainedCount=projected.items.length,originalItemCount=originalItems.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=originalItems[retainedCount-1];if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+originalItemOffset+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}function captureReadOutputContinuationState(projected,source,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length,continued=cursor?.path===collection.path;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued?cursor.offset:0,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]})),cursorContinuesExistingPage=typeof projected.next_cursor=="string",originalItemOffset=cursor?.path==="items"?cursor.offset:0;return{collectionsBeforeBudget,originalItems:Array.isArray(source.items)?originalItemOffset>0?source.items.slice(originalItemOffset):source.items:[],originalItemOffset,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource);const continuationCursorRebased=rebaseCompactedProducerCursor(compacted,continuationState.originalItems,continuationState.cursorSource,continuationState.cursorContinuesExistingPage,continuationState.originalItemOffset);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget,projected),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES2 as PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
|
|
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]="46bfc647-3c37-5357-8cd5-96dd3d21d737")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS,PM_READ_OUTPUT_SURFACES}from"./read-output/options.js";import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand}from"./read-output/extension.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections,refreshReadOutputDeliveredCounts}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint}from"./read-output/continuation.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as PM_READ_OUTPUT_SURFACES2}from"./read-output/options.js";const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS,LEGACY_FLAGS_BY_COMMAND={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]),BEHAVIOR_PRESERVING_MIGRATION_HINTS=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded --output-budget unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function flagSelector(flag){return flag.slice(2).replaceAll("-","_")}function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command]??{},dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptionsForSurface(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract)),SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase()),extension=resolveExtensionOutputCommand(normalizedCommand);return extension!==void 0?extension.read_output===void 0?void 0:`extension:${extension.command}`:resolveNativeReadOutputSurface(normalizedCommand,options)}function resolveNativeReadOutputSurface(normalizedCommand,options){const root=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===!0||options.target==="catalog"||options.action==="catalog")?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0],normalized=root.startsWith("list-")?"list":root==="ctx"?"context":root;return PM_READ_OUTPUT_SURFACES.includes(normalized)?normalized:void 0}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],HYBRID_READ_MUTATION_KEYS={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>(parseReadOutputSession(value),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value=="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){const encoding=options.outputFormat??options.output_format;if(encoding!==void 0&&encoding!=="json"&&encoding!=="toon")throw new PmCliError("--output-format must be toon or json.",EXIT_CODE.USAGE);if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE);if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==!1))throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE);for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value))throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);return surface?readOutputIncludeModeOptionsForSurface(surface):new Map}function readOutputIncludeModeOptionsForSurface(surface){return new Map((LEGACY_FLAGS_BY_COMMAND[surface]?.include??[]).filter(flag=>!VALUE_BEARING_INCLUDE_ALIASES.has(flag)&&BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0).map(flag=>[flagSelector(flag),optionKey(flag)]))}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual,Object.hasOwn(options,"output_include")&&(options.output_include=residual)}function optionKey(flag){return flag.slice(2).replace(/-([a-z])/gu,(_,character)=>character.toUpperCase())}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).flatMap(entry=>typeof entry=="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(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 resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0)return{source:"canonical",value:canonicalLimit};if(!legacy)return;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0)return{source:"canonical",value:canonicalBudget};if(!legacy)return;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon")return{source:"canonical",value:canonical};if(legacy)return legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)return!explicitLegacyAliases.has(flag);const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance,options){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||isRequestedOption(readOption(options,"--no-truncate"))&&!shouldIgnoreReadOutputLegacyAlias(provenance,"amount","--no-truncate")||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand)??buildSurfaceContract(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)},legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance,options),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result),unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0)throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE);const fullItem=selectors.includes("item"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0)throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE);const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item:itemSelectors.length>0&&(projected.item=projectRecordFields(vocabulary.item,itemSelectors));const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get")return applyGetIncludeProjection(result,selectors);const rows=readOutputRowPaths(result),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount);if(!truncated)return bounded;if(bounded.has_more=!0,bounded.truncated=!0,typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens,previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format),preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate)return withSession}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).some(group=>isRecord(group)&&group.name==="diagnostic_rows"))return result;const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))],diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector=="string"?existingContract.jq_selector:".checks[].details"}}}function projectReadOutputRows(result,resolved,session,cursor,options){let projected={...result};if(resolved.include?.source==="canonical"&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,result,resolved.command,cursor,options);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value),continuationState.cursorContinuesExistingPage&&rebaseCompactedProducerCursor(projected,continuationState.originalItems,continuationState.cursorSource,!0,continuationState.originalItemOffset)),refreshReadOutputDeliveredCounts(projected,continuationSource),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default"||resolved.command==="context"&&resolved.cost.source==="legacy")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]].sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function hasContextIntentBudgetReceipt(result,tokens){return isRecord(result.context_intent)&&result.context_intent.command==="context"&&result.context_intent.token_budget===tokens&&result.context_intent.within_budget===!0}function readOutputBudgetReceiptFields(budget,result={}){return budget?.source==="default"||budget?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,budget.tokens)?{budget_source:budget.source,budget_tokens:budget.tokens}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens)throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE);return boundedOmission}function requiresReadOutputAudit(resolved,options,result){return resolved.command==="context"&&resolved.cost?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,resolved.cost.value)||options.outputRowContract===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options,result))return!1;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"&&resolved.command!=="context"||estimateReadOutputTokens(options.outputRowContract===!1?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);if(retainedRows>=before.rows)return[];const offset=before.baseOffset+retainedRows;return[{path,cursor:encodeReadOutputContinuationCursor({command:resolved.command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint}),retained_rows:retainedRows,remaining_rows:before.totalRows-offset,total_rows:before.totalRows}]}),primary=continuations[0],continuationHint=primary?"; page --output-cursor":"",budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});primary&&!continuationCursorRebased&&(typeof projected.next_cursor!="string"||projected.continuation_kind==="output_cursor")&&(projected.next_cursor=primary.cursor),projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none",projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseCompactedProducerCursor(projected,originalItems,cursorSource,cursorContinuesExistingPage,originalItemOffset){if(typeof cursorSource!="string"||!Array.isArray(projected.items))return!1;const retainedCount=projected.items.length,originalItemCount=originalItems.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=originalItems[retainedCount-1];if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+originalItemOffset+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}function captureReadOutputContinuationState(projected,source,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length,continued=cursor?.path===collection.path;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued?cursor.offset:0,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]})),cursorContinuesExistingPage=typeof projected.next_cursor=="string",originalItemOffset=cursor?.path==="items"?cursor.offset:0;return{collectionsBeforeBudget,originalItems:Array.isArray(source.items)?originalItemOffset>0?source.items.slice(originalItemOffset):source.items:[],originalItemOffset,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource);const continuationCursorRebased=rebaseCompactedProducerCursor(compacted,continuationState.originalItems,continuationState.cursorSource,continuationState.cursorContinuesExistingPage,continuationState.originalItemOffset);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget,projected),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES2 as PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
|
|
2
2
|
//# sourceMappingURL=read-output-contracts.js.map
|
|
@@ -18,6 +18,8 @@ id:string;
|
|
|
18
18
|
/** Resolvable reference to the session fact already in caller context. */
|
|
19
19
|
context_ref:string;
|
|
20
20
|
}
|
|
21
|
+
/** Narrow a delivered reference before accessing the original row's fields. */
|
|
22
|
+
export declare function isReadOutputSessionReference(value:unknown):value is PmReadOutputSessionReference;
|
|
21
23
|
/** Receipt proving cross-call suppression and budget accounting. */
|
|
22
24
|
export interface PmReadOutputSessionReceipt {
|
|
23
25
|
/** Session-receipt schema version. */
|
|
@@ -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]="37a4f41e-7c66-5b8f-8c10-8aef5b75a55e")}catch{}})();import{estimateReadOutputTokens}from"./read-output-budget.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{mapReadOutputRows,readOutputRowCollections}from"./read-output-rows.js";function isReadOutputSessionReference(value){return typeof value=="object"&&value!==null&&"id"in value&&typeof value.id=="string"&&"context_ref"in value&&typeof value.context_ref=="string"&&value.context_ref.startsWith("session:")&&value.context_ref.endsWith(`:${value.id}`)}const PM_READ_OUTPUT_SESSION_MIN_TOKENS=256,PM_READ_OUTPUT_SESSION_MAX_SEEN_ITEM_IDS=1e4,SESSION_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,ITEM_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,SESSION_KEYS=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),SESSION_FIELD_VALIDATIONS=[{valid:state=>state.version===1,reason:"version must equal 1."},{valid:state=>typeof state.id=="string"&&SESSION_ID_PATTERN.test(state.id),reason:"id must be 1-64 portable identifier characters."},{valid:state=>Number.isSafeInteger(state.token_budget)&&state.token_budget>=PM_READ_OUTPUT_SESSION_MIN_TOKENS,reason:`token_budget must be a safe integer of at least ${PM_READ_OUTPUT_SESSION_MIN_TOKENS}.`},{valid:state=>Number.isSafeInteger(state.spent_tokens)&&state.spent_tokens>=0&&state.spent_tokens<=state.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:state=>Array.isArray(state.seen_item_ids)&&state.seen_item_ids.length<=PM_READ_OUTPUT_SESSION_MAX_SEEN_ITEM_IDS&&state.seen_item_ids.every(id=>typeof id=="string"&&ITEM_ID_PATTERN.test(id)),reason:`seen_item_ids must contain at most ${PM_READ_OUTPUT_SESSION_MAX_SEEN_ITEM_IDS} portable item identifiers.`}];function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function invalidSession(reason){throw new PmCliError(`--output-session ${reason}`,EXIT_CODE.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function parseReadOutputSession(value){if(value===void 0)return;let parsed=value;if(typeof value=="string")try{parsed=JSON.parse(value)}catch{invalidSession("must be a valid JSON object.")}isRecord(parsed)||invalidSession("must be a JSON object.");const unknownKeys=Object.keys(parsed).filter(key=>!SESSION_KEYS.has(key));unknownKeys.length>0&&invalidSession(`contains unknown field "${unknownKeys.sort()[0]}".`);const invalidField=SESSION_FIELD_VALIDATIONS.find(validation=>!validation.valid(parsed));invalidField!==void 0&&invalidSession(invalidField.reason);const seenItemIds=[...new Set(parsed.seen_item_ids)].sort();return{version:1,id:parsed.id,token_budget:parsed.token_budget,spent_tokens:parsed.spent_tokens,seen_item_ids:seenItemIds}}function itemIdFromRow(row){if(isRecord(row))return typeof row.id=="string"?row.id:typeof row.item_id=="string"?row.item_id:isRecord(row.item)&&typeof row.item.id=="string"?row.item.id:void 0}function summarizeReadOutputSessionRows(result){const deliveredIds=new Set;let suppressedRepeatCount=0;const collections=readOutputRowCollections(result),declaredPaths=new Set(collections.map(({path})=>path)),additionalCollections=Object.entries(result).flatMap(([path,value])=>Array.isArray(value)&&!declaredPaths.has(path)?[{path,value}]:[]);for(const collection of[...collections,...additionalCollections]){const rows=Array.isArray(collection.value)?collection.value:Object.values(collection.value);for(const row of rows){if(!isRecord(row))continue;if(typeof row.context_ref=="string"){suppressedRepeatCount+=1;continue}const itemId=itemIdFromRow(row);itemId!==void 0&&ITEM_ID_PATTERN.test(itemId)&&deliveredIds.add(itemId)}}return{deliveredIds,suppressedRepeatCount}}function applyReadOutputSessionReferences(result,state){const seen=new Set(state.seen_item_ids);return mapReadOutputRows(result,row=>{const itemId=itemIdFromRow(row);return itemId!==void 0&&seen.has(itemId)?{id:itemId,context_ref:`session:${state.id}:${itemId}`}:row})}function attachReadOutputSessionReceipt(result,state,format){const{deliveredIds,suppressedRepeatCount}=summarizeReadOutputSessionRows(result),alreadySeen=new Set(state.seen_item_ids),newlySeen=[...deliveredIds].filter(id=>!alreadySeen.has(id)).sort(),retainedNewIds=newlySeen.slice(0,PM_READ_OUTPUT_SESSION_MAX_SEEN_ITEM_IDS-state.seen_item_ids.length),nextSeen=[...state.seen_item_ids,...retainedNewIds].sort(),seenItemOverflowCount=newlySeen.length-retainedNewIds.length,receipt={contract_version:1,id:state.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:state.token_budget,spent_before_tokens:state.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:state.spent_tokens,remaining_tokens:state.token_budget-state.spent_tokens,exhausted:!1,seen_before_count:state.seen_item_ids.length,new_item_count:deliveredIds.size,...seenItemOverflowCount===0?{}:{seen_item_overflow_count:seenItemOverflowCount},suppressed_repeat_count:suppressedRepeatCount,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --brief",next_state:{version:1,id:state.id,token_budget:state.token_budget,spent_tokens:state.spent_tokens,seen_item_ids:nextSeen}},withReceipt={...result,read_session:receipt},applyEstimate=estimate2=>{receipt.spent_this_call_tokens=estimate2,receipt.charged_this_call_tokens=Math.min(state.token_budget-state.spent_tokens,estimate2),receipt.spent_total_tokens=Math.min(state.token_budget,state.spent_tokens+receipt.charged_this_call_tokens),receipt.remaining_tokens=Math.max(0,state.token_budget-receipt.spent_total_tokens),receipt.exhausted=receipt.remaining_tokens<PM_READ_OUTPUT_SESSION_MIN_TOKENS,receipt.next_state.spent_tokens=receipt.spent_total_tokens};let estimate=0,highestMeasuredEstimate=0;for(let iteration=0;iteration<8;iteration+=1){applyEstimate(estimate);const measured=estimateReadOutputTokens(withReceipt,format);if(measured===estimate)return withReceipt;highestMeasuredEstimate=Math.max(highestMeasuredEstimate,measured),estimate=measured}return applyEstimate(highestMeasuredEstimate),withReceipt}function readOutputSessionRemainingTokens(state){return Math.max(0,state.token_budget-state.spent_tokens)}export{PM_READ_OUTPUT_SESSION_MAX_SEEN_ITEM_IDS,PM_READ_OUTPUT_SESSION_MIN_TOKENS,applyReadOutputSessionReferences,attachReadOutputSessionReceipt,isReadOutputSessionReference,parseReadOutputSession,readOutputSessionRemainingTokens};
|
|
2
2
|
//# sourceMappingURL=read-output-session.js.map
|
|
@@ -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]="3b494263-6359-57e9-8f34-b0bdcdeda93f")}catch{}})();import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart}from"./pagination.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET=1200,RELATIONSHIP_CONTEXT_ROLE_PRIORITY=["prerequisite","dependent","ancestor","descendant","provenance","related"],tokenEncoder=new TextEncoder;function positiveInteger(value,fallback,field){const resolved=value??fallback;if(!Number.isInteger(resolved)||resolved<1)throw new TypeError(`Relationship context ${field} must be positive`);return resolved}function estimateTokens(value){return Math.max(1,Math.ceil(tokenEncoder.encode(JSON.stringify(value)).byteLength/4))}function explainDirectEdge(edge,node,registry){const definition=registry.resolve(edge.kind);if(definition?.ordering){const before=(definition.precedence??"source_before_target")==="source_before_target"?edge.source:edge.target;return node===before?"prerequisite":"dependent"}if(definition?.hierarchy){const parent=definition.hierarchyDirection==="source_parent"?edge.source:edge.target;return node===parent?"ancestor":"descendant"}return edge.kind==="discovered_from"||edge.kind==="incident_from"?"provenance":"related"}function directReasons(rootEdges,root,node,registry){const reasons=rootEdges.filter(edge=>edge.source===root&&edge.target===node||edge.target===root&&edge.source===node).map(edge=>explainDirectEdge(edge,node,registry));return[...new Set(reasons)].sort()}function primaryRole(roles){return RELATIONSHIP_CONTEXT_ROLE_PRIORITY.find(role=>roles.includes(role))}function discoverNodes(graph,root,registry,options){const direction=options.direction??"both",maxDepth=options.maxDepth??3;if(!Number.isInteger(maxDepth)||maxDepth<0)throw new TypeError("Relationship context maxDepth must be non-negative");const seen=new Set([root]),queue=[{id:root,distance:0}],rows=[];let inspectedEdges=0,depthTruncated=!1;for(let index=0;index<queue.length;index+=1){options.signal?.throwIfAborted();const current=queue[index];if(current.distance>=maxDepth&&depthTruncated)continue;const adjacent=graph.neighborEdges(current.id,{direction,kinds:options.kinds,signal:options.signal});if(inspectedEdges+=adjacent.meta.inspectedEdges,current.distance>=maxDepth){adjacent.value.some(row=>!seen.has(row.id))&&(depthTruncated=!0);continue}for(const{id,edge}of adjacent.value){if(seen.has(id))continue;seen.add(id);const row={id,distance:current.distance+1,via:current.id,role:explainDirectEdge(edge,id,registry)};rows.push(row),queue.push(row)}}return{rows,visitedNodes:queue.length,inspectedEdges,depthTruncated}}function summarizeDirectEdges(graph,root,registry,options){const directEdges={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},rows=graph.neighborEdges(root,{direction:options.direction??"both",kinds:options.kinds,signal:options.signal}).value;for(const{id,edge}of rows)directEdges[explainDirectEdge(edge,id,registry)]+=1;return{directEdges,directTotal:rows.length,rootEdges:rows.map(({edge})=>edge)}}function orderContextNodes(rows,rootEdges,rootId,registry){const requiredIds=new Set;for(const edge of rootEdges){const id=edge.source===rootId?edge.target:edge.source,role=explainDirectEdge(edge,id,registry);(role==="prerequisite"||role==="ancestor")&&requiredIds.add(id)}return[...rows].sort((left,right)=>Number(requiredIds.has(right.id))-Number(requiredIds.has(left.id))||left.distance-right.distance||left.id.localeCompare(right.id))}function projectContextNode(candidate,params){const direct=candidate.distance===1?directReasons(params.rootEdges,params.rootId,candidate.id,params.registry):[];return{...params.details.get(candidate.id)??{id:candidate.id},distance:candidate.distance,role:direct.length>0?primaryRole(direct):candidate.role,via:candidate.via,reasons:direct.length>0?direct:[`${candidate.role} via ${candidate.via} (depth ${candidate.distance})`]}}function selectContextNodes(params){const nodes=[];let usedTokens=params.initialTokens,reservedTokens=0;for(const candidate of params.candidates){if(nodes.length>=params.nodeLimit)break;const node=projectContextNode(candidate,params),cost=estimateTokens(node);if(usedTokens+cost>params.tokenBudget)break;const edgeCost=params.rootEdges.filter(edge=>edge.source===candidate.id||edge.target===candidate.id).reduce((sum,edge)=>sum+estimateTokens(edge),0);if(usedTokens+reservedTokens+cost+edgeCost>params.tokenBudget){if(nodes.length>0)break}else reservedTokens+=edgeCost;nodes.push(node),usedTokens+=cost}if(params.candidates.length>0&&nodes.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes,usedTokens}}function selectContextEdges(params){const kinds=params.options.kinds?new Set(params.options.kinds.map(kind=>params.registry.require(kind).kind)):void 0,candidates=params.graph.edges().filter(edge=>{if(!params.included.has(edge.source)||!params.included.has(edge.target))return!1;if(kinds===void 0||kinds.has(edge.kind))return!0;const inverse=params.registry.resolve(edge.kind)?.inverse;return inverse!==void 0&&kinds.has(inverse)}).sort((left,right)=>+(right.source===params.rootId||right.target===params.rootId)-+(left.source===params.rootId||left.target===params.rootId)),edges=[];let usedTokens=params.initialTokens;for(const edge of candidates){if(edges.length>=params.edgeLimit)break;const cost=estimateTokens(edge);usedTokens+cost>params.tokenBudget||(edges.push(edge),usedTokens+=cost)}return{edges,usedTokens,candidateCount:candidates.length}}function buildRelationshipContext(graph,rootId,details,options={}){if(!graph.nodes().includes(rootId))throw new TypeError(`Relationship node not found: ${rootId}`);const nodeLimit=positiveInteger(options.nodeLimit,20,"nodeLimit"),edgeLimit=positiveInteger(options.edgeLimit,40,"edgeLimit"),tokenBudget=positiveInteger(options.tokenBudget,DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,"tokenBudget"),registry=options.registry??createRelationshipKindRegistry(),byId=new Map(details.map(detail=>[detail.id,detail])),rootDetails=byId.get(rootId)??{id:rootId},{evidence:rootEvidence=[],...root}=rootDetails,evidence=[...rootEvidence],discovery=discoverNodes(graph,rootId,registry,options),{rootEdges,...directSummary}=summarizeDirectEdges(graph,rootId,registry,options),orderedRows=orderContextNodes(discovery.rows,rootEdges,rootId,registry),fingerprint=createQueryFingerprint("relationship-context",{rootId,direction:options.direction??"both",kinds:[...options.kinds??[]].sort(),maxDepth:options.maxDepth??3,ordering:"required-root-evidence-first-v1"}),pageStart=resolveQueryCursorStart(orderedRows,options.cursor,fingerprint,({id})=>id,"--cursor"),candidates=orderedRows.slice(pageStart),initialTokens=estimateTokens(root)+estimateTokens(evidence);if(initialTokens>tokenBudget)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");const nodeSelection=selectContextNodes({candidates,details:byId,rootEdges,rootId,registry,nodeLimit,tokenBudget,initialTokens}),{nodes}=nodeSelection,included=new Set([rootId,...nodes.map(({id})=>id)]),edgeSelection=selectContextEdges({graph,rootId,included,options,registry,edgeLimit,tokenBudget,initialTokens:nodeSelection.usedTokens}),{edges,usedTokens}=edgeSelection,consumed=pageStart+nodes.length,hasMoreNodes=consumed<orderedRows.length,lastNode=nodes.at(-1),omittedEdges=edgeSelection.candidateCount-edges.length,truncated=discovery.depthTruncated||hasMoreNodes||omittedEdges>0,summary={rootId,...root.status===void 0?{}:{rootStatus:root.status},...directSummary,discoveredNodes:orderedRows.length,returnedNodes:nodes.length,returnedEdges:edges.length,omittedNodes:orderedRows.length-consumed,omittedEdges,evidenceCount:evidence.length,hasMore:hasMoreNodes};return{root,summary,nodes,edges,evidence,meta:{exact:!0,truncated,completeness:truncated?"truncated":"complete",nodeLimit,edgeLimit,tokenBudget,usedTokens,visitedNodes:discovery.visitedNodes,inspectedEdges:discovery.inspectedEdges,omittedNodes:orderedRows.length-consumed,omittedEdges,...hasMoreNodes&&lastNode?{nextCursor:encodeQueryCursor(fingerprint,lastNode.id,consumed-1)}:{}}}}export{DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,buildRelationshipContext};
|
|
2
2
|
//# sourceMappingURL=relationship-context.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Validate only native create/update clients; MCP retains its declared transport admission. */
|
|
2
|
+
export declare function assertNativeMutationOptions(action:"create" | "update",args:Record<string,unknown>,options:Record<string,unknown>,pmRoot:string | undefined,hoistedKeys:readonly string[]):Promise<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]="d19ff816-7570-5e8a-a4de-ad2ca48f0df0")}catch{}})();import{readRuntimeFieldOptionValue}from"../../core/schema/runtime-field-values.js";import{resolveRuntimeFieldRegistry,runtimeFieldOptionTarget}from"../../core/schema/runtime-schema.js";import{readSettings}from"../../core/store/settings.js";import{resolvePmRoot}from"../../core/store/paths.js";import{PmCliError}from"../../core/shared/errors.js";import{levenshteinDistanceWithinLimit}from"../../core/shared/levenshtein.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"../cli-contracts/commander-mutation-options.js";import{CREATE_FLAG_CONTRACTS,UPDATE_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{isMcpMutationTransportInput,isRuntimeRecord}from"../runtime-input.js";function refuseKey(action,key,allowed,misplaced=!1){const suggestion=[...allowed].map(candidate=>({candidate,distance:levenshteinDistanceWithinLimit(key,candidate,3)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0]?.candidate,correction=misplaced?`Put mutation fields under options (options.${key}).`:suggestion?`Did you mean "${suggestion}"?`:"Use the declared command options or the field option for registered item fields.";throw new PmCliError(`Unknown ${action} ${misplaced?"argument":"option"} "${key}". ${correction} No changes were made.`,2,{code:"invalid_argument_value",reason:"unknown_mutation_option",changed:!1,field:key,required:correction,nextSteps:[correction]})}async function assertNativeMutationOptions(action,args,options,pmRoot,hoistedKeys){if(isMcpMutationTransportInput(args))return;const contracts=action==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,flagKeys=(action==="create"?CREATE_FLAG_CONTRACTS:UPDATE_FLAG_CONTRACTS).map(({flag})=>flag.slice(2).replace(/-([a-z])/gu,(_match,letter)=>letter.toUpperCase())),allowed=new Set([...contracts.flatMap(contract=>[contract.target,...contract.keys]),...flagKeys]),outputKeys=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];for(const key of["author","message","force","fullChangedFields","idOnly",...outputKeys])allowed.add(key);const topLevel=new Set(["action","options","path","cwd","author","force","noExtensions","no_extensions","fullChangedFields","idOnly",...outputKeys,...hoistedKeys,...action==="update"?["id"]:[]]);for(const key of Object.keys(args))topLevel.has(key)||refuseKey(action,key,allowed,allowed.has(key));const rawOptions=args.options;if(rawOptions!==void 0&&!isRuntimeRecord(rawOptions))throw new PmCliError("Mutation options must be an object. No changes were made.",2,{code:"invalid_argument_value",changed:!1});const unknown=[...new Set([...Object.keys(rawOptions??{}),...Object.keys(options)])].filter(key=>!allowed.has(key));if(unknown.length===0)return;const fields=resolveRuntimeFieldRegistry((await readSettings(resolvePmRoot(process.cwd(),pmRoot))).schema).command_to_fields.get(action)??[];for(const field of fields)allowed.add(runtimeFieldOptionTarget(field));for(const key of unknown)fields.some(field=>readRuntimeFieldOptionValue({[key]:!0},field)===!0)||refuseKey(action,key,allowed)}export{assertNativeMutationOptions};
|
|
2
|
+
//# sourceMappingURL=mutation-admission.js.map
|
|
@@ -23,6 +23,8 @@ export declare function parseRuntimeInteger(value:unknown,label:string):number |
|
|
|
23
23
|
export declare function resolveRuntimeLimit(args:Record<string,unknown>,options:Record<string,unknown>):number | string | undefined;
|
|
24
24
|
/** Fixed SDK-runtime global options derived from one untyped action payload. */
|
|
25
25
|
export declare function actionGlobalOptions(args:Record<string,unknown>):GlobalOptions;
|
|
26
|
+
/** Supported top-level aliases, shared with native mutation admission. */
|
|
27
|
+
export declare const HOISTED_ACTION_OPTION_KEYS:Readonly<Record<string,readonly string[]>>;
|
|
26
28
|
/** Reconcile MCP array/scalar option spellings with CLI flag expectations. */
|
|
27
29
|
export declare function normalizeMcpOptionsArrays(options:Record<string,unknown>,action?:string):Record<string,unknown>;
|
|
28
30
|
/** Merge hoisted top-level action arguments and author aliases into options. */
|
|
@@ -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]="0f604cc2-c8cd-5c15-8fec-2243f64ef7d2")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{normalizeListOptions,normalizeUpdateOptions}from"./cli-contracts/registration-helpers.js";import{UPDATE_COMMANDER_STRING_OPTION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";import{normalizeBulkIdsValue}from"../core/io/bulk-ids-input.js";import{overlayMutationStdinTokenPolicy,preserveMutationStdinTokenLiterals,transferMutationStdinTokenPolicy}from"../core/item/parse.js";const MCP_MUTATION_TRANSPORT=Symbol("pm.mcp-mutation-transport"),WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function markMcpMutationTransportInput(input){return Object.defineProperty(input,MCP_MUTATION_TRANSPORT,{value:!0,enumerable:!0}),input}function isMcpMutationTransportInput(input){return MCP_MUTATION_TRANSPORT in input}function preserveTransportLiteralOptions(source,options){return isMcpMutationTransportInput(source)?preserveMutationStdinTokenLiterals(options):transferMutationStdinTokenPolicy(source,options)}function mutationOptionsWithOverrides(source,overrides,omittedKeys=[]){const options=transferMutationStdinTokenPolicy(source,{...source,...overrides});for(const key of omittedKeys)Reflect.deleteProperty(options,key);return options}function readRuntimeString(args,key){const value=args[key];return typeof value=="string"&&value.trim().length>0?value:void 0}function readRuntimeScalarString(args,key){const value=args[key];return typeof value=="string"?value.trim().length>0?value:void 0:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function readRuntimeScalarStringAllowBlank(args,key){const value=args[key];return typeof value=="string"?value:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function isRuntimeRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function parseRuntimeInteger(value,label){if(typeof value=="number"){if(!Number.isInteger(value))throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE);return value}if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(!Number.isInteger(parsed))throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE);return parsed}}function resolveRuntimeLimit(args,options){return typeof args.limit=="number"&&Number.isFinite(args.limit)?args.limit:typeof options.limit=="number"&&Number.isFinite(options.limit)?options.limit:readRuntimeString(args,"limit")??readRuntimeString(options,"limit")}function actionGlobalOptions(args){const outputFormat=readRuntimeString(args,"outputFormat");return{json:!0,quiet:!0,author:readRuntimeString(args,"author"),path:readRuntimeString(args,"path"),noExtensions:args.noExtensions===!0||args.no_extensions===!0,noPager:!0,outputInclude:readRuntimeString(args,"outputInclude"),outputLimit:readRuntimeScalarString(args,"outputLimit"),outputBudget:readRuntimeScalarString(args,"outputBudget"),outputSession:readRuntimeString(args,"outputSession"),outputCursor:readRuntimeString(args,"outputCursor"),outputFormat:outputFormat==="json"||outputFormat==="toon"?outputFormat:void 0}}const ARRAY_TO_CSV_FIELDS=new Set(["tags","blockedBy","blocked_by","skills","fields"]),SCALAR_TO_ARRAY_FIELDS=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),ANNOTATION_SCALAR_TO_ARRAY_FIELDS=new Set([...SCALAR_TO_ARRAY_FIELDS].filter(field=>field!=="file")),ARRAY_ADD_REMOVE_ACTIONS=new Set(["files","files-discover","docs","test","test-all"]),SCALAR_ANNOTATION_SOURCE_ACTIONS=new Set(["comments","notes","learnings"]);function assertMcpAnnotationFileUnavailable(action,options){if(!(!SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)||!Object.prototype.hasOwnProperty.call(options,"file")))throw new PmCliError(`MCP ${action} does not accept options.file. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}const LIFECYCLE_AUTHOR_ALIAS_ACTIONS=new Set(["claim","release","start-task","pause-task","close-task"]),HOISTED_ACTION_OPTION_KEYS={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},UNIVERSAL_READ_OUTPUT_OPTION_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function normalizeMcpOptionsArrays(options,action=""){const result={},promoteAddRemove=ARRAY_ADD_REMOVE_ACTIONS.has(action),preserveStandaloneNote=action==="files"||action==="files-discover"||action==="docs",scalarToArrayFields=SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)?ANNOTATION_SCALAR_TO_ARRAY_FIELDS:SCALAR_TO_ARRAY_FIELDS;for(const[key,value]of Object.entries(options)){if(Array.isArray(value)&&ARRAY_TO_CSV_FIELDS.has(key)){result[key]=value.join(",");continue}if(key==="note"&&preserveStandaloneNote){result[key]=value;continue}if(typeof value=="string"&&scalarToArrayFields.has(key)){result[key]=[value];continue}if(typeof value=="string"&&promoteAddRemove&&(key==="add"||key==="remove")){result[key]=[value];continue}result[key]=value}return Object.assign(result,Object.fromEntries(Object.getOwnPropertySymbols(options).map(symbol=>[symbol,Reflect.get(options,symbol)]))),result}function resolveMcpActionAuthor(args,options,action){const author=readRuntimeString(args,"author");return author!==void 0?author:action!==void 0&&LIFECYCLE_AUTHOR_ALIAS_ACTIONS.has(action)?readRuntimeString(args,"assignee")??readRuntimeString(options,"assignee"):void 0}function withResolvedAuthor(options,author){return author!==void 0&&options.author===void 0?{...options,author}:options}function optionsWithAuthor(args,action){const sourceOptions=isRuntimeRecord(args.options)?args.options:void 0,baseOptions=asRecordClone(args.options),hoistedTopLevel={},hoistKey=key=>{baseOptions[key]!==void 0||args[key]===void 0||(hoistedTopLevel[key]=args[key])};for(const key of HOISTED_ACTION_OPTION_KEYS[action??""]??[])hoistKey(key);for(const key of UNIVERSAL_READ_OUTPUT_OPTION_KEYS)hoistKey(key);action!==void 0&&isMcpMutationTransportInput(args)&&assertMcpAnnotationFileUnavailable(action,baseOptions);const options=normalizeMcpOptionsArrays({...hoistedTopLevel,...baseOptions},action);if(action==="history-attest"&&isMcpMutationTransportInput(args)&&(options.output!==void 0||typeof options.verify=="string"))throw new PmCliError("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",EXIT_CODE.USAGE);const stdinPolicySource=isMcpMutationTransportInput(args)?args:sourceOptions??args;return preserveTransportLiteralOptions(stdinPolicySource,withResolvedAuthor(options,resolveMcpActionAuthor(args,options,action)))}function withAddNoteOption(options){if(options.addNote===void 0)return options;const next={...options};return next.note===void 0&&typeof next.addNote=="string"&&(next.note=next.addNote),delete next.addNote,next}function withFilesDiscoveryOptions(options){const next={...options};return next.discoveryNote!==void 0&&next.note===void 0&&typeof next.discoveryNote=="string"&&(next.note=next.discoveryNote),delete next.discover,delete next.discoveryNote,next}function normalizeActionName(value){const chunks=[];let lastWasSeparator=!0;for(const character of value.trim().toLowerCase()){if(character>="a"&&character<="z"||character>="0"&&character<="9"){chunks.push(character),lastWasSeparator=!1;continue}lastWasSeparator||(chunks.push("-"),lastWasSeparator=!0)}return chunks.at(-1)==="-"&&chunks.pop(),chunks.join("")}function shouldInvalidateWorkspaceContractsCacheAfterAction(action){return!WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS.has(normalizeActionName(action))}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function readRuntimeStringArray(value){return Array.isArray(value)?value.map(entry=>String(entry)).filter(entry=>entry.length>0):[]}function extensionOptionsFromArgs(args,options){const reserved=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),passthrough={};for(const[key,value]of Object.entries(args))reserved.has(key)||(passthrough[key]=value);const normalizedOptions={...passthrough,...options};return delete normalizedOptions.args,normalizedOptions}function withMutationCompaction(args,options){const runnerOptions=preserveTransportLiteralOptions(options??{},{...options});return{changedFields:args.fullChangedFields===!0?"full":"compact",idOnly:args.idOnly===!0,runnerOptions}}function mutationListOptions(options){return{type:readRuntimeScalarString(options,"filterType"),tag:readRuntimeScalarString(options,"filterTag"),priority:readRuntimeScalarString(options,"filterPriority"),deadlineBefore:readRuntimeScalarString(options,"filterDeadlineBefore"),deadlineAfter:readRuntimeScalarString(options,"filterDeadlineAfter"),updatedAfter:readRuntimeScalarString(options,"filterUpdatedAfter"),updatedBefore:readRuntimeScalarString(options,"filterUpdatedBefore"),createdAfter:readRuntimeScalarString(options,"filterCreatedAfter"),createdBefore:readRuntimeScalarString(options,"filterCreatedBefore"),ids:normalizeBulkIdsValue(options.ids),assignee:readRuntimeScalarString(options,"filterAssignee"),assigneeFilter:readRuntimeScalarString(options,"filterAssigneeFilter")??readRuntimeScalarString(options,"filterAssignee_filter"),parent:readRuntimeScalarString(options,"filterParent"),sprint:readRuntimeScalarString(options,"filterSprint"),release:readRuntimeScalarString(options,"filterRelease"),limit:readRuntimeScalarString(options,"limit"),offset:readRuntimeScalarString(options,"offset")}}function readGraphIdListOption(value){if(typeof value=="string"&&value.trim().length>0)return value;if(Array.isArray(value))return readRuntimeStringArray(value)}function readGraphBoundOption(value){if(typeof value=="number"&&Number.isFinite(value)||typeof value=="string"&&value.trim().length>0)return value}function graphOptionsFromFlat(options){const kind=readGraphIdListOption(options.kind),exemptIsolate=readGraphIdListOption(options.exemptIsolate),exemptIsolateType=readGraphIdListOption(options.exemptIsolateType);return{...kind===void 0?{}:{kind},maxDepth:readGraphBoundOption(options.maxDepth),limit:readGraphBoundOption(options.limit),after:readRuntimeString(options,"after"),direction:readRuntimeString(options,"direction"),maxPaths:readGraphBoundOption(options.maxPaths),sample:readGraphBoundOption(options.sample),...exemptIsolate===void 0?{}:{exemptIsolate},...exemptIsolateType===void 0?{}:{exemptIsolateType},saveBaseline:options.saveBaseline===!0,rebuild:options.rebuild===!0,clear:options.clear===!0,summary:options.summary===!0,...options.full===!0?{full:!0}:{}}}function normalizeBulkMutationListOptions(options){const normalized=normalizeListOptions(options);return options.ids!==void 0&&(normalized.ids=normalizeBulkIdsValue(options.ids)),normalized}function closeManyOptionsFromFlat(options){return{status:readRuntimeString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),reason:readRuntimeString(options,"reason"),resolution:readRuntimeString(options,"resolution"),expectedResult:readRuntimeString(options,"expectedResult")??readRuntimeString(options,"expected_result")??readRuntimeString(options,"expected"),actualResult:readRuntimeString(options,"actualResult")??readRuntimeString(options,"actual_result")??readRuntimeString(options,"actual"),validateClose:readRuntimeString(options,"validateClose")??readRuntimeString(options,"validate_close"),author:readRuntimeString(options,"author"),message:readRuntimeString(options,"message"),force:options.force===!0?!0:void 0,dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}const UPDATE_MANY_FLAT_CONTROL_KEYS=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function updateManyUpdateOptionsFromFlat(options){const update={};for(const[key,value]of Object.entries(options))UPDATE_MANY_FLAT_CONTROL_KEYS.has(key)||(update[key]=value);return normalizeMcpUpdateOptions(update)}function normalizeMcpUpdateOptions(options){const normalizedInput=normalizeMcpOptionsArrays(options,"update-many");for(const contract of UPDATE_COMMANDER_STRING_OPTION_CONTRACTS)for(const key of contract.keys){const value=normalizedInput[key];typeof value=="number"&&Number.isFinite(value)&&(normalizedInput[key]=String(value))}return normalizeUpdateOptions(normalizedInput)}function updateManyOptionsFromFlat(options){if(isRuntimeRecord(options.list)||isRuntimeRecord(options.update)){const updateSource=isRuntimeRecord(options.update)?options.update:updateManyUpdateOptionsFromFlat(options),normalizedUpdate=preserveTransportLiteralOptions(options,normalizeMcpUpdateOptions(updateSource));return{status:readRuntimeScalarString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),update:overlayMutationStdinTokenPolicy(updateSource,normalizedUpdate),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}return{status:readRuntimeScalarString(options,"filterStatus"),list:mutationListOptions(options),update:preserveTransportLiteralOptions(options,updateManyUpdateOptionsFromFlat(options)),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}export{actionGlobalOptions,closeManyOptionsFromFlat,extensionOptionsFromArgs,graphOptionsFromFlat,isMcpMutationTransportInput,isRuntimeRecord,markMcpMutationTransportInput,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,parseRuntimeInteger,readRuntimeScalarString,readRuntimeScalarStringAllowBlank,readRuntimeString,readRuntimeStringArray,resolveRuntimeLimit,shouldInvalidateWorkspaceContractsCacheAfterAction,updateManyOptionsFromFlat,updateManyUpdateOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};
|
|
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]="b7b0588b-c59a-528c-9d1d-2a3dfc9f8017")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{normalizeListOptions,normalizeCreateOptions,normalizeUpdateOptions}from"./cli-contracts/registration-helpers.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS}from"./cli-contracts/tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES}from"./cli-contracts/tool-parameter-tables.js";import{normalizeBulkIdsValue}from"../core/io/bulk-ids-input.js";import{overlayMutationStdinTokenPolicy,preserveMutationStdinTokenLiterals,transferMutationStdinTokenPolicy}from"../core/item/parse.js";const MCP_MUTATION_TRANSPORT=Symbol("pm.mcp-mutation-transport"),MCP_MUTATION_OPTION_CONTRACTS={create:{parameters:TOOL_CREATE_OPTION_CONTRACTS,aliases:CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,strings:CREATE_COMMANDER_STRING_OPTION_CONTRACTS,repeatables:CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS},update:{parameters:TOOL_UPDATE_OPTION_CONTRACTS,aliases:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,strings:UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,repeatables:UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS}},WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function markMcpMutationTransportInput(input){return Object.defineProperty(input,MCP_MUTATION_TRANSPORT,{value:!0,enumerable:!0}),input}function isMcpMutationTransportInput(input){return MCP_MUTATION_TRANSPORT in input}function preserveTransportLiteralOptions(source,options){return isMcpMutationTransportInput(source)?preserveMutationStdinTokenLiterals(options):transferMutationStdinTokenPolicy(source,options)}function mutationOptionsWithOverrides(source,overrides,omittedKeys=[]){const options=transferMutationStdinTokenPolicy(source,{...source,...overrides});for(const key of omittedKeys)Reflect.deleteProperty(options,key);return options}function readRuntimeString(args,key){const value=args[key];return typeof value=="string"&&value.trim().length>0?value:void 0}function readRuntimeScalarString(args,key){const value=args[key];return typeof value=="string"?value.trim().length>0?value:void 0:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function readRuntimeScalarStringAllowBlank(args,key){const value=args[key];return typeof value=="string"?value:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function isRuntimeRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function parseRuntimeInteger(value,label){if(typeof value=="number"){if(!Number.isInteger(value))throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE);return value}if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(!Number.isInteger(parsed))throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE);return parsed}}function resolveRuntimeLimit(args,options){return typeof args.limit=="number"&&Number.isFinite(args.limit)?args.limit:typeof options.limit=="number"&&Number.isFinite(options.limit)?options.limit:readRuntimeString(args,"limit")??readRuntimeString(options,"limit")}function actionGlobalOptions(args){const outputFormat=readRuntimeString(args,"outputFormat");return{json:!0,quiet:!0,author:readRuntimeString(args,"author"),path:readRuntimeString(args,"path"),noExtensions:args.noExtensions===!0||args.no_extensions===!0,noPager:!0,outputInclude:readRuntimeString(args,"outputInclude"),outputLimit:readRuntimeScalarString(args,"outputLimit"),outputBudget:readRuntimeScalarString(args,"outputBudget"),outputSession:readRuntimeString(args,"outputSession"),outputCursor:readRuntimeString(args,"outputCursor"),outputFormat:outputFormat==="json"||outputFormat==="toon"?outputFormat:void 0}}const ARRAY_TO_CSV_FIELDS=new Set(["tags","blockedBy","blocked_by","skills","fields"]),SCALAR_TO_ARRAY_FIELDS=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),ANNOTATION_SCALAR_TO_ARRAY_FIELDS=new Set([...SCALAR_TO_ARRAY_FIELDS].filter(field=>field!=="file")),ARRAY_ADD_REMOVE_ACTIONS=new Set(["files","files-discover","docs","test","test-all"]),SCALAR_ANNOTATION_SOURCE_ACTIONS=new Set(["comments","notes","learnings"]);function assertMcpAnnotationFileUnavailable(action,options){if(!(!SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)||!Object.prototype.hasOwnProperty.call(options,"file")))throw new PmCliError(`MCP ${action} does not accept options.file. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}const LIFECYCLE_AUTHOR_ALIAS_ACTIONS=new Set(["claim","release","start-task","pause-task","close-task"]),HOISTED_ACTION_OPTION_KEYS={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},UNIVERSAL_READ_OUTPUT_OPTION_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function normalizeMcpOptionsArrays(options,action=""){const result={},promoteAddRemove=ARRAY_ADD_REMOVE_ACTIONS.has(action),preserveStandaloneNote=action==="files"||action==="files-discover"||action==="docs",scalarToArrayFields=SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)?ANNOTATION_SCALAR_TO_ARRAY_FIELDS:SCALAR_TO_ARRAY_FIELDS;for(const[key,value]of Object.entries(options)){if(Array.isArray(value)&&ARRAY_TO_CSV_FIELDS.has(key)){result[key]=value.join(",");continue}if(key==="note"&&preserveStandaloneNote){result[key]=value;continue}if(typeof value=="string"&&scalarToArrayFields.has(key)){result[key]=[value];continue}if(typeof value=="string"&&promoteAddRemove&&(key==="add"||key==="remove")){result[key]=[value];continue}result[key]=value}return Object.assign(result,Object.fromEntries(Object.getOwnPropertySymbols(options).map(symbol=>[symbol,Reflect.get(options,symbol)]))),result}function resolveMcpActionAuthor(args,options,action){const author=readRuntimeString(args,"author");return author!==void 0?author:action!==void 0&&LIFECYCLE_AUTHOR_ALIAS_ACTIONS.has(action)?readRuntimeString(args,"assignee")??readRuntimeString(options,"assignee"):void 0}function withResolvedAuthor(options,author){return author!==void 0&&options.author===void 0?{...options,author}:options}function hoistedMcpMutationOptions(action,args,nested){const result={},contracts=MCP_MUTATION_OPTION_CONTRACTS[action],parameters=new Set([...contracts.parameters.map(({param})=>param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(({param})=>param),...HOISTED_ACTION_OPTION_KEYS[action],...UNIVERSAL_READ_OUTPUT_OPTION_KEYS,"force"]);for(const param of parameters){const keys=contracts.aliases.find(contract=>contract.keys.includes(param))?.keys??[param];args[param]===void 0||keys.some(key=>nested[key]!==void 0)||(result[param]=args[param])}return result}function refuseMcpMutationValue(action,field){throw new PmCliError(`Invalid MCP ${action} value for "${field}". No changes were made.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"invalid_mutation_option_value",changed:!1,field,required:`Provide valid ${action} field values and an options object; inspect the pm_${action} input schema for supported types.`})}function assertMcpMutationBooleans(action,args,options){const contracts=MCP_MUTATION_OPTION_CONTRACTS[action],parameters=[...contracts.parameters,...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,{param:"force"}];for(const{param}of parameters){if(asRecordClone(PM_TOOL_PARAMETER_PROPERTIES[param]).type!=="boolean")continue;const invalid=(contracts.aliases.find(contract=>contract.keys.includes(param))?.keys??[param]).find(key=>options[key]!==void 0&&typeof options[key]!="boolean");invalid!==void 0&&refuseMcpMutationValue(action,invalid)}for(const key of["idOnly","fullChangedFields"])args[key]!==void 0&&typeof args[key]!="boolean"&&refuseMcpMutationValue(action,key)}function checkedMcpMutationOptions(action,args,options){args.options!==void 0&&!isRuntimeRecord(args.options)&&refuseMcpMutationValue(action,"options"),assertMcpMutationBooleans(action,args,options);for(const key of ARRAY_TO_CSV_FIELDS){const value=options[key];Array.isArray(value)&&value.some(entry=>typeof entry!="string")&&refuseMcpMutationValue(action,key)}const normalized=normalizeMcpMutationOptions(options,action),contracts=MCP_MUTATION_OPTION_CONTRACTS[action];for(const{keys,target}of contracts.strings)keys.some(key=>options[key]!==void 0)&&normalized[target]===void 0&&refuseMcpMutationValue(action,target);const invalidRepeatable=contracts.repeatables.flatMap(({keys})=>keys).find(key=>{const value=options[key];return value!==void 0&&typeof value!="string"&&(!Array.isArray(value)||value.some(entry=>typeof entry!="string"))});return invalidRepeatable!==void 0&&refuseMcpMutationValue(action,invalidRepeatable),normalized}function normalizedActionOptions(args,action,hoisted,nested){const mcpMutation=(action==="create"||action==="update")&&isMcpMutationTransportInput(args),options={...mcpMutation?hoistedMcpMutationOptions(action,args,nested):hoisted,...nested};return mcpMutation?checkedMcpMutationOptions(action,args,options):normalizeMcpOptionsArrays(options,action)}function optionsWithAuthor(args,action){const sourceOptions=isRuntimeRecord(args.options)?args.options:void 0,baseOptions=asRecordClone(args.options),hoistedTopLevel={},hoistKey=key=>{baseOptions[key]!==void 0||args[key]===void 0||(hoistedTopLevel[key]=args[key])};for(const key of HOISTED_ACTION_OPTION_KEYS[action??""]??[])hoistKey(key);for(const key of UNIVERSAL_READ_OUTPUT_OPTION_KEYS)hoistKey(key);action!==void 0&&isMcpMutationTransportInput(args)&&assertMcpAnnotationFileUnavailable(action,baseOptions);const options=normalizedActionOptions(args,action,hoistedTopLevel,baseOptions);if(action==="history-attest"&&isMcpMutationTransportInput(args)&&(options.output!==void 0||typeof options.verify=="string"))throw new PmCliError("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",EXIT_CODE.USAGE);const stdinPolicySource=isMcpMutationTransportInput(args)?args:sourceOptions??args;return preserveTransportLiteralOptions(stdinPolicySource,withResolvedAuthor(options,resolveMcpActionAuthor(args,options,action)))}function withAddNoteOption(options){if(options.addNote===void 0)return options;const next={...options};return next.note===void 0&&typeof next.addNote=="string"&&(next.note=next.addNote),delete next.addNote,next}function withFilesDiscoveryOptions(options){const next={...options};return next.discoveryNote!==void 0&&next.note===void 0&&typeof next.discoveryNote=="string"&&(next.note=next.discoveryNote),delete next.discover,delete next.discoveryNote,next}function normalizeActionName(value){const chunks=[];let lastWasSeparator=!0;for(const character of value.trim().toLowerCase()){if(character>="a"&&character<="z"||character>="0"&&character<="9"){chunks.push(character),lastWasSeparator=!1;continue}lastWasSeparator||(chunks.push("-"),lastWasSeparator=!0)}return chunks.at(-1)==="-"&&chunks.pop(),chunks.join("")}function shouldInvalidateWorkspaceContractsCacheAfterAction(action){return!WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS.has(normalizeActionName(action))}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function readRuntimeStringArray(value){return Array.isArray(value)?value.map(entry=>String(entry)).filter(entry=>entry.length>0):[]}function extensionOptionsFromArgs(args,options){const reserved=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),passthrough={};for(const[key,value]of Object.entries(args))reserved.has(key)||(passthrough[key]=value);const normalizedOptions={...passthrough,...options};return delete normalizedOptions.args,delete normalizedOptions.author,normalizedOptions}function withMutationCompaction(args,options){const runnerOptions=preserveTransportLiteralOptions(options??{},{...options});return{changedFields:args.fullChangedFields===!0?"full":"compact",idOnly:args.idOnly===!0,runnerOptions}}function mutationListOptions(options){return{type:readRuntimeScalarString(options,"filterType"),tag:readRuntimeScalarString(options,"filterTag"),priority:readRuntimeScalarString(options,"filterPriority"),deadlineBefore:readRuntimeScalarString(options,"filterDeadlineBefore"),deadlineAfter:readRuntimeScalarString(options,"filterDeadlineAfter"),updatedAfter:readRuntimeScalarString(options,"filterUpdatedAfter"),updatedBefore:readRuntimeScalarString(options,"filterUpdatedBefore"),createdAfter:readRuntimeScalarString(options,"filterCreatedAfter"),createdBefore:readRuntimeScalarString(options,"filterCreatedBefore"),ids:normalizeBulkIdsValue(options.ids),assignee:readRuntimeScalarString(options,"filterAssignee"),assigneeFilter:readRuntimeScalarString(options,"filterAssigneeFilter")??readRuntimeScalarString(options,"filterAssignee_filter"),parent:readRuntimeScalarString(options,"filterParent"),sprint:readRuntimeScalarString(options,"filterSprint"),release:readRuntimeScalarString(options,"filterRelease"),limit:readRuntimeScalarString(options,"limit"),offset:readRuntimeScalarString(options,"offset")}}function readGraphIdListOption(value){if(typeof value=="string"&&value.trim().length>0)return value;if(Array.isArray(value))return readRuntimeStringArray(value)}function readGraphBoundOption(value){if(typeof value=="number"&&Number.isFinite(value)||typeof value=="string"&&value.trim().length>0)return value}function graphOptionsFromFlat(options){const kind=readGraphIdListOption(options.kind),exemptIsolate=readGraphIdListOption(options.exemptIsolate),exemptIsolateType=readGraphIdListOption(options.exemptIsolateType);return{...kind===void 0?{}:{kind},maxDepth:readGraphBoundOption(options.maxDepth),limit:readGraphBoundOption(options.limit),after:readRuntimeString(options,"after"),direction:readRuntimeString(options,"direction"),maxPaths:readGraphBoundOption(options.maxPaths),sample:readGraphBoundOption(options.sample),...exemptIsolate===void 0?{}:{exemptIsolate},...exemptIsolateType===void 0?{}:{exemptIsolateType},saveBaseline:options.saveBaseline===!0,rebuild:options.rebuild===!0,clear:options.clear===!0,summary:options.summary===!0,...options.full===!0?{full:!0}:{}}}function normalizeBulkMutationListOptions(options){const normalized=normalizeListOptions(options);return options.ids!==void 0&&(normalized.ids=normalizeBulkIdsValue(options.ids)),normalized}function closeManyOptionsFromFlat(options){return{status:readRuntimeString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),reason:readRuntimeString(options,"reason"),resolution:readRuntimeString(options,"resolution"),expectedResult:readRuntimeString(options,"expectedResult")??readRuntimeString(options,"expected_result")??readRuntimeString(options,"expected"),actualResult:readRuntimeString(options,"actualResult")??readRuntimeString(options,"actual_result")??readRuntimeString(options,"actual"),validateClose:readRuntimeString(options,"validateClose")??readRuntimeString(options,"validate_close"),author:readRuntimeString(options,"author"),message:readRuntimeString(options,"message"),force:options.force===!0?!0:void 0,dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}const UPDATE_MANY_FLAT_CONTROL_KEYS=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function updateManyUpdateOptionsFromFlat(options){const update={};for(const[key,value]of Object.entries(options))UPDATE_MANY_FLAT_CONTROL_KEYS.has(key)||(update[key]=value);return normalizeMcpUpdateOptions(update)}function normalizeMcpUpdateOptions(options){return normalizeMcpMutationOptions(options,"update")}function normalizeMcpMutationOptions(options,action){const normalizedInput=normalizeMcpOptionsArrays(options,action),contracts=MCP_MUTATION_OPTION_CONTRACTS[action],booleanishKeys=new Set([...contracts.parameters,...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS].filter(({booleanish})=>booleanish===!0).map(({param})=>param));for(const{keys}of contracts.repeatables)for(const key of keys)typeof normalizedInput[key]=="string"&&(normalizedInput[key]=[normalizedInput[key]]);for(const contract of contracts.strings)for(const key of contract.keys){const value=normalizedInput[key];(typeof value=="number"&&Number.isFinite(value)||value===!1&&booleanishKeys.has(key))&&(normalizedInput[key]=String(value))}return action==="create"?{...normalizeCreateOptions(normalizedInput,{requireType:!1})}:normalizeUpdateOptions(normalizedInput)}function updateManyOptionsFromFlat(options){if(isRuntimeRecord(options.list)||isRuntimeRecord(options.update)){const updateSource=isRuntimeRecord(options.update)?options.update:updateManyUpdateOptionsFromFlat(options),normalizedUpdate=preserveTransportLiteralOptions(options,normalizeMcpUpdateOptions(updateSource));return{status:readRuntimeScalarString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),update:overlayMutationStdinTokenPolicy(updateSource,normalizedUpdate),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}return{status:readRuntimeScalarString(options,"filterStatus"),list:mutationListOptions(options),update:preserveTransportLiteralOptions(options,updateManyUpdateOptionsFromFlat(options)),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:readRuntimeString(options,"rollback"),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}export{HOISTED_ACTION_OPTION_KEYS,actionGlobalOptions,closeManyOptionsFromFlat,extensionOptionsFromArgs,graphOptionsFromFlat,isMcpMutationTransportInput,isRuntimeRecord,markMcpMutationTransportInput,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,parseRuntimeInteger,readRuntimeScalarString,readRuntimeScalarStringAllowBlank,readRuntimeString,readRuntimeStringArray,resolveRuntimeLimit,shouldInvalidateWorkspaceContractsCacheAfterAction,updateManyOptionsFromFlat,updateManyUpdateOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};
|
|
2
2
|
//# sourceMappingURL=runtime-input.js.map
|
|
@@ -44,6 +44,12 @@ export { resolveConfiguredPmPackageRoot,resolvePmCliVersion,resolvePmPackageRoot
|
|
|
44
44
|
export { buildInvalidTypeError } from "../core/schema/item-types-file.js";
|
|
45
45
|
export { collectRuntimeFilterValues,matchesRuntimeFilters,} from "../core/schema/runtime-field-filters.js";
|
|
46
46
|
export { collectRuntimeCreateFieldValues,collectRuntimeUpdateFieldValues,} from "../core/schema/runtime-field-values.js";
|
|
47
|
+
/**
|
|
48
|
+
* Reads the first defined own option value for a runtime field, checking its
|
|
49
|
+
* configured target, camelized key, CLI flag and aliases in that order.
|
|
50
|
+
* Preserves explicit false and null values; returns undefined when none match.
|
|
51
|
+
*/
|
|
52
|
+
export { readRuntimeFieldOptionValue } from "../core/schema/runtime-field-values.js";
|
|
47
53
|
export { type RuntimeFieldCommand,type RuntimeFieldRegistry,type RuntimeStatusRegistry,normalizeStatusInputWithRegistry,resolveItemTypesFilePath,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,statusIsTerminal,} from "../core/schema/runtime-schema.js";
|
|
48
54
|
export { type NormalizedTypeWorkflow,describeAllowedTransitions,evaluateTransition,resolveTypeWorkflows,} from "../core/schema/type-workflows.js";
|
|
49
55
|
export { REINDEX_LOCK_ID,shouldRunSearchRefreshInForeground,} from "../core/search/background-refresh.js";
|