@unbrained/pm-cli 2026.10.30 → 2026.10.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +32 -0
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.d.ts +45 -5
- package/dist/cli/error-guidance.js +5 -3
- package/dist/cli/extension-command-help.d.ts +1 -0
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli/main.d.ts +1 -5
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.d.ts +1 -1
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/preflight-warnings.d.ts +11 -0
- package/dist/cli/preflight-warnings.js +4 -0
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-24J6TNYE.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-EHBGHX55.js → chunk-2AHSPMKJ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MVL27TAH.js → chunk-35Q2B2GJ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-43R7UTWV.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6PSDQ7T7.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-UUQX3PFD.js → chunk-BS2KXT24.js} +70 -70
- package/dist/cli-bundle/chunks/{chunk-Y6NC3X3E.js → chunk-GMBDZID5.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-HSBTITO4.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-LWW4F4G2.js → chunk-MRUA2Z43.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-P3LNMWL2.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-S2U7ECUJ.js → chunk-PT7TS6E7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TH5KPAN4.js → chunk-SBVX5CMV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4BQD5SW2.js → chunk-TL3O5GZA.js} +30 -30
- package/dist/cli-bundle/chunks/chunk-U7JXZMU5.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-GRABKNFL.js → chunk-V6EWBTNH.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VC7TA67O.js +20 -0
- package/dist/cli-bundle/chunks/chunk-WNF6FOL7.js +31 -0
- package/dist/cli-bundle/chunks/chunk-WRXQAW7Q.js +114 -0
- package/dist/cli-bundle/chunks/{chunk-RZQNFHXO.js → chunk-WX25MU4N.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-XDDPSWIW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YT5D5HNG.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ZTJVOBDU.js +128 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-LHLE7PSG.js → indexed-receipt-blobs-KGMJVFH2.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-UWV6UNSV.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-TRGAVS7N.js → mutation-admission-I4RHIT3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-BH4F6M7Z.js → register-list-query-MVDL5EXG.js} +3 -3
- package/dist/cli-bundle/chunks/register-mutation-GAF7LXRB.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-JLFRL36Q.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-QPWSVHFZ.js → register-setup-MZN6ONB3.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-MN3Y7LVX.js → settlement-hook-YWSWFOZY.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-RTB6RAAO.js → stage-2ZORTOF6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-S23ZUASN.js → chunk-2J7T2UCH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4QPGJO2G.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-YU7QOYYV.js → chunk-57HPXGOQ.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-5MCGYBOQ.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-6F6APBCX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AFVN2KCP.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RKPUQDWF.js → chunk-DFUTCKUF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EA65HVBO.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-GP2WU43K.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-YQUZL2CK.js → chunk-HPWT3RBG.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-HSAEEWSI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BPE6JTKL.js → chunk-JLXGRDTG.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-FRFNGMAK.js → chunk-JNKRUCVZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BCIUAEWX.js → chunk-KH5QJXY7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KKRIFBSL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RGQEJFXO.js → chunk-MW77Q3AQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NOKG4RFN.js +22 -0
- package/dist/cli-bundle/focused-chunks/{chunk-POJPJX64.js → chunk-NRBUMDLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3SRX77ES.js → chunk-PC3R5CJV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RYEZSZJ7.js → chunk-PFBQOZPK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SAT7IAEB.js → chunk-QFMJGQGO.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-VFWCSQAG.js → chunk-SFQKCA5K.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WHIE2C6Q.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y6UYRMVG.js +6 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-VK2363JB.js → indexed-receipt-blobs-KHWT44EK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-LU75EG7D.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-admission-7VUODEPJ.js → mutation-admission-KDJ7SCPA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-OK6A7PG2.js → settlement-hook-SJV52ZTV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-S5RP5SZH.js → stage-R4KEBO37.js} +2 -2
- package/dist/cli-bundle/main.js +26 -22
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +4 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/output.js +2 -2
- package/dist/core/schema/fields-file.js +1 -1
- package/dist/core/sentry/helpers.d.ts +6 -0
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.d.ts +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/errors.d.ts +6 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/output-unicode.d.ts +10 -0
- package/dist/core/shared/output-unicode.js +2 -0
- package/dist/core/store/settings-validator.d.ts +1 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/core/telemetry/policy.d.ts +8 -0
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/runtime.js +3 -3
- package/dist/sdk/agent/command-recovery.d.ts +15 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +28 -0
- package/dist/sdk/cli-contracts/agent-output-contracts.js +2 -2
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion/fish.js +4 -4
- package/dist/sdk/completion/zsh.js +3 -3
- package/dist/sdk/config.d.ts +1 -0
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/core.d.ts +1 -0
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/error-runtime.d.ts +9 -0
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/index.d.ts +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/plan.d.ts +2 -3
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/repeated-terminal-state.d.ts +45 -0
- package/dist/sdk/lifecycle/repeated-terminal-state.js +2 -0
- package/dist/sdk/lifecycle/shared-unset-fields.d.ts +9 -0
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/update-many.d.ts +0 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +29 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/output/table-rows.d.ts +7 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.d.ts +18 -0
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/get.d.ts +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/next-ranking-policy.d.ts +35 -0
- package/dist/sdk/query/next-ranking-policy.js +2 -0
- package/dist/sdk/query/next.d.ts +12 -2
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/projection-contracts.d.ts +4 -0
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/surfaces.d.ts +27 -0
- package/dist/sdk/read-output/surfaces.js +2 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution-receipts.d.ts +25 -0
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.d.ts +5 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_OUTPUT_ENCODINGS.md +12 -0
- package/docs/AGENT_UX_CONTRACTS.md +2 -1
- package/docs/COMMANDS.md +58 -5
- package/docs/CONFIGURATION.md +48 -1
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -0
- package/docs/PACKED_FIRST_RUN.md +2 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +24 -6
- package/docs/SDK.md +73 -2
- package/docs/TESTING.md +38 -2
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
- 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-34MP7WKK.js +0 -6
- package/dist/cli-bundle/chunks/chunk-3KMYHYJV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-42BHHNTL.js +0 -128
- package/dist/cli-bundle/chunks/chunk-I5O3XZOA.js +0 -2
- package/dist/cli-bundle/chunks/chunk-LEIVUGDH.js +0 -8
- package/dist/cli-bundle/chunks/chunk-OH7WPD42.js +0 -114
- package/dist/cli-bundle/chunks/chunk-OOD2A7AF.js +0 -20
- package/dist/cli-bundle/chunks/chunk-Q5V7P6NM.js +0 -2
- package/dist/cli-bundle/chunks/chunk-QLPFYBXN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SA5NYLPE.js +0 -8
- package/dist/cli-bundle/chunks/chunk-VHLAVTJN.js +0 -31
- package/dist/cli-bundle/chunks/chunk-XAOVJG52.js +0 -3
- package/dist/cli-bundle/chunks/chunk-XPQ4RTSF.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-WIOBZW4E.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-5V2NANIS.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-XSFRMUFX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2V6NMNYN.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-ASHGXMX4.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-CKBN2D42.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-I642DXOT.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-K7DKG5HM.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-NMQBXU7N.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-PGM3ENGZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QFNV4JTA.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-QVJCQMZY.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-R2TPPPVU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VJVJ2ZX2.js +0 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-ZFDKJIP7.js +0 -2
package/dist/sdk/query/get.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { type ResolvedBlocker } from "../actionability.js";
|
|
|
4
4
|
import { type ChildRollupContext } from "../item-children.js";
|
|
5
5
|
import { type ItemScheduleContext } from "../item-schedule.js";
|
|
6
6
|
import type { ItemMetadata,Dependency,LinkedDoc,LinkedFile,LinkedTest } from "../../types/index.js";
|
|
7
|
-
export { GET_DEPTH_VALUES,listGetProjectionFields,} from "./projection-contracts.js";
|
|
7
|
+
export { GET_DEPTH_INPUT_VALUES,GET_DEPTH_VALUES,listGetProjectionFields,} from "./projection-contracts.js";
|
|
8
8
|
/** Latest claim or release coordinate exposed without its mutation patch. */
|
|
9
9
|
interface ClaimHistoryContext {
|
|
10
10
|
ts:string;
|
package/dist/sdk/query/get.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1815b206-18b5-5e76-b863-8b0f8ac2947a")}catch{}})();import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{readdir}from"node:fs/promises";import path from"node:path";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{createPmCliExpectedError}from"../errors.js";import{collectBlockedByIds,resolveItemBlockers}from"../actionability.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../../core/item/dependency-reference.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]),BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]))}function itemMaterialFieldGroups(item,body,children,currentSnapshot,projection){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee=="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[],...currentSnapshot&&collectBlockedByIds(item).length>0?["blockers"]:[],...!projection.full&&item.dependencies?.some(({id:_id,kind:_kind,...provenance})=>Object.values(provenance).some(value=>value!==void 0))?["dependency_provenance"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim(),normalizedAssignee=assignee&&assignee.length>0?assignee:null,lastClaim=[...history].reverse().find(entry=>entry.op==="claim"),lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0)return"standard";const normalized=raw.trim().toLowerCase();if(normalized==="full")return"deep";if(GET_DEPTH_VALUES.includes(normalized))return normalized;throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE,{field:"depth",value:raw,recovery:{allowed_values:[...GET_DEPTH_VALUES,"full"]}})}function projectItemForDepth(item,depth,full){const collectionCounts=itemCollectionCounts(item),projectedItem={...item};if(!full&&item.dependencies!==void 0&&(projectedItem.dependencies=item.dependencies.map(({id,kind})=>({id,kind}))),depth==="deep")return{...projectedItem,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts};const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=projectedItem;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0)return null;const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0)throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice(5):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null)return;const allowedValues=listGetProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues),unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){return Object.hasOwn(counts,field)?counts[field]:source[field]!==void 0?source[field]:EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item),omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)},projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")||normalized==="blockers"||(projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized))}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??!1}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0))throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}});if(options.tree!==!0&&options.treeDepth!==void 0)throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE);if(options.at!==void 0&&options.tree===!0)throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE);return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===!0||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===!0?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder);const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=[...resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key),...collectRegisteredItemFieldNames(getActiveExtensionRegistrations())];if(validateGetFields(fields,runtimeMetadataKeys,id),historical&&fieldsIncludeRoot(fields??[],"children"))throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE);if(historical&&fieldsIncludeRoot(fields??[],"blockers"))throw new PmCliError("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",EXIT_CODE.USAGE)}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;return fieldProjection?field==="body"||field==="linked"?fieldsInclude(fields,field):fieldsIncludeRoot(fields,field):depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState)return;const historyPath=getHistoryPath(context.pmRoot,context.locatedId),history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files"),includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests"),includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs||(result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]})}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren)return;const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema),corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function canonicalizeDeclaredBlockers(blockers,targets){const canonical=new Map;for(const blocker of blockers){const id=blocker.external?blocker.id:targets.get(blocker.id.toLowerCase())?.id??blocker.id;canonical.set(blocker.external?`external:${id}`:`local:${id.toLowerCase()}`,{...blocker,id})}return[...canonical.values()]}async function resolvePhysicalBlockerId(itemPath,probedId){const filename=path.basename(itemPath),physicalId=(await readdir(path.dirname(itemPath)).catch(error=>{throw createPmCliExpectedError("Cannot verify the blocker's physical file identity",{exitCode:EXIT_CODE.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:error})})).filter(name=>name.toLowerCase()===filename.toLowerCase()).sort((left,right)=>+(right===filename)-+(left===filename)||left.localeCompare(right)).map(name=>path.parse(name).name)[0];if(physicalId===void 0)throw new PmCliError(`Blocker canonical file disappeared during identity verification: ${probedId}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return physicalId}async function attachGetBlockers(result,context,projection){if(context.historical!==void 0||!(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"blockers"):projection.depth!=="brief"))return;const ids=collectBlockedByIds(context.metadata);if(ids.length===0)return;const declaredIds=new Map([context.metadata.blocked_by,...(context.metadata.dependencies??[]).filter(dependency=>dependency.kind==="blocked_by").map(dependency=>dependency.id)].filter(id=>typeof id=="string").map(id=>[id.trim().toLowerCase(),id.trim()])),targets=new Map;for(const id of ids){if(isExternalDependencyReference(id)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(id)||context.metadata.dependencies?.some(dependency=>dependency.id.trim()===id&&dependency.kind==="blocked_by"&&isExternalDependencySourceKind(dependency.source_kind)))continue;const located=await locateItem(context.pmRoot,declaredIds.get(id),context.settings.id_prefix,context.settings.item_format,context.typeToFolder);if(located===null)continue;const loaded=await readLocatedItem(located,{schema:context.settings.schema});if(located.id=await resolvePhysicalBlockerId(located.itemPath,located.id),loaded.document.metadata.id!==located.id)throw new PmCliError(`Blocker identity differs from its canonical file: ${located.id}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});targets.set(id.toLowerCase(),loaded.document.metadata)}const resolved=canonicalizeDeclaredBlockers(resolveItemBlockers({blocked_by:context.metadata.blocked_by,dependencies:context.metadata.dependencies,updated_at:context.metadata.updated_at},targets,resolveRuntimeStatusRegistry(context.settings.schema)),targets);result.blockers={scope:"declared",open:resolved.filter(blocker=>!blocker.resolved).map(({resolved:_resolved,...blocker})=>blocker),closed_count:resolved.filter(blocker=>blocker.resolved).length},!projection.fieldProjection&&!projection.full&&delete result.item.blocked_by}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule)return;const schedule=buildItemSchedule(context.metadata);if(schedule){if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==!0)return;const subtree=await runList(void 0,{parent:context.locatedId,tree:!0,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:!0},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id),context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"}),includeLinked=shouldIncludeGetField({...projection,field:"linked"}),includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"}),includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type))),includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief",claimState=await resolveGetClaimState(context,includeClaimState),result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth,projection.full)};includeBody&&(result.item.body=context.body),attachGetLinked(result,context,projection.fields,includeLinked),claimState&&(result.claim_state=claimState),attachGetSchedule(result,context,projection.fields,includeSchedule),await attachGetBlockers(result,context,projection);const children=await buildGetChildrenRollup(context,includeChildren);children!==void 0&&(result.children=children);const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0&&(result.tree=tree),context.historical&&(result.reconstructed=!0,result.as_of_version=context.historical.as_of_version,result.as_of_timestamp=context.historical.as_of_timestamp),context.historical===void 0)try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}return registerOutputMaterialFieldGroups(result,projection.fieldProjection?[]:itemMaterialFieldGroups(context.metadata,context.body,children,context.historical===void 0,projection)),result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
|
|
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]="bf7cac44-d2fc-5e7c-a9f1-a82c7460b07c")}catch{}})();import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{readdir}from"node:fs/promises";import path from"node:path";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,toItemRecord,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,TYPE_TO_FOLDER,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,getHistoryPath,resolvePmRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{renderPmCommand}from"../command-line.js";import{recordContextUsageTouches}from"../context-usage.js";import{createPmCliExpectedError}from"../errors.js";import{collectBlockedByIds,resolveItemBlockers}from"../actionability.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../../core/item/dependency-reference.js";import{buildItemChildrenRollup}from"../item-children.js";import{buildItemSchedule}from"../item-schedule.js";import{getItemAt}from"../history-read.js";import{parseIntegerLimit}from"./parsers.js";import{runList}from"./list.js";import{registerOutputMaterialFieldGroups}from"../output-projection.js";import{GET_DEPTH_INPUT_VALUES,GET_DEPTH_VALUES,listGetProjectionFields}from"./projection-contracts.js";import{GET_DEPTH_INPUT_VALUES as GET_DEPTH_INPUT_VALUES2,GET_DEPTH_VALUES as GET_DEPTH_VALUES2,listGetProjectionFields as listGetProjectionFields2}from"./projection-contracts.js";const AUTOMATIC_CHILD_ROLLUP_TYPES=new Set(["epic","feature","milestone","plan"]),BUILTIN_ITEM_TYPES=new Set(Object.keys(TYPE_TO_FOLDER).map(type=>type.toLowerCase()));function itemCollectionCounts(item){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(key=>[key,item[key]?.length??0]))}function itemMaterialFieldGroups(item,body,children,currentSnapshot,projection){const collectionCounts=itemCollectionCounts(item);return[...body.length>0?["body"]:[],...Object.entries(collectionCounts).flatMap(([name,count])=>count>0?[name]:[]),...collectionCounts.files+collectionCounts.tests+collectionCounts.docs>0?["linked"]:[],...children===void 0?["children"]:children.count>0?["children"]:[],...typeof item.assignee=="string"&&item.assignee.trim().length>0?["claim_state"]:[],...buildItemSchedule(item)?["schedule"]:[],...currentSnapshot&&collectBlockedByIds(item).length>0?["blockers"]:[],...!projection.full&&item.dependencies?.some(({id:_id,kind:_kind,...provenance})=>Object.values(provenance).some(value=>value!==void 0))?["dependency_provenance"]:[]]}function shouldAutoIncludeGetChildren(itemType){const normalizedType=itemType.trim().toLowerCase();return normalizedType.length>0&&(AUTOMATIC_CHILD_ROLLUP_TYPES.has(normalizedType)||!BUILTIN_ITEM_TYPES.has(normalizedType))}function toClaimHistoryContext(entry){return{ts:entry.ts,author:entry.author,message:entry.message??null}}function resolveClaimStateContext(assigneeValue,history){const assignee=assigneeValue?.trim(),normalizedAssignee=assignee&&assignee.length>0?assignee:null,lastClaim=[...history].reverse().find(entry=>entry.op==="claim"),lastRelease=[...history].reverse().find(entry=>entry.op==="release");return{claimed:normalizedAssignee!==null,assignee:normalizedAssignee,last_claim:lastClaim?toClaimHistoryContext(lastClaim):null,last_release:lastRelease?toClaimHistoryContext(lastRelease):null}}function parseGetDepth(raw){if(raw===void 0||raw.trim().length===0)return"standard";const normalized=raw.trim().toLowerCase();if(normalized==="full")return"deep";if(GET_DEPTH_VALUES.includes(normalized))return normalized;throw new PmCliError("Get --depth must be one of brief|standard|deep|full",EXIT_CODE.USAGE,{field:"depth",value:raw,recovery:{allowed_values:[...GET_DEPTH_INPUT_VALUES]}})}function projectItemForDepth(item,depth,full){const collectionCounts=itemCollectionCounts(item),projectedItem={...item};if(!full&&item.dependencies!==void 0&&(projectedItem.dependencies=item.dependencies.map(({id,kind})=>({id,kind}))),depth==="deep")return{...projectedItem,comments:item.comments??[],notes:item.notes??[],learnings:item.learnings??[],files:item.files??[],tests:item.tests??[],docs:item.docs??[],reminders:item.reminders??[],events:item.events??[],notes_count:collectionCounts.notes,tests_count:collectionCounts.tests,collection_counts:collectionCounts};const{comments:_comments,notes:_notes,learnings:_learnings,files:_files,tests:_tests,docs:_docs,reminders:_reminders,events:_events,...projected}=projectedItem;return{...projected,notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:collectionCounts}}function parseGetFields(raw){if(raw===void 0)return null;const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0)throw new PmCliError("Get --fields requires a comma-separated list of field names",EXIT_CODE.USAGE);return fields}function normalizeGetField(field){return field.startsWith("item.")?field.slice(5):field}function validateGetFields(fields,runtimeMetadataKeys,id){if(fields===null)return;const allowedValues=listGetProjectionFields(runtimeMetadataKeys),allowed=new Set(allowedValues),unknown=fields.filter(field=>{const normalized=normalizeGetField(field);return!allowed.has(field)&&!allowed.has(normalized)});if(unknown.length>0){const suggestedRetryArguments=["get",id,"--fields",fields.filter(field=>!unknown.includes(field)).join(",")||"id,title,status"];throw new PmCliError(`Unknown get --fields value(s): ${unknown.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:allowedValues,suggested_retry:renderPmCommand(suggestedRetryArguments),suggested_retry_args:suggestedRetryArguments}})}}const EMPTY_PROJECTED_COLLECTION_FIELDS=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function projectedMetadataValue(source,counts,field){return Object.hasOwn(counts,field)?counts[field]:source[field]!==void 0?source[field]:EMPTY_PROJECTED_COLLECTION_FIELDS.has(field)?[]:void 0}function projectItemForFields(item,fields){const source=toItemRecord(item),omittedCounts={notes_count:item.notes?.length??0,tests_count:item.tests?.length??0,collection_counts:itemCollectionCounts(item)},projected={id:item.id};for(const field of fields){const normalized=normalizeGetField(field);normalized==="body"||normalized==="linked"||normalized.startsWith("linked.")||normalized==="claim_state"||normalized.startsWith("claim_state.")||normalized==="children"||normalized.startsWith("children.")||normalized==="schedule"||normalized.startsWith("schedule.")||normalized==="blockers"||(projected[normalized]=projectedMetadataValue(source,omittedCounts,normalized))}return projected}function fieldsInclude(fields,name){return fields?.some(field=>field===name||field===`item.${name}`)??!1}function fieldsIncludeRoot(fields,name){return fields.some(field=>{const normalized=normalizeGetField(field);return normalized===name||normalized.startsWith(`${name}.`)})}function resolveGetProjection(options,id){if(options.full&&(options.fields!==void 0||options.depth!==void 0))throw new PmCliError("Get projection options are mutually exclusive; remove the extra projection flag and retry.",EXIT_CODE.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:renderPmCommand(["get",id,"--full"]),suggested_retry_args:["get",id,"--full"]}});if(options.tree!==!0&&options.treeDepth!==void 0)throw new PmCliError("Get --tree-depth requires --tree",EXIT_CODE.USAGE);if(options.at!==void 0&&options.tree===!0)throw new PmCliError("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",EXIT_CODE.USAGE);return{depth:options.full?"deep":parseGetDepth(options.depth),full:options.full===!0||options.depth?.trim().toLowerCase()==="full",treeDepth:options.tree===!0?parseIntegerLimit(options.treeDepth,"--tree-depth"):void 0,fields:parseGetFields(options.fields),fieldProjection:options.fields!==void 0}}async function loadGetItemContext(id,global2,at){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());if(at!==void 0){const historical=await getItemAt(id,at,{pmRoot:global2.path});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:historical.document.metadata.id,metadata:historical.document.metadata,body:historical.document.body,historical}}const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeRegistry.type_to_folder);const loaded=await readLocatedItem(located,{schema:settings.schema});return{pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,locatedId:located.id,metadata:loaded.document.metadata,body:loaded.document.body}}function validateGetProjectionFields(fields,settings,historical,id){const runtimeMetadataKeys=[...resolveRuntimeFieldRegistry(settings.schema).definitions.map(field=>field.metadata_key),...collectRegisteredItemFieldNames(getActiveExtensionRegistrations())];if(validateGetFields(fields,runtimeMetadataKeys,id),historical&&fieldsIncludeRoot(fields??[],"children"))throw new PmCliError("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",EXIT_CODE.USAGE);if(historical&&fieldsIncludeRoot(fields??[],"blockers"))throw new PmCliError("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",EXIT_CODE.USAGE)}function shouldIncludeGetField(params){const{fieldProjection,depth,fields,field}=params;return fieldProjection?field==="body"||field==="linked"?fieldsInclude(fields,field):fieldsIncludeRoot(fields,field):depth!=="brief"}async function resolveGetClaimState(context,includeClaimState){if(!includeClaimState)return;const historyPath=getHistoryPath(context.pmRoot,context.locatedId),history=await readHistoryEntries(historyPath,context.locatedId);return resolveClaimStateContext(context.metadata.assignee,context.historical?history.slice(0,context.historical.target.historyIndex+1):history)}function attachGetLinked(result,context,fields,includeLinked){const includeLinkedFiles=includeLinked||fieldsInclude(fields,"linked.files"),includeLinkedTests=includeLinked||fieldsInclude(fields,"linked.tests"),includeLinkedDocs=includeLinked||fieldsInclude(fields,"linked.docs");!includeLinked&&!includeLinkedFiles&&!includeLinkedTests&&!includeLinkedDocs||(result.linked={files:includeLinkedFiles?context.metadata.files??[]:[],tests:includeLinkedTests?context.metadata.tests??[]:[],docs:includeLinkedDocs?context.metadata.docs??[]:[]})}async function buildGetChildrenRollup(context,includeChildren){if(!includeChildren)return;const statusRegistry=resolveRuntimeStatusRegistry(context.settings.schema),corpus=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,context.typeToFolder,void 0,context.settings.schema);return buildItemChildrenRollup(context.locatedId,corpus,statusRegistry)}function canonicalizeDeclaredBlockers(blockers,targets){const canonical=new Map;for(const blocker of blockers){const id=blocker.external?blocker.id:targets.get(blocker.id.toLowerCase())?.id??blocker.id;canonical.set(blocker.external?`external:${id}`:`local:${id.toLowerCase()}`,{...blocker,id})}return[...canonical.values()]}async function resolvePhysicalBlockerId(itemPath,probedId){const filename=path.basename(itemPath),physicalId=(await readdir(path.dirname(itemPath)).catch(error=>{throw createPmCliExpectedError("Cannot verify the blocker's physical file identity",{exitCode:EXIT_CODE.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:error})})).filter(name=>name.toLowerCase()===filename.toLowerCase()).sort((left,right)=>+(right===filename)-+(left===filename)||left.localeCompare(right)).map(name=>path.parse(name).name)[0];if(physicalId===void 0)throw new PmCliError(`Blocker canonical file disappeared during identity verification: ${probedId}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return physicalId}async function attachGetBlockers(result,context,projection){if(context.historical!==void 0||!(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"blockers"):projection.depth!=="brief"))return;const ids=collectBlockedByIds(context.metadata);if(ids.length===0)return;const declaredIds=new Map([context.metadata.blocked_by,...(context.metadata.dependencies??[]).filter(dependency=>dependency.kind==="blocked_by").map(dependency=>dependency.id)].filter(id=>typeof id=="string").map(id=>[id.trim().toLowerCase(),id.trim()])),targets=new Map;for(const id of ids){if(isExternalDependencyReference(id)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(id)||context.metadata.dependencies?.some(dependency=>dependency.id.trim()===id&&dependency.kind==="blocked_by"&&isExternalDependencySourceKind(dependency.source_kind)))continue;const located=await locateItem(context.pmRoot,declaredIds.get(id),context.settings.id_prefix,context.settings.item_format,context.typeToFolder);if(located===null)continue;const loaded=await readLocatedItem(located,{schema:context.settings.schema});if(located.id=await resolvePhysicalBlockerId(located.itemPath,located.id),loaded.document.metadata.id!==located.id)throw new PmCliError(`Blocker identity differs from its canonical file: ${located.id}`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});targets.set(id.toLowerCase(),loaded.document.metadata)}const resolved=canonicalizeDeclaredBlockers(resolveItemBlockers({blocked_by:context.metadata.blocked_by,dependencies:context.metadata.dependencies,updated_at:context.metadata.updated_at},targets,resolveRuntimeStatusRegistry(context.settings.schema)),targets);result.blockers={scope:"declared",open:resolved.filter(blocker=>!blocker.resolved).map(({resolved:_resolved,...blocker})=>blocker),closed_count:resolved.filter(blocker=>blocker.resolved).length},!projection.fieldProjection&&!projection.full&&delete result.item.blocked_by}function attachGetSchedule(result,context,fields,includeSchedule){if(!includeSchedule)return;const schedule=buildItemSchedule(context.metadata);if(schedule){if(fields===null||fieldsInclude(fields,"schedule")){result.schedule=schedule;return}result.schedule=Object.fromEntries(Object.entries(schedule).filter(([key])=>fields.some(field=>normalizeGetField(field)===`schedule.${key}`)))}}async function buildGetTree(context,options,treeDepth,global2){if(options.tree!==!0)return;const subtree=await runList(void 0,{parent:context.locatedId,tree:!0,treeDepth:treeDepth===void 0?void 0:String(treeDepth),full:!0},global2);return{root_id:context.locatedId,root_title:context.metadata.title,depth_limit:treeDepth??null,count:subtree.count,items:subtree.items.map(entry=>toItemRecord(entry))}}async function runGet(id,global2,options={}){const projection=resolveGetProjection(options,id),context=await loadGetItemContext(id,global2,options.at);validateGetProjectionFields(projection.fields,context.settings,context.historical!==void 0,context.locatedId);const includeBody=shouldIncludeGetField({...projection,field:"body"}),includeLinked=shouldIncludeGetField({...projection,field:"linked"}),includeClaimState=shouldIncludeGetField({...projection,field:"claim_state"}),includeChildren=context.historical===void 0&&(projection.fieldProjection?fieldsIncludeRoot(projection.fields,"children"):projection.depth==="deep"&&(projection.full||shouldAutoIncludeGetChildren(context.metadata.type))),includeSchedule=projection.fieldProjection?fieldsIncludeRoot(projection.fields,"schedule"):projection.depth!=="brief",claimState=await resolveGetClaimState(context,includeClaimState),result={item:projection.fieldProjection?projectItemForFields(context.metadata,projection.fields):projectItemForDepth(context.metadata,projection.depth,projection.full)};includeBody&&(result.item.body=context.body),attachGetLinked(result,context,projection.fields,includeLinked),claimState&&(result.claim_state=claimState),attachGetSchedule(result,context,projection.fields,includeSchedule),await attachGetBlockers(result,context,projection);const children=await buildGetChildrenRollup(context,includeChildren);children!==void 0&&(result.children=children);const tree=await buildGetTree(context,options,projection.treeDepth,global2);if(tree!==void 0&&(result.tree=tree),context.historical&&(result.reconstructed=!0,result.as_of_version=context.historical.as_of_version,result.as_of_timestamp=context.historical.as_of_timestamp),context.historical===void 0)try{await recordContextUsageTouches({pmRoot:context.pmRoot,author:resolveAuthor(void 0,context.settings.author_default),itemIds:[context.locatedId],intent:"get"})}catch{}return registerOutputMaterialFieldGroups(result,projection.fieldProjection?[]:itemMaterialFieldGroups(context.metadata,context.body,children,context.historical===void 0,projection)),result}const _testOnlyGetCommand={shouldAutoIncludeGetChildren};export{GET_DEPTH_INPUT_VALUES2 as GET_DEPTH_INPUT_VALUES,GET_DEPTH_VALUES2 as GET_DEPTH_VALUES,_testOnlyGetCommand,listGetProjectionFields2 as listGetProjectionFields,runGet};
|
|
2
2
|
//# sourceMappingURL=get.js.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module sdk/query/next-ranking-policy
|
|
3
|
+
*
|
|
4
|
+
* Ranking policies for the `pm next` ready queue (GH-1618). The policy
|
|
5
|
+
* decides whether priority tiers bound the blended relevance order, and the
|
|
6
|
+
* reason helper names any disagreement between policy and relevance. Kept
|
|
7
|
+
* apart from the public `pm next` module so these pure internals stay off the
|
|
8
|
+
* published `./sdk/query` surface while remaining directly testable; the
|
|
9
|
+
* refusal for an unknown policy stays in `next.ts`, the command that owns it.
|
|
10
|
+
*/
|
|
11
|
+
import type { ActionableEntry } from "../actionability.js";
|
|
12
|
+
import { type RuntimeStatusRegistry } from "../runtime-primitives.js";
|
|
13
|
+
import type { ItemMetadata } from "../../types/index.js";
|
|
14
|
+
/**
|
|
15
|
+
* Ordering policy applied to the ready queue after relevance scoring.
|
|
16
|
+
* `priority_floor` (default) resumes in-progress work first, then orders by
|
|
17
|
+
* priority tier and lets relevance order items only within a tier, so
|
|
18
|
+
* automated comment churn cannot lift a P2 log above ready P0 work.
|
|
19
|
+
* `weighted` keeps the blended relevance order (GH-1618).
|
|
20
|
+
*/
|
|
21
|
+
export type NextRankingPolicy = "priority_floor" | "weighted";
|
|
22
|
+
/** Policies `pm next` accepts, in documentation order. */
|
|
23
|
+
export declare const NEXT_RANKING_POLICIES:readonly NextRankingPolicy[];
|
|
24
|
+
/**
|
|
25
|
+
* Reorder a scored ready queue under the policy. Returns each id's relevance
|
|
26
|
+
* rank before the policy so explanations and reasons can name it. Only the
|
|
27
|
+
* built-in weighted model is reordered; a project's own scorer keeps its order.
|
|
28
|
+
*/
|
|
29
|
+
export declare function applyNextRankingPolicy<T extends {
|
|
30
|
+
id:string;
|
|
31
|
+
rank:number;
|
|
32
|
+
item:ItemMetadata;
|
|
33
|
+
}>(ranked:T[],statusRegistry:RuntimeStatusRegistry,policy:NextRankingPolicy,model:string):Map<string,number>;
|
|
34
|
+
/** Explain, in the default reasons, when policy and relevance disagree about the recommendation. */
|
|
35
|
+
export declare function describeRankingPolicyReason(projectedReady:readonly ActionableEntry[],relevanceRank:ReadonlyMap<string,number>,statusRegistry:RuntimeStatusRegistry,policy:NextRankingPolicy):string | undefined;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c12559a3-2703-5665-9ec2-7309589be511")}catch{}})();import{normalizeStatusForRegistry}from"../runtime-primitives.js";const NEXT_RANKING_POLICIES=["priority_floor","weighted"],DEFAULT_WEIGHTED_RELEVANCE_MODEL="default-weighted-v1";function applyNextRankingPolicy(ranked,statusRegistry,policy,model){const relevanceRank=new Map(ranked.map(entry=>[entry.id,entry.rank]));if(policy!=="priority_floor"||model!==DEFAULT_WEIGHTED_RELEVANCE_MODEL)return relevanceRank;const inProgressStatus=statusRegistry.in_progress_status,tier=entry=>normalizeStatusForRegistry(entry.item.status,statusRegistry)===inProgressStatus?-1:entry.item.priority;return ranked.sort((left,right)=>tier(left)-tier(right)||left.rank-right.rank),ranked.forEach((entry,index)=>{entry.rank=index+1}),relevanceRank}function describeRankingPolicyReason(projectedReady,relevanceRank,statusRegistry,policy){const leader=projectedReady[0];if(!leader)return;if(policy==="priority_floor"){const rank=relevanceRank.get(leader.item.id);return rank!==void 0&&rank!==1?`priority floor (relevance rank ${rank})`:void 0}const inProgressStatus=statusRegistry.in_progress_status,higherPriority=projectedReady.slice(1).filter(entry=>entry.item.priority<leader.item.priority&&normalizeStatusForRegistry(entry.item.status,statusRegistry)!==inProgressStatus).map(entry=>entry.item.priority);return higherPriority.length>0?`relevance over p${Math.min(...higherPriority)} ready work`:void 0}export{NEXT_RANKING_POLICIES,applyNextRankingPolicy,describeRankingPolicyReason};
|
|
2
|
+
//# sourceMappingURL=next-ranking-policy.js.map
|
package/dist/sdk/query/next.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ import { type ActionableEntry } from "../actionability.js";
|
|
|
12
12
|
import { type GlobalOptions } from "../runtime-primitives.js";
|
|
13
13
|
import type { ItemTypeRegistry } from "../../core/item/type-registry.js";
|
|
14
14
|
import type { ItemStatus } from "../../types/index.js";
|
|
15
|
+
import { type NextRankingPolicy } from "./next-ranking-policy.js";
|
|
16
|
+
export { NEXT_RANKING_POLICIES,type NextRankingPolicy } from "./next-ranking-policy.js";
|
|
15
17
|
import { type ContextFocusItem,type ContextRankingSummary,type ContextPackingSummary } from "./context.js";
|
|
16
18
|
import { type NextReadyBudgetReceipt } from "./next-ready-budget.js";
|
|
17
19
|
/** Supported values accepted by the next output contract. */
|
|
@@ -46,6 +48,8 @@ readyOnly?:boolean;
|
|
|
46
48
|
format?:string;
|
|
47
49
|
/** Value that configures or reports explain ranking for this contract. */
|
|
48
50
|
explainRanking?:boolean;
|
|
51
|
+
/** Ready-queue ordering policy; defaults to the `context.next_ranking_policy` setting (GH-1618). */
|
|
52
|
+
rankingPolicy?:NextRankingPolicy;
|
|
49
53
|
/** Maximum rendered tokens for the recommendation and ready alternatives; companion queues use outputBudget. */
|
|
50
54
|
tokenBudget?:string | number;
|
|
51
55
|
/** Include human-gated Decision items in the claimable ready queue. */
|
|
@@ -145,7 +149,14 @@ ready_only:boolean;
|
|
|
145
149
|
include_decisions:boolean;
|
|
146
150
|
include_gates?:boolean;
|
|
147
151
|
include_containers?:boolean;
|
|
148
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Requested recommended+ready selection ceiling, or null when none was
|
|
154
|
+
* requested. The complete response is bounded by the universal output
|
|
155
|
+
* budget and disclosed by its `read_output` receipt (GH-1627).
|
|
156
|
+
*/
|
|
157
|
+
token_budget:number | null;
|
|
158
|
+
/** Ordering policy that produced the ready queue (GH-1618). */
|
|
159
|
+
ranking_policy:NextRankingPolicy;
|
|
149
160
|
};
|
|
150
161
|
/** Value that configures or reports suggestions for this contract. */
|
|
151
162
|
suggestions?:string[];
|
|
@@ -194,4 +205,3 @@ export declare function runNext(options:NextOptions,global:GlobalOptions):Promis
|
|
|
194
205
|
* `--ready-only`) the blocked queue annotated with each item's open blockers.
|
|
195
206
|
*/
|
|
196
207
|
export declare function renderNextMarkdown(result:NextResult):string;
|
|
197
|
-
export {};
|
package/dist/sdk/query/next.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f610c3be-8212-56de-86d4-2b5b9752b87c")}catch{}})();import{collectBlockedByIds,computeActionabilityReport,resolveItemExecutionRole,selectActionableEntries}from"../actionability.js";import{resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,nowIso,normalizeStatusInput,normalizeStatusForRegistry,resolvePmRoot,readSettings,resolveAuthor,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{parseIntegerLimit}from"./parsers.js";import{buildChildrenByParent,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,resolveContextTokenBudget,toContextPackingSummary,toContextRankingSummary,toContextFocusItem}from"./context.js";import{runList}from"./list.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{applyNextReadyBudget}from"./next-ready-budget.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";const NEXT_OUTPUT_VALUES=["markdown","toon","json"],DEFAULT_NEXT_LIMIT=5,MS_PER_DAY=1440*60*1e3;function parseNextOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!NEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Next format must be one of markdown|toon|json",EXIT_CODE.USAGE);return normalized}function resolveNextOutputFormat(options,global2){const commandFormat=parseNextOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?"json":commandFormat??"toon"}function parseNextLimit(raw,flag,fallback){const parsed=parseIntegerLimit(raw,flag);return parsed===void 0||parsed<=0?fallback:parsed}function toNextActionableItem(entry,statusRegistry,childrenByParent,rank){return{...toContextFocusItem(entry.item,statusRegistry,childrenByParent),open_blocker_count:entry.open_blockers.length,blockers:entry.open_blockers.map(blocker=>({id:blocker.id,title:blocker.title,status:blocker.status,...blocker.external?{external:!0}:{},...blocker.blocked_since?{blocked_since:blocker.blocked_since}:{},...blocker.external?{resolver:blocker.resolver??null}:{}})),unblocks:entry.unblocks,rank}}function buildRecommendationReasons(entry,statusRegistry,now,completedContainer){const item=entry.item,reasons=[],inProgressStatus=normalizeStatusInput("in_progress",statusRegistry);return reasons.push(normalizeStatusForRegistry(item.status,statusRegistry)===inProgressStatus?"resume work":"ready"),completedContainer&&reasons.push("completed container \u2014 governance closeout"),reasons.push(`p${item.priority}${item.priority===0?" (highest)":""}`),typeof item.deadline=="string"&&item.deadline.trim().length>0&&reasons.push(describeDeadline(item.deadline,now)),reasons.push(collectBlockedByIds(item).length>0?"all blockers resolved":"no blockers"),typeof item.parent=="string"&&item.parent.trim().length>0&&reasons.push(`advances ${item.parent.trim()}`),entry.unblocks.length>0&&reasons.push(`unblocks ${entry.unblocks.length} item(s)`),reasons}function partitionCallerOwnedReady(ready,fallbackAuthor,explicitAuthor){const caller=resolveAuthor(explicitAuthor,fallbackAuthor),available=[],held=[];for(const entry of ready){const assignee=typeof entry.item.assignee=="string"?entry.item.assignee.trim():"";assignee.length>0&&assignee!==caller?held.push({id:entry.item.id,assignee}):available.push(entry)}return{available,held}}const _testOnlyNextCommand={partitionCallerOwnedReady,resolveNextCallerAuthor:(options,settingsAuthor)=>resolveNextCallerAuthor(options,settingsAuthor)};function partitionDecisionEntries(ready,includeDecisions,typeRegistry){const decisions=ready.filter(entry=>resolveItemExecutionRole(entry.item.type,typeRegistry)==="human");return{agent:includeDecisions?ready:ready.filter(entry=>resolveItemExecutionRole(entry.item.type,typeRegistry)!=="human"),decisions:includeDecisions?[]:decisions}}function describeDeadline(deadline,now){const deadlineMs=Date.parse(deadline);if(!Number.isFinite(deadlineMs))return`deadline ${deadline.trim()}`;const dateToken=new Date(deadlineMs).toISOString().slice(0,10),nowToken=new Date(Date.parse(now)).toISOString().slice(0,10),days=Math.round((Date.parse(dateToken)-Date.parse(nowToken))/MS_PER_DAY);return days<0?`deadline ${dateToken} (overdue ${-days}d)`:days===0?`deadline ${dateToken} (due today)`:`deadline ${dateToken} (in ${days}d)`}function inProgressReadyCount(ready,statusRegistry){const inProgressStatus=normalizeStatusInput("in_progress",statusRegistry);return ready.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===inProgressStatus).length}function hasCompletedDescendants(item,childrenByParent){return(childrenByParent.get(item.id.trim().toLowerCase())??[]).length>0}function nextListOptions(options,extra){return{type:options.type,tag:options.tag,priority:typeof options.priority=="number"?String(options.priority):options.priority,assignee:options.assignee,assigneeFilter:options.assigneeFilter,sprint:options.sprint,release:options.release,noTruncate:!0,...extra}}function rankNextReadyEntries(ready,childrenByParent,statusRegistry){return[...ready].sort((left,right)=>{const leftCompletedContainer=hasCompletedDescendants(left.item,childrenByParent),rightCompletedContainer=hasCompletedDescendants(right.item,childrenByParent);return leftCompletedContainer!==rightCompletedContainer?Number(leftCompletedContainer)-Number(rightCompletedContainer):compareCriticalItems(left.item,right.item,statusRegistry)})}function buildNextRecommendation(params){return params.projectedReady.length===0?null:{...params.readyRows[0],reasons:buildRecommendationReasons(params.projectedReady[0],params.statusRegistry,params.now,params.completedContainer)}}function buildNextSuggestions(recommended,blockedRows,gateCount){if(recommended!==null)return;const gateGuidance=gateCount>0?["No executable recommendation: outcome gates require verification. Inspect gate_needed, or use pm next --include-gates to opt in."]:[];if(blockedRows.length>0){const blockedWithReferences=blockedRows.find(item=>item.blockers.length>0);return[...gateGuidance,blockedWithReferences?`${blockedRows.length} item(s) are blocked; unblock the top one by closing ${blockedWithReferences.blockers.map(blocker=>blocker.id).join(", ")}`:`${blockedRows.length} item(s) are blocked; add blocker context or move the top item back to an active status`,"pm next --ready-only after a blocker closes to re-check ready work",'pm create --type Task --title "..." to add new ready work']}return[...gateGuidance,'pm create --type Task --title "..." to add a new work item',"pm list --status in_progress to review work already underway","pm context --depth deep for the full project snapshot"]}function buildNextTruncation(decisionCount,heldCount,readyCount,limit){const truncation={};return decisionCount>limit&&(truncation.decision_needed_total=decisionCount),heldCount>limit&&(truncation.held_by_others_total=heldCount),readyCount>limit+1&&(truncation.ready_total=readyCount),Object.keys(truncation).length>0?truncation:void 0}async function attachNextUsageFeedback(params){try{const included=new Set([...params.result.recommended?[params.result.recommended.id]:[],...params.result.ready.map(entry=>entry.id)]),rows=params.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(params.result,"next"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot:params.pmRoot,author:params.author,surface:"next",profile:"next",rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(params.result,receipt)}catch{params.result.warnings=mergeSortedWarnings(params.result.warnings,["context_usage_feedback_write_failed"])}}async function finalizeNextResult(params){const warnings=[...new Set([...params.candidatesWarnings??[],...params.corpusWarnings??[],...params.readyRanking.warnings??[],...params.featureStore.warnings])].sort((left,right)=>left.localeCompare(right));return warnings.length>0&&(params.result.warnings=warnings),params.result.suggestions=buildNextSuggestions(params.recommended,params.blockedRows,params.gateCount),params.tokenBudget!==void 0&&applyNextReadyBudget(params.result,params.tokenBudget,params.hasIntentBudget),params.explainRanking&&(params.result.ranking=toContextRankingSummary(params.readyRanking,params.featureStore,new Set([...params.result.recommended?[params.result.recommended.id]:[],...params.result.ready.map(entry=>entry.id)])),params.result.packing=toContextPackingSummary(packRankedContextItems(params.readyRanking,params.packingBudget,new Set,"next"))),await attachNextUsageFeedback({result:params.result,pmRoot:params.pmRoot,author:params.author,ranking:params.readyRanking}),params.result}function filterCandidatesByParentScope(candidates,corpus,parentScope){if(!parentScope)return candidates;const subtree=collectSubtreeIds(corpus,parentScope);if(!subtree.found)throw new PmCliError(`Next --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return candidates.filter(item=>subtree.ids.has(item.id.trim().toLowerCase()))}async function rankReadyEntriesWithRelevance(rankedReady,childrenByParent,statusRegistry,now,callerAuthor,pmRoot,includeContainers){const concreteReady=rankedReady.filter(entry=>!hasCompletedDescendants(entry.item,childrenByParent)),structuralReady=includeContainers||concreteReady.length===0?rankedReady:concreteReady,usage=await readContextUsageAffinity({pmRoot,author:callerAuthor,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structuralReady.map(entry=>entry.item),{pmRoot,storeKey:"next",statusRegistry,now,author:callerAuthor,usageAffinity:usage.affinity}),ranking=await scoreContextCandidatesWithActiveExtensions("next",featureStore.candidates),readyById=new Map(structuralReady.map(entry=>[entry.item.id,entry]));return{projectedReady:ranking.ranked.map(entry=>readyById.get(entry.id)).filter(entry=>entry!==void 0),ranking,completedContainer:concreteReady.length===0&&!includeContainers,featureStore}}function resolveNextCallerAuthor(options,settingsAuthor){const requestedAssignee=options.assignee?.trim();return resolveAuthor(options.callerAuthor??(requestedAssignee&&requestedAssignee.length>0?requestedAssignee:void 0),settingsAuthor)}async function runNext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),callerAuthor=resolveNextCallerAuthor(options,settings.author_default),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),now=nowIso(),limit=parseNextLimit(options.limit,"--limit",DEFAULT_NEXT_LIMIT),tokenBudget=resolveContextTokenBudget(options.tokenBudget,Math.max(192,limit*128)),blockedLimit=parseNextLimit(options.blockedLimit,"--blocked-limit",limit),readyOnly=options.readyOnly===!0,parentScope=typeof options.parent=="string"?options.parent.trim():"",candidatesList=await runList(void 0,nextListOptions(options,{excludeTerminal:!0}),global2),corpusList=await runList(void 0,{excludeTerminal:!1,noTruncate:!0},global2),candidates=filterCandidatesByParentScope(candidatesList.items,corpusList.items,parentScope),corpus=corpusList.items,report=computeActionabilityReport(candidates,corpus,statusRegistry,typeRegistry),childrenByParent=buildChildrenByParent(corpus),selected=selectActionableEntries(report,statusRegistry,options,typeRegistry),callerPartition=partitionCallerOwnedReady(selected.ready,settings.author_default,callerAuthor),rankedReady=rankNextReadyEntries(callerPartition.available,childrenByParent,statusRegistry),rankedBlocked=[...report.blocked].sort((left,right)=>compareCriticalItems(left.item,right.item,statusRegistry)),{projectedReady,ranking:readyRanking,completedContainer,featureStore}=await rankReadyEntriesWithRelevance(rankedReady,childrenByParent,statusRegistry,now,callerAuthor,pmRoot,options.includeContainers===!0),readyRows=projectedReady.map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),blockedRows=rankedBlocked.map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),decisionRows=rankNextReadyEntries(selected.decisions,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),gateRows=rankNextReadyEntries(selected.gates,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),containerRows=rankNextReadyEntries(report.containers,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),recommended=buildNextRecommendation({projectedReady,readyRows,statusRegistry,now,completedContainer}),truncation=buildNextTruncation(decisionRows.length,callerPartition.held.length,readyRows.length,limit)??{};gateRows.length>limit&&(truncation.gate_needed_total=gateRows.length),containerRows.length>limit&&(truncation.containers_total=containerRows.length);const result={output_default:"toon",now,recommended,ready:readyRows.slice(1,limit+1),decision_needed:decisionRows.slice(0,limit),gate_needed:gateRows.slice(0,limit),containers:containerRows.slice(0,limit),blocked:readyOnly?[]:blockedRows.slice(0,blockedLimit),held_by_others:callerPartition.held.slice(0,limit),summary:{recommended:recommended!==null,ready:readyRows.length,blocked:blockedRows.length,in_progress:inProgressReadyCount(readyRows,statusRegistry),candidates:report.active_count,containers:report.container_count,decision_needed:decisionRows.length,gate_needed:gateRows.length,held_by_others:callerPartition.held.length},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,parent:parentScope.length>0?parentScope:null,limit,blocked_limit:blockedLimit,ready_only:readyOnly,include_decisions:options.includeDecisions===!0,include_gates:options.includeGates===!0,include_containers:options.includeContainers===!0,token_budget:tokenBudget},truncation:Object.keys(truncation).length>0?truncation:void 0};return finalizeNextResult({result,recommended,blockedRows,gateCount:gateRows.length,candidatesWarnings:candidatesList.warnings,corpusWarnings:corpusList.warnings,readyRanking,explainRanking:options.explainRanking===!0,pmRoot,author:callerAuthor,packingBudget:tokenBudget,featureStore,tokenBudget:options.tokenBudget===void 0?void 0:tokenBudget,hasIntentBudget:typeof options.for=="string"})}function renderNextMarkdown(result){const lines=["# pm next","",...renderNextSummaryLines(result)];for(const[title,rows]of[["Gate verification needed",result.gate_needed],["Containers",result.containers]])rows&&rows.length>0&&lines.push(...renderNextSection(title,rows.map(item=>`- ${formatNextLine(item)}`),""));if(lines.push(...renderNextSection("Recommended",renderNextRecommendedRows(result.recommended),result.truncation?.ready_budget?.recommendation_omitted?"Recommendation omitted by the selection budget; ready work still exists.":"No ready work.")),lines.push(...renderNextSection("Decision needed",(result.decision_needed??[]).map(item=>`- ${formatNextLine(item)}`),"No human-gated decisions.")),lines.push(...renderNextSection("Ready",result.ready.map(item=>`- ${formatNextLine(item)}`),"No ready items.")),result.filters.ready_only||lines.push(...renderNextSection("Blocked",result.blocked.map(item=>`- ${formatNextBlockedLine(item)}`),"No blocked items.")),result.suggestions&&result.suggestions.length>0){lines.push("## Suggestions");for(const suggestion of result.suggestions)lines.push(`- ${suggestion}`)}return lines.join(`
|
|
2
|
-
`).trimEnd()}function renderNextSummaryLines(result){const lines=[`- now: ${result.now}`,`- ready: ${result.summary.ready} (in_progress: ${result.summary.in_progress}), blocked: ${result.summary.blocked}, candidates: ${result.summary.candidates}`];return result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(""),lines}function renderNextRecommendedRows(recommended){return recommended?[`- ${formatNextLine(recommended)}`,` why: ${recommended.reasons.join("; ")}`]:[]}function renderNextSection(header,rows,emptyMessage){return[`## ${header}`,...rows.length===0?[emptyMessage]:rows,""]}function formatNextBlockedLine(item){const by=item.blockers.map(blocker=>`${blocker.id}(${blocker.status??"?"})`).join(", ");return`${formatNextLine(item)} blocked_by:${by}`}function formatNextLine(item){const deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",unblocksToken=item.unblocks.length>0?` unblocks:${item.unblocks.length}`:"";return`${Number.isInteger(item.rank)?`#${item.rank} `:""}${item.id} p${item.priority} ${item.status} ${item.type} deadline:${deadlineToken}${parentToken}${unblocksToken} ${item.title}`}export{NEXT_OUTPUT_VALUES,_testOnlyNextCommand,partitionDecisionEntries,renderNextMarkdown,resolveNextOutputFormat,runNext};
|
|
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]="b01faffe-d88f-5095-8d28-167943ec5067")}catch{}})();import{collectBlockedByIds,computeActionabilityReport,resolveItemExecutionRole,selectActionableEntries}from"../actionability.js";import{resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,nowIso,normalizeStatusInput,normalizeStatusForRegistry,resolvePmRoot,readSettings,resolveAuthor,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{parseIntegerLimit}from"./parsers.js";import{NEXT_RANKING_POLICIES,applyNextRankingPolicy,describeRankingPolicyReason}from"./next-ranking-policy.js";import{NEXT_RANKING_POLICIES as NEXT_RANKING_POLICIES2}from"./next-ranking-policy.js";import{buildChildrenByParent,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,resolveContextTokenBudget,toContextPackingSummary,toContextRankingSummary,toContextFocusItem}from"./context.js";import{runList}from"./list.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{applyNextReadyBudget}from"./next-ready-budget.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";const NEXT_OUTPUT_VALUES=["markdown","toon","json"],DEFAULT_NEXT_LIMIT=5,MS_PER_DAY=1440*60*1e3;function resolveNextRankingPolicy(requested,configured){const candidate=requested??configured;if(typeof candidate=="string"&&NEXT_RANKING_POLICIES.includes(candidate))return candidate;throw new PmCliError(`Unknown next ranking policy ${JSON.stringify(candidate)}. Accepted values: ${NEXT_RANKING_POLICIES.join(", ")}.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",value:String(candidate),recovery:{allowed_values:[...NEXT_RANKING_POLICIES]}})}function parseNextOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!NEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Next format must be one of markdown|toon|json",EXIT_CODE.USAGE);return normalized}function resolveNextOutputFormat(options,global2){const commandFormat=parseNextOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?"json":commandFormat??"toon"}function parseNextLimit(raw,flag,fallback){const parsed=parseIntegerLimit(raw,flag);return parsed===void 0||parsed<=0?fallback:parsed}function toNextActionableItem(entry,statusRegistry,childrenByParent,rank){return{...toContextFocusItem(entry.item,statusRegistry,childrenByParent),open_blocker_count:entry.open_blockers.length,blockers:entry.open_blockers.map(blocker=>({id:blocker.id,title:blocker.title,status:blocker.status,...blocker.external?{external:!0}:{},...blocker.blocked_since?{blocked_since:blocker.blocked_since}:{},...blocker.external?{resolver:blocker.resolver??null}:{}})),unblocks:entry.unblocks,rank}}function buildRecommendationReasons(entry,statusRegistry,now,completedContainer){const item=entry.item,reasons=[],inProgressStatus=normalizeStatusInput("in_progress",statusRegistry);return reasons.push(normalizeStatusForRegistry(item.status,statusRegistry)===inProgressStatus?"resume work":"ready"),completedContainer&&reasons.push("completed container \u2014 governance closeout"),reasons.push(`p${item.priority}${item.priority===0?" (highest)":""}`),typeof item.deadline=="string"&&item.deadline.trim().length>0&&reasons.push(describeDeadline(item.deadline,now)),reasons.push(collectBlockedByIds(item).length>0?"all blockers resolved":"no blockers"),typeof item.parent=="string"&&item.parent.trim().length>0&&reasons.push(`advances ${item.parent.trim()}`),entry.unblocks.length>0&&reasons.push(`unblocks ${entry.unblocks.length} item(s)`),reasons}function partitionCallerOwnedReady(ready,fallbackAuthor,explicitAuthor){const caller=resolveAuthor(explicitAuthor,fallbackAuthor),available=[],held=[];for(const entry of ready){const assignee=typeof entry.item.assignee=="string"?entry.item.assignee.trim():"";assignee.length>0&&assignee!==caller?held.push({id:entry.item.id,assignee}):available.push(entry)}return{available,held}}const _testOnlyNextCommand={partitionCallerOwnedReady,resolveNextCallerAuthor:(options,settingsAuthor)=>resolveNextCallerAuthor(options,settingsAuthor)};function partitionDecisionEntries(ready,includeDecisions,typeRegistry){const decisions=ready.filter(entry=>resolveItemExecutionRole(entry.item.type,typeRegistry)==="human");return{agent:includeDecisions?ready:ready.filter(entry=>resolveItemExecutionRole(entry.item.type,typeRegistry)!=="human"),decisions:includeDecisions?[]:decisions}}function describeDeadline(deadline,now){const deadlineMs=Date.parse(deadline);if(!Number.isFinite(deadlineMs))return`deadline ${deadline.trim()}`;const dateToken=new Date(deadlineMs).toISOString().slice(0,10),nowToken=new Date(Date.parse(now)).toISOString().slice(0,10),days=Math.round((Date.parse(dateToken)-Date.parse(nowToken))/MS_PER_DAY);return days<0?`deadline ${dateToken} (overdue ${-days}d)`:days===0?`deadline ${dateToken} (due today)`:`deadline ${dateToken} (in ${days}d)`}function inProgressReadyCount(ready,statusRegistry){const inProgressStatus=normalizeStatusInput("in_progress",statusRegistry);return ready.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===inProgressStatus).length}function hasCompletedDescendants(item,childrenByParent){return(childrenByParent.get(item.id.trim().toLowerCase())??[]).length>0}function nextListOptions(options,extra){return{type:options.type,tag:options.tag,priority:typeof options.priority=="number"?String(options.priority):options.priority,assignee:options.assignee,assigneeFilter:options.assigneeFilter,sprint:options.sprint,release:options.release,noTruncate:!0,...extra}}function rankNextReadyEntries(ready,childrenByParent,statusRegistry){return[...ready].sort((left,right)=>{const leftCompletedContainer=hasCompletedDescendants(left.item,childrenByParent),rightCompletedContainer=hasCompletedDescendants(right.item,childrenByParent);return leftCompletedContainer!==rightCompletedContainer?Number(leftCompletedContainer)-Number(rightCompletedContainer):compareCriticalItems(left.item,right.item,statusRegistry)})}function buildNextRecommendation(params){return params.projectedReady.length===0?null:{...params.readyRows[0],reasons:[...buildRecommendationReasons(params.projectedReady[0],params.statusRegistry,params.now,params.completedContainer),...params.policyReason?[params.policyReason]:[]]}}function buildNextSuggestions(recommended,blockedRows,gateCount){if(recommended!==null)return;const gateGuidance=gateCount>0?["No executable recommendation: outcome gates require verification. Inspect gate_needed, or use pm next --include-gates to opt in."]:[];if(blockedRows.length>0){const blockedWithReferences=blockedRows.find(item=>item.blockers.length>0);return[...gateGuidance,blockedWithReferences?`${blockedRows.length} item(s) are blocked; unblock the top one by closing ${blockedWithReferences.blockers.map(blocker=>blocker.id).join(", ")}`:`${blockedRows.length} item(s) are blocked; add blocker context or move the top item back to an active status`,"pm next --ready-only after a blocker closes to re-check ready work",'pm create --type Task --title "..." to add new ready work']}return[...gateGuidance,'pm create --type Task --title "..." to add a new work item',"pm list --status in_progress to review work already underway","pm context --depth deep for the full project snapshot"]}function buildNextTruncation(decisionCount,heldCount,readyCount,limit){const truncation={};return decisionCount>limit&&(truncation.decision_needed_total=decisionCount),heldCount>limit&&(truncation.held_by_others_total=heldCount),readyCount>limit+1&&(truncation.ready_total=readyCount),Object.keys(truncation).length>0?truncation:void 0}async function attachNextUsageFeedback(params){try{const included=new Set([...params.result.recommended?[params.result.recommended.id]:[],...params.result.ready.map(entry=>entry.id)]),rows=params.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(params.result,"next"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot:params.pmRoot,author:params.author,surface:"next",profile:"next",rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(params.result,receipt)}catch{params.result.warnings=mergeSortedWarnings(params.result.warnings,["context_usage_feedback_write_failed"])}}async function finalizeNextResult(params){const warnings=[...new Set([...params.candidatesWarnings??[],...params.corpusWarnings??[],...params.readyRanking.warnings??[],...params.featureStore.warnings])].sort((left,right)=>left.localeCompare(right));return warnings.length>0&&(params.result.warnings=warnings),params.result.suggestions=buildNextSuggestions(params.recommended,params.blockedRows,params.gateCount),params.tokenBudget!==null&&applyNextReadyBudget(params.result,params.tokenBudget,params.hasIntentBudget),params.explainRanking&&(params.result.ranking=toContextRankingSummary(params.readyRanking,params.featureStore,new Set([...params.result.recommended?[params.result.recommended.id]:[],...params.result.ready.map(entry=>entry.id)])),params.result.packing=toContextPackingSummary(packRankedContextItems(params.readyRanking,params.packingBudget,new Set,"next"))),await attachNextUsageFeedback({result:params.result,pmRoot:params.pmRoot,author:params.author,ranking:params.readyRanking}),params.result}function filterCandidatesByParentScope(candidates,corpus,parentScope){if(!parentScope)return candidates;const subtree=collectSubtreeIds(corpus,parentScope);if(!subtree.found)throw new PmCliError(`Next --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return candidates.filter(item=>subtree.ids.has(item.id.trim().toLowerCase()))}async function rankReadyEntriesWithRelevance(rankedReady,childrenByParent,statusRegistry,now,callerAuthor,pmRoot,includeContainers,rankingPolicy){const concreteReady=rankedReady.filter(entry=>!hasCompletedDescendants(entry.item,childrenByParent)),structuralReady=includeContainers||concreteReady.length===0?rankedReady:concreteReady,usage=await readContextUsageAffinity({pmRoot,author:callerAuthor,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structuralReady.map(entry=>entry.item),{pmRoot,storeKey:"next",statusRegistry,now,author:callerAuthor,usageAffinity:usage.affinity}),ranking=await scoreContextCandidatesWithActiveExtensions("next",featureStore.candidates),relevanceRank=applyNextRankingPolicy(ranking.ranked,statusRegistry,rankingPolicy,ranking.model),readyById=new Map(structuralReady.map(entry=>[entry.item.id,entry]));return{projectedReady:ranking.ranked.map(entry=>readyById.get(entry.id)).filter(entry=>entry!==void 0),ranking,completedContainer:concreteReady.length===0&&!includeContainers,featureStore,relevanceRank}}function resolveNextCallerAuthor(options,settingsAuthor){const requestedAssignee=options.assignee?.trim();return resolveAuthor(options.callerAuthor??(requestedAssignee&&requestedAssignee.length>0?requestedAssignee:void 0),settingsAuthor)}function requestedSelectionBudget(options,resolved){return options.tokenBudget===void 0?null:resolved}async function runNext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),callerAuthor=resolveNextCallerAuthor(options,settings.author_default),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),rankingPolicy=resolveNextRankingPolicy(options.rankingPolicy,settings.context.next_ranking_policy),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),now=nowIso(),limit=parseNextLimit(options.limit,"--limit",DEFAULT_NEXT_LIMIT),tokenBudget=resolveContextTokenBudget(options.tokenBudget,Math.max(192,limit*128)),requestedTokenBudget=requestedSelectionBudget(options,tokenBudget),blockedLimit=parseNextLimit(options.blockedLimit,"--blocked-limit",limit),readyOnly=options.readyOnly===!0,parentScope=typeof options.parent=="string"?options.parent.trim():"",candidatesList=await runList(void 0,nextListOptions(options,{excludeTerminal:!0}),global2),corpusList=await runList(void 0,{excludeTerminal:!1,noTruncate:!0},global2),candidates=filterCandidatesByParentScope(candidatesList.items,corpusList.items,parentScope),corpus=corpusList.items,report=computeActionabilityReport(candidates,corpus,statusRegistry,typeRegistry),childrenByParent=buildChildrenByParent(corpus),selected=selectActionableEntries(report,statusRegistry,options,typeRegistry),callerPartition=partitionCallerOwnedReady(selected.ready,settings.author_default,callerAuthor),rankedReady=rankNextReadyEntries(callerPartition.available,childrenByParent,statusRegistry),rankedBlocked=[...report.blocked].sort((left,right)=>compareCriticalItems(left.item,right.item,statusRegistry)),{projectedReady,ranking:readyRanking,completedContainer,featureStore,relevanceRank}=await rankReadyEntriesWithRelevance(rankedReady,childrenByParent,statusRegistry,now,callerAuthor,pmRoot,options.includeContainers===!0,rankingPolicy),readyRows=projectedReady.map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),blockedRows=rankedBlocked.map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),decisionRows=rankNextReadyEntries(selected.decisions,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),gateRows=rankNextReadyEntries(selected.gates,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),containerRows=rankNextReadyEntries(report.containers,childrenByParent,statusRegistry).map((entry,index)=>toNextActionableItem(entry,statusRegistry,childrenByParent,index+1)),recommended=buildNextRecommendation({projectedReady,readyRows,statusRegistry,now,completedContainer,policyReason:describeRankingPolicyReason(projectedReady,relevanceRank,statusRegistry,rankingPolicy)}),truncation=buildNextTruncation(decisionRows.length,callerPartition.held.length,readyRows.length,limit)??{};gateRows.length>limit&&(truncation.gate_needed_total=gateRows.length),containerRows.length>limit&&(truncation.containers_total=containerRows.length);const result={output_default:"toon",now,recommended,ready:readyRows.slice(1,limit+1),decision_needed:decisionRows.slice(0,limit),gate_needed:gateRows.slice(0,limit),containers:containerRows.slice(0,limit),blocked:readyOnly?[]:blockedRows.slice(0,blockedLimit),held_by_others:callerPartition.held.slice(0,limit),summary:{recommended:recommended!==null,ready:readyRows.length,blocked:blockedRows.length,in_progress:inProgressReadyCount(readyRows,statusRegistry),candidates:report.active_count,containers:report.container_count,decision_needed:decisionRows.length,gate_needed:gateRows.length,held_by_others:callerPartition.held.length},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,parent:parentScope.length>0?parentScope:null,limit,blocked_limit:blockedLimit,ready_only:readyOnly,include_decisions:options.includeDecisions===!0,include_gates:options.includeGates===!0,include_containers:options.includeContainers===!0,token_budget:requestedTokenBudget,ranking_policy:rankingPolicy},truncation:Object.keys(truncation).length>0?truncation:void 0};return finalizeNextResult({result,recommended,blockedRows,gateCount:gateRows.length,candidatesWarnings:candidatesList.warnings,corpusWarnings:corpusList.warnings,readyRanking,explainRanking:options.explainRanking===!0,pmRoot,author:callerAuthor,packingBudget:tokenBudget,featureStore,tokenBudget:requestedTokenBudget,hasIntentBudget:typeof options.for=="string"})}function renderNextMarkdown(result){const lines=["# pm next","",...renderNextSummaryLines(result)];for(const[title,rows]of[["Gate verification needed",result.gate_needed],["Containers",result.containers]])rows&&rows.length>0&&lines.push(...renderNextSection(title,rows.map(item=>`- ${formatNextLine(item)}`),""));if(lines.push(...renderNextSection("Recommended",renderNextRecommendedRows(result.recommended),result.truncation?.ready_budget?.recommendation_omitted?"Recommendation omitted by the selection budget; ready work still exists.":"No ready work.")),lines.push(...renderNextSection("Decision needed",(result.decision_needed??[]).map(item=>`- ${formatNextLine(item)}`),"No human-gated decisions.")),lines.push(...renderNextSection("Ready",result.ready.map(item=>`- ${formatNextLine(item)}`),"No ready items.")),result.filters.ready_only||lines.push(...renderNextSection("Blocked",result.blocked.map(item=>`- ${formatNextBlockedLine(item)}`),"No blocked items.")),result.suggestions&&result.suggestions.length>0){lines.push("## Suggestions");for(const suggestion of result.suggestions)lines.push(`- ${suggestion}`)}return lines.join(`
|
|
2
|
+
`).trimEnd()}function renderNextSummaryLines(result){const lines=[`- now: ${result.now}`,`- ready: ${result.summary.ready} (in_progress: ${result.summary.in_progress}), blocked: ${result.summary.blocked}, candidates: ${result.summary.candidates}`];return result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(""),lines}function renderNextRecommendedRows(recommended){return recommended?[`- ${formatNextLine(recommended)}`,` why: ${recommended.reasons.join("; ")}`]:[]}function renderNextSection(header,rows,emptyMessage){return[`## ${header}`,...rows.length===0?[emptyMessage]:rows,""]}function formatNextBlockedLine(item){const by=item.blockers.map(blocker=>`${blocker.id}(${blocker.status??"?"})`).join(", ");return`${formatNextLine(item)} blocked_by:${by}`}function formatNextLine(item){const deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",unblocksToken=item.unblocks.length>0?` unblocks:${item.unblocks.length}`:"";return`${Number.isInteger(item.rank)?`#${item.rank} `:""}${item.id} p${item.priority} ${item.status} ${item.type} deadline:${deadlineToken}${parentToken}${unblocksToken} ${item.title}`}export{NEXT_OUTPUT_VALUES,NEXT_RANKING_POLICIES2 as NEXT_RANKING_POLICIES,_testOnlyNextCommand,partitionDecisionEntries,renderNextMarkdown,resolveNextOutputFormat,runNext};
|
|
3
3
|
//# sourceMappingURL=next.js.map
|
|
@@ -21,6 +21,10 @@ export type ListCommandName = keyof typeof LIST_COMMAND_DEFAULT_PROJECTIONS;
|
|
|
21
21
|
export declare function listListProjectionFields(runtimeMetadataKeys?:Iterable<string>):string[];
|
|
22
22
|
/** Canonical get depth values. The CLI also accepts full as an alias for deep. */
|
|
23
23
|
export declare const GET_DEPTH_VALUES:readonly ["brief","standard","deep"];
|
|
24
|
+
/** Every get `--depth` spelling the CLI accepts, including the full alias. */
|
|
25
|
+
export declare const GET_DEPTH_INPUT_VALUES:readonly ["brief","standard","deep","full"];
|
|
26
|
+
/** Supported values accepted by the plan show depth contract. */
|
|
27
|
+
export declare const PLAN_SHOW_DEPTH_VALUES:readonly ["brief","standard","deep"];
|
|
24
28
|
/** Return every accepted get projection selector for core and runtime metadata. */
|
|
25
29
|
export declare function listGetProjectionFields(runtimeMetadataKeys?:Iterable<string>):string[];
|
|
26
30
|
/** Stable field order for compact search results. */
|
|
@@ -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]="88ed7e44-a3a0-5a23-9d7b-b00087bff331")}catch{}})();import{ITEM_METADATA_KEY_ORDER}from"../../core/shared/item-metadata-contract.js";const DEFAULT_COMPACT_LIST_FIELDS=["id","title","status","type","priority","parent","updated_at"],BRIEF_LIST_FIELDS=["id","status","type","title"],LIST_COMMAND_DEFAULT_PROJECTIONS={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},TREE_METADATA_FIELDS=["tree_depth","tree_parent","tree_children","tree_title"];function listListProjectionFields(runtimeMetadataKeys=[]){return[...new Set([...ITEM_METADATA_KEY_ORDER,"body",...TREE_METADATA_FIELDS,...runtimeMetadataKeys])].flatMap(field=>[field,`item.${field}`]).sort()}const GET_DEPTH_VALUES=["brief","standard","deep"],GET_DEPTH_INPUT_VALUES=[...GET_DEPTH_VALUES,"full"],PLAN_SHOW_DEPTH_VALUES=["brief","standard","deep"],GET_ROOT_PROJECTION_FIELDS=["body","linked","claim_state","children","schedule","blockers"],GET_LINKED_PROJECTION_FIELDS=["linked.files","linked.tests","linked.docs"],GET_CLAIM_STATE_PROJECTION_FIELDS=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],GET_SCHEDULE_PROJECTION_FIELDS=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function listGetProjectionFields(runtimeMetadataKeys=[]){return[...[...new Set([...ITEM_METADATA_KEY_ORDER,...runtimeMetadataKeys,"notes_count","tests_count","collection_counts"])].flatMap(field=>[field,`item.${field}`]),...GET_ROOT_PROJECTION_FIELDS,...GET_LINKED_PROJECTION_FIELDS,...GET_CLAIM_STATE_PROJECTION_FIELDS,...GET_SCHEDULE_PROJECTION_FIELDS].sort()}const DEFAULT_COMPACT_SEARCH_FIELDS=["id","title","status","type","priority","updated_at","score","matched_fields"],SEARCH_HIT_FIELD_KEYS=["score","matched_fields","highlights"],SEARCH_ITEM_FIELD_KEYS=["id","title","description","type","status","priority","tags","created_at","updated_at","deadline","assignee","author","estimated_minutes","acceptance_criteria","dependencies","comments","notes","learnings","reminders","events","files","tests","docs","close_reason","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result","affected_version","fixed_version","component","regression","customer_impact","definition_of_ready","order","rank","goal","objective","value","impact","outcome","why_now","plan"];function listSearchProjectionFields(runtimeMetadataKeys=[]){const runtimeKeys=[...new Set(runtimeMetadataKeys)];return[...SEARCH_HIT_FIELD_KEYS,...SEARCH_ITEM_FIELD_KEYS,...SEARCH_ITEM_FIELD_KEYS.map(field=>`item.${field}`),...runtimeKeys,...runtimeKeys.map(field=>`item.${field}`)].sort()}export{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,DEFAULT_COMPACT_SEARCH_FIELDS,GET_DEPTH_INPUT_VALUES,GET_DEPTH_VALUES,LIST_COMMAND_DEFAULT_PROJECTIONS,PLAN_SHOW_DEPTH_VALUES,SEARCH_HIT_FIELD_KEYS,SEARCH_ITEM_FIELD_KEYS,listGetProjectionFields,listListProjectionFields,listSearchProjectionFields};
|
|
2
2
|
//# sourceMappingURL=projection-contracts.js.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module sdk/read-output/surfaces
|
|
3
|
+
*
|
|
4
|
+
* Native read-surface identity and legacy projection-mode tables. Kept free of
|
|
5
|
+
* renderer and budget imports so bootstrap-time recovery can derive a command's
|
|
6
|
+
* completeness vocabulary without loading the output formatters.
|
|
7
|
+
*/
|
|
8
|
+
import { PM_READ_OUTPUT_SURFACES } from "./options.js";
|
|
9
|
+
/** Native read surface named by the universal output contract. */
|
|
10
|
+
type NativeReadOutputSurface = (typeof PM_READ_OUTPUT_SURFACES)[number];
|
|
11
|
+
/** Output dimension that a legacy flag aliases. */
|
|
12
|
+
type ReadOutputDimension = "include" | "amount" | "cost" | "encoding";
|
|
13
|
+
/** Legacy per-command flags grouped by the universal dimension they alias. */
|
|
14
|
+
export declare const LEGACY_FLAGS_BY_COMMAND:Readonly<Partial<Record<string,Partial<Record<ReadOutputDimension,string[]>>>>>;
|
|
15
|
+
/** Include aliases that carry a value rather than naming a projection mode. */
|
|
16
|
+
export declare const VALUE_BEARING_INCLUDE_ALIASES:Set<string>;
|
|
17
|
+
/** Legacy flags whose behavior the canonical dimension does not replace. */
|
|
18
|
+
export declare const BEHAVIOR_PRESERVING_MIGRATION_HINTS:Readonly<Record<string,string>>;
|
|
19
|
+
/** Translate a CLI flag into the underscore selector used by projection-mode contracts. */
|
|
20
|
+
export declare function flagSelector(flag:string):string;
|
|
21
|
+
/** Resolve native read aliases without consulting request-local extension state. */
|
|
22
|
+
export declare function resolveNativeReadOutputSurface(normalizedCommand:string,options?:Record<string,unknown>):NativeReadOutputSurface | undefined;
|
|
23
|
+
/** Build compatibility include modes without invoking runtime registry discovery. */
|
|
24
|
+
export declare function readOutputIncludeModeOptionsForSurface(surface:string):ReadonlyMap<string,string>;
|
|
25
|
+
/** Convert a dashed CLI flag to the camel-case key accepted by command option records. */
|
|
26
|
+
export declare function optionKey(flag:string):string;
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="03289358-031e-50aa-b94b-644697c4afc7")}catch{}})();import{PM_READ_OUTPUT_SURFACES}from"./options.js";const LEGACY_FLAGS_BY_COMMAND={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded","--after"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]),BEHAVIOR_PRESERVING_MIGRATION_HINTS=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded --output-budget unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function flagSelector(flag){return flag.slice(2).replaceAll("-","_")}function resolveNativeReadOutputSurface(normalizedCommand,options={}){const root=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===!0||options.target==="catalog"||options.action==="catalog")?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0],normalized=root.startsWith("list-")?"list":root==="ctx"?"context":root;return PM_READ_OUTPUT_SURFACES.includes(normalized)?normalized:void 0}function readOutputIncludeModeOptionsForSurface(surface){return new Map((LEGACY_FLAGS_BY_COMMAND[surface]?.include??[]).filter(flag=>!VALUE_BEARING_INCLUDE_ALIASES.has(flag)&&BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0).map(flag=>[flagSelector(flag),optionKey(flag)]))}function optionKey(flag){return flag.slice(2).replace(/-([a-z])/gu,(_,character)=>character.toUpperCase())}export{BEHAVIOR_PRESERVING_MIGRATION_HINTS,LEGACY_FLAGS_BY_COMMAND,VALUE_BEARING_INCLUDE_ALIASES,flagSelector,optionKey,readOutputIncludeModeOptionsForSurface,resolveNativeReadOutputSurface};
|
|
2
|
+
//# sourceMappingURL=surfaces.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]="a829643f-ca94-51b0-a6ae-27583cd95b3d")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS,PM_READ_OUTPUT_SURFACES}from"./read-output/options.js";import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand}from"./read-output/extension.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections,refreshReadOutputDeliveredCounts}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint}from"./read-output/continuation.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as PM_READ_OUTPUT_SURFACES2}from"./read-output/options.js";const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS,LEGACY_FLAGS_BY_COMMAND={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded","--after"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},VALUE_BEARING_INCLUDE_ALIASES=new Set(["--collapse","--fields","--section"]),BEHAVIOR_PRESERVING_MIGRATION_HINTS=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded --output-budget unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function flagSelector(flag){return flag.slice(2).replaceAll("-","_")}function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command]??{},dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptionsForSurface(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract)),SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase()),extension=resolveExtensionOutputCommand(normalizedCommand);return extension!==void 0?extension.read_output===void 0?void 0:`extension:${extension.command}`:resolveNativeReadOutputSurface(normalizedCommand,options)}function resolveNativeReadOutputSurface(normalizedCommand,options){const root=normalizedCommand==="package catalog"||normalizedCommand==="packages catalog"||normalizedCommand==="package-catalog"||(normalizedCommand==="package"||normalizedCommand==="packages"||normalizedCommand==="extension")&&(options.catalog===!0||options.target==="catalog"||options.action==="catalog")?"package-catalog":normalizedCommand==="package manage"||normalizedCommand==="package-manage"?"package-manage":normalizedCommand.split(" ")[0],normalized=root.startsWith("list-")?"list":root==="ctx"?"context":root;return PM_READ_OUTPUT_SURFACES.includes(normalized)?normalized:void 0}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],HYBRID_READ_MUTATION_KEYS={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>(parseReadOutputSession(value),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value=="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){const encoding=options.outputFormat??options.output_format;if(encoding!==void 0&&encoding!=="json"&&encoding!=="toon")throw new PmCliError("--output-format must be toon or json.",EXIT_CODE.USAGE);if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE);if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==!1))throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE);for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value))throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);return surface?readOutputIncludeModeOptionsForSurface(surface):new Map}function readOutputIncludeModeOptionsForSurface(surface){return new Map((LEGACY_FLAGS_BY_COMMAND[surface]?.include??[]).filter(flag=>!VALUE_BEARING_INCLUDE_ALIASES.has(flag)&&BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0).map(flag=>[flagSelector(flag),optionKey(flag)]))}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual,Object.hasOwn(options,"output_include")&&(options.output_include=residual)}function optionKey(flag){return flag.slice(2).replace(/-([a-z])/gu,(_,character)=>character.toUpperCase())}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).flatMap(entry=>typeof entry=="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0)return{source:"canonical",value:canonicalLimit};if(!legacy)return;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0)return{source:"canonical",value:canonicalBudget};if(!legacy)return;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon")return{source:"canonical",value:canonical};if(legacy)return legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)return!explicitLegacyAliases.has(flag);const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance,options){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||isRequestedOption(readOption(options,"--no-truncate"))&&!shouldIgnoreReadOutputLegacyAlias(provenance,"amount","--no-truncate")||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand)??buildSurfaceContract(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)},legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance,options),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result),unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0)throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE);const fullItem=selectors.includes("item"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0)throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE);const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item:itemSelectors.length>0&&(projected.item=projectRecordFields(vocabulary.item,itemSelectors));const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get")return applyGetIncludeProjection(result,selectors);const rows=readOutputRowPaths(result),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount);if(!truncated)return bounded;if(bounded.has_more=!0,bounded.truncated=!0,typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens,previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format),preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate)return withSession}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).some(group=>isRecord(group)&&group.name==="diagnostic_rows"))return result;const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))],diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector=="string"?existingContract.jq_selector:".checks[].details"}}}function projectReadOutputRows(result,resolved,session,cursor,options){let projected={...result};if(resolved.include?.source==="canonical"&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,result,resolved.command,cursor,options);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value),continuationState.cursorContinuesExistingPage&&rebaseCompactedProducerCursor(projected,continuationState.originalItems,continuationState.cursorSource,!0,continuationState.originalItemOffset)),refreshReadOutputDeliveredCounts(projected,continuationSource),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default"||resolved.command==="context"&&resolved.cost.source==="legacy")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]].sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function hasContextIntentBudgetReceipt(result,tokens){return isRecord(result.context_intent)&&result.context_intent.command==="context"&&result.context_intent.token_budget===tokens&&result.context_intent.within_budget===!0}function readOutputBudgetReceiptFields(budget,result={}){return budget?.source==="default"||budget?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,budget.tokens)?{budget_source:budget.source,budget_tokens:budget.tokens}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens)throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE);return boundedOmission}function requiresReadOutputAudit(resolved,options,result){return resolved.command==="context"&&resolved.cost?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,resolved.cost.value)||options.outputRowContract===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options,result))return!1;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"&&resolved.command!=="context"||estimateReadOutputTokens(options.outputRowContract===!1?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);if(retainedRows>=before.rows)return[];const offset=before.baseOffset+retainedRows;return[{path,cursor:encodeReadOutputContinuationCursor({command:resolved.command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint}),retained_rows:retainedRows,remaining_rows:before.totalRows-offset,total_rows:before.totalRows}]}),primary=continuations[0],continuationHint=primary?"; page --output-cursor":"",budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});primary&&!continuationCursorRebased&&(typeof projected.next_cursor!="string"||projected.continuation_kind==="output_cursor")&&(projected.next_cursor=primary.cursor),projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none",projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseCompactedProducerCursor(projected,originalItems,cursorSource,cursorContinuesExistingPage,originalItemOffset){if(typeof cursorSource!="string"||!Array.isArray(projected.items))return!1;const retainedCount=projected.items.length,originalItemCount=originalItems.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=originalItems[retainedCount-1];if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+originalItemOffset+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}function captureReadOutputContinuationState(projected,source,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length,continued=cursor?.path===collection.path;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued?cursor.offset:0,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]})),cursorContinuesExistingPage=typeof projected.next_cursor=="string",originalItemOffset=cursor?.path==="items"?cursor.offset:0;return{collectionsBeforeBudget,originalItems:Array.isArray(source.items)?originalItemOffset>0?source.items.slice(originalItemOffset):source.items:[],originalItemOffset,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource);const continuationCursorRebased=rebaseCompactedProducerCursor(compacted,continuationState.originalItems,continuationState.cursorSource,continuationState.cursorContinuesExistingPage,continuationState.originalItemOffset);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget,projected),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES2 as PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="dd173d3c-f3da-53f3-b24c-118364961db7")}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,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections,refreshReadOutputDeliveredCounts}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint}from"./read-output/continuation.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as PM_READ_OUTPUT_SURFACES2}from"./read-output/options.js";const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS;function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command]??{},dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptionsForSurface(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract)),SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase()),extension=resolveExtensionOutputCommand(normalizedCommand);return extension!==void 0?extension.read_output===void 0?void 0:`extension:${extension.command}`:resolveNativeReadOutputSurface(normalizedCommand,options)}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],HYBRID_READ_MUTATION_KEYS={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>(parseReadOutputSession(value),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value=="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){const encoding=options.outputFormat??options.output_format;if(encoding!==void 0&&encoding!=="json"&&encoding!=="toon")throw new PmCliError("--output-format must be toon or json.",EXIT_CODE.USAGE);if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE);if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==!1))throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE);for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value))throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);return surface?readOutputIncludeModeOptionsForSurface(surface):new Map}function 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){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount);if(!truncated)return bounded;if(bounded.has_more=!0,bounded.truncated=!0,typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens,previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format),preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate)return withSession}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).some(group=>isRecord(group)&&group.name==="diagnostic_rows"))return result;const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))],diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector=="string"?existingContract.jq_selector:".checks[].details"}}}function projectReadOutputRows(result,resolved,session,cursor,options){let projected={...result};if(resolved.include?.source==="canonical"&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,result,resolved.command,cursor,options);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value),continuationState.cursorContinuesExistingPage&&rebaseCompactedProducerCursor(projected,continuationState.originalItems,continuationState.cursorSource,!0,continuationState.originalItemOffset)),refreshReadOutputDeliveredCounts(projected,continuationSource),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default"||resolved.command==="context"&&resolved.cost.source==="legacy")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]].sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function hasContextIntentBudgetReceipt(result,tokens){return isRecord(result.context_intent)&&result.context_intent.command==="context"&&result.context_intent.token_budget===tokens&&result.context_intent.within_budget===!0}function 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||requiresReadOutputAudit(resolved,options,result))return!1;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"&&resolved.command!=="context"||estimateReadOutputTokens(options.outputRowContract===!1?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);if(retainedRows>=before.rows)return[];const offset=before.baseOffset+retainedRows;return[{path,cursor:encodeReadOutputContinuationCursor({command:resolved.command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint}),retained_rows:retainedRows,remaining_rows:before.totalRows-offset,total_rows:before.totalRows}]}),primary=continuations[0],continuationHint=primary?"; page --output-cursor":"",budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});primary&&!continuationCursorRebased&&(typeof projected.next_cursor!="string"||projected.continuation_kind==="output_cursor")&&(projected.next_cursor=primary.cursor),projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none",projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseCompactedProducerCursor(projected,originalItems,cursorSource,cursorContinuesExistingPage,originalItemOffset){if(typeof cursorSource!="string"||!Array.isArray(projected.items))return!1;const retainedCount=projected.items.length,originalItemCount=originalItems.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=originalItems[retainedCount-1];if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+originalItemOffset+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}function captureReadOutputContinuationState(projected,source,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length,continued=cursor?.path===collection.path;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued?cursor.offset:0,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]})),cursorContinuesExistingPage=typeof projected.next_cursor=="string",originalItemOffset=cursor?.path==="items"?cursor.offset:0;return{collectionsBeforeBudget,originalItems:Array.isArray(source.items)?originalItemOffset>0?source.items.slice(originalItemOffset):source.items:[],originalItemOffset,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource);const continuationCursorRebased=rebaseCompactedProducerCursor(compacted,continuationState.originalItems,continuationState.cursorSource,continuationState.cursorContinuesExistingPage,continuationState.originalItemOffset);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget,projected),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES2 as PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
|
|
2
2
|
//# sourceMappingURL=read-output-contracts.js.map
|
|
@@ -91,3 +91,4 @@ export { persistSelectedItemFormat,readSettings,readSettingsWithMetadata,runWith
|
|
|
91
91
|
export { maybeRunFirstUseTelemetryPrompt } from "../core/telemetry/consent.js";
|
|
92
92
|
export { type TelemetryCommandResolution,type TelemetryResolutionStage,deriveTelemetryCommandResolution,} from "../core/telemetry/observability.js";
|
|
93
93
|
export { type ActiveTelemetryCommand,type TelemetryCommandOutcome,emitTelemetryErrorEvent,finishTelemetryCommand,startTelemetryCommand,} from "../core/telemetry/runtime.js";
|
|
94
|
+
export { resolveTelemetrySourceAttribution } from "../core/telemetry/policy.js";
|