@unbrained/pm-cli 2026.10.28 → 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 +50 -0
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/commands/lifecycle/append.d.ts +4 -0
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/create.d.ts +4 -0
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/plan.d.ts +3 -0
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.d.ts +4 -0
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.d.ts +4 -0
- package/dist/cli/commands/lifecycle/update.js +1 -1
- 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/help-content.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-list-query.js +3 -3
- 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-YYD5MNAV.js → chunk-2AHSPMKJ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-35Q2B2GJ.js +2 -0
- 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-YUBUNECD.js → chunk-BS2KXT24.js} +84 -84
- package/dist/cli-bundle/chunks/{chunk-D3AIQZXF.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-PT7TS6E7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TH5KPAN4.js → chunk-SBVX5CMV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D6P6IBPN.js → chunk-TL3O5GZA.js} +45 -45
- package/dist/cli-bundle/chunks/chunk-U7JXZMU5.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-DM3PICGU.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-GKDKHRTZ.js → mutation-admission-I4RHIT3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-MHJJUM6M.js → register-list-query-MVDL5EXG.js} +6 -6
- 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-WUZ2ZSMY.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-2FYJGGG3.js → stage-2ZORTOF6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4GN2ZPT5.js → chunk-2J7T2UCH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YLVHHWHN.js → chunk-4PW5XWVI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4QPGJO2G.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IQKLJFJE.js → chunk-57HPXGOQ.js} +18 -18
- 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-ON5WFDCG.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-C2GLO7HU.js → chunk-HPWT3RBG.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-HSAEEWSI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7SZPZOIC.js → chunk-JLXGRDTG.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-JNKRUCVZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JTCGDODH.js → chunk-KH5QJXY7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KKRIFBSL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TUN4M757.js → chunk-MW77Q3AQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NOKG4RFN.js +22 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DRN4W3YJ.js → chunk-NRBUMDLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ML5JIUM6.js → chunk-PC3R5CJV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PFBQOZPK.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-R3EA3SDW.js → chunk-QFMJGQGO.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-I4X6AKOO.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-5H6RMRTK.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-TM3SVU2O.js → mutation-admission-KDJ7SCPA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-LBVWWSCF.js → settlement-hook-SJV52ZTV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-7ZBRX2Q2.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 -43
- 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 +61 -61
- 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/history/operation-contract.d.ts +2 -2
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/item/literal-mutation-input.d.ts +12 -0
- package/dist/core/item/literal-mutation-input.js +2 -0
- package/dist/core/item/parse.d.ts +2 -0
- package/dist/core/item/parse.js +2 -2
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/output.js +3 -3
- 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/item-store.js +1 -1
- 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/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/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/item-transaction.d.ts +33 -2
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/append.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.d.ts +4 -0
- package/dist/sdk/lifecycle/cli-input.js +2 -0
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/plan.d.ts +2 -3
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/reopen.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 +15 -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/history.d.ts +2 -0
- package/dist/sdk/query/history.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/mutation-value-validation.d.ts +16 -0
- package/dist/sdk/runtime/mutation-value-validation.js +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +2 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +14 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.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/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.d.ts +54 -0
- package/dist/sdk/workspace-transaction.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 +73 -15
- package/docs/CONFIGURATION.md +48 -1
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +24 -2
- package/docs/PACKED_FIRST_RUN.md +2 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +24 -6
- package/docs/SDK.md +207 -11
- package/docs/TESTING.md +46 -2
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- 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-2J7I54MQ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-3KMYHYJV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +0 -2
- package/dist/cli-bundle/chunks/chunk-7V37RC2L.js +0 -114
- package/dist/cli-bundle/chunks/chunk-AHVN4GHF.js +0 -31
- package/dist/cli-bundle/chunks/chunk-CS7QDSUX.js +0 -128
- package/dist/cli-bundle/chunks/chunk-CXUQEZDX.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DKLEDWVW.js +0 -3
- package/dist/cli-bundle/chunks/chunk-E5QBZ4HI.js +0 -8
- package/dist/cli-bundle/chunks/chunk-JESLOJD7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-PQLRKFPZ.js +0 -20
- package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHONSCLJ.js +0 -6
- package/dist/cli-bundle/chunks/chunk-ZX3XMTZG.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-SN425O3R.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-EYUIUGPW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3EHVI673.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-46WLWK73.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6L4KKRK7.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-6VDRAJYX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-B4ZQJEMT.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-BZSACRVX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-F6UQJJYB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-L5GX2FGZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LPWZERVD.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-OASYSUOH.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-QUPGBO2L.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-Z26ZPQH6.js +0 -3
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
|
|
@@ -9,6 +9,8 @@ export { verifyHistoryChain };
|
|
|
9
9
|
export interface HistoryCommandOptions {
|
|
10
10
|
/** Value that configures or reports limit for this contract. */
|
|
11
11
|
limit?:string;
|
|
12
|
+
/** Display direction after selecting the latest entries; defaults by projection. */
|
|
13
|
+
order?:"oldest_first" | "newest_first";
|
|
12
14
|
/** Value that configures or reports diff for this contract. */
|
|
13
15
|
diff?:boolean;
|
|
14
16
|
/** Restrict --diff to a single field's before/after transitions (implies --diff). */
|
|
@@ -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]="284b91be-bd4e-5345-969b-0304834b0da8")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{historyVersionOffset}from"../../core/history/version-address.js";import{pathExists,computeHistoryDiff,patchPathToChangedField,normalizeReplayPatchOps,verifyHistoryChain,enforceHistoryStreamPolicyForItem,EXIT_CODE,PmCliError,getActiveExtensionRegistrations,normalizeItemId,resolveItemTypeRegistry,locateItem,readLocatedItem,getHistoryPath,getWorkspaceHistoryPath,inspectWorkspaceHistoryState,resolvePmRoot,readSettings,WORKSPACE_HISTORY_ID}from"../runtime-primitives.js";import{readHistoryEntries,verifyHistoryEntries}from"../history-read.js";import{readHistoryEntries as readHistoryEntries2}from"../history-read.js";import{parseLimit}from"./parsers.js";import{resolveModePairedOutputOmissionReceipt}from"../output-projection.js";import{compileHistoryProvenanceMatcher,projectHistoryProvenance,resolveHistoryProvenanceDimensions,summarizeHistoryProvenance}from"../history-provenance.js";function limitEntries(values,limit){return limit===void 0?values:values.slice(Math.max(0,values.length-limit))}function buildDiffEntries(entries,addressing){return entries.map(({entry,version})=>{const changedFields=new Set,patch=normalizeReplayPatchOps(entry.patch);for(const op of patch)changedFields.add(patchPathToChangedField(op.path)),op.from&&changedFields.add(patchPathToChangedField(op.from));return{index:version,...addressing?{version:addressing.offset===null?null:addressing.offset+version}:{},ts:entry.ts,op:entry.op,author:entry.author,patch_ops:patch.length,changed_fields:[...changedFields].sort((left,right)=>left.localeCompare(right))}})}function buildVersionAddressing(history){if(history[0]?.op!=="history_compact_baseline")return;const offset=historyVersionOffset(history,!0);return{offset,first_version:offset===null?null:offset+1,last_version:offset===null?null:offset+history.length}}async function resolveHistoryReadTarget(id,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),workspaceHistoryRequested=id.trim()===WORKSPACE_HISTORY_ID,normalizedId=workspaceHistoryRequested?WORKSPACE_HISTORY_ID:normalizeItemId(id,settings.id_prefix),located=await locateItem(pmRoot,normalizedId,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder),resolvedId=located?.id??normalizedId,historyPath=workspaceHistoryRequested?getWorkspaceHistoryPath(pmRoot):getHistoryPath(pmRoot,resolvedId);if(!located&&!await pathExists(historyPath))throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);return located&&await enforceHistoryStreamPolicyForItem({pmRoot,settings,itemId:located.id,commandLabel:"history"}),{historyPath,located,resolvedId,settings}}function buildHistoryProjection(params){const{resolvedId,selectedHistory,options,limit,addressing,vocabulary,total}=params,compact=options.compact===!0,newestFirst=(options.order??(compact||options.provenance===!0?"newest_first":"oldest_first"))==="newest_first",displayedHistory=newestFirst?[...selectedHistory].reverse():selectedHistory,history=displayedHistory.map(({entry})=>entry),compactHistory=compact?buildDiffEntries(displayedHistory,addressing):void 0,provenanceHistory=options.provenance===!0?displayedHistory.map(({entry,durableVersion})=>projectHistoryProvenance(entry,vocabulary,{itemId:resolvedId,version:durableVersion})):void 0,projectionMode=options.provenance===!0?"provenance":compact?"compact":"full",rowProjection={compact:{compact_history:compactHistory},provenance:{provenance_history:provenanceHistory},full:{history}}[projectionMode];return{id:resolvedId,...rowProjection,compact,projection:{mode:projectionMode,row_key:{compact:"compact_history",provenance:"provenance_history",full:"history"}[projectionMode]},omission_receipt:resolveModePairedOutputOmissionReceipt("history",projectionMode),count:history.length,total,order:newestFirst?"newest_first":"oldest_first",limit:limit??null,version_addressing:addressing}}async function runHistory(id,options,global2){if(options.order!==void 0&&options.order!=="oldest_first"&&options.order!=="newest_first")throw new PmCliError("--order must be oldest_first or newest_first",EXIT_CODE.USAGE);const limit=parseLimit(options.limit),{historyPath,located,resolvedId,settings}=await resolveHistoryReadTarget(id,global2),fullHistory=await readHistoryEntries(historyPath,resolvedId),addressing=buildVersionAddressing(fullHistory),vocabulary=settings.agent_identity.identity_vocabulary,provenanceDimensions=resolveHistoryProvenanceDimensions(settings.agent_identity.harness_signals),matchesProvenance=compileHistoryProvenanceMatcher({harness:options.harness,agentInstance:options.agentInstance,provenance:options.provenanceFilter},vocabulary,provenanceDimensions),filteredHistory=indexHistoryEntries(fullHistory).filter(({entry})=>matchesProvenance(entry)),selectedHistory=limitEntries(filteredHistory,limit),result=buildHistoryProjection({resolvedId,selectedHistory,options,limit,addressing,vocabulary,total:filteredHistory.length});if(options.provenanceSummary===!0&&(result.provenance_summary=summarizeHistoryProvenance(filteredHistory.map(({entry})=>entry),vocabulary,provenanceDimensions)),options.diff||options.field!==void 0){const selectedIndices=new Set(selectedHistory.map(({version})=>version));result.diff=computeHistoryDiff(fullHistory,{windowStartIndex:(selectedHistory[0]?.version??fullHistory.length+1)-1,field:options.field}).filter(row=>selectedIndices.has(row.index)),result.order==="newest_first"&&result.diff.reverse()}if(options.verify){const currentDocument=located?(await readLocatedItem(located,{schema:settings.schema})).document:void 0;if(result.verification=verifyHistoryEntries(fullHistory,currentDocument),resolvedId===WORKSPACE_HISTORY_ID&&result.verification.ok){const agreement=await inspectWorkspaceHistoryState(resolvePmRoot(process.cwd(),global2.path));result.verification={...result.verification,ok:agreement.ok,errors:agreement.ok?result.verification.errors:[...result.verification.errors,"verify_failed:workspace_state_mismatch"],workspace_state_matches_latest:agreement.ok,workspace_state_mismatches:agreement.mismatched_documents,workspace_state_missing:agreement.missing_documents,workspace_state_unreadable:agreement.unreadable_documents}}}return result}function indexHistoryEntries(history){const offset=historyVersionOffset(history,!0);return history.map((entry,index)=>({entry,version:index+1,durableVersion:offset===null?void 0:offset+index+1}))}export{readHistoryEntries2 as readHistoryEntries,runHistory,verifyHistoryChain};
|
|
2
2
|
//# sourceMappingURL=history.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
|