@unbrained/pm-cli 2026.9.27 → 2026.9.28
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 +4 -6
- package/CHANGELOG.md +26 -0
- package/dist/cli/help-json-payload.js +1 -1
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +154 -154
- package/dist/cli-bundle/chunks/{chunk-OKVDVERQ.js → chunk-35DME35A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AUS6USO4.js → chunk-A2G5OG6W.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-CPOWTIIS.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-7TAGYNFP.js → chunk-GLH2LNRH.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3BTJ66CB.js → chunk-NBDB3SRC.js} +48 -48
- package/dist/cli-bundle/chunks/{chunk-JX6WCCHL.js → chunk-NEUIVBFO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6OJVQ7SW.js → chunk-OYCCWPBM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LKGQUZ5M.js → chunk-PLNNUAFZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4SLLCDFL.js → chunk-PR4UAMI5.js} +8 -8
- package/dist/cli-bundle/chunks/{chunk-TSF2LPIH.js → chunk-UT7GRGHY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-V5UGBYHN.js → chunk-VMJLM7P2.js} +62 -62
- package/dist/cli-bundle/chunks/{chunk-IEP3VAT5.js → chunk-YERBAGQD.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-ZFHJP7YD.js +29 -0
- package/dist/cli-bundle/chunks/{register-list-query-6PAJ4PBU.js → register-list-query-N6RP6PSP.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-RZCXZXYS.js → register-mutation-CY7JGQE6.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-GK6VU2H2.js → register-operations-53HAD3QP.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-ASEMNMBF.js → register-setup-NVX6374E.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OJRX6G22.js → chunk-5KJXX2TZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MILJCOFJ.js → chunk-6IVQPNYN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NETVXIH5.js → chunk-A5O3VYWV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-AZA4AEOR.js +75 -0
- package/dist/cli-bundle/focused-chunks/chunk-BGWF6CMP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PDVL7QYU.js → chunk-BRLXKRI2.js} +15 -15
- package/dist/cli-bundle/focused-chunks/{chunk-SMADBUPL.js → chunk-DTLRXY77.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-6UNKK3UH.js → chunk-IJXZQE3D.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NWRVNHAD.js → chunk-IWLMQLBO.js} +6 -6
- package/dist/cli-bundle/focused-chunks/chunk-K7GSZ7YZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OJKJFDIG.js → chunk-ONDNR3VU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NZAG7OKB.js → chunk-OVVCXTIE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GZD4ZYIB.js → chunk-V7OPZRL6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LBDWUHQD.js → chunk-Y5Z3XNGY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QO4MTAEA.js → chunk-YZB7IPR6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-DQ3MB7BO.js → chunk-ZMQTIS3L.js} +2 -2
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +18 -18
- 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 +51 -51
- 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 +1 -1
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/item/item-format.js +1 -1
- package/dist/core/store/settings.js +3 -3
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/completion/fish.js +3 -3
- package/dist/sdk/completion/zsh.js +3 -3
- package/dist/sdk/extension/copy-scope.d.ts +2 -2
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-runtime.js +2 -2
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.d.ts +18 -0
- package/dist/sdk/governance/health-merge-evidence.js +2 -0
- package/dist/sdk/governance/health.js +1 -1
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/output-projection.d.ts +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-budget.d.ts +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/test/execution.d.ts +11 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/test/parsers.d.ts +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/types.js +1 -1
- package/docs/AGENT_READ_AND_TEST_RECEIPTS.md +21 -0
- package/docs/CLAUDE_CODE_PLUGIN.md +12 -7
- package/docs/CONFIGURATION.md +2 -0
- package/docs/PACKAGE_EVIDENCE.md +18 -7
- package/docs/README.md +1 -0
- package/docs/TESTING.md +14 -3
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +7 -3
- package/marketplace.json +4 -6
- package/package.json +5 -5
- 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 +4 -2
- package/plugins/pm-claude/.mcp.json +1 -2
- package/plugins/pm-claude/README.md +7 -7
- package/plugins/pm-claude/package.json +2 -2
- package/plugins/pm-claude/{commands/pm-calendar.md → skills/pm-calendar/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-close-task.md → skills/pm-close-task/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-init.md → skills/pm-init/SKILL.md} +2 -1
- package/plugins/pm-claude/{commands/pm-list.md → skills/pm-list/SKILL.md} +2 -1
- package/plugins/pm-claude/{commands/pm-new.md → skills/pm-new/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-search.md → skills/pm-search/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-start-task.md → skills/pm-start-task/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-status.md → skills/pm-status/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-triage.md → skills/pm-triage/SKILL.md} +1 -0
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4UPZLUT2.js +0 -29
- package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6J2YCGSN.js +0 -75
- package/dist/cli-bundle/focused-chunks/chunk-E7LYK7V5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +0 -2
- package/plugins/pm-claude/commands/pm-audit.md +0 -38
- package/plugins/pm-claude/commands/pm-developer.md +0 -38
- package/plugins/pm-claude/commands/pm-planner.md +0 -54
- package/plugins/pm-claude/commands/pm-release.md +0 -41
- package/plugins/pm-claude/commands/pm-workflow.md +0 -49
|
@@ -29,4 +29,4 @@ export declare function estimateReadOutputTokens(result: unknown, format?: "json
|
|
|
29
29
|
/** Update a receipt to the fixed-point estimate of the result containing it. */
|
|
30
30
|
export declare function updateReadOutputReceiptEstimate(result: Record<string, unknown>, receipt: PmReadOutputReceipt, format?: "json" | "toon"): void;
|
|
31
31
|
/** Compact strings and rows in place, then return the final exact estimate. */
|
|
32
|
-
export declare function compactReadOutputToBudget(result: Record<string, unknown>, receipt: PmReadOutputReceipt, budget: number, minimumRowsByPath?: ReadonlyMap<string, number>, format?: "json" | "toon", finalize?: (result: Record<string, unknown>) => void): Record<string, unknown>;
|
|
32
|
+
export declare function compactReadOutputToBudget(result: Record<string, unknown>, receipt: PmReadOutputReceipt, budget: number, minimumRowsByPath?: ReadonlyMap<string, number>, format?: "json" | "toon", finalize?: (result: Record<string, unknown>) => void, preserveStrings?: boolean): Record<string, unknown>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f960f91a-c5a7-5114-b4d2-7d562a8b6fdb")}catch(e2){}})();import{formatBuiltInOutput}from"../core/output/output.js";import{countReadOutputRows,readOutputBudgetCollections}from"./read-output-rows.js";const MAX_ESTIMATE_ITERATIONS=8;const MAX_COMPACTION_ITERATIONS=64;const RECOVERY_MARGIN_NUMERATOR=5;const RECOVERY_MARGIN_DENOMINATOR=4;const RECOVERY_ROUNDING_TOKENS=100;function projectReadOutputItemToBrief(command,options,result){if(command!=="get"||!isRecord(result.item)||["fields","outputInclude","output_include","outputCursor","output_cursor"].some(key=>options[key]!==void 0)||options.full===true||options.tree===true||options.depth!==void 0&&options.depth!=="standard")return void 0;const item=result.item;const sections=["linked","claim_state","schedule"];const omitted=sections.filter(key=>Object.hasOwn(result,key));const projected=Object.fromEntries(Object.entries(result).filter(([key])=>!sections.includes(key)));projected.item=Object.fromEntries(Object.entries(item).filter(([key])=>key!=="body"));if(Object.hasOwn(item,"body"))omitted.push("body");const previous=isRecord(result.omission_receipt)&&Array.isArray(result.omission_receipt.omitted_field_groups)?result.omission_receipt.omitted_field_groups:[];const groups=[...previous,...omitted.map(name=>({name,restore_with:`--fields ${name}`}))];projected.omission_receipt={has_omissions:groups.length>0,omitted_field_group_count:groups.length,omitted_field_groups:groups};return projected}function resolveReadOutputRecoveryBudget(input){const binding=Math.trunc(input.effective_budget_tokens);const measured=Math.trunc(input.measured_result_tokens);if(!Number.isSafeInteger(binding)||binding<=0||!Number.isSafeInteger(measured)||measured<=0){return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}const baseline=Math.max(binding+1,measured);const withMargin=Math.ceil(baseline*RECOVERY_MARGIN_NUMERATOR/RECOVERY_MARGIN_DENOMINATOR);const rounded=Math.ceil(withMargin/RECOVERY_ROUNDING_TOKENS)*RECOVERY_ROUNDING_TOKENS;if(!Number.isSafeInteger(rounded)){return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}return{output_budget:rounded,recovery_budget_multiplier:rounded/binding,rule_version:"v1"}}function preserveReadOutputRowContract(source,target,suppress=false){const descriptor=Object.getOwnPropertyDescriptor(source,"row_contract");if(descriptor&&(suppress||descriptor.enumerable===false)){Object.defineProperty(target,"row_contract",{...descriptor,enumerable:false})}}function estimateReadOutputTokens(result,format){const rendered=format===void 0?JSON.stringify(result):formatBuiltInOutput(result,format);return Math.ceil(Buffer.byteLength(rendered,"utf8")/4)}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function compactStrings(value,state,preserveStrings=false){if(typeof value==="string"){if(preserveStrings||value.length<=240)return value;state.compacted=true;return`${value.slice(0,240)}\u2026`}if(Array.isArray(value)){return value.map(entry=>compactStrings(entry,state,preserveStrings))}if(!isRecord(value))return value;return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactStrings(entry,state,preserveStrings)]))}function updateReadOutputReceiptEstimate(result,receipt,format){let estimate=receipt.estimated_tokens;for(let iteration=0;iteration<MAX_ESTIMATE_ITERATIONS;iteration+=1){receipt.estimated_tokens=estimate;const measured=estimateReadOutputTokens(result,format);if(measured===estimate)return;estimate=measured}receipt.estimated_tokens=estimate}function selectCompactionCollection(result,minimumRowsByPath){return readOutputBudgetCollections(result).filter(collection=>{const length=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length;return length>Math.max(1,minimumRowsByPath.get(collection.path)??0)}).map(collection=>({collection,length:Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length})).sort((left,right)=>right.length-left.length||left.collection.path.localeCompare(right.collection.path))[0]?.collection}function compactRowsToBudget(result,receipt,budget,minimumRowsByPath,format,finalize){for(let iteration=0;iteration<MAX_COMPACTION_ITERATIONS;iteration+=1){finalize?.(result);updateReadOutputReceiptEstimate(result,receipt,format);if(receipt.estimated_tokens<=budget)return;const candidate=selectCompactionCollection(result,minimumRowsByPath);if(!candidate)return;const minimumRows=Math.max(1,minimumRowsByPath.get(candidate.path)??0);const values=Array.isArray(candidate.value)?[...candidate.value]:Object.entries(candidate.value);const retainPrefix=length=>{if(Array.isArray(candidate.value)){candidate.value.length=length;for(let index=0;index<length;index+=1)candidate.value[index]=values[index]}else{for(const key of Object.keys(candidate.value))delete candidate.value[key];Object.defineProperties(candidate.value,Object.getOwnPropertyDescriptors(Object.fromEntries(values.slice(0,length))))}if(typeof result.count==="number")result.count=countReadOutputRows(result);if(candidate.path==="items")result.applied_limit=length;finalize?.(result);updateReadOutputReceiptEstimate(result,receipt,format)};receipt.rows_compacted=true;receipt.compacted_row_paths=[...new Set([...receipt.compacted_row_paths??[],candidate.path])].sort((left,right)=>left.localeCompare(right));result.has_more=true;result.truncated=true;let low=minimumRows;let high=values.length-1;let retained=minimumRows;while(low<=high){const middle=Math.floor((low+high)/2);retainPrefix(middle);if(receipt.estimated_tokens<=budget){retained=middle;low=middle+1}else{high=middle-1}}retainPrefix(retained)}}function compactReadOutputToBudget(result,receipt,budget,minimumRowsByPath=new Map,format,finalize,preserveStrings=false){const stringCompactionState={compacted:false};const compacted=Object.fromEntries(Object.entries(result).map(([key,value])=>[key,compactStrings(value,stringCompactionState,preserveStrings&&key==="diff")]));preserveReadOutputRowContract(result,compacted);receipt.strings_compacted=stringCompactionState.compacted;compacted.read_output=receipt;compactRowsToBudget(compacted,receipt,budget,minimumRowsByPath,format,finalize);updateReadOutputReceiptEstimate(compacted,receipt,format);return compacted}export{compactReadOutputToBudget,estimateReadOutputTokens,preserveReadOutputRowContract,projectReadOutputItemToBrief,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate};
|
|
2
2
|
//# sourceMappingURL=read-output-budget.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7e99eae1-0d3d-5c91-8ba7-a103601ccfe7")}catch(e2){}})();import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.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}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"];const PM_READ_OUTPUT_SURFACES=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"];const CANONICAL_OPTIONS={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};const PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension]));const PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]);const 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:{}};const VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]);const 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.","--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];const dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:true,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([...readOutputIncludeModeOptions(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract));const 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());const packageMode=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===true||options.target==="catalog"||options.action==="catalog");const root=packageMode?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0];const 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"];const 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);return true},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]!==false)){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);if(!surface)return new Map;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)??[];const modeOptions=readOutputIncludeModeOptions(command);const selectors=[];const modes=[];const optionsWithProvenance=commandOptions;const existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE];const canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]);const 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("_","-")}`;if(isRequestedOption(readOption(commandOptions,legacyFlag))){explicitLegacyAliases.add(legacyFlag)}commandOptions[option]=true;modes.push(token);canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[];const forwardedGetFields=forwardedGetFieldSelectors.length>0;if(forwardedGetFields){commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(",");canonicalModes.add("fields")}if(modes.length>0||forwardedGetFields){optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===true?{cli_invocation_observed:true}:{}}}return{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;if(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===false)return true;return void 0}function isRequestedOption(value){return value!==void 0&&value!==false&&value!==null}function stringList(value){const values=Array.isArray(value)?value:[value];const normalized=values.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);const candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}return void 0}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(!legacy)return void 0;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 void 0;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 void 0;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 void 0;if(legacy.flag==="--stream"||legacy.flag==="--follow"){return{source:"legacy",value:"stream"}}return legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return false;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===true||provenance.sdk_invocation_observed===true){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){const root=command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0];return root==="list-all"||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===true}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 void 0;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand);const invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE];const 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)};const 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))]));const legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]});const migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];if(!resolved)return[];const alias=contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag);return[alias.migration_hint]});const encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding);const include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include);const amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount);const explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost);const completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance);const budget=resolvePmCommandOutputBudget(command,{generateFallback:true});const resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon";const cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});const resolvedByDimension={include,amount,cost,encoding};return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed(resolvedByDimension,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"]);const 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:{};const itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right));const 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);const 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");const itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice("item.".length)]: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)));const projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));if(fullItem){projected.item=vocabulary.item}else if(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}`}))];const inheritedOmittedFieldGroups=isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[];const combinedOmittedFieldGroups=[...inheritedOmittedFieldGroups,...omittedFieldGroups];projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups};return projected}function countPopulatedRows(result){let populated=0;mapReadOutputRows({...result},entry=>{if(isRecord(entry)&&Object.keys(entry).length>0)populated+=1;return entry});return populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0){return}const modes=[...readOutputIncludeModeOptions(command).keys()];const 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);const qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[]));const 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};const rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors;const shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);rejectEmptyIncludeProjection(command,result,shaped,rowSelectors);return 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;bounded.has_more=true;bounded.truncated=true;if(typeof bounded.count==="number"){bounded.count=countReadOutputRows(bounded)}bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount};return 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;const 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);const receipt=result.read_output;const session=parseReadOutputSession(options.outputSession??options.output_session);if(session===void 0){updateReadOutputReceiptEstimate(result,receipt,format);return result}return attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;const declaredFieldGroups=Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[];if(!declaredFieldGroups.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)))];const 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:{};const existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry==="string"):[];const existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry==="string"):[];const rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys;const 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){let projected={...result};if(resolved.include?.source==="canonical"){projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)}if(resolved.command==="assurance"){projected=prioritizeAssuranceAssertions(projected)}projected=applyReadOutputContinuation(projected,resolved.command,cursor);if(resolved.amount?.source==="canonical"){projected=applyAmountBound(projected,resolved.amount.value)}return session===void 0?projected:applyReadOutputSessionReferences(projected,session)}function resolveBindingReadOutputBudget(resolved,session){const budgets=[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]];return budgets.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 omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:false,strings_compacted:false,rows_compacted:false,result_omitted:true,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}};const omitted={output_budget_exceeded:{omitted_result:true,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt};const boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0){updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format)}if(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){return options.outputRowContract===true||options.output_row_contract===true||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===true}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options))return false;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 false}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"||estimateReadOutputTokens(options.outputRowContract===false?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"]:[];const afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length]));const 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}]});const primary=continuations[0];const continuationHint=primary?"; page --output-cursor":"";const 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});if(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 rebaseBudgetCompactedCursor(projected,originalItemCount,cursorSource,cursorContinuesExistingPage){if(typeof cursorSource!=="string"||!Array.isArray(projected.items)){return false}const retainedCount=projected.items.length;if(retainedCount===0||retainedCount>=originalItemCount){return false}let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return false}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return false;const last=projected.items.at(-1);if(Object.prototype.toString.call(last)!=="[object Object]"){return false}const lastId=Reflect.get(last,"id");if(typeof lastId!=="string"||lastId.length===0)return false;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+retainedCount;if(afterIndex<0)return false;projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot);return true}function captureReadOutputContinuationState(projected,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;const 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)}]}));const cursorContinuesExistingPage=typeof projected.next_cursor==="string";return{collectionsBeforeBudget,originalItemCount:Array.isArray(projected.items)?projected.items.length:0,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0;return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,assuranceMinimumRows>0?new Map([["assertions",assuranceMinimumRows]]):new Map,format,compacted=>{const continuationCursorRebased=rebaseBudgetCompactedCursor(compacted,continuationState.originalItemCount,continuationState.cursorSource,continuationState.cursorContinuesExistingPage);attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget);if(session!==void 0){Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))}})}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options);const session=parseReadOutputSession(options.outputSession??options.output_session);const rawCursor=options.outputCursor??options.output_cursor;const cursor=typeof rawCursor==="string"?decodeReadOutputContinuationCursor(rawCursor):void 0;const requested=requestedDimensions(resolved);const continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options)){return continuationReadyResult}const bindingBudget=resolveBindingReadOutputBudget(resolved,session);let projected=projectReadOutputRows(continuationReadyResult,resolved,session,cursor);preserveReadOutputRowContract(projected,projected,options.outputRowContract===false);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget?.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:true,strings_compacted:false,rows_compacted:false,result_omitted:false};projected.read_output=receipt;projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format);updateReadOutputReceiptEstimate(projected,receipt,format);if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);if(brief!==void 0){receipt.applied_depth="brief";receipt.degradation_reason="output_budget_reached";preserveReadOutputRowContract(projected,brief);projected=stabilizeReadOutputReceiptEstimates(brief,options)}if(receipt.estimated_tokens>bindingBudget.tokens){projected=compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,captureReadOutputContinuationState(projected,resolved.command,cursor,options),receipt.estimated_tokens,format)}}if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){return omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format)}return projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===true&&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_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="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="72058f24-2965-5a9a-994d-e84a9af0c558")}catch(e2){}})();import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.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}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"];const PM_READ_OUTPUT_SURFACES=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"];const CANONICAL_OPTIONS={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};const PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension]));const PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]);const 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:{}};const VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]);const 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.","--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];const dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:true,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([...readOutputIncludeModeOptions(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract));const 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());const packageMode=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===true||options.target==="catalog"||options.action==="catalog");const root=packageMode?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0];const 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"];const 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);return true},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]!==false)){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);if(!surface)return new Map;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)??[];const modeOptions=readOutputIncludeModeOptions(command);const selectors=[];const modes=[];const optionsWithProvenance=commandOptions;const existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE];const canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]);const 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("_","-")}`;if(isRequestedOption(readOption(commandOptions,legacyFlag))){explicitLegacyAliases.add(legacyFlag)}commandOptions[option]=true;modes.push(token);canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[];const forwardedGetFields=forwardedGetFieldSelectors.length>0;if(forwardedGetFields){commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(",");canonicalModes.add("fields")}if(modes.length>0||forwardedGetFields){optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===true?{cli_invocation_observed:true}:{}}}return{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;if(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===false)return true;return void 0}function isRequestedOption(value){return value!==void 0&&value!==false&&value!==null}function stringList(value){const values=Array.isArray(value)?value:[value];const normalized=values.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);const candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}return void 0}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(!legacy)return void 0;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 void 0;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 void 0;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 void 0;if(legacy.flag==="--stream"||legacy.flag==="--follow"){return{source:"legacy",value:"stream"}}return legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return false;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===true||provenance.sdk_invocation_observed===true){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){const root=command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0];return root==="list-all"||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===true}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 void 0;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand);const invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE];const 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)};const 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))]));const legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]});const migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];if(!resolved)return[];const alias=contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag);return[alias.migration_hint]});const encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding);const include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include);const amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount);const explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost);const completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance);const budget=resolvePmCommandOutputBudget(command,{generateFallback:true});const resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon";const cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});const resolvedByDimension={include,amount,cost,encoding};return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed(resolvedByDimension,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"]);const 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:{};const itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right));const 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);const 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");const itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice("item.".length)]: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)));const projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));if(fullItem){projected.item=vocabulary.item}else if(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}`}))];const inheritedOmittedFieldGroups=isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[];const combinedOmittedFieldGroups=[...inheritedOmittedFieldGroups,...omittedFieldGroups];projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups};return projected}function countPopulatedRows(result){let populated=0;mapReadOutputRows({...result},entry=>{if(isRecord(entry)&&Object.keys(entry).length>0)populated+=1;return entry});return populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0){return}const modes=[...readOutputIncludeModeOptions(command).keys()];const 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);const qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[]));const 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};const rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors;const shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);rejectEmptyIncludeProjection(command,result,shaped,rowSelectors);return 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;bounded.has_more=true;bounded.truncated=true;if(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)}bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount};return 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;const 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);const receipt=result.read_output;const session=parseReadOutputSession(options.outputSession??options.output_session);if(session===void 0){updateReadOutputReceiptEstimate(result,receipt,format);return result}return attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;const declaredFieldGroups=Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[];if(!declaredFieldGroups.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)))];const 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:{};const existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry==="string"):[];const existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry==="string"):[];const rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys;const 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){let projected={...result};if(resolved.include?.source==="canonical"){projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)}if(resolved.command==="assurance"){projected=prioritizeAssuranceAssertions(projected)}projected=applyReadOutputContinuation(projected,resolved.command,cursor);if(resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path));if(isRecord(projected.projection)){projected.projection={...projected.projection,row_key:cursor.path}}if(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}if(resolved.amount?.source==="canonical"){projected=applyAmountBound(projected,resolved.amount.value)}return session===void 0?projected:applyReadOutputSessionReferences(projected,session)}function resolveBindingReadOutputBudget(resolved,session){const budgets=[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]];return budgets.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 omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:false,strings_compacted:false,rows_compacted:false,result_omitted:true,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}};const omitted={output_budget_exceeded:{omitted_result:true,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt};const boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0){updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format)}if(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){return options.outputRowContract===true||options.output_row_contract===true||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===true}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options))return false;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 false}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"||estimateReadOutputTokens(options.outputRowContract===false?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"]:[];const afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length]));const 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}]});const primary=continuations[0];const continuationHint=primary?"; page --output-cursor":"";const 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});if(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 rebaseBudgetCompactedCursor(projected,originalItemCount,cursorSource,cursorContinuesExistingPage){if(typeof cursorSource!=="string"||!Array.isArray(projected.items)){return false}const retainedCount=projected.items.length;if(retainedCount===0||retainedCount>=originalItemCount){return false}let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return false}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return false;const last=projected.items.at(-1);if(Object.prototype.toString.call(last)!=="[object Object]"){return false}const lastId=Reflect.get(last,"id");if(typeof lastId!=="string"||lastId.length===0)return false;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+retainedCount;if(afterIndex<0)return false;projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot);return true}function captureReadOutputContinuationState(projected,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;const 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)}]}));const cursorContinuesExistingPage=typeof projected.next_cursor==="string";return{collectionsBeforeBudget,originalItemCount:Array.isArray(projected.items)?projected.items.length:0,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0;const minimumRowsByPath=new Map;if(assuranceMinimumRows>0){minimumRowsByPath.set("assertions",assuranceMinimumRows)}if(resolved.command==="history"&&Array.isArray(projected.diff)){for(const collection of readOutputBudgetCollections(projected)){if(!collection.path.startsWith("diff."))continue;minimumRowsByPath.set(collection.path,Object.keys(collection.value).length)}}return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{const continuationCursorRebased=rebaseBudgetCompactedCursor(compacted,continuationState.originalItemCount,continuationState.cursorSource,continuationState.cursorContinuesExistingPage);attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget);if(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;if(typeof rowKey==="string"&&Array.isArray(compacted[rowKey])){compacted.count=compacted[rowKey].length}}if(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);const session=parseReadOutputSession(options.outputSession??options.output_session);const rawCursor=options.outputCursor??options.output_cursor;const cursor=typeof rawCursor==="string"?decodeReadOutputContinuationCursor(rawCursor):void 0;const requested=requestedDimensions(resolved);const continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options)){return continuationReadyResult}const bindingBudget=resolveBindingReadOutputBudget(resolved,session);let projected=projectReadOutputRows(continuationReadyResult,resolved,session,cursor);preserveReadOutputRowContract(projected,projected,options.outputRowContract===false);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...bindingBudget?.source==="default"?{budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens}:{},precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:true,strings_compacted:false,rows_compacted:false,result_omitted:false};projected.read_output=receipt;projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format);updateReadOutputReceiptEstimate(projected,receipt,format);if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);if(brief!==void 0){receipt.applied_depth="brief";receipt.degradation_reason="output_budget_reached";preserveReadOutputRowContract(projected,brief);projected=stabilizeReadOutputReceiptEstimates(brief,options)}if(receipt.estimated_tokens>bindingBudget.tokens){projected=compactReadOutputProjection(projected,resolved,receipt,bindingBudget,session,captureReadOutputContinuationState(projected,resolved.command,cursor,options),receipt.estimated_tokens,format)}}if(bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){return omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format)}return projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===true&&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_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
|
|
@@ -166,6 +166,17 @@ export interface TestResult {
|
|
|
166
166
|
warnings?: string[];
|
|
167
167
|
/** Value that configures or reports changed for this contract. */
|
|
168
168
|
changed: boolean;
|
|
169
|
+
/** Whether this execution appended evidence to the item's immutable history. */
|
|
170
|
+
evidence_recording?: {
|
|
171
|
+
/** True only after the item history mutation succeeds. */
|
|
172
|
+
recorded: boolean;
|
|
173
|
+
/** Why the current execution did or did not reach item history. */
|
|
174
|
+
reason: "recorded" | "tracking_disabled" | "write_failed";
|
|
175
|
+
/** Identifier of the execution summary, even when item tracking is disabled. */
|
|
176
|
+
run_id: string;
|
|
177
|
+
/** Executable next step when recording was disabled. */
|
|
178
|
+
recovery_command?: string;
|
|
179
|
+
};
|
|
169
180
|
/** Value that configures or reports count for this contract. */
|
|
170
181
|
count: number;
|
|
171
182
|
/** Number of linked-test entries removed by this mutation. */
|