@unbrained/pm-cli 2026.11.19 → 2026.11.21
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/.agents/skills/pm-sdk/SKILL.md +1 -1
- package/.agents/skills/pm-test-audit/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +1 -1
- package/CONTRIBUTING.md +2 -1
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +21 -0
- package/dist/cli-bundle/chunks/{chunk-AGPFANRX.js → chunk-5647LU3A.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-CR5GC3VO.js → chunk-6QLEXRUG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XPBPGDFW.js → chunk-AHQB7W2H.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4FNMPZ7Y.js → chunk-BKSVHOWI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GQCMICAL.js → chunk-CASX6SFI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NMVPQTZI.js → chunk-CIKGG34F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-IQKCRLQP.js → chunk-D6ILFXZY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AOV5HG3Y.js → chunk-IUIOTAF6.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-PRVT7ITI.js → chunk-JVGRFU5H.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-IUTN67EB.js → chunk-KVBIMFUG.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-AMHD7WIV.js → chunk-NCFCBKIP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-M76BEWTT.js → chunk-NT5AKFE5.js} +30 -30
- package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +125 -0
- package/dist/cli-bundle/chunks/{chunk-2UTJ5QIE.js → chunk-RMIRNYRG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CNMGGAZO.js → chunk-RULHZRFN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O7IFAJ76.js → chunk-S6HB3WL2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CTOE26W4.js → chunk-SA4BNP3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Z5LHCEXG.js → chunk-SRVTCYAU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-N2CPCFSN.js → chunk-WELSVDPU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-P4A5RFLX.js → chunk-XHJ3H5PL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Q32Q3LRH.js → chunk-XWHJIRNV.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +8 -0
- package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-Y4LXVPA5.js → chunk-YMUSRWV4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HQYIKAC6.js → chunk-YR2KEBHP.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-ELEMA7IW.js → indexed-receipt-blobs-ITTXIN4K.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-YJKGOYBR.js → item-revision-R5SZPJZ5.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-DDYJW5B4.js → mutation-actor-3TG636XG.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-JLMQJ2M5.js → mutation-admission-LICSDNNO.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-4AXLLXK7.js → register-list-query-SPGPS3OS.js} +10 -10
- package/dist/cli-bundle/chunks/{register-mutation-FJIXGGF4.js → register-mutation-WWVECKFQ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-W4E2KEMA.js → register-operations-L6HFJNWD.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-RYRIBNSN.js → register-setup-K7UFG5TD.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-E5LHZ4RD.js → settlement-hook-BXN5LEQD.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-XGWW3T64.js → stage-57KH3KAC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IXYBN6D2.js → chunk-3IRCYJI5.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-DH4DHL6V.js → chunk-3V53UBHN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2XULTI5B.js → chunk-532WZV65.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZFUZ4YYN.js → chunk-7A4QWNZX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7RF2YPZ5.js → chunk-CWWKRI5P.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ICEHI4SN.js → chunk-HGFNL5XI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +13 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OF4UM5B6.js → chunk-J63D6QST.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OAIAZHRG.js → chunk-JMQJBZQ5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4S7I342K.js → chunk-LNHUE4VV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MTBC32ZR.js → chunk-MKM5NKD7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EZXLY6S4.js → chunk-NP72ZDXE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +102 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OPY43DNJ.js → chunk-QGKLRXP7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-77CDWGBW.js → chunk-QSJW6NSQ.js} +53 -53
- package/dist/cli-bundle/focused-chunks/{chunk-7Z2NYAK4.js → chunk-RPE6IX26.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-D72EQN7Z.js → chunk-UOC6257J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FPPYE6CY.js → chunk-URJ2E6AS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-N64BUB63.js → chunk-XCJSHNXK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GAOWBALE.js → chunk-XQQSSKJI.js} +5 -5
- package/dist/cli-bundle/focused-chunks/{chunk-XS2YZCT5.js → chunk-YOAYY3HE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ZTRFCPH7.js → indexed-receipt-blobs-AF4U3F3D.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-32HFGFYG.js → item-revision-3V3UIP5X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-C4VW3SHX.js → item-transaction-HLBW7B3J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-2SVBO324.js → mutation-actor-62HKR5IO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-PNK6ORZR.js → mutation-admission-X4PF2SG3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-OUBUN45C.js → settlement-hook-ARYCZQY4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-LVAGKCEE.js → stage-O7T7CXBB.js} +2 -2
- package/dist/cli-bundle/main.js +25 -25
- 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 +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +58 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/extensions/index.d.ts +2 -0
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/fs/fs-utils.d.ts +3 -1
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/read.d.ts +11 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/stream-summary.d.ts +129 -0
- package/dist/core/history/stream-summary.js +3 -0
- package/dist/core/shared/errors.d.ts +8 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/text-normalization.d.ts +9 -0
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workspace-position.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/merge/index.d.ts +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.d.ts +20 -6
- package/dist/sdk/merge/install.js +3 -3
- package/dist/sdk/merge/worktree-config.js +2 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.d.ts +67 -5
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/context.d.ts +13 -3
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query.d.ts +1 -1
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output/continuation.d.ts +9 -3
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output-budget.d.ts +44 -3
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/docs/COMMANDS.md +56 -2
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/MUTATION_INTEGRITY.md +3 -1
- package/docs/PERFORMANCE.md +17 -2
- package/docs/README.md +6 -4
- package/docs/READ_OUTPUT_CONTRACTS.md +16 -1
- package/docs/SDK.md +25 -1
- package/docs/TESTING.md +8 -697
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +1 -1
- package/marketplace.json +1 -1
- package/package.json +6 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-5OFMWP3Q.js +0 -3
- package/dist/cli-bundle/chunks/chunk-723PMYNX.js +0 -125
- package/dist/cli-bundle/chunks/chunk-7UUPLMCU.js +0 -115
- package/dist/cli-bundle/chunks/chunk-H64BNM4A.js +0 -8
- package/dist/cli-bundle/chunks/chunk-OESI2ETD.js +0 -20
- package/dist/cli-bundle/chunks/chunk-VS565KBX.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-K4YZ7GWR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5JVB42Z7.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-7A4VIRIU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-A2CLYPDA.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HO2YUD4P.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-P4TG4VMJ.js +0 -12
- package/docs/MCP_2026_07_28_CONFORMANCE.md +0 -41
- package/docs/QUALITY_EVIDENCE.md +0 -130
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +0 -117
- package/docs/performance/cli-transport-overhead.md +0 -51
- package/docs/performance/runner-qualification.md +0 -36
- package/docs/performance/sdk-entrypoint-import-costs.md +0 -32
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
import type{PmReadOutputReceipt}from "./read-output-contracts.js";
|
|
2
2
|
/** Fixpoint bound for receipts whose estimate is part of the rendering it measures. */
|
|
3
3
|
export declare const MAX_ESTIMATE_ITERATIONS=8;
|
|
4
|
+
/** Hooks the trusted intent layer registers for one read-output pass. */
|
|
5
|
+
export interface ReadOutputPassHooks{
|
|
6
|
+
/**
|
|
7
|
+
* Result whose continuation collections bind this pass's output cursors
|
|
8
|
+
* (GH-1753): an intent read's uncompacted producer rows, cut to the prefix
|
|
9
|
+
* its first pass kept. The delivered rows may be string-compacted, and a
|
|
10
|
+
* settled intent read over its budget is projected again with the envelope
|
|
11
|
+
* overhead charged, keeping a shorter prefix; binding either would let
|
|
12
|
+
* compaction hide an edit or leave a cursor that a replay, whose first pass
|
|
13
|
+
* keeps the uncharged prefix, could never accept.
|
|
14
|
+
*/
|
|
15
|
+
continuationBinding?:Record<string,unknown>;
|
|
16
|
+
/**
|
|
17
|
+
* Copy each candidate estimate into a companion receipt that reports the
|
|
18
|
+
* same delivered envelope, so compaction measures the digits and fit flag
|
|
19
|
+
* that receipt will finally carry instead of a stale earlier estimate.
|
|
20
|
+
*/
|
|
21
|
+
mirrorEstimate?:(result:Record<string,unknown>,estimate:number)=> void;}
|
|
22
|
+
/** Register the hooks of the read-output pass invoked with exactly `options`. */
|
|
23
|
+
export declare function registerReadOutputPassHooks(options:Record<string,unknown>,hooks:ReadOutputPassHooks):void;
|
|
24
|
+
/** The hooks the intent layer registered for the pass invoked with `options`. */
|
|
25
|
+
export declare function resolveReadOutputPassHooks(options:Record<string,unknown>):ReadOutputPassHooks|undefined;
|
|
26
|
+
/** Settle `mirror` inside every estimate fixpoint of `receipt`. */
|
|
27
|
+
export declare function mirrorReadOutputReceiptEstimate(receipt:PmReadOutputReceipt,mirror:NonNullable<ReadOutputPassHooks["mirrorEstimate"]>):void;
|
|
4
28
|
/** Project a standard item read to brief depth, preserving metadata and disclosing every removed section. */
|
|
5
29
|
export declare function projectReadOutputItemToBrief(command:string,options:Record<string,unknown>,result:Record<string,unknown>):Record<string,unknown>|undefined;
|
|
6
30
|
/** Input to the deterministic finite-retry recommendation contract. */
|
|
@@ -36,7 +60,24 @@ export declare function readOutputMeasurementFormat(options:Record<string,unknow
|
|
|
36
60
|
export declare function withDeliveredOutputRenderer<T>(format:"json"|"toon",render:(result:unknown)=> string,run:()=> T):T;
|
|
37
61
|
/** Estimate UTF-8 token cost using the delivered JSON/TOON renderer, or compact JSON for structured SDK calls without a renderer. */
|
|
38
62
|
export declare function estimateReadOutputTokens(result:unknown,format?:"json"|"toon"):number;
|
|
39
|
-
/**
|
|
40
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Update a receipt to the fixed-point estimate of the result containing it,
|
|
65
|
+
* returning whether it converged. A renderer whose layout depends on the
|
|
66
|
+
* estimate need not converge; the bounded result is then no proof of fit.
|
|
67
|
+
*/
|
|
68
|
+
export declare function updateReadOutputReceiptEstimate(result:Record<string,unknown>,receipt:PmReadOutputReceipt,format?:"json"|"toon"):boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Settle a compaction candidate's estimate for a fit decision. The
|
|
71
|
+
* measurement grows with the digits of the estimates the page prints, so a
|
|
72
|
+
* page just above a power of ten can also be consistent one digit shorter
|
|
73
|
+
* (1000 and 999). Only when the settled estimate misses the budget there is
|
|
74
|
+
* the candidate settled again from zero, which rises to that smaller
|
|
75
|
+
* estimate; a candidate that fits, or misses by more than a digit can explain,
|
|
76
|
+
* keeps its estimate and costs no further rendering. Only a converged retry
|
|
77
|
+
* that fits is kept; any other restores the first estimate.
|
|
78
|
+
*/
|
|
79
|
+
declare function settleCandidateEstimate(result:Record<string,unknown>,receipt:PmReadOutputReceipt,budget:number,format:"json"|"toon"|undefined):void;
|
|
80
|
+
/** Internal hooks for estimate-settlement tests; not part of any public surface. */
|
|
81
|
+
export declare const _testOnly:{settleCandidateEstimate:typeof settleCandidateEstimate;};
|
|
41
82
|
/** Compact strings and rows in place, then return the final exact estimate. */
|
|
42
|
-
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,retainsTail?:(path:string)=> boolean):Record<string,unknown>;
|
|
83
|
+
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,retainsTail?:(path:string)=> boolean,surface?:string):Record<string,unknown>;export{};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="42dab49d-bb4e-558c-9cc1-3f50ac354f3b")}catch{}})();import{formatBuiltInOutput}from"../core/output/output.js";import{COMPACTED_STRING_LENGTH,compactExplanatoryString,isContinuationTokenKey,isTrackerItemDocumentKey}from"../core/shared/text-normalization.js";import{countReadOutputRows,readOutputBudgetCollections}from"./read-output-rows.js";const MAX_ESTIMATE_ITERATIONS=8,MAX_COMPACTION_ITERATIONS=64,RECOVERY_MARGIN_NUMERATOR=5,RECOVERY_MARGIN_DENOMINATOR=4,RECOVERY_ROUNDING_TOKENS=100,readOutputPassHooks=new WeakMap,readOutputEstimateMirrors=new WeakMap;function registerReadOutputPassHooks(options,hooks){readOutputPassHooks.set(options,hooks)}function resolveReadOutputPassHooks(options){return readOutputPassHooks.get(options)}function mirrorReadOutputReceiptEstimate(receipt,mirror){readOutputEstimateMirrors.set(receipt,mirror)}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===!0||options.tree===!0||options.depth!==void 0&&options.depth!=="standard")return;const item=result.item,sections=["linked","claim_state","schedule"],omitted=sections.filter(key=>Object.hasOwn(result,key)),projected=Object.fromEntries(Object.entries(result).filter(([key])=>!sections.includes(key)));projected.item=Object.fromEntries(Object.entries(item).filter(([key])=>key!=="body")),Object.hasOwn(item,"body")&&omitted.push("body");const groups=[...isRecord(result.omission_receipt)&&Array.isArray(result.omission_receipt.omitted_field_groups)?result.omission_receipt.omitted_field_groups:[],...omitted.map(name=>({name,restore_with:`--fields ${name}`}))];return projected.omission_receipt={has_omissions:groups.length>0,omitted_field_group_count:groups.length,omitted_field_groups:groups},projected}function resolveReadOutputRecoveryBudget(input){const binding=Math.trunc(input.effective_budget_tokens),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),withMargin=Math.ceil(baseline*RECOVERY_MARGIN_NUMERATOR/RECOVERY_MARGIN_DENOMINATOR),rounded=Math.ceil(withMargin/RECOVERY_ROUNDING_TOKENS)*RECOVERY_ROUNDING_TOKENS;return Number.isSafeInteger(rounded)?{output_budget:rounded,recovery_budget_multiplier:rounded/binding,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function preserveReadOutputRowContract(source,target,suppress=!1){const descriptor=Object.getOwnPropertyDescriptor(source,"row_contract");descriptor&&(suppress||descriptor.enumerable===!1)&&Object.defineProperty(target,"row_contract",{...descriptor,enumerable:!1})}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}let activeDeliveredOutput;function withDeliveredOutputRenderer(format,render,run){const previous=activeDeliveredOutput;activeDeliveredOutput={format,render};try{return run()}finally{activeDeliveredOutput=previous}}function estimateReadOutputTokens(result,format){const rendered=format===void 0?JSON.stringify(result):activeDeliveredOutput!==void 0&&activeDeliveredOutput.format===format?renderOutsideDeliveredScope(activeDeliveredOutput,result):formatBuiltInOutput(result,format);return Math.ceil(Buffer.byteLength(rendered,"utf8")/4)}function renderOutsideDeliveredScope(delivered,result){activeDeliveredOutput=void 0;try{return delivered.render(result)}finally{activeDeliveredOutput=delivered}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function compactStrings(value,state,preserveStrings=!1,exemptTokens=!0){return typeof value=="string"?preserveStrings?value:(value.length>COMPACTED_STRING_LENGTH&&(state.compacted=!0),compactExplanatoryString(value)):Array.isArray(value)?value.map(entry=>compactStrings(entry,state,preserveStrings,exemptTokens)):isRecord(value)?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactStrings(entry,state,preserveStrings||exemptTokens&&(key==="focus_row_states"||typeof entry=="string"&&isContinuationTokenKey(key)),exemptTokens)])):value}function updateReadOutputReceiptEstimate(result,receipt,format){let estimate=receipt.estimated_tokens;for(let iteration=0;iteration<MAX_ESTIMATE_ITERATIONS;iteration+=1){setReadOutputEstimate(result,receipt,estimate);const measured=estimateReadOutputTokens(result,format);if(measured===estimate)return!0;estimate=measured}return setReadOutputEstimate(result,receipt,estimate),!1}function setReadOutputEstimate(result,receipt,estimate){receipt.estimated_tokens=estimate,readOutputEstimateMirrors.get(receipt)?.(result,estimate)}const DIGIT_BOUNDARY_SLACK_TOKENS=4;function settleCandidateEstimate(result,receipt,budget,format){updateReadOutputReceiptEstimate(result,receipt,format);const estimate=receipt.estimated_tokens;estimate<=budget||estimate-10**(String(estimate).length-1)>=DIGIT_BOUNDARY_SLACK_TOKENS||(receipt.estimated_tokens=0,!(updateReadOutputReceiptEstimate(result,receipt,format)&&receipt.estimated_tokens<=budget)&&setReadOutputEstimate(result,receipt,estimate))}const _testOnly={settleCandidateEstimate};function selectCompactionCollection(result,minimumRowsByPath){return readOutputBudgetCollections(result).filter(collection=>(Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).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,retainsTail){for(let iteration=0;iteration<MAX_COMPACTION_ITERATIONS;iteration+=1){if(finalize?.(result),settleCandidateEstimate(result,receipt,budget,format),receipt.estimated_tokens<=budget)return;const candidate=selectCompactionCollection(result,minimumRowsByPath);if(!candidate)return;const minimumRows=Math.max(1,minimumRowsByPath.get(candidate.path)??0),values=Array.isArray(candidate.value)?[...candidate.value]:Object.entries(candidate.value),tail=retainsTail(candidate.path),retainRows=length=>{const start=tail?values.length-length:0;if(Array.isArray(candidate.value)){candidate.value.length=length;for(let index=0;index<length;index+=1)candidate.value[index]=values[start+index]}else{for(const key of Object.keys(candidate.value))delete candidate.value[key];Object.defineProperties(candidate.value,Object.getOwnPropertyDescriptors(Object.fromEntries(values.slice(start,start+length))))}typeof result.count=="number"&&(result.count=countReadOutputRows(result)),typeof result.returned_count=="number"&&(result.returned_count=countReadOutputRows(result)),candidate.path==="items"&&(result.applied_limit=length),finalize?.(result),settleCandidateEstimate(result,receipt,budget,format)};receipt.rows_compacted=!0,receipt.compacted_row_paths=[...new Set([...receipt.compacted_row_paths??[],candidate.path])].sort((left,right)=>left.localeCompare(right)),result.has_more=!0,result.truncated=!0;let low=minimumRows,high=values.length-1,retained=minimumRows;for(;low<=high;){const middle=Math.floor((low+high)/2);retainRows(middle),receipt.estimated_tokens<=budget?(retained=middle,low=middle+1):high=middle-1}retainRows(retained)}}function compactReadOutputToBudget(result,receipt,budget,minimumRowsByPath=new Map,format,finalize,preserveStrings=!1,retainsTail=()=>!1,surface){const stringCompactionState={compacted:!1},compacted=Object.fromEntries(Object.entries(result).map(([key,value])=>[key,compactStrings(value,stringCompactionState,preserveStrings&&key==="diff"||typeof value=="string"&&isContinuationTokenKey(key),!isTrackerItemDocumentKey(surface,key))]));return preserveReadOutputRowContract(result,compacted),receipt.strings_compacted=stringCompactionState.compacted,compacted.read_output=receipt,compactRowsToBudget(compacted,receipt,budget,minimumRowsByPath,format,finalize,retainsTail),updateReadOutputReceiptEstimate(compacted,receipt,format),compacted}export{MAX_ESTIMATE_ITERATIONS,_testOnly,compactReadOutputToBudget,estimateReadOutputTokens,mirrorReadOutputReceiptEstimate,preserveReadOutputRowContract,projectReadOutputItemToBrief,readOutputMeasurementFormat,registerReadOutputPassHooks,resolveReadOutputPassHooks,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate,withDeliveredOutputRenderer};
|
|
2
2
|
//# sourceMappingURL=read-output-budget.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2a596392-747a-5b55-854d-1e80964468d3")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS,PM_READ_OUTPUT_SURFACES}from"./read-output/options.js";import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand}from"./read-output/extension.js";import{BEHAVIOR_PRESERVING_MIGRATION_HINTS,LEGACY_FLAGS_BY_COMMAND,VALUE_BEARING_INCLUDE_ALIASES,flagSelector,optionKey,readOutputIncludeModeOptionsForSurface,resolveNativeReadOutputSurface}from"./read-output/surfaces.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,readOutputMeasurementFormat,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections,refreshReadOutputDeliveredCounts}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint,refreshReadOutputDeliveredRowCounters}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,readOutputRetainsTail}from"./read-output/tail-retention.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES as PM_READ_OUTPUT_TAIL_RETENTION_POLICIES2,readOutputRetainsTail as readOutputRetainsTail2}from"./read-output/tail-retention.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as PM_READ_OUTPUT_SURFACES2}from"./read-output/options.js";const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS;function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command]??{},dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":Object.hasOwn(PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,command)?"ordered_suffix":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptionsForSurface(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract)),SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase()),extension=resolveExtensionOutputCommand(normalizedCommand);return extension!==void 0?extension.read_output===void 0?void 0:`extension:${extension.command}`:resolveNativeReadOutputSurface(normalizedCommand,options)}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],HYBRID_READ_MUTATION_KEYS={comments:["add","body","comment","text","stdin","file","edit","delete"],notes:["add","note","text","addJson","stdin","file","edit","delete"],learnings:["add","learning","text","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>(parseReadOutputSession(value),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value=="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}],READ_OUTPUT_MUTATION_CONFLICT_CODE="read_output_mutation_conflict",READ_OUTPUT_SHAPING_CONTROLS=[{flag:"--output-include",keys:["outputInclude","output_include"]},{flag:"--output-limit",keys:["outputLimit","output_limit"]},{flag:"--output-budget",keys:["outputBudget","output_budget"]},{flag:"--output-session",keys:["outputSession","output_session"]},{flag:"--output-cursor",keys:["outputCursor","output_cursor"]},{flag:"--output-row-contract",keys:["outputRowContract","output_row_contract"]}],READ_OUTPUT_SHAPING_CONTROL_FLAGS=READ_OUTPUT_SHAPING_CONTROLS.map(({flag})=>flag);function readOutputMutationConflict(surface,options,mutationOptions){const present=READ_OUTPUT_SHAPING_CONTROLS.filter(({keys})=>keys.some(key=>options[key]!==void 0)),flags=present.map(({flag})=>flag),optionKeys=present.flatMap(({keys})=>keys.filter(key=>options[key]!==void 0)),listed=flags.join(", ");return new PmCliError(`Universal output controls (${listed}) cannot be combined with a ${surface} mutation; nothing was written.`,EXIT_CODE.USAGE,{code:"read_output_mutation_conflict",field:flags[0],details:{surface,output_controls:flags,output_option_keys:optionKeys,mutation_options:[...mutationOptions]},required:`Retry the ${surface} mutation without ${listed}. To bound or page the result, read it with those controls in a separate call after the write.`,why:"Universal output controls shape a read. A mutation returns its own bounded receipt, so the controls have nothing to shape and the write is refused before it runs.",examples:[...READ_OUTPUT_MUTATION_RETRY_EXAMPLES[surface]]})}const READ_OUTPUT_MUTATION_RETRY_EXAMPLES={comments:['pm comments <id> --add "<text>"',"pm comments <id> --output-limit 5"],notes:['pm notes <id> --add "<text>"',"pm notes <id> --output-limit 5"],learnings:['pm learnings <id> --add "<text>"',"pm learnings <id> --output-limit 5"],files:["pm files <id> --add path=<path>","pm files <id> --output-limit 5"],docs:["pm docs <id> --add path=<path>","pm docs <id> --output-limit 5"],"package-catalog":["pm package install <source> --project","pm package catalog --output-limit 5"]};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(Object.hasOwn(HYBRID_READ_MUTATION_KEYS,normalizedCommand)){const surface=normalizedCommand,mutationOptions=HYBRID_READ_MUTATION_KEYS[surface].filter(key=>options[key]!==void 0&&options[key]!==!1);if(mutationOptions.length>0)throw readOutputMutationConflict(surface,options,mutationOptions)}for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value))throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);return surface?readOutputIncludeModeOptionsForSurface(surface):new Map}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual,Object.hasOwn(options,"output_include")&&(options.output_include=residual)}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).flatMap(entry=>typeof entry=="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0)return{source:"canonical",value:canonicalLimit};if(!legacy)return;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0)return{source:"canonical",value:canonicalBudget};if(!legacy)return;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon")return{source:"canonical",value:canonical};if(legacy)return legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)return!explicitLegacyAliases.has(flag);const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance,options){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||isRequestedOption(readOption(options,"--no-truncate"))&&!shouldIgnoreReadOutputLegacyAlias(provenance,"amount","--no-truncate")||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand)??buildSurfaceContract(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)},legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance,options),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result),unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0)throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE);const fullItem=selectors.includes("item"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0)throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE);const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item:itemSelectors.length>0&&(projected.item=projectRecordFields(vocabulary.item,itemSelectors));const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get")return applyGetIncludeProjection(result,selectors);const rows=readOutputRowPaths(result),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount,command,collectionsBeforeBound){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount,path=>readOutputRetainsTail(command,path));if(!truncated)return bounded;if(bounded.has_more=!0,bounded.truncated=!0,attachTailRetentionTotal(bounded,command,[...collectionsBeforeBound.entries()].flatMap(([path,before])=>before.rows>amount?[{path,total_rows:before.totalRows}]:[])),typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return typeof bounded.returned_count=="number"&&(bounded.returned_count=countReadOutputRows(bounded)),bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens,previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format),preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate)return withSession}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).some(group=>isRecord(group)&&group.name==="diagnostic_rows"))return result;const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))],diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector=="string"?existingContract.jq_selector:".checks[].details"}}}function includeProjectionApplies(resolved,result){return resolved.include?.source==="canonical"&&!isReadResultOmittedForBudget(result)}function projectReadOutputRows(result,resolved,session,cursor,options){let projected={...result};if(includeProjectionApplies(resolved,result)&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,result,resolved.command,cursor,options);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value,resolved.command,continuationState.collectionsBeforeBudget),continuationState.cursorContinuesExistingPage&&rebaseCompactedProducerCursor(projected,continuationState.originalItems,continuationState.cursorSource,!0,continuationState.originalItemOffset)),refreshReadOutputDeliveredCounts(projected,continuationSource),refreshTailRetentionRowCounters(projected,resolved.command,continuationState),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default"||resolved.command==="context"&&resolved.cost.source==="legacy")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]].sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function hasContextIntentBudgetReceipt(result,tokens){return isRecord(result.context_intent)&&result.context_intent.command==="context"&&result.context_intent.token_budget===tokens&&result.context_intent.within_budget===!0}function requiresNextSelectionBudgetAudit(resolved,options,result){return resolved.command!=="next"||(options.tokenBudget??options.token_budget)===void 0?!1:!(isRecord(result.context_intent)&&result.context_intent.command==="next"&&result.context_intent.within_budget===!0)}function readOutputBudgetReceiptFields(budget,result={}){return budget?.source==="default"||budget?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,budget.tokens)?{budget_source:budget.source,budget_tokens:budget.tokens}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens)throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE);return boundedOmission}function requiresReadOutputAudit(resolved,options,result){return resolved.command==="context"&&resolved.cost?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,resolved.cost.value)||requiresNextSelectionBudgetAudit(resolved,options,result)||options.outputRowContract===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||isReadResultOmittedForBudget(result)||requiresReadOutputAudit(resolved,options,result))return!1;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"&&resolved.command!=="context"||estimateReadOutputTokens(options.outputRowContract===!1?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachTailRetentionTotal(projected,command,continuations){const policy=Object.hasOwn(PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,command)?PM_READ_OUTPUT_TAIL_RETENTION_POLICIES[command]:void 0,withheld=continuations.find(entry=>policy?.paths.includes(entry.path));policy!==void 0&&withheld!==void 0&&typeof projected[policy.total_key]!="number"&&(projected[policy.total_key]=withheld.total_rows)}function refreshTailRetentionRowCounters(delivered,command,continuationState){const path=PM_READ_OUTPUT_TAIL_RETENTION_POLICIES[command]?.paths[0];path!==void 0&&refreshReadOutputDeliveredRowCounters(delivered,command,continuationState.producer,continuationState.collectionsBeforeBudget.get(path)?.rows)}function buildReadOutputContinuation(command,path,before,retainedRows){const offset=before.backward?before.rows-retainedRows:before.baseOffset+retainedRows;return{path,cursor:encodeReadOutputContinuationCursor({command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint,...before.backward?{direction:"backward"}:{}}),retained_rows:retainedRows,remaining_rows:before.backward?offset:before.totalRows-offset,total_rows:before.totalRows}}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);return retainedRows>=before.rows?[]:[buildReadOutputContinuation(resolved.command,path,before,retainedRows)]}),primary=continuations[0];attachTailRetentionTotal(projected,resolved.command,continuations);const continuationHint=primary?"; page --output-cursor":"",budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});primary&&!continuationCursorRebased&&(typeof projected.next_cursor!="string"||projected.continuation_kind==="output_cursor")&&(projected.next_cursor=primary.cursor),projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none",projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseCompactedProducerCursor(projected,originalItems,cursorSource,cursorContinuesExistingPage,originalItemOffset){if(typeof cursorSource!="string"||!Array.isArray(projected.items))return!1;const retainedCount=projected.items.length,originalItemCount=originalItems.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=originalItems[retainedCount-1];if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+originalItemOffset+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}function captureReadOutputContinuationState(projected,source,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length,continued=cursor?.path===collection.path,backward=readOutputRetainsTail(command,collection.path);return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued&&!backward?cursor.offset:0,backward,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]})),cursorContinuesExistingPage=typeof projected.next_cursor=="string",originalItemOffset=cursor?.path==="items"?cursor.offset:0;return{collectionsBeforeBudget,originalItems:Array.isArray(source.items)?originalItemOffset>0?source.items.slice(originalItemOffset):source.items:[],originalItemOffset,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after,producer:source}}function compactReadOutputProjection(projected,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource),refreshTailRetentionRowCounters(compacted,resolved.command,continuationState);const continuationCursorRebased=rebaseCompactedProducerCursor(compacted,continuationState.originalItems,continuationState.cursorSource,continuationState.cursorContinuesExistingPage,continuationState.originalItemOffset);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff),path=>readOutputRetainsTail(resolved.command,path))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);const intentOmitted=isReadResultOmittedForBudget(projected),receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget,projected),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:!intentOmitted,strings_compacted:!1,rows_compacted:!1,result_omitted:intentOmitted};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isContextIntentResultOmitted(result){return isRecord(result)&&isRecord(result.context_intent)&&result.context_intent.result_omitted===!0}function isReadResultOmittedForBudget(result){return isReadOutputBudgetExceeded(result)||isContextIntentResultOmitted(result)}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES2 as PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,PM_READ_OUTPUT_TAIL_RETENTION_POLICIES2 as PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,READ_OUTPUT_MUTATION_CONFLICT_CODE,READ_OUTPUT_SHAPING_CONTROL_FLAGS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,isReadResultOmittedForBudget,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,readOutputRetainsTail2 as readOutputRetainsTail,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0456278a-5928-5a60-8d53-d12ffb1a7a5d")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS,PM_READ_OUTPUT_SURFACES}from"./read-output/options.js";import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand}from"./read-output/extension.js";import{BEHAVIOR_PRESERVING_MIGRATION_HINTS,LEGACY_FLAGS_BY_COMMAND,VALUE_BEARING_INCLUDE_ALIASES,flagSelector,optionKey,readOutputIncludeModeOptionsForSurface,resolveNativeReadOutputSurface}from"./read-output/surfaces.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,readOutputMeasurementFormat,projectReadOutputItemToBrief,preserveReadOutputRowContract,mirrorReadOutputReceiptEstimate,resolveReadOutputPassHooks,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections,refreshReadOutputDeliveredCounts}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint,refreshReadOutputDeliveredRowCounters}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,readOutputRetainsTail}from"./read-output/tail-retention.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES as PM_READ_OUTPUT_TAIL_RETENTION_POLICIES2,readOutputRetainsTail as readOutputRetainsTail2}from"./read-output/tail-retention.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as PM_READ_OUTPUT_SURFACES2}from"./read-output/options.js";const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS;function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command]??{},dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":Object.hasOwn(PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,command)?"ordered_suffix":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptionsForSurface(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract)),SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase()),extension=resolveExtensionOutputCommand(normalizedCommand);return extension!==void 0?extension.read_output===void 0?void 0:`extension:${extension.command}`:resolveNativeReadOutputSurface(normalizedCommand,options)}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],HYBRID_READ_MUTATION_KEYS={comments:["add","body","comment","text","stdin","file","edit","delete"],notes:["add","note","text","addJson","stdin","file","edit","delete"],learnings:["add","learning","text","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>(parseReadOutputSession(value),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value=="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}],READ_OUTPUT_MUTATION_CONFLICT_CODE="read_output_mutation_conflict",READ_OUTPUT_SHAPING_CONTROLS=[{flag:"--output-include",keys:["outputInclude","output_include"]},{flag:"--output-limit",keys:["outputLimit","output_limit"]},{flag:"--output-budget",keys:["outputBudget","output_budget"]},{flag:"--output-session",keys:["outputSession","output_session"]},{flag:"--output-cursor",keys:["outputCursor","output_cursor"]},{flag:"--output-row-contract",keys:["outputRowContract","output_row_contract"]}],READ_OUTPUT_SHAPING_CONTROL_FLAGS=READ_OUTPUT_SHAPING_CONTROLS.map(({flag})=>flag);function readOutputMutationConflict(surface,options,mutationOptions){const present=READ_OUTPUT_SHAPING_CONTROLS.filter(({keys})=>keys.some(key=>options[key]!==void 0)),flags=present.map(({flag})=>flag),optionKeys=present.flatMap(({keys})=>keys.filter(key=>options[key]!==void 0)),listed=flags.join(", ");return new PmCliError(`Universal output controls (${listed}) cannot be combined with a ${surface} mutation; nothing was written.`,EXIT_CODE.USAGE,{code:"read_output_mutation_conflict",field:flags[0],details:{surface,output_controls:flags,output_option_keys:optionKeys,mutation_options:[...mutationOptions]},required:`Retry the ${surface} mutation without ${listed}. To bound or page the result, read it with those controls in a separate call after the write.`,why:"Universal output controls shape a read. A mutation returns its own bounded receipt, so the controls have nothing to shape and the write is refused before it runs.",examples:[...READ_OUTPUT_MUTATION_RETRY_EXAMPLES[surface]]})}const READ_OUTPUT_MUTATION_RETRY_EXAMPLES={comments:['pm comments <id> --add "<text>"',"pm comments <id> --output-limit 5"],notes:['pm notes <id> --add "<text>"',"pm notes <id> --output-limit 5"],learnings:['pm learnings <id> --add "<text>"',"pm learnings <id> --output-limit 5"],files:["pm files <id> --add path=<path>","pm files <id> --output-limit 5"],docs:["pm docs <id> --add path=<path>","pm docs <id> --output-limit 5"],"package-catalog":["pm package install <source> --project","pm package catalog --output-limit 5"]};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(Object.hasOwn(HYBRID_READ_MUTATION_KEYS,normalizedCommand)){const surface=normalizedCommand,mutationOptions=HYBRID_READ_MUTATION_KEYS[surface].filter(key=>options[key]!==void 0&&options[key]!==!1);if(mutationOptions.length>0)throw readOutputMutationConflict(surface,options,mutationOptions)}for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value))throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);return surface?readOutputIncludeModeOptionsForSurface(surface):new Map}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual,Object.hasOwn(options,"output_include")&&(options.output_include=residual)}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).flatMap(entry=>typeof entry=="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0)return{source:"canonical",value:canonicalLimit};if(!legacy)return;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0)return{source:"canonical",value:canonicalBudget};if(!legacy)return;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon")return{source:"canonical",value:canonical};if(legacy)return legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)return!explicitLegacyAliases.has(flag);const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance,options){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||isRequestedOption(readOption(options,"--no-truncate"))&&!shouldIgnoreReadOutputLegacyAlias(provenance,"amount","--no-truncate")||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand)??buildSurfaceContract(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)},legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance,options),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result),unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0)throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE);const fullItem=selectors.includes("item"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0)throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE);const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item:itemSelectors.length>0&&(projected.item=projectRecordFields(vocabulary.item,itemSelectors));const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get")return applyGetIncludeProjection(result,selectors);const rows=readOutputRowPaths(result),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount,command,collectionsBeforeBound){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount,path=>readOutputRetainsTail(command,path));if(!truncated)return bounded;if(bounded.has_more=!0,bounded.truncated=!0,attachTailRetentionTotal(bounded,command,[...collectionsBeforeBound.entries()].flatMap(([path,before])=>before.rows>amount?[{path,total_rows:before.totalRows}]:[])),typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return typeof bounded.returned_count=="number"&&(bounded.returned_count=countReadOutputRows(bounded)),bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens,previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format),preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate)return withSession}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).some(group=>isRecord(group)&&group.name==="diagnostic_rows"))return result;const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))],diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector=="string"?existingContract.jq_selector:".checks[].details"}}}function includeProjectionApplies(resolved,result){return resolved.include?.source==="canonical"&&!isReadResultOmittedForBudget(result)}function prepareReadOutputContinuationSource(result,resolved){let projected={...result};return includeProjectionApplies(resolved,result)&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"?prioritizeAssuranceAssertions(projected):projected}function resolveReadOutputContinuationBindings(resolved,options){const binding=resolveReadOutputPassHooks(options)?.continuationBinding;if(binding===void 0)return;const source=prepareReadOutputContinuationSource(attachValidateDiagnosticRowContract(resolved.command,binding),resolved);return new Map(readOutputContinuationRowCollections(source).filter(collection=>!readOutputRetainsTail(resolved.command,collection.path)).map(collection=>[collection.path,collection]))}function projectReadOutputRows(result,resolved,session,cursor,options){let projected=prepareReadOutputContinuationSource(result,resolved);refreshReadOutputDeliveredCounts(projected,result);const bindings=resolveReadOutputContinuationBindings(resolved,options);if(projected=applyReadOutputContinuation(projected,resolved.command,cursor,bindings),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,result,resolved.command,cursor,options,bindings);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value,resolved.command,continuationState.collectionsBeforeBudget),continuationState.cursorContinuesExistingPage&&rebaseCompactedProducerCursor(projected,continuationState.originalItems,continuationState.cursorSource,!0,continuationState.originalItemOffset)),refreshReadOutputDeliveredCounts(projected,continuationSource),refreshTailRetentionRowCounters(projected,resolved.command,continuationState),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default"||resolved.command==="context"&&resolved.cost.source==="legacy")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]].sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function hasContextIntentBudgetReceipt(result,tokens){return isRecord(result.context_intent)&&result.context_intent.command==="context"&&result.context_intent.token_budget===tokens&&result.context_intent.within_budget===!0}function requiresNextSelectionBudgetAudit(resolved,options,result){return resolved.command!=="next"||(options.tokenBudget??options.token_budget)===void 0?!1:!(isRecord(result.context_intent)&&result.context_intent.command==="next"&&result.context_intent.within_budget===!0)}function readOutputBudgetReceiptFields(budget,result={}){return budget?.source==="default"||budget?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,budget.tokens)?{budget_source:budget.source,budget_tokens:budget.tokens}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens)throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE);return boundedOmission}function requiresReadOutputAudit(resolved,options,result){return resolved.command==="context"&&resolved.cost?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,resolved.cost.value)||requiresNextSelectionBudgetAudit(resolved,options,result)||options.outputRowContract===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||isReadResultOmittedForBudget(result)||requiresReadOutputAudit(resolved,options,result))return!1;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"&&resolved.command!=="context"||estimateReadOutputTokens(options.outputRowContract===!1?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachTailRetentionTotal(projected,command,continuations){const policy=Object.hasOwn(PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,command)?PM_READ_OUTPUT_TAIL_RETENTION_POLICIES[command]:void 0,withheld=continuations.find(entry=>policy?.paths.includes(entry.path));policy!==void 0&&withheld!==void 0&&typeof projected[policy.total_key]!="number"&&(projected[policy.total_key]=withheld.total_rows)}function refreshTailRetentionRowCounters(delivered,command,continuationState){const path=PM_READ_OUTPUT_TAIL_RETENTION_POLICIES[command]?.paths[0];path!==void 0&&refreshReadOutputDeliveredRowCounters(delivered,command,continuationState.producer,continuationState.collectionsBeforeBudget.get(path)?.rows)}function buildReadOutputContinuation(command,path,before,retainedRows){const offset=before.backward?before.rows-retainedRows:before.baseOffset+retainedRows;return{path,cursor:encodeReadOutputContinuationCursor({command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint,...before.backward?{direction:"backward"}:{}}),retained_rows:retainedRows,remaining_rows:before.backward?offset:before.totalRows-offset,total_rows:before.totalRows}}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);return retainedRows>=before.rows?[]:[buildReadOutputContinuation(resolved.command,path,before,retainedRows)]}),primary=continuations[0];attachTailRetentionTotal(projected,resolved.command,continuations);const continuationHint=primary?"; page --output-cursor":"",budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});primary&&!continuationCursorRebased&&(typeof projected.next_cursor!="string"||projected.continuation_kind==="output_cursor")&&(projected.next_cursor=primary.cursor),projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none",projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseCompactedProducerCursor(projected,originalItems,cursorSource,cursorContinuesExistingPage,originalItemOffset){if(typeof cursorSource!="string"||!Array.isArray(projected.items))return!1;const retainedCount=projected.items.length,originalItemCount=originalItems.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=originalItems[retainedCount-1];if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+originalItemOffset+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}function rowCount(value){return Array.isArray(value)?value.length:Object.keys(value).length}function captureReadOutputContinuationState(projected,source,command,cursor,options,bindings){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=rowCount(collection.value),continued=cursor?.path===collection.path,backward=readOutputRetainsTail(command,collection.path),bound=bindings?.get(collection.path)??collection;let fingerprint;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rowCount(bound.value),baseOffset:continued&&!backward?cursor.offset:0,backward,get fingerprint(){return fingerprint??=continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,bound.value,command),fingerprint}}]})),cursorContinuesExistingPage=typeof projected.next_cursor=="string",originalItemOffset=cursor?.path==="items"?cursor.offset:0;return{collectionsBeforeBudget,originalItems:Array.isArray(source.items)?originalItemOffset>0?source.items.slice(originalItemOffset):source.items:[],originalItemOffset,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after,producer:source}}function compactReadOutputProjection(projected,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource),refreshTailRetentionRowCounters(compacted,resolved.command,continuationState);const continuationCursorRebased=rebaseCompactedProducerCursor(compacted,continuationState.originalItems,continuationState.cursorSource,continuationState.cursorContinuesExistingPage,continuationState.originalItemOffset);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff),path=>readOutputRetainsTail(resolved.command,path),resolved.command)}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);const intentOmitted=isReadResultOmittedForBudget(projected),receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget,projected),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:!intentOmitted,strings_compacted:!1,rows_compacted:!1,result_omitted:intentOmitted};projected.read_output=receipt;const estimateMirror=resolveReadOutputPassHooks(options)?.mirrorEstimate;if(estimateMirror!==void 0&&mirrorReadOutputReceiptEstimate(receipt,estimateMirror),projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isContextIntentResultOmitted(result){return isRecord(result)&&isRecord(result.context_intent)&&result.context_intent.result_omitted===!0}function isReadResultOmittedForBudget(result){return isReadOutputBudgetExceeded(result)||isContextIntentResultOmitted(result)}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES2 as PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,PM_READ_OUTPUT_TAIL_RETENTION_POLICIES2 as PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,READ_OUTPUT_MUTATION_CONFLICT_CODE,READ_OUTPUT_SHAPING_CONTROL_FLAGS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,isReadResultOmittedForBudget,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,readOutputRetainsTail2 as readOutputRetainsTail,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
|
|
2
2
|
//# sourceMappingURL=read-output-contracts.js.map
|
package/docs/COMMANDS.md
CHANGED
|
@@ -188,7 +188,9 @@ pm list --status in_progress --assignee-filter unassigned --updated-before -72h
|
|
|
188
188
|
`pm health` prints these sweeps (with the configured status id and threshold)
|
|
189
189
|
as the remedies of its `in_progress_unowned`, `in_progress_idle` and
|
|
190
190
|
`stale_in_progress_items` advisories, and `pm context` counts
|
|
191
|
-
`in_progress_unowned` and `in_progress_idle` next to `in_progress`.
|
|
191
|
+
`in_progress_unowned` and `in_progress_idle` next to `in_progress`. All three
|
|
192
|
+
count items in the configured progress status, whatever role that status
|
|
193
|
+
carries, so neither advisory can exceed `in_progress` (GH-1756). The sweeps
|
|
192
194
|
select by `updated_at`, so they are candidate lists: an item restored within
|
|
193
195
|
the window keeps an older `updated_at` but recent history, and only
|
|
194
196
|
`--takeover-stale` applies the full activity clock.
|
|
@@ -1355,7 +1357,7 @@ Use dry-run modes before broad lifecycle or cleanup changes.
|
|
|
1355
1357
|
|
|
1356
1358
|
`pm gc --scope` accepts `index`, `embeddings`, `runtime`, `locks`, and `checkpoints`, comma-separated or repeated. Omitting the flag selects all scopes:
|
|
1357
1359
|
|
|
1358
|
-
- `runtime` clears `runtime/test-runs
|
|
1360
|
+
- `runtime` clears `runtime/test-runs/`, `runtime/history-drift-cache.json` and `runtime/history-stream-summary.json`. It never follows a link: a cache target that is one is retained with a `not_a_file` or `not_a_directory` warning, and when `runtime/` itself is a link, junction or file nothing under it is removed (`redirected_runtime_directory:runtime`). The next health check rescans history drift, and the next activity or context read parses every history stream once to rebuild the stream summary.
|
|
1359
1361
|
- `embeddings` removes keyword/semantic artifacts (`search/embeddings.jsonl`, `search/vectorization-status.json`, `search/lancedb/`) plus `search/pending-refresh.json` and its gate, preventing a background worker from rebuilding a partial index against an empty ledger. Rebuild with keyword reindex and semantic reindex when enabled.
|
|
1360
1362
|
- `locks` removes locks with an expired embedded `created_at + ttl_seconds` lease or positive same-host original-owner death evidence. It rechecks the observed receipt under the writer cleanup gate before deletion; replaced or initializing locks remain. Active, unreadable, or unparseable locks remain. The result reports `scanned`, `removed`, and `retained` counts.
|
|
1361
1363
|
|
|
@@ -1538,6 +1540,58 @@ metadata changes may also require a restart. Continuation does not retain a
|
|
|
1538
1540
|
persisted or atomic cross-file snapshot. Use `--from` for a starting timestamp;
|
|
1539
1541
|
`--since` refusals suggest that correction. Use an envelope (for example `--json`
|
|
1540
1542
|
without `--stream`) when paging: stream mode emits rows without cursor metadata.
|
|
1543
|
+
|
|
1544
|
+
On a tracker with 500 or more history streams, activity reads and the
|
|
1545
|
+
`pm context` activity section are bounded by their window instead of the
|
|
1546
|
+
history archive (GH-1664). A derived, gitignored
|
|
1547
|
+
`runtime/history-stream-summary.json` records each stream's entry count and
|
|
1548
|
+
oldest/newest timestamps under the stat signature (device, inode, size, mtime,
|
|
1549
|
+
ctime and the reader's credentials: effective user, group and supplementary
|
|
1550
|
+
groups on POSIX, the account name on Windows) of the open file that supplied
|
|
1551
|
+
the bytes, with a checksum over the file. A read skips a stream only while that
|
|
1552
|
+
signature is unchanged and the stream had not changed within two seconds of the
|
|
1553
|
+
read that recorded it, so appends, redaction, compaction, repair and restore
|
|
1554
|
+
all invalidate it without cooperation, and other POSIX credentials never reuse
|
|
1555
|
+
bounds for a stream they may not be allowed to read. Like the metadata cache,
|
|
1556
|
+
the summary trusts the filesystem's stat results: on Windows, processes of one
|
|
1557
|
+
account share it whatever their token, and a network mount that caches
|
|
1558
|
+
attributes can delay invalidation until its cache expires. Rows, totals, cursors and errors equal those of a complete read.
|
|
1559
|
+
A stream the window reaches is still parsed in full, so a read costs the size
|
|
1560
|
+
of the streams with entries in its window, not the size of the archive. Before
|
|
1561
|
+
it finishes, a bounded read re-stats the streams it skipped on their bounds and
|
|
1562
|
+
reads any that changed, a best-effort per-stream recheck. Like a complete read,
|
|
1563
|
+
it is not an atomic snapshot: a write that lands in a stream after that stream
|
|
1564
|
+
was read or rechecked is not reflected. The
|
|
1565
|
+
context activity section takes the newest rows directly and returns no
|
|
1566
|
+
cursor. When a read could not be bounded it adds `history_read` (context:
|
|
1567
|
+
`activity_history_read`) with `reason` (`summary_missing`, `summary_invalid`,
|
|
1568
|
+
`summary_stale` or `irregular_timestamps`, named by the larger cause, when
|
|
1569
|
+
streams lack usable regular bounds because they changed or hold timestamps that
|
|
1570
|
+
are not canonical millisecond UTC: more than half of all streams as the read
|
|
1571
|
+
opens, or, when the read parsed most streams, more than half of those it
|
|
1572
|
+
parsed; `read_hooks_active` when read hooks were active as the read opened or
|
|
1573
|
+
became active while it ran, which ends pruning (a hook active at open keeps the
|
|
1574
|
+
complete read in file order; one registered mid-read observes every stream the
|
|
1575
|
+
read has not yet read, exactly once, but a side effect it has on a stream the
|
|
1576
|
+
reordered read already parsed is not reflected); `unwindowed_query` when a
|
|
1577
|
+
read with no `--from` bound parsed most streams, or `window_reaches_most_streams`
|
|
1578
|
+
when current bounds still left most streams inside the window), `streams_read`
|
|
1579
|
+
(streams parsed; one removed after the listing is not counted) and
|
|
1580
|
+
`streams_total`; `--stream` carries it on the `meta` record, markdown context
|
|
1581
|
+
adds a `history read:` line, and NDJSON context, whose stdout carries focus rows
|
|
1582
|
+
only, writes `[pm] warning: activity_history_read reason=<reason>
|
|
1583
|
+
streams_read=<read>/<total>` to stderr. Bounded reads add nothing. On POSIX the summary file is written owner-only (mode 0600) and is
|
|
1584
|
+
trusted only when the reading user owns it and no one else can write it; on
|
|
1585
|
+
Windows it inherits the runtime directory's ACL. A summary in a redirected
|
|
1586
|
+
`runtime/` (symbolic link or junction), or any entry at the summary path that
|
|
1587
|
+
is not a regular file (a link, directory, FIFO or socket), is never read,
|
|
1588
|
+
written or replaced, and the read then computes no bounds at all; an oversized
|
|
1589
|
+
summary is never read. Like the context-usage ledger, the
|
|
1590
|
+
checks reject existing redirections and require trusted, stable workspace
|
|
1591
|
+
directories: portable Node APIs cannot pin `runtime/` against an actor that
|
|
1592
|
+
replaces it concurrently.
|
|
1593
|
+
Extensions with read hooks keep the complete read, so every stream read is
|
|
1594
|
+
still observed.
|
|
1541
1595
|
Workspace-scoped mutations to settings, schema, profiles, init state, and
|
|
1542
1596
|
extension/package activation are recorded in
|
|
1543
1597
|
`.agents/pm/history/_workspace.jsonl` using the same patch/hash format.
|
package/docs/MERGE_SAFETY.md
CHANGED
|
@@ -109,6 +109,14 @@ Removing a sibling worktree does not remove a separately installed main driver.
|
|
|
109
109
|
Use `pm merge install` in the affected worktree to repair stale, missing, or
|
|
110
110
|
incompatible commands. A dry run changes neither configuration nor attributes.
|
|
111
111
|
|
|
112
|
+
Attribute evidence stops at the active worktree's top level
|
|
113
|
+
([pm-gh1759](../.agents/pm/issues/pm-gh1759.toon)). Git never reads a
|
|
114
|
+
`.gitattributes` above it, so a matching fence in an enclosing, different
|
|
115
|
+
repository never satisfies `pm health`, `pm validate` or the workspace
|
|
116
|
+
position read: a linked worktree without its own fence reports
|
|
117
|
+
`merge_fence_missing`. A fence at the worktree root, or in a directory between
|
|
118
|
+
that root and the tracker, still counts.
|
|
119
|
+
|
|
112
120
|
### Fence coverage contract
|
|
113
121
|
|
|
114
122
|
Extension assets are tracked by [pm-gh1460](../.agents/pm/issues/pm-gh1460.toon).
|
|
@@ -104,7 +104,9 @@ time: it can include an item whose history is newer than its `updated_at`
|
|
|
104
104
|
(for example after a restore), which the advisory does not count;
|
|
105
105
|
`pm claim <id> --takeover-stale` re-judges each one under the item lock. `pm context` reports `in_progress_unowned`
|
|
106
106
|
and `in_progress_idle` next to `in_progress` in its summary when they are
|
|
107
|
-
non-zero, so unattended work is not read as active work.
|
|
107
|
+
non-zero, so unattended work is not read as active work. `in_progress` counts
|
|
108
|
+
the same population as both advisories: every item in the configured progress
|
|
109
|
+
status, whatever role that status carries (GH-1756).
|
|
108
110
|
|
|
109
111
|
A blocking secret policy may be bypassed only by an explicit `--force` on a
|
|
110
112
|
force-capable mutation. The warning records that an override occurred while
|
package/docs/PERFORMANCE.md
CHANGED
|
@@ -57,11 +57,26 @@ For a fast, deterministic one-item cold-start floor covering `get`, `list`,
|
|
|
57
57
|
pnpm benchmark:transport:check
|
|
58
58
|
```
|
|
59
59
|
|
|
60
|
-
The committed [CLI transport report](performance/cli-transport-overhead.md)
|
|
60
|
+
The committed [CLI transport report](https://github.com/unbraind/pm-cli/blob/main/docs/performance/cli-transport-overhead.md)
|
|
61
61
|
contains best/p50/p95 measurements and a stage breakdown. SDK entrypoint import
|
|
62
62
|
costs are independently gated with `pnpm benchmark:sdk-entrypoints:check` and
|
|
63
63
|
documented in the
|
|
64
|
-
[SDK entrypoint report](performance/sdk-entrypoint-import-costs.md).
|
|
64
|
+
[SDK entrypoint report](https://github.com/unbraind/pm-cli/blob/main/docs/performance/sdk-entrypoint-import-costs.md). The committed reports under `docs/performance/` are repository-only and excluded from npm.
|
|
65
|
+
|
|
66
|
+
Recent-activity reads are gated on history volume rather than item count
|
|
67
|
+
(GH-1664). `node scripts/bench/history-read-costs.mjs --check`, part of
|
|
68
|
+
`pnpm quality:static`, measures `pm context --for orient --limit 3` on a
|
|
69
|
+
fixture with 2,000 history streams and over 100 MiB of history, once with
|
|
70
|
+
trusted derived stream bounds and once with the summary path blocked before
|
|
71
|
+
every sample, which forces a complete traversal that persists nothing. The bounded p50 must stay below 0.6 of the same runner's full-scan p50;
|
|
72
|
+
on a qualified runner whose full scan exceeds the declared ceiling it must also
|
|
73
|
+
stay below that ceiling, and elsewhere the absolute check is reported as
|
|
74
|
+
unverified. See the
|
|
75
|
+
[history read report](https://github.com/unbraind/pm-cli/blob/main/docs/performance/history-read-costs.md). The bounds live in
|
|
76
|
+
`runtime/history-stream-summary.json`, a checksummed derived file trusted per
|
|
77
|
+
stream only while the stream's stat signature (device, inode, size, mtime,
|
|
78
|
+
ctime and the reader's credentials) is unchanged; it is safe to delete, and trackers
|
|
79
|
+
under 500 history streams never write it.
|
|
65
80
|
|
|
66
81
|
The metadata read cache is rebuildable derived state. Workspaces with at least
|
|
67
82
|
500 indexed items use its directory-validated fast path to avoid per-item
|
package/docs/README.md
CHANGED
|
@@ -22,7 +22,7 @@ pm guide release --json
|
|
|
22
22
|
| New user | [Quickstart](QUICKSTART.md) | [Command Reference](COMMANDS.md) |
|
|
23
23
|
| New maintainer | [Onboarding](ONBOARDING.md) | [Agent Guide](AGENT_GUIDE.md), [Testing](TESTING.md), [Releasing](https://github.com/unbraind/pm-cli/blob/main/docs/RELEASING.md) (repository-only, excluded from npm) |
|
|
24
24
|
| Coding agent | [Agent Guide](AGENT_GUIDE.md) | [Configuration](CONFIGURATION.md), then command help |
|
|
25
|
-
| Maintainer | [Contributing](../CONTRIBUTING.md) | [Testing](TESTING.md), [Releasing](https://github.com/unbraind/pm-cli/blob/main/docs/RELEASING.md) (repository-only, excluded from npm), [Architecture](ARCHITECTURE.md) |
|
|
25
|
+
| Maintainer | [Contributing](../CONTRIBUTING.md) | [Testing](TESTING.md), [Repository Testing](https://github.com/unbraind/pm-cli/blob/main/docs/REPOSITORY_TESTING.md) (repository-only, excluded from npm), [Releasing](https://github.com/unbraind/pm-cli/blob/main/docs/RELEASING.md) (repository-only, excluded from npm), [Architecture](ARCHITECTURE.md) |
|
|
26
26
|
| Package author | [Packages and Extensions](EXTENSIONS.md) | [SDK](SDK.md), [starter extension](examples/starter-extension/README.md) |
|
|
27
27
|
| Codex or ChatGPT plugin implementer | [Codex Plugin](CODEX_PLUGIN.md) | [Native ChatGPT and Codex Plugin Implementation Plan](https://github.com/unbraind/pm-cli/blob/main/docs/CHATGPT_CODEX_PLUGIN_IMPLEMENTATION.md) (repository-only, excluded from npm) |
|
|
28
28
|
| Codex user | [Codex Plugin](CODEX_PLUGIN.md) | [Agent Guide](AGENT_GUIDE.md), then [Command Reference](COMMANDS.md) |
|
|
@@ -43,7 +43,8 @@ pm guide release --json
|
|
|
43
43
|
- [CLI Scripting Contract](SCRIPTING.md) - exit codes, flat mutation receipts versus read envelopes, stdout/stderr boundaries, stable JSON fields, uniform OR filters, and shell composition recipes.
|
|
44
44
|
- [Configuration](CONFIGURATION.md) - settings, storage formats, output, search, validation, and environment variables.
|
|
45
45
|
- [Semantic Batching and Retrieval Quality](SEARCH_QUALITY.md) - independent request bounds, execution receipts, and per-query quality floors.
|
|
46
|
-
- [Testing](TESTING.md) - sandbox-safe
|
|
46
|
+
- [Testing](TESTING.md) - sandbox-safe linked-test orchestration.
|
|
47
|
+
- [Repository Testing](https://github.com/unbraind/pm-cli/blob/main/docs/REPOSITORY_TESTING.md) - this repository's own local checks, CI layout, coverage governance and release gates (repository-only, excluded from npm).
|
|
47
48
|
- [Faithful Package Acceptance](PACKAGE_GATE_ACCEPTANCE.md) - self-isolating package gates, independent Git snapshots, native diagnostics and isolated timing admission.
|
|
48
49
|
- [Completion Portability and Bounded Replication Checks](VALIDATION_PORTABILITY.md) - literal Bash choices across versions and locales, and semantic Git diff collection.
|
|
49
50
|
- [Build and Release Acceptance](BUILD_AND_RELEASE_ACCEPTANCE.md) - complete-build leases and cross-platform registry installation controls.
|
|
@@ -56,7 +57,7 @@ pm guide release --json
|
|
|
56
57
|
- [SDK Action and Boundary Conformance](SDK_ACTION_CONFORMANCE.md) - derived CLI/SDK/MCP action vocabulary, public-import ratchets, intent budget diagnostics, and package-runner proof.
|
|
57
58
|
- [MCP 2026-07-28 Protocol Decision](MCP_2026_07_28.md) - stateless request metadata, discovery, result envelopes, explicit legacy boundary, and migration policy.
|
|
58
59
|
- [Progressive Tool Discovery](PROGRESSIVE_TOOL_DISCOVERY.md) - opt-in bounded MCP catalogs, public SDK ranking and pagination, canonical results, and compatibility isolation.
|
|
59
|
-
- [MCP 2026-07-28 Conformance Matrix](MCP_2026_07_28_CONFORMANCE.md) - official revision changes mapped to canonical owners and executable evidence.
|
|
60
|
+
- [MCP 2026-07-28 Conformance Matrix](https://github.com/unbraind/pm-cli/blob/main/docs/MCP_2026_07_28_CONFORMANCE.md) - official revision changes mapped to canonical owners and executable evidence (repository-only, excluded from npm).
|
|
60
61
|
- [MCP Interaction and Task SDK](SDK_MCP_INTERACTIONS.md) - public MRTR continuation, cache/schema validation, and durable task-store contracts.
|
|
61
62
|
- [MCP Skills and Apps](MCP_SKILLS_AND_APPS.md) - negotiated draft workflow discovery, stable interactive views, digests, provenance, accessibility, and trust boundaries.
|
|
62
63
|
- [MCP Remote Transport, Authorization, and Migration](MCP_REMOTE_TRANSPORT_SECURITY.md) - Streamable HTTP operation, subscriptions, OAuth and trace boundaries, threat model, and deprecated-feature ratchet.
|
|
@@ -76,6 +77,7 @@ pm guide release --json
|
|
|
76
77
|
- [History Algorithms and Detached Attestations](HISTORY_ATTESTATION.md) - named record digests, portable exact-byte proofs, and read-only verification.
|
|
77
78
|
- [History-derived Governance Repair](HISTORY_GOVERNANCE_REPAIR.md) - verified closure timestamps and typed issue-code lineage.
|
|
78
79
|
- [History Maintenance and Recovery](HISTORY_MAINTENANCE.md) - native history commands, permanent aliases, shared SDK transforms, and transactional recovery.
|
|
80
|
+
- [History Durability and Recovery](HISTORY_RECOVERY.md) - history-only lifecycle reconstruction and recovery contracts.
|
|
79
81
|
- [Agent Recovery and Guidance](AGENT_RECOVERY_AND_GUIDANCE.md) - policy refusal evidence, canonical help, and managed instruction freshness.
|
|
80
82
|
- [Declarative Workflow Policies](WORKFLOW_POLICIES.md) - portable lifecycle requirements, independent approvals, and completeness reports.
|
|
81
83
|
- [Mutation Integrity](MUTATION_INTEGRITY.md) - shared CLI/SDK/MCP author, secret, append-only disposition, and stale-work guardrails.
|
|
@@ -123,7 +125,7 @@ Additional SDK, operations, and generated contracts:
|
|
|
123
125
|
- [SDK Runtime Boundaries](SDK_RUNTIME_BOUNDARIES.md) - runtime ownership and import boundaries.
|
|
124
126
|
- [Sentry Contract Epochs](SENTRY_CONTRACT_EPOCHS.md) - diagnostic compatibility and release epochs.
|
|
125
127
|
- [Generated Agent Command Surface](generated/AGENT_COMMAND_SURFACE.md) - command routing inventory.
|
|
126
|
-
- [Generated Flag Lexicon Budgets](generated/FLAG_LEXICON_BUDGETS.md) - flag vocabulary and budget inventory.
|
|
128
|
+
- [Generated Flag Lexicon Budgets](https://github.com/unbraind/pm-cli/blob/main/docs/generated/FLAG_LEXICON_BUDGETS.md) (repository-only, excluded from npm; `listPmFlagLexicon()` returns the same inventory) - flag vocabulary and budget inventory.
|
|
127
129
|
|
|
128
130
|
## Guide Topic Map
|
|
129
131
|
|
|
@@ -358,7 +358,7 @@ rows; it can never leave the packer's earlier inclusions marked as served.
|
|
|
358
358
|
`PmClient` finalizes the receipt before resolving, while the CLI finalizes it
|
|
359
359
|
from the exact active result passed to telemetry and after-command hooks.
|
|
360
360
|
|
|
361
|
-
String compaction shortens an explanatory string longer than 240 UTF-16 code units to a Unicode-safe prefix followed by the compaction marker `…[+N chars]`, where `N` is the number of code units left out. The marker is the write-side signal: `pm comments`, `pm notes` and `pm learnings` refuse an `--edit` whose replacement text ends with it (`annotation_text_compacted`, exit 2, nothing written), because that text came from a compacted read and would replace the stored entry with the prefix. Re-read the entry with `--output-budget unbounded`, apply the change to the full text, and retry; a bare trailing ellipsis is ordinary text and is accepted. A continuation token is never compacted: any string under a `cursor` key or a key ending in `_cursor` (`next_cursor`, `output_cursor`, `source_cursor`, ...) is emitted whole in JSON and TOON, with or without `--for`. A cursor argument that still carries an ellipsis is refused with `invalid_query_cursor` (or `read_output_cursor_invalid` for `--output-cursor`) and the reason `cursor_compacted`, naming the larger-budget read that returns it whole.
|
|
361
|
+
String compaction shortens an explanatory string longer than 240 UTF-16 code units to a Unicode-safe prefix followed by the compaction marker `…[+N chars]`, where `N` is the number of code units left out. The marker is the write-side signal: `pm comments`, `pm notes` and `pm learnings` refuse an `--edit` whose replacement text ends with it (`annotation_text_compacted`, exit 2, nothing written), because that text came from a compacted read and would replace the stored entry with the prefix. Re-read the entry with `--output-budget unbounded`, apply the change to the full text, and retry; a bare trailing ellipsis is ordinary text and is accepted. A continuation token is never compacted: any string under a `cursor` key or a key ending in `_cursor` (`next_cursor`, `output_cursor`, `source_cursor`, ...) is emitted whole in JSON and TOON, with or without `--for`. The exemption covers the envelope and its sections, not tracker item documents: on the native item reads `get`, `list` and `search`, the fields of `item` and of every `items` row are item content, so a custom field named like a continuation key (`sync_cursor`, `next_cursor`) compacts like any other string and a budgeted page still returns its rows. Every other surface keeps the exemption at any depth, including an extension that declares `items` rows, because its rows may carry genuine tokens. A cursor argument that still carries an ellipsis is refused with `invalid_query_cursor` (or `read_output_cursor_invalid` for `--output-cursor`) and the reason `cursor_compacted`, naming the larger-budget read that returns it whole.
|
|
362
362
|
|
|
363
363
|
When rows are dropped to satisfy a ceiling, the result also carries `output_budget_truncation`, naming the binding budget and its source, any explicitly requested dimension the budget overrode, every compacted collection path, and executable CLI/SDK/MCP recovery options — a default ceiling can override an explicit `--output-limit unbounded`, and that override is reported rather than silent. If a producer supplied an opaque item-page cursor, compaction rebases it to the last row actually returned and reports `continuation_cursor_rebased: true`; following the cursor therefore cannot skip rows removed from the middle of a producer page. If no useful content can fit, `PmReadOutputBudgetExceeded` provides a discriminated omission result, a compact `{ outputBudget: "unbounded" }` recovery object, and `omitted_result_estimated_tokens`, the last useful-result estimate before omission; use `isReadOutputBudgetExceeded` before accessing result-specific fields. The encoding control `--output-format <toon|json>` also applies to mutation envelopes, including the mutation modes of `comments`, `notes`, `files`, and `docs`. Other universal read controls remain rejected before mutation execution. `--json` remains supported.
|
|
364
364
|
|
|
@@ -389,6 +389,21 @@ an unbounded multi-megabyte response;
|
|
|
389
389
|
`recovery_budget_multiplier: 1` declares that each next page retains the same
|
|
390
390
|
useful-result ceiling.
|
|
391
391
|
|
|
392
|
+
An intent read (`--for`) binds its output cursors to the producer's
|
|
393
|
+
uncompacted rows, cut to the prefix its intent projection keeps before any
|
|
394
|
+
envelope overhead is charged. That is the collection an unchanged replay
|
|
395
|
+
rebuilds, and because the fingerprint covers the uncompacted text, string
|
|
396
|
+
compaction cannot hide an edit in an omitted suffix. Row compaction measures the intent
|
|
397
|
+
receipt with the estimate it will finally report, so the settled envelope fits
|
|
398
|
+
the budget it was compacted to. When a settled envelope still exceeds the intent
|
|
399
|
+
budget and is projected again with that overhead charged, the second pass
|
|
400
|
+
delivers a shorter prefix, but its cursors keep the first pass's row count and
|
|
401
|
+
fingerprint. A replay therefore resumes right after the last delivered row, and
|
|
402
|
+
`read_output_cursor_stale` stays reserved for a changed source. An output
|
|
403
|
+
cursor issued by 2026.11.19 or earlier over a string-compacted intent page
|
|
404
|
+
fingerprinted the compacted rows, so after upgrading it fails closed with
|
|
405
|
+
`read_output_cursor_stale`; restart the bounded read without the cursor.
|
|
406
|
+
|
|
392
407
|
Chronological annotation collections keep their newest rows instead
|
|
393
408
|
([pm-8s53lj](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8s53lj.toon);
|
|
394
409
|
tracker record excluded from npm). `PM_READ_OUTPUT_TAIL_RETENTION_POLICIES`
|
package/docs/SDK.md
CHANGED
|
@@ -129,7 +129,7 @@ surface change. The bare
|
|
|
129
129
|
`@unbrained/pm-cli` root export is recorded as an `aggregate_alias` of
|
|
130
130
|
`@unbrained/pm-cli/sdk`: its symbols are not duplicated, but a retarget of its
|
|
131
131
|
declaration path is a snapshot change. The committed
|
|
132
|
-
[entrypoint import-cost table](performance/sdk-entrypoint-import-costs.md)
|
|
132
|
+
[entrypoint import-cost table](https://github.com/unbraind/pm-cli/blob/main/docs/performance/sdk-entrypoint-import-costs.md) (repository-only, excluded from npm)
|
|
133
133
|
records fresh-process latency, RSS, and reduction versus the aggregate barrel.
|
|
134
134
|
Every narrow entrypoint is bundled and type-tested independently.
|
|
135
135
|
|
|
@@ -830,6 +830,30 @@ Content fingerprints hash canonical rows incrementally, bounding additional
|
|
|
830
830
|
serialization storage to the largest row. Digest activity also hashes its full
|
|
831
831
|
source events incrementally so hidden patch changes still invalidate a cursor.
|
|
832
832
|
|
|
833
|
+
On a tracker with 500 or more history streams, `runActivity` parses only the
|
|
834
|
+
streams its window can reach, using derived per-stream bounds that are trusted
|
|
835
|
+
only while each stream's stat signature is unchanged; rows, totals, cursors and
|
|
836
|
+
errors are those of a complete read. A stream the window reaches is parsed in
|
|
837
|
+
full, so the cost follows the streams with entries in the window, not the
|
|
838
|
+
archive. A read that could not be bounded carries
|
|
839
|
+
`history_read: { reason, streams_read, streams_total }`, where `reason` is
|
|
840
|
+
`summary_missing`, `summary_invalid`, `summary_stale` or
|
|
841
|
+
`irregular_timestamps` (named by the larger cause, when more than half of all
|
|
842
|
+
streams lack usable regular bounds as the read opens, or when the read parsed
|
|
843
|
+
most streams and more than half of those it parsed were stale or irregular),
|
|
844
|
+
`read_hooks_active` (read hooks were active when the read opened, or became
|
|
845
|
+
active while it ran, which ends pruning), `unwindowed_query`
|
|
846
|
+
(no `from` bound and most streams parsed; pass one to bound the read), or
|
|
847
|
+
`window_reaches_most_streams` (current bounds, but the window still reached
|
|
848
|
+
most streams).
|
|
849
|
+
`readRecentActivity({ limit }, global)` returns the newest compact rows (the
|
|
850
|
+
first page of `raw: true`) without totals or a cursor. `limit` caps the rows
|
|
851
|
+
returned, not the streams parsed: with usable stream bounds and no active read
|
|
852
|
+
hooks it prunes streams that cannot reach those rows, while under 500 streams
|
|
853
|
+
or with read hooks it parses every stream. `pm context` builds its activity
|
|
854
|
+
section with it and reports a fallback as `activity_history_read`. Repository tracking:
|
|
855
|
+
[pm-gh1664](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1664.toon).
|
|
856
|
+
|
|
833
857
|
`runCalendar` uses the same `after` contract and frozen clock. `total_count`
|
|
834
858
|
counts matching expanded rows within the selected window and recurrence caps;
|
|
835
859
|
`count`, `page_start`, `omitted_count`, `has_more`, and `next_cursor` describe
|