@unbrained/pm-cli 2026.10.21 → 2026.10.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +117 -77
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-KBSVPUFD.js → chunk-35ISFIPC.js} +35 -35
- package/dist/cli-bundle/chunks/{chunk-DIR3YEFD.js → chunk-5LSN7K4N.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DR6DUBTU.js → chunk-7OTYULIJ.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-TMXWWOPJ.js → chunk-AOAQDCXX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZNKFMIVA.js → chunk-BAIVTLJM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NNB65OOO.js → chunk-C37RDYZI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-EMGMLKRV.js → chunk-E3JC3WQL.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-5PZ7JNMI.js → chunk-HC2DCGFA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-V5GJTXYW.js → chunk-J444ZX23.js} +26 -26
- package/dist/cli-bundle/chunks/{chunk-V3XONSVC.js → chunk-LIC5EUQS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DJQVNDXO.js → chunk-MV3KYY2A.js} +6 -6
- package/dist/cli-bundle/chunks/chunk-O67N62DT.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-C6SAXKBO.js → chunk-PCPOTFJP.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-TNU3XVPC.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-MOC5BJHW.js → chunk-URV4VHQ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QPV6UD55.js → chunk-UYYTV2TX.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +9 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-65XXSPPR.js → indexed-receipt-blobs-L3BOTMZN.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-FNWOVJLN.js → mutation-admission-TATOFEXF.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-6PT5Y2EZ.js → register-list-query-GULR2IYO.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-TAIQV46L.js → register-mutation-HLSQ4WVW.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-ONIRO22G.js → register-operations-FE3GGA7O.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-OQMUZBJV.js → register-setup-XUIKAIZA.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-FCPVFO3B.js → stage-QCPZBZRC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-25L3L2PF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PDOWLRHC.js → chunk-25NQRZ7J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XE7P7N5X.js → chunk-2GFTVXKZ.js} +6 -6
- package/dist/cli-bundle/focused-chunks/chunk-46HBJC6J.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-32ZKLRWM.js → chunk-A52W6GLA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CB7TSZ7P.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-5IMM7GOF.js → chunk-CX5FNEFC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VD64TPXI.js → chunk-EHPRSWJE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-P5D7MHDS.js → chunk-GC4VMLXL.js} +15 -15
- package/dist/cli-bundle/focused-chunks/{chunk-CUWNNU4N.js → chunk-GVKYTDOH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HNCMYF2W.js → chunk-KM77WU5U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QGDKWULS.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-YIWDX6KO.js → chunk-QWKCQ5PW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-4HJVAUFX.js → chunk-SXVJRLLP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KVYUQS6Y.js → chunk-TMN3RAXZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7UD7XTOE.js → chunk-UQ5JPBY2.js} +11 -11
- package/dist/cli-bundle/focused-chunks/{chunk-JMZPZQHR.js → chunk-UUPJ6OZL.js} +13 -13
- package/dist/cli-bundle/focused-chunks/{chunk-JI3RXXRN.js → chunk-VYAZND5Q.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-T27TLSEU.js → chunk-W2CND3BD.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-44353U27.js → chunk-XX5JQCLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-CRP6HAZY.js → indexed-receipt-blobs-AAQOKO5B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-KM57KDDF.js → mutation-admission-TBKR4KRM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-UJYGWNZ7.js → stage-RM6MJIMT.js} +2 -2
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +21 -21
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +58 -58
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +7 -7
- package/dist/mcp/server.d.ts +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/agent/command-recovery.d.ts +2 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/context-intent-contracts.d.ts +13 -0
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/contracts.d.ts +1 -1
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core.d.ts +2 -2
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/define.d.ts +15 -16
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +5 -0
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/read-output/session-result.d.ts +39 -0
- package/dist/sdk/read-output/session-result.js +2 -0
- package/dist/sdk/read-output-contracts.d.ts +18 -5
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-session.d.ts +2 -0
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +6 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +10 -8
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/workspace.d.ts +3 -1
- package/dist/sdk/workspace.js +8 -5
- package/docs/CONFIGURATION.md +9 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +30 -0
- package/docs/MCP_OPTION_CONFORMANCE.md +27 -1
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +79 -0
- package/docs/RELATIONSHIP_GRAPH.md +15 -0
- package/docs/RELEASING.md +8 -0
- package/docs/SDK.md +37 -7
- package/docs/TESTING.md +5 -0
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4OYU5OXQ.js +0 -6
- package/dist/cli-bundle/chunks/chunk-DIKQ2AL5.js +0 -2
- package/dist/cli-bundle/chunks/chunk-MZZIAC6S.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-6QSZHRM7.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-E2S42XCT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GRSQGMRR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IAGFXKMZ.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-O3M6YWVL.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VE6MTRH5.js +0 -2
|
@@ -82,6 +82,19 @@ export declare function contextIntentRowId(row:unknown):string | undefined;
|
|
|
82
82
|
export declare function attachContextIntentReceipt<Result extends Record<string,unknown>>(command:string,options:Record<string,unknown>,result:Result):Result & {
|
|
83
83
|
context_intent?:PmContextIntentReceipt;
|
|
84
84
|
};
|
|
85
|
+
declare const CONTINUATION_METADATA_KEYS:readonly ["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];
|
|
86
|
+
/** Producer page whose repeated metadata is referenced from the original page. */
|
|
87
|
+
export type PmReadOutputProducerContinuation<Result> = Result extends unknown ? Omit<Result,(typeof CONTINUATION_METADATA_KEYS)[number]> & Partial<Pick<Result,Extract<keyof Result,(typeof CONTINUATION_METADATA_KEYS)[number]>>> & {
|
|
88
|
+
/** Identity and recovery for metadata served by the initial producer page. */
|
|
89
|
+
continuation_contract:{
|
|
90
|
+
/** Query identity carried by the producer cursor. */
|
|
91
|
+
fingerprint:string;
|
|
92
|
+
/** Repeated metadata remains in the caller's original page. */
|
|
93
|
+
metadata:"reference";
|
|
94
|
+
/** Reissue the initial query to restore its metadata. */
|
|
95
|
+
restore_with:"omit --after";
|
|
96
|
+
};
|
|
97
|
+
} :never;
|
|
85
98
|
/** Attach universal row, omission, and optional intent-budget contracts in rendering order. */
|
|
86
99
|
export declare function attachReadOutputContracts(command:string | undefined,options:Record<string,unknown>,result:unknown):unknown;
|
|
87
100
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6a604d54-5425-5ae7-8f20-9d5f1d33c20c")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{attachExtensionReadOutputRows}from"./read-output/extension.js";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{unicodeSafePrefix}from"../core/shared/text-normalization.js";const PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit),derivedLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=derivedLimit),projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit);(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit)))},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit);(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit)))}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0,projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){return Array.isArray(value)?value.map(compactContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)])):typeof value=="string"&&value.length>240?`${unicodeSafePrefix(value,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const contextOrient=command==="context"&&intent==="orient",overhead=command==="context"?contextOrient?1200:800:command==="list"?520:480,rowCost=command==="context"?contextOrient?600:500:16,calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit}let projected={...resultWithDiagnostics,context_intent:receipt};return updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt},updateContextIntentEstimate(projected,receipt)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt)),receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget,receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,receipt.within_budget=!1,projected={budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}),projected}function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0)return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"])delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0,recoveryPositional=recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`,boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&updateContextIntentEstimate(finalized,finalized.context_intent),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,attachExtensionReadOutputRows(command??"",result)),projected=typeof disclosedResult=="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",{...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0},collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||typeof projected!="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract"))return projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
|
|
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]="417afa3c-d34b-53d9-b273-86903e17576f")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{attachExtensionReadOutputRows}from"./read-output/extension.js";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{unicodeSafePrefix}from"../core/shared/text-normalization.js";const PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit),derivedLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=derivedLimit),projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit);(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit)))},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveIntentTokenBudget(projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget),requestedLimit=parsePositiveIntentTokenBudget(projected.limit);(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit)))}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0,projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){return Array.isArray(value)?value.map(compactContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactContextIntentValue(entry)])):typeof value=="string"&&value.length>240?`${unicodeSafePrefix(value,240)}\u2026`:value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const contextOrient=command==="context"&&intent==="orient",overhead=command==="context"?contextOrient?1200:800:command==="list"?520:480,rowCost=command==="context"?contextOrient?600:500:16,calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt){let measuredTokens=receipt.estimated_tokens;for(;;){receipt.estimated_tokens=measuredTokens;const nextMeasurement=Math.ceil(Buffer.byteLength(JSON.stringify(projected),"utf8")/4);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement}}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),effectiveTokenBudget=resolveIntentTokenBudget(options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0);if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit}let projected={...resultWithDiagnostics,context_intent:receipt};return updateContextIntentEstimate(projected,receipt),receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected={...compactContextIntentValue(resultWithDiagnostics),context_intent:receipt},updateContextIntentEstimate(projected,receipt)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt)),receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget,receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,receipt.within_budget=!1,projected={budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,receipt,resultWithDiagnostics)},context_intent:receipt}),projected}const CONTINUATION_METADATA_KEYS=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0)return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of CONTINUATION_METADATA_KEYS)delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0,recoveryPositional=recoveryTarget===void 0?"":` '${recoveryTarget.replaceAll("'",`'"'"'`)}'`,boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`;return`pm ${command}${recoveryPositional} --for ${intent} --token-budget ${Math.ceil(receipt.estimated_tokens/100)*100}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&updateContextIntentEstimate(finalized,finalized.context_intent),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,attachExtensionReadOutputRows(command??"",result)),projected=typeof disclosedResult=="object"&&disclosedResult!==null&&!Array.isArray(disclosedResult)?applyReadOutputDimensions(command??"",{...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0},collapseContinuationMetadata(options,attachContextIntentReceipt(command??"",options,disclosedResult))):disclosedResult;if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||typeof projected!="object"||projected===null||Array.isArray(projected)||!Object.hasOwn(projected,"row_contract"))return projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
|
|
2
2
|
//# sourceMappingURL=context-intent-contracts.js.map
|
package/dist/sdk/contracts.d.ts
CHANGED
|
@@ -22,4 +22,4 @@ export * from "../core/history/operation-contract.js";
|
|
|
22
22
|
export * from "./agent/refusal-closure.js";
|
|
23
23
|
export * from "./agent/closed-domain-contracts.js";
|
|
24
24
|
export * from "./agent/tracker-preflight-contracts.js";
|
|
25
|
-
export type { PmReadOutputSessionReceipt,PmReadOutputSessionState,} from "./read-output-session.js";
|
|
25
|
+
export type { PmReadOutputSessionReceipt,PmReadOutputSessionReference,PmReadOutputSessionState,} from "./read-output-session.js";
|
package/dist/sdk/contracts.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]="
|
|
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]="ed3a9b17-2de7-507d-8351-b4c9c454200a")}catch{}})();export*from"./cli-contracts.js";export*from"./graph/query-contracts.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-intent-contracts.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./flag-invocation-contracts.js";import{resolveExtensionFlagValueContract}from"../core/extensions/flag-value-types.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./output-token-accounting.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./read-output-contracts.js";export*from"./history/attestation-contract.js";export*from"../core/history/operation-contract.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/tracker-preflight-contracts.js";export{resolveExtensionFlagValueContract};
|
|
2
2
|
//# sourceMappingURL=contracts.js.map
|
package/dist/sdk/core.d.ts
CHANGED
|
@@ -10,8 +10,8 @@ export { isItemAlreadyExistsError,type PmItemAlreadyExistsError,isPmTokenBudgetR
|
|
|
10
10
|
export * from "./agent-session-context.js";
|
|
11
11
|
export { isAlreadyClaimedError } from "./lifecycle/claim.js";
|
|
12
12
|
export { PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions,} from "./read-output-contracts.js";
|
|
13
|
-
export { applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,} from "./read-output-session.js";
|
|
14
|
-
export type { PmReadOutputBudgetExceeded,PmReadOutputContinuation,PmReadOutputCursorEnvelope,PmReadOutputDimension,PmReadOutputLegacyAlias,PmReadOutputOptions,PmReadOutputReceipt,PmReadOutputResult,PmReadOutputResultFor,PmReadOutputSurface,PmReadOutputSurfaceContract,} from "./read-output-contracts.js";
|
|
13
|
+
export { applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference,} from "./read-output-session.js";
|
|
14
|
+
export type { PmReadOutputBudgetExceeded,PmReadOutputContinuation,PmReadOutputCursorEnvelope,PmReadOutputDimension,PmReadOutputLegacyAlias,PmReadOutputOptions,PmReadOutputProducerContinuation,PmReadOutputReceipt,PmReadOutputResult,PmReadOutputResultFor,PmReadOutputSessionResult,PmReadOutputSurface,PmReadOutputSurfaceContract,} from "./read-output-contracts.js";
|
|
15
15
|
export type { PmReadOutputSessionReceipt,PmReadOutputSessionReference,PmReadOutputSessionState,} from "./read-output-session.js";
|
|
16
16
|
export type { ItemDocument,ItemMetadata,ItemStatus,ItemType,PmSettings,} from "../types/index.js";
|
|
17
17
|
export type { CloseEvidenceFollowUp } from "./lifecycle-policy.js";
|
package/dist/sdk/core.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]="
|
|
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]="3156fd3f-6fa1-53e3-9ef8-a63433f4bc1f")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference}from"./read-output-session.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,isReadOutputSessionReference,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,update,updateLinkedTest,validateReadOutputOptions};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|
package/dist/sdk/define.d.ts
CHANGED
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
* - Definitions can be colocated, exported, reused, and unit-tested apart from
|
|
25
25
|
* the `activate` call instead of being trapped as inline literals.
|
|
26
26
|
*
|
|
27
|
-
* Object-definition builders use
|
|
28
|
-
*
|
|
27
|
+
* Object-definition builders use const type parameters and exact-key constraints
|
|
28
|
+
* so literals survive the round-trip and misspelled metadata fails at author time.
|
|
29
29
|
* Function-definition builders are intentionally non-generic: a generic
|
|
30
30
|
* constrained to a whole function type suppresses contextual typing of a bare
|
|
31
31
|
* arrow's parameter (it would fall back to implicit `any`), whereas the
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
import type { AfterCommandHook,BeforeCommandHook,BeforeMutationHook,CommandDefinition,CommandOverride,Exporter,ExtensionManifest,FlagDefinition,Importer,OnIndexHook,OnReadHook,OnWriteHook,ParserOverride,PreflightOverride,ScopedPreflightOverrideDefinition,RendererOverride,ScopedRendererOverrideDefinition,SchemaFieldDefinition,SchemaItemTypeDefinition,SchemaMigrationDefinition,SearchProviderDefinition,ServiceOverride,ServiceOverrideDecision,VectorStoreAdapterDefinition } from "../core/extensions/loader.js";
|
|
36
36
|
import type { ProjectProfileDefinition } from "../core/profile/profile-presets.js";
|
|
37
37
|
type ExactDefinition<TDefinition,TContract> = TDefinition & Record<Exclude<keyof TDefinition,keyof TContract>,never>;
|
|
38
|
-
type FlagAuthoringDefinition = Pick<FlagDefinition,"long" | "short" | "value_name" | "description" | "required" | "enabled" | "visible" | "value_type" | "type" | "list" | "default">;
|
|
38
|
+
type FlagAuthoringDefinition = Pick<FlagDefinition,"long" | "short" | "value_name" | "description" | "required" | "enabled" | "visible" | "value_type" | "type" | "list" | "repeatable" | "default" | "value_validation">;
|
|
39
39
|
type ItemFieldAuthoringDefinition = Pick<SchemaFieldDefinition,"name" | "type" | "optional" | "default" | "values">;
|
|
40
40
|
type ItemTypeAuthoringDefinition = Pick<SchemaItemTypeDefinition,"name" | "folder" | "aliases" | "required_create_fields" | "required_create_repeatables" | "command_option_policies" | "options" | "description" | "default_status" | "execution_role">;
|
|
41
41
|
type MigrationAuthoringDefinition = Pick<SchemaMigrationDefinition,"id" | "description" | "status" | "mandatory" | "run">;
|
|
@@ -51,7 +51,7 @@ type VectorStoreAdapterAuthoringDefinition = Pick<VectorStoreAdapterDefinition,"
|
|
|
51
51
|
* {@link ./compose.js#deriveExtensionCapabilities | `deriveExtensionCapabilities`}
|
|
52
52
|
* to keep `capabilities` matched to the surfaces the extension actually registers.
|
|
53
53
|
*/
|
|
54
|
-
export declare function defineExtensionManifest<TManifest extends ExtensionManifest>(manifest:TManifest):TManifest;
|
|
54
|
+
export declare function defineExtensionManifest<const TManifest extends ExtensionManifest>(manifest:ExactDefinition<TManifest,ExtensionManifest>):TManifest;
|
|
55
55
|
/**
|
|
56
56
|
* Type a project-profile definition for the profile registry.
|
|
57
57
|
*
|
|
@@ -64,7 +64,7 @@ export declare function defineExtensionManifest<TManifest extends ExtensionManif
|
|
|
64
64
|
* typed at the definition site, mirroring {@link defineItemType}. It is the
|
|
65
65
|
* authoring anchor a first-party or third-party profile package builds on.
|
|
66
66
|
*/
|
|
67
|
-
export declare function defineProjectProfile<TProfile extends ProjectProfileDefinition>(profile:TProfile):TProfile;
|
|
67
|
+
export declare function defineProjectProfile<const TProfile extends ProjectProfileDefinition>(profile:ExactDefinition<TProfile,ProjectProfileDefinition>):TProfile;
|
|
68
68
|
/**
|
|
69
69
|
* Type a command definition for `api.registerCommand(definition)`.
|
|
70
70
|
*
|
|
@@ -73,7 +73,7 @@ export declare function defineProjectProfile<TProfile extends ProjectProfileDefi
|
|
|
73
73
|
* types. Pass the result straight to `registerCommand`, or export it so the
|
|
74
74
|
* command can be invoked in tests via `runRegisteredCommandForTest`.
|
|
75
75
|
*/
|
|
76
|
-
export declare function defineCommand<TDefinition extends CommandDefinition>(definition:TDefinition):TDefinition;
|
|
76
|
+
export declare function defineCommand<const TDefinition extends CommandDefinition>(definition:ExactDefinition<TDefinition,CommandDefinition>):TDefinition;
|
|
77
77
|
/**
|
|
78
78
|
* Type a single flag definition for a `api.registerFlags(command, flags)` array.
|
|
79
79
|
*
|
|
@@ -82,22 +82,21 @@ export declare function defineCommand<TDefinition extends CommandDefinition>(def
|
|
|
82
82
|
* per-flag contract checking — `value_type`, `list`, and `default` included —
|
|
83
83
|
* instead of validating a loosely-typed literal array all at once.
|
|
84
84
|
*/
|
|
85
|
-
export declare function defineFlag<TFlag extends FlagAuthoringDefinition>(flag:ExactDefinition<TFlag,FlagAuthoringDefinition>):TFlag;
|
|
85
|
+
export declare function defineFlag<const TFlag extends FlagAuthoringDefinition>(flag:ExactDefinition<TFlag,FlagAuthoringDefinition>):TFlag;
|
|
86
86
|
/**
|
|
87
87
|
* Type a custom item-type definition for `api.registerItemTypes([...])`.
|
|
88
88
|
*
|
|
89
89
|
* Preserves the literal `name`/`folder`/`aliases` so a project archetype's
|
|
90
90
|
* domain types stay strongly typed where the definition is declared and reused.
|
|
91
91
|
*/
|
|
92
|
-
export declare function defineItemType<TType extends ItemTypeAuthoringDefinition>(type:ExactDefinition<TType,ItemTypeAuthoringDefinition>):TType;
|
|
92
|
+
export declare function defineItemType<const TType extends ItemTypeAuthoringDefinition>(type:ExactDefinition<TType,ItemTypeAuthoringDefinition>):TType;
|
|
93
93
|
/**
|
|
94
94
|
* Type a custom item-metadata field definition for `api.registerItemFields([...])`.
|
|
95
95
|
*
|
|
96
96
|
* Checks `name`/`type`/`optional` against {@link SchemaFieldDefinition} while
|
|
97
|
-
*
|
|
98
|
-
* intact.
|
|
97
|
+
* preserving literal names and supported default/value metadata.
|
|
99
98
|
*/
|
|
100
|
-
export declare function defineItemField<TField extends ItemFieldAuthoringDefinition>(field:ExactDefinition<TField,ItemFieldAuthoringDefinition>):TField;
|
|
99
|
+
export declare function defineItemField<const TField extends ItemFieldAuthoringDefinition>(field:ExactDefinition<TField,ItemFieldAuthoringDefinition>):TField;
|
|
101
100
|
/**
|
|
102
101
|
* Type a schema migration definition for `api.registerMigration(definition)`.
|
|
103
102
|
*
|
|
@@ -105,7 +104,7 @@ export declare function defineItemField<TField extends ItemFieldAuthoringDefinit
|
|
|
105
104
|
* runner's context, so the same definition can be registered and later exercised
|
|
106
105
|
* through `runRegisteredMigrationForTest`.
|
|
107
106
|
*/
|
|
108
|
-
export declare function defineMigration<TMigration extends MigrationAuthoringDefinition>(migration:ExactDefinition<TMigration,MigrationAuthoringDefinition>):TMigration;
|
|
107
|
+
export declare function defineMigration<const TMigration extends MigrationAuthoringDefinition>(migration:ExactDefinition<TMigration,MigrationAuthoringDefinition>):TMigration;
|
|
109
108
|
/**
|
|
110
109
|
* Type a search-provider definition for `api.registerSearchProvider(provider)`.
|
|
111
110
|
*
|
|
@@ -113,7 +112,7 @@ export declare function defineMigration<TMigration extends MigrationAuthoringDef
|
|
|
113
112
|
* so a custom retrieval backend is type-checked at the definition site and
|
|
114
113
|
* reusable in `runRegisteredSearchProviderForTest`.
|
|
115
114
|
*/
|
|
116
|
-
export declare function defineSearchProvider<TProvider extends SearchProviderAuthoringDefinition>(provider:ExactDefinition<TProvider,SearchProviderAuthoringDefinition>):TProvider;
|
|
115
|
+
export declare function defineSearchProvider<const TProvider extends SearchProviderAuthoringDefinition>(provider:ExactDefinition<TProvider,SearchProviderAuthoringDefinition>):TProvider;
|
|
117
116
|
/**
|
|
118
117
|
* Type a vector-store adapter definition for `api.registerVectorStoreAdapter(adapter)`.
|
|
119
118
|
*
|
|
@@ -121,7 +120,7 @@ export declare function defineSearchProvider<TProvider extends SearchProviderAut
|
|
|
121
120
|
* its own semantic index storage gets contract checking before activation and a
|
|
122
121
|
* definition it can drive through `runRegisteredVectorStoreAdapterForTest`.
|
|
123
122
|
*/
|
|
124
|
-
export declare function defineVectorStoreAdapter<TAdapter extends VectorStoreAdapterAuthoringDefinition>(adapter:ExactDefinition<TAdapter,VectorStoreAdapterAuthoringDefinition>):TAdapter;
|
|
123
|
+
export declare function defineVectorStoreAdapter<const TAdapter extends VectorStoreAdapterAuthoringDefinition>(adapter:ExactDefinition<TAdapter,VectorStoreAdapterAuthoringDefinition>):TAdapter;
|
|
125
124
|
/**
|
|
126
125
|
* Type a command-override handler for `api.registerCommand(command, override)`.
|
|
127
126
|
*
|
|
@@ -146,7 +145,7 @@ export declare function defineParserOverride(override:ParserOverride):ParserOver
|
|
|
146
145
|
*/
|
|
147
146
|
export declare function definePreflightOverride(override:PreflightOverride):PreflightOverride;
|
|
148
147
|
/** Type a scoped preflight definition while preserving literal command ownership. */
|
|
149
|
-
export declare function definePreflightOverride<TDefinition extends ScopedPreflightOverrideDefinition>(override:ExactDefinition<TDefinition,ScopedPreflightOverrideDefinition>):TDefinition;
|
|
148
|
+
export declare function definePreflightOverride<const TDefinition extends ScopedPreflightOverrideDefinition>(override:ExactDefinition<TDefinition,ScopedPreflightOverrideDefinition>):TDefinition;
|
|
150
149
|
/**
|
|
151
150
|
* Type a service-override handler for `api.registerService(service, override)`.
|
|
152
151
|
*
|
|
@@ -173,7 +172,7 @@ export declare function defineRendererOverride(renderer:RendererOverride):Render
|
|
|
173
172
|
* Type a scoped renderer definition while preserving its command/result
|
|
174
173
|
* ownership literals for declarative composition and static introspection.
|
|
175
174
|
*/
|
|
176
|
-
export declare function defineRendererOverride<TDefinition extends ScopedRendererOverrideDefinition>(renderer:ExactDefinition<TDefinition,ScopedRendererOverrideDefinition>):TDefinition;
|
|
175
|
+
export declare function defineRendererOverride<const TDefinition extends ScopedRendererOverrideDefinition>(renderer:ExactDefinition<TDefinition,ScopedRendererOverrideDefinition>):TDefinition;
|
|
177
176
|
/**
|
|
178
177
|
* Type an importer handler for `api.registerImporter(name, importer, options)`.
|
|
179
178
|
*
|
package/dist/sdk/define.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]="
|
|
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]="4c9a1aa8-05b6-53da-a8b1-f1a7289d39cf")}catch{}})();function defineExtensionManifest(manifest){return manifest}function defineProjectProfile(profile){return profile}function defineCommand(definition){return definition}function defineFlag(flag){return flag}function defineItemType(type){return type}function defineItemField(field){return field}function defineMigration(migration){return migration}function defineSearchProvider(provider){return provider}function defineVectorStoreAdapter(adapter){return adapter}function defineCommandOverride(override){return override}function defineParserOverride(override){return override}function definePreflightOverride(override){return override}function defineServiceOverride(override){return override}function handleServiceOverride(result){return{handled:!0,result}}function declineServiceOverride(){return{handled:!1}}function defineRendererOverride(renderer){return renderer}function defineImporter(importer){return importer}function defineExporter(exporter){return exporter}function defineBeforeCommandHook(hook){return hook}function defineBeforeMutationHook(hook){return hook}function defineAfterCommandHook(hook){return hook}function defineOnWriteHook(hook){return hook}function defineOnReadHook(hook){return hook}function defineOnIndexHook(hook){return hook}export{declineServiceOverride,defineAfterCommandHook,defineBeforeCommandHook,defineBeforeMutationHook,defineCommand,defineCommandOverride,defineExporter,defineExtensionManifest,defineFlag,defineImporter,defineItemField,defineItemType,defineMigration,defineOnIndexHook,defineOnReadHook,defineOnWriteHook,defineParserOverride,definePreflightOverride,defineProjectProfile,defineRendererOverride,defineSearchProvider,defineServiceOverride,defineVectorStoreAdapter,handleServiceOverride};
|
|
2
2
|
//# sourceMappingURL=define.js.map
|
package/dist/sdk/dependencies.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]="aaf07c3b-4c16-5374-bf61-934114075578")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{getActiveCommandContext,getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isTerminalStatus}from"../core/item/status.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{formatBuiltInOutput}from"../core/output/output.js";import{listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{estimatePmOutputTokens}from"./cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./command-line.js";import{createPmCliExpectedError}from"./errors.js";import{isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,PM_READ_OUTPUT_SURFACE_CONTRACTS}from"./read-output-contracts.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";import{attachReadOutputContracts}from"./context-intent-contracts.js";import{attachOutputTokenAccounting}from"./output-token-accounting.js";import{assertProjectionModeChoice}from"./output-projection.js";import{assembleWorkspaceRelationshipGraph,collectDanglingDependencyReferences,resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./graph/cache.js";import{buildRelationshipContext,DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET}from"./relationship-context.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEPS_FORMAT_VALUES=["tree","graph","context"],DEPS_COLLAPSE_VALUES=["none","repeated"],DEPS_DIRECTION_VALUES=["outgoing","incoming","both"],DEFAULT_DEPS_TREE_MAX_DEPTH=32,DEFAULT_DEPS_TREE_NODE_LIMIT=200,DEFAULT_DEPS_TREE_EDGE_LIMIT=400,DEFAULT_DEPS_TREE_TOKEN_BUDGET=16e3;function parseFormat(raw){const candidate=raw?.trim().toLowerCase()??"tree";if(DEPS_FORMAT_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --format value "${raw}". Use "tree", "graph", or "context".`,EXIT_CODE.USAGE)}function parsePositiveInteger(raw,flag){if(raw===void 0)return;const value=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(value)||value<1)throw new PmCliError(`Invalid --${flag} value "${raw}". Use a positive integer.`,EXIT_CODE.USAGE);return value}function parseMaxDepth(raw){if(raw===void 0)return;const normalized=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(normalized)||normalized<0)throw new PmCliError(`Invalid --max-depth value "${raw}". Use a non-negative integer.`,EXIT_CODE.USAGE);return normalized}function parseCollapse(raw){const candidate=raw?.trim().toLowerCase()??"none";if(DEPS_COLLAPSE_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --collapse value "${raw}". Use "none" or "repeated".`,EXIT_CODE.USAGE)}function parseDirection(raw){const candidate=raw?.trim().toLowerCase()??"both";if(DEPS_DIRECTION_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --direction value "${raw}". Use "outgoing", "incoming", or "both".`,EXIT_CODE.USAGE)}function parseKinds(raw,registry=createRelationshipKindRegistry()){if(raw===void 0)return;const values=(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)return;const kinds=new Set;for(const value of values){const definition=registry.resolve(value);if(!definition){const known=registry.list().map(entry=>entry.kind).join(", ");throw new PmCliError(`Invalid --kind value "${value}". Registered kinds: ${known}.`,EXIT_CODE.USAGE)}kinds.add(definition.kind)}return[...kinds].sort()}function normalizeDependencies(dependencies){if(!dependencies||dependencies.length===0)return[];const sorted=dependencies.map(({id,kind})=>({id:id.trim(),kind:kind.trim().toLowerCase()})).sort((left,right)=>{const byKind=left.kind.localeCompare(right.kind);return byKind!==0?byKind:left.id.localeCompare(right.id)}),deduped=new Map;for(const dependency of sorted){const key=`${dependency.kind.toLowerCase()}::${dependency.id.toLowerCase()}`;deduped.has(key)||deduped.set(key,{id:dependency.id,kind:dependency.kind})}return[...deduped.values()]}function toIndexedItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,dependencies:normalizeDependencies(item.dependencies)}}function estimateTreeNodeTokens(node){return estimatePmOutputTokens(new TextEncoder().encode(JSON.stringify({...node,dependencies:void 0})).byteLength)}function appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth){for(const dependency of item.dependencies){const edgeTokens=Math.max(1,Math.ceil(JSON.stringify({from:baseNode.id,to:dependency.id,kind:dependency.kind}).length/3));if(budget.nodes>=budget.nodeLimit){baseNode.truncated=!0,budget.reasons.add("node_limit");break}if(budget.edges>=budget.edgeLimit){baseNode.truncated=!0,budget.reasons.add("edge_limit");break}if(budget.estimatedTokens+edgeTokens>=budget.tokenBudget){baseNode.truncated=!0,budget.reasons.add("token_budget");break}budget.edges+=1,budget.estimatedTokens+=edgeTokens,baseNode.dependencies.push(toTreeNode(dependency.id,index,nextLineage,maxDepth,collapse,expanded,budget,depth+1,dependency.kind))}}function shouldStopTreeNodeExpansion(node,item,lookupId,maxDepth,collapse,expanded,budget,depth){return budget.estimatedTokens>=budget.tokenBudget&&item?.dependencies.length?(node.truncated=!0,budget.reasons.add("token_budget"),!0):!item||node.cycle?!0:maxDepth!==void 0&&depth>=maxDepth?(item.dependencies.length>0&&(node.truncated=!0,budget.reasons.add("max_depth")),!0):collapse==="repeated"&&expanded.has(lookupId)?(node.collapsed=!0,!0):!1}function toTreeNode(id,index,lineage,maxDepth,collapse,expanded,budget,depth=0,via){const lookupId=id.trim().toLowerCase(),item=index.get(lookupId),baseNode={id:item?.id??id,title:item?.title,type:item?.type,status:item?.status,via,missing:!item,cycle:lineage.has(lookupId),dependencies:[]};if(budget.nodes+=1,budget.estimatedTokens+=estimateTreeNodeTokens(baseNode),shouldStopTreeNodeExpansion(baseNode,item,lookupId,maxDepth,collapse,expanded,budget,depth))return baseNode;collapse==="repeated"&&expanded.add(lookupId);const nextLineage=new Set(lineage);return nextLineage.add(lookupId),appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth),baseNode}function mergeGraphNode(existing,candidate){return!existing||existing.missing&&!candidate.missing?candidate:{...existing,title:existing.title??candidate.title,type:existing.type??candidate.type,status:existing.status??candidate.status}}function toGraph(root){const nodesById=new Map,edgesByKey=new Map,pending=[root];for(;pending.length>0;){const node=pending.pop();nodesById.set(node.id,mergeGraphNode(nodesById.get(node.id),{id:node.id,title:node.title,type:node.type,status:node.status,missing:node.missing}));for(const child of node.dependencies){nodesById.set(child.id,mergeGraphNode(nodesById.get(child.id),{id:child.id,title:child.title,type:child.type,status:child.status,missing:child.missing}));const relationKind=child.via??"related",edgeKey=`${node.id}::${child.id}::${relationKind}`;edgesByKey.has(edgeKey)||edgesByKey.set(edgeKey,{from:node.id,to:child.id,kind:relationKind}),child.cycle||pending.push(child)}}const nodes=[...nodesById.values()].sort((left,right)=>left.id.localeCompare(right.id)),edges=[...edgesByKey.values()].sort((left,right)=>{const byFrom=left.from.localeCompare(right.from);if(byFrom!==0)return byFrom;const byTo=left.to.localeCompare(right.to);return byTo!==0?byTo:left.kind.localeCompare(right.kind)}),missingIds=nodes.filter(node=>node.missing).map(node=>node.id);return{root_id:root.id,nodes,edges,missing_ids:missingIds}}function countDependencyGraph(rootId,index,maxDepth){const nodeIds=new Set,edgeKeys=new Set,missingIds=new Set,expanded=new Set,pending=[{id:rootId,depth:0}];let pendingIndex=0;for(;pendingIndex<pending.length;){const current=pending[pendingIndex++],lookupId=current.id.trim().toLowerCase();nodeIds.add(lookupId);const item=index.get(lookupId);if(!item){missingIds.add(lookupId);continue}if(!(maxDepth!==void 0&¤t.depth>=maxDepth)&&!expanded.has(lookupId)){expanded.add(lookupId);for(const dependency of item.dependencies)edgeKeys.add(`${lookupId}::${dependency.id.trim().toLowerCase()}::${dependency.kind}`),pending.push({id:dependency.id,depth:current.depth+1})}}return{node_count:nodeIds.size,edge_count:edgeKeys.size,edge_basis:"deduplicated_directed",missing_count:missingIds.size}}function parseDepsContextOptions(options,registry=createRelationshipKindRegistry()){const maxDepth=parseMaxDepth(options.maxDepth),nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit"),edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit"),tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget"),kinds=parseKinds(options.kind,registry);return{direction:parseDirection(options.direction),...kinds===void 0?{}:{kinds},...maxDepth===void 0?{}:{maxDepth},...nodeLimit===void 0?{}:{nodeLimit},...edgeLimit===void 0?{}:{edgeLimit},...tokenBudget===void 0?{}:{tokenBudget},...options.cursor?.trim()?{cursor:options.cursor.trim()}:{}}}function buildContextFromAssembly(assembly,rootId,options,rootEvidence){return buildRelationshipContext(assembly.graph,rootId,assembly.details.map(detail=>detail.id===rootId&&rootEvidence.length>0?{...detail,evidence:rootEvidence}:detail),options)}function buildDepsRelationshipContext(rootId,items,options,rootEvidence=[]){const assembly=assembleWorkspaceRelationshipGraph(items);return buildContextFromAssembly(assembly,rootId,parseDepsContextOptions(options,assembly.graph.registry()),rootEvidence)}function appendEvidencePointers(evidence,label,values,limit){for(const value of values.slice(0,limit)){const trimmed=value?.trim();trimmed&&evidence.push(`${label}:${trimmed}`)}}async function collectRootEvidence(pmRoot,id,settings,typeToFolder){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)return[];const{document}=await readLocatedItem(located,{schema:settings.schema}),metadata=document.metadata,files=metadata.files??[],tests=metadata.tests??[],docs=metadata.docs??[],counts=[["files",files.length],["tests",tests.length],["docs",docs.length],["comments",(metadata.comments??[]).length],["notes",(metadata.notes??[]).length],["learnings",(metadata.learnings??[]).length]];if(counts.every(([,count])=>count===0))return[];const evidence=[`linked:${counts.map(([key,count])=>`${key}=${count}`).join(",")}`];return appendEvidencePointers(evidence,"file",files.map(file=>file.path),3),appendEvidencePointers(evidence,"test",tests.map(test=>test.command??test.path),2),appendEvidencePointers(evidence,"doc",docs.map(doc=>doc.path),2),evidence}function createContextDepsResult(params){const{canonicalId,context,missingCount,missingReferences,referenceLimit,summaryOnly}=params;return{id:canonicalId,format:"context",node_count:context.nodes.length+1,edge_count:context.edges.length,edge_basis:"deduplicated_directed",missing_count:missingCount,missing_scope:"traversal",missing_reference_count:missingReferences.length,...summaryOnly?{}:{missing_references:missingReferences.slice(0,referenceLimit),context}}}function includesContextMissingReference(params){const{row,missingReachableSet,packetIds,filteredKinds,registry}=params;if(row.no_active_blocker_sentinel||!missingReachableSet.has(row.target_id.trim().toLowerCase())||!packetIds.has(row.holder_id))return!1;if(filteredKinds===void 0)return!0;const definition=registry.resolve(row.kind);return definition!==void 0&&(filteredKinds.has(definition.kind)||definition.inverse!==void 0&&filteredKinds.has(definition.inverse))}function discloseDepsOutput(result,rendering){const activeCommand=getActiveCommandContext(),commandOptions=rendering.commandOptionsOverride??(activeCommand?.command==="deps"?activeCommand.options:rendering.commandOptions);return attachReadOutputContracts("deps",{...commandOptions,...rendering.global,resolvedOutputFormat:rendering.format},result)}function renderDepsOutput(result,rendering){const disclosed=discloseDepsOutput(result,rendering),render=value=>formatBuiltInOutput(value,rendering.format,rendering.global.lean===!0);return render(rendering.global.tokenAccounting===!0?attachOutputTokenAccounting(disclosed,render):disclosed)}function settleRenderedTokenCount(result,rendering,assign){let embeddedTokens;for(;;){const measuredTokens=estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(result,rendering)).byteLength);if(measuredTokens===embeddedTokens)return measuredTokens;assign(measuredTokens),embeddedTokens=measuredTokens}}function isContextBudgetFloorError(error){return error instanceof TypeError&&error.message.startsWith("Relationship context tokenBudget cannot fit ")}function enforceContextRenderedTokenBudget(params){const{assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,rendering,missingCount,missingReferences}=params,referenceLimit=contextOptions.edgeLimit??40;let emittedReferenceLimit=Math.min(referenceLimit,missingReferences.length),internalTokenBudget=contextOptions.tokenBudget,requestedTokenBudget;for(;;){const context=buildContextFromAssembly(assembly,canonicalId,{...contextOptions,...internalTokenBudget===void 0?{}:{tokenBudget:internalTokenBudget}},rootEvidence);requestedTokenBudget??=context.meta.tokenBudget,internalTokenBudget??=requestedTokenBudget;const result=createContextDepsResult({canonicalId,context,missingCount,missingReferences,referenceLimit:emittedReferenceLimit,summaryOnly});if(summaryOnly){if(estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(attachDepsProjection(result,!0,rendering.legacyAliasCounts),rendering)).byteLength)>requestedTokenBudget)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return result}if(context.meta.tokenBudget=requestedTokenBudget,context.meta.usedTokens=settleRenderedTokenCount(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering,tokens=>{context.meta.usedTokens=tokens}),context.meta.usedTokens<=requestedTokenBudget)return result;if(emittedReferenceLimit>0){emittedReferenceLimit-=1;continue}const currentInternalBudget=internalTokenBudget,scaledInternalBudget=currentInternalBudget*requestedTokenBudget/context.meta.usedTokens;internalTokenBudget=Math.min(currentInternalBudget-1,Math.max(1,Math.floor(scaledInternalBudget*.9)))}}function createContextRetryPlan(params,budget){const options=params.contextOptions,global2={...params.rendering.global,outputFormat:params.rendering.format},args=["--pm-path",params.pmRoot,"item","deps",params.canonicalId,"--format","context","--output-format",params.rendering.format,"--token-budget"],budgetIndex=args.length;args.push(String(budget));const provided=new Set(["--pm-path","--format","--output-format","--token-budget"]),commandOptions={format:"context",tokenBudget:budget,kind:options.kinds},values=[["--max-depth","maxDepth",options.maxDepth],["--node-limit","nodeLimit",options.nodeLimit],["--edge-limit","edgeLimit",options.edgeLimit],["--direction","direction",options.direction],["--cursor","cursor",options.cursor],["--output-include","outputInclude",global2.outputInclude],["--output-limit","outputLimit",global2.outputLimit],["--output-budget","outputBudget",global2.outputBudget],["--output-session","outputSession",global2.outputSession],["--output-cursor","outputCursor",global2.outputCursor]];for(const[flag,key,value]of values)value!==void 0&&(args.push(flag,String(value)),provided.add(flag),commandOptions[key]=value);for(const kind of options.kinds??[])args.push("--kind",kind),provided.add("--kind");const booleans=[["--summary","summary",params.summaryOnly],["--full","full",params.rendering.commandOptions.full],["--json","json",global2.json],["--lean","lean",global2.lean],["--output-row-contract","outputRowContract",global2.outputRowContract],["--token-accounting","tokenAccounting",global2.tokenAccounting],["--no-extensions","noExtensions",global2.noExtensions],["--no-pager","noPager",global2.noPager]];for(const[flag,key,enabled]of booleans)enabled===!0&&(args.push(flag),provided.add(flag),commandOptions[key]=!0);const contract=PM_READ_OUTPUT_SURFACE_CONTRACTS.find(candidate=>candidate.command==="deps");return Reflect.set(commandOptions,READ_OUTPUT_INVOCATION_PROVENANCE,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(contract.dimensions).flatMap(dimension=>dimension.legacy_aliases.flatMap(alias=>provided.has(alias.flag)?[alias.flag]:[]))}),normalizeReadOutputIncludeModeOptions("deps",commandOptions),assertProjectionModeChoice(commandOptions.summary===!0,commandOptions.full===!0,"--summary"),global2.outputInclude=commandOptions.outputInclude,{args,budgetIndex,summaryOnly:commandOptions.summary===!0,rendering:{...params.rendering,global:global2,commandOptionsOverride:commandOptions}}}function probeContextRetry(params,plan,budget){const rendering={...plan.rendering,commandOptionsOverride:{...plan.rendering.commandOptionsOverride,tokenBudget:budget}};let result;try{result=enforceContextRenderedTokenBudget({...params,contextOptions:{...params.contextOptions,tokenBudget:budget},summaryOnly:plan.summaryOnly,rootEvidence:plan.summaryOnly?[]:params.rootEvidence,rendering})}catch(error){if(!isContextBudgetFloorError(error))throw error;return"native_floor"}const disclosed=discloseDepsOutput(attachDepsProjection(result,plan.summaryOnly,rendering.legacyAliasCounts),rendering);return isReadOutputBudgetExceeded(disclosed)?"output_constraints":"fits"}async function createContextBudgetRefusal(params,cause){const requested=params.contextOptions.tokenBudget??DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,plan=createContextRetryPlan(params,requested),workUnits=(plan.summaryOnly?1:1+Math.min(params.contextOptions.edgeLimit??40,params.missingReferences.length))*(params.assembly.details.reduce((sum,node)=>sum+node.id.length+node.title.length+node.status.length+(node.type?.length??0),params.assembly.graph.edges().length+params.missingReferences.length)+(plan.summaryOnly?[]:params.rootEvidence).reduce((sum,pointer)=>sum+pointer.length,0)),{findContextBudgetRecovery}=await import("./dependencies/context-budget-recovery.js"),bounds=findContextBudgetRecovery({requested,initialBudget:DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,workUnits,probe:budget=>probeContextRetry(params,plan,budget)}),inspectionArgs=["--pm-path",params.pmRoot,"item","deps",params.canonicalId,"--format","tree","--summary"],inspection=renderPmCommand(inspectionArgs),retryArgs=bounds.feasible_tokens===null?inspectionArgs:[...plan.args];bounds.feasible_tokens!==null&&(retryArgs[plan.budgetIndex]=String(bounds.feasible_tokens));const retry=renderPmCommand(retryArgs);return createPmCliExpectedError("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:EXIT_CODE.USAGE,cause,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(requested),required:bounds.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+bounds.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[retry,inspection],nextSteps:[retry],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:bounds,suggested_retry_args:retryArgs,suggested_retry:retry,next_best_command:inspection,fallback_candidates:[{source:"relationship_summary",command:inspection,reason:"Inspect bounded counts separately from context rows."}]}}})}async function buildContextDepsResult(params){const{pmRoot,assembly,canonicalId,options,rootEvidence,summaryOnly,rendering}=params,contextOptions=parseDepsContextOptions(options,assembly.graph.registry()),reachable=assembly.graph.closure(canonicalId,{direction:contextOptions.direction,...contextOptions.kinds===void 0?{}:{kinds:contextOptions.kinds},maxDepth:contextOptions.maxDepth??3}),missingReachable=reachable.value.filter(nodeId=>assembly.missingIdSet.has(nodeId.toLowerCase())),missingReachableSet=new Set(missingReachable.map(nodeId=>nodeId.toLowerCase())),relationshipRegistry=assembly.graph.registry(),filteredKinds=contextOptions.kinds?new Set(contextOptions.kinds.map(kind=>relationshipRegistry.require(kind).kind)):void 0,packetIds=new Set([canonicalId,...reachable.value]),missingReferences=[...assembly.dangling.active,...assembly.dangling.legacy_terminal].filter(row=>includesContextMissingReference({row,missingReachableSet,packetIds,filteredKinds,registry:relationshipRegistry})),budgetParams={pmRoot,assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,rendering,missingCount:missingReachable.length,missingReferences};try{return enforceContextRenderedTokenBudget(budgetParams)}catch(error){if(error instanceof PmCliError&&error.code==="invalid_query_cursor"){const plan=createContextRetryPlan({...budgetParams,contextOptions:{...contextOptions,cursor:void 0},rendering:{...rendering,global:{...rendering.global,outputCursor:void 0}}},contextOptions.tokenBudget??DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET),retry=renderPmCommand(plan.args);throw new PmCliError(error.message,error.exitCode,{...error.context,nextSteps:[...error.context.nextSteps,retry],recovery:{suggested_retry:retry,suggested_retry_args:plan.args}})}throw isContextBudgetFloorError(error)?await createContextBudgetRefusal(budgetParams,error):error}}function trimDeepestDependency(tree){const pending=[tree];let parentToTrim;for(;pending.length>0;){const current=pending.pop();current.dependencies.length>0&&(parentToTrim=current,pending.push(...current.dependencies))}return parentToTrim?(parentToTrim.dependencies.pop(),parentToTrim.truncated=!0,!0):!1}function buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,rendering){const effectiveMaxDepth=maxDepth??DEFAULT_DEPS_TREE_MAX_DEPTH,nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit")??DEFAULT_DEPS_TREE_NODE_LIMIT,edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit")??DEFAULT_DEPS_TREE_EDGE_LIMIT,tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget")??DEFAULT_DEPS_TREE_TOKEN_BUDGET,budget={nodeLimit,edgeLimit,tokenBudget,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},tree=toTreeNode(id,index,new Set,effectiveMaxDepth,format==="graph"?"repeated":collapse,new Set,budget),totals=countDependencyGraph(id,index,void 0);let result;for(;;){const graph=toGraph(tree),truncation=budget.reasons.size===0?void 0:{reasons:[...budget.reasons].sort(),limits:{max_depth:effectiveMaxDepth,node_limit:nodeLimit,edge_limit:edgeLimit,token_budget:tokenBudget},estimated_tokens:0,total_node_count:totals.node_count,total_edge_count:totals.edge_count,omitted_node_count:Math.max(0,totals.node_count-graph.nodes.length),omitted_edge_count:Math.max(0,totals.edge_count-graph.edges.length)},baseResult={id,format,node_count:graph.nodes.length,edge_count:graph.edges.length,edge_basis:"deduplicated_directed",missing_count:graph.missing_ids.length,...truncation?{truncation}:{}};if(result=format==="tree"?{...baseResult,tree}:{...baseResult,graph},(result.truncation===void 0?estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering)).byteLength):settleRenderedTokenCount(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering,tokens=>{result.truncation.estimated_tokens=tokens}))<=tokenBudget)return result;if(!trimDeepestDependency(tree))return budget.reasons.add("token_budget"),result;budget.reasons.add("token_budget")}}function attachDepsProjection(result,summaryOnly,legacyAliasCounts={}){const group={name:result.format==="tree"?"dependency_tree":result.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...result,legacy_alias_counts:legacyAliasCounts,projection:{mode:summaryOnly?"summary":"full",declared_field_groups:[group],included_field_groups:summaryOnly?[]:[group.name]}}}async function runDeps(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const format=parseFormat(options.format),maxDepth=parseMaxDepth(options.maxDepth),collapse=parseCollapse(options.collapse);assertProjectionModeChoice(options.summary===!0,options.full===!0,"--summary");const summaryOnly=options.summary===!0,settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,settings.schema),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),index=new Map(items.map(item=>[item.id.trim().toLowerCase(),toIndexedItem(item)])),dangling=collectDanglingDependencyReferences(items,status=>isTerminalStatus(status,statusRegistry));for(const reference of[...dangling.active,...dangling.legacy_terminal]){const holder=index.get(reference.holder_id.trim().toLowerCase()),referenceKind=reference.kind.trim().toLowerCase();holder&&!holder.dependencies.some(dependency=>dependency.id.trim().toLowerCase()===reference.target_id.trim().toLowerCase()&&dependency.kind===referenceKind)&&holder.dependencies.push({id:reference.target_id,kind:referenceKind})}if(!index.has(id.trim().toLowerCase()))throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const outputFormat=global2.outputFormat??(global2.json===!0||global2.json===void 0&&global2.defaultOutputFormat==="json"?"json":"toon");if(format==="context"){const canonicalId=index.get(id.trim().toLowerCase()).id,rootEvidence=summaryOnly?[]:await collectRootEvidence(pmRoot,canonicalId,settings,typeRegistry.type_to_folder),isTerminal=status=>isTerminalStatus(status,statusRegistry),relationshipRegistry=resolveWorkspaceRelationshipKindRegistry(),lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry));return attachDepsProjection(await buildContextDepsResult({pmRoot,assembly:lookup.assembly,canonicalId,options,rootEvidence,summaryOnly,rendering:{format:outputFormat,global:global2,commandOptions:options,legacyAliasCounts:lookup.assembly.legacyAliasCounts}}),summaryOnly,lookup.assembly.legacyAliasCounts)}const legacyAliasCounts=Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts));return summaryOnly?attachDepsProjection({id,format,...countDependencyGraph(id,index,maxDepth)},!0,legacyAliasCounts):attachDepsProjection(buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,{format:outputFormat,global:global2,commandOptions:options,legacyAliasCounts}),!1,legacyAliasCounts)}export{DEPS_COLLAPSE_VALUES,DEPS_DIRECTION_VALUES,DEPS_FORMAT_VALUES,buildDepsRelationshipContext,parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger,runDeps};
|
|
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]="196b7f2d-b09b-5432-b4ef-9cdf82e92731")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{getActiveCommandContext,getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isTerminalStatus}from"../core/item/status.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{formatBuiltInOutput}from"../core/output/output.js";import{listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{estimatePmOutputTokens}from"./cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./command-line.js";import{createPmCliExpectedError}from"./errors.js";import{isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,PM_READ_OUTPUT_SURFACE_CONTRACTS}from"./read-output-contracts.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";import{attachReadOutputContracts}from"./context-intent-contracts.js";import{attachOutputTokenAccounting}from"./output-token-accounting.js";import{assertProjectionModeChoice}from"./output-projection.js";import{assembleWorkspaceRelationshipGraph,collectDanglingDependencyReferences,resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./graph/cache.js";import{buildRelationshipContext,DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET}from"./relationship-context.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEPS_FORMAT_VALUES=["tree","graph","context"],DEPS_COLLAPSE_VALUES=["none","repeated"],DEPS_DIRECTION_VALUES=["outgoing","incoming","both"],DEFAULT_DEPS_TREE_MAX_DEPTH=32,DEFAULT_DEPS_TREE_NODE_LIMIT=200,DEFAULT_DEPS_TREE_EDGE_LIMIT=400,DEFAULT_DEPS_TREE_TOKEN_BUDGET=16e3;function parseFormat(raw){const candidate=raw?.trim().toLowerCase()??"tree";if(DEPS_FORMAT_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --format value "${raw}". Use "tree", "graph", or "context".`,EXIT_CODE.USAGE)}function parsePositiveInteger(raw,flag){if(raw===void 0)return;const value=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(value)||value<1)throw new PmCliError(`Invalid --${flag} value "${raw}". Use a positive integer.`,EXIT_CODE.USAGE);return value}function parseMaxDepth(raw){if(raw===void 0)return;const normalized=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(normalized)||normalized<0)throw new PmCliError(`Invalid --max-depth value "${raw}". Use a non-negative integer.`,EXIT_CODE.USAGE);return normalized}function parseCollapse(raw){const candidate=raw?.trim().toLowerCase()??"none";if(DEPS_COLLAPSE_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --collapse value "${raw}". Use "none" or "repeated".`,EXIT_CODE.USAGE)}function parseDirection(raw){const candidate=raw?.trim().toLowerCase()??"both";if(DEPS_DIRECTION_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --direction value "${raw}". Use "outgoing", "incoming", or "both".`,EXIT_CODE.USAGE)}function parseKinds(raw,registry=createRelationshipKindRegistry()){if(raw===void 0)return;const values=(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)return;const kinds=new Set;for(const value of values){const definition=registry.resolve(value);if(!definition){const known=registry.list().map(entry=>entry.kind).join(", ");throw new PmCliError(`Invalid --kind value "${value}". Registered kinds: ${known}.`,EXIT_CODE.USAGE)}kinds.add(definition.kind)}return[...kinds].sort()}function normalizeDependencies(dependencies){if(!dependencies||dependencies.length===0)return[];const sorted=dependencies.map(({id,kind})=>({id:id.trim(),kind:kind.trim().toLowerCase()})).sort((left,right)=>{const byKind=left.kind.localeCompare(right.kind);return byKind!==0?byKind:left.id.localeCompare(right.id)}),deduped=new Map;for(const dependency of sorted){const key=`${dependency.kind.toLowerCase()}::${dependency.id.toLowerCase()}`;deduped.has(key)||deduped.set(key,{id:dependency.id,kind:dependency.kind})}return[...deduped.values()]}function toIndexedItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,dependencies:normalizeDependencies(item.dependencies)}}function estimateTreeNodeTokens(node){return estimatePmOutputTokens(new TextEncoder().encode(JSON.stringify({...node,dependencies:void 0})).byteLength)}function appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth){for(const dependency of item.dependencies){const edgeTokens=Math.max(1,Math.ceil(JSON.stringify({from:baseNode.id,to:dependency.id,kind:dependency.kind}).length/3));if(budget.nodes>=budget.nodeLimit){baseNode.truncated=!0,budget.reasons.add("node_limit");break}if(budget.edges>=budget.edgeLimit){baseNode.truncated=!0,budget.reasons.add("edge_limit");break}if(budget.estimatedTokens+edgeTokens>=budget.tokenBudget){baseNode.truncated=!0,budget.reasons.add("token_budget");break}budget.edges+=1,budget.estimatedTokens+=edgeTokens,baseNode.dependencies.push(toTreeNode(dependency.id,index,nextLineage,maxDepth,collapse,expanded,budget,depth+1,dependency.kind))}}function shouldStopTreeNodeExpansion(node,item,lookupId,maxDepth,collapse,expanded,budget,depth){return budget.estimatedTokens>=budget.tokenBudget&&item?.dependencies.length?(node.truncated=!0,budget.reasons.add("token_budget"),!0):!item||node.cycle?!0:maxDepth!==void 0&&depth>=maxDepth?(item.dependencies.length>0&&(node.truncated=!0,budget.reasons.add("max_depth")),!0):collapse==="repeated"&&expanded.has(lookupId)?(node.collapsed=!0,!0):!1}function toTreeNode(id,index,lineage,maxDepth,collapse,expanded,budget,depth=0,via){const lookupId=id.trim().toLowerCase(),item=index.get(lookupId),baseNode={id:item?.id??id,title:item?.title,type:item?.type,status:item?.status,via,missing:!item,cycle:lineage.has(lookupId),dependencies:[]};if(budget.nodes+=1,budget.estimatedTokens+=estimateTreeNodeTokens(baseNode),shouldStopTreeNodeExpansion(baseNode,item,lookupId,maxDepth,collapse,expanded,budget,depth))return baseNode;collapse==="repeated"&&expanded.add(lookupId);const nextLineage=new Set(lineage);return nextLineage.add(lookupId),appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth),baseNode}function mergeGraphNode(existing,candidate){return!existing||existing.missing&&!candidate.missing?candidate:{...existing,title:existing.title??candidate.title,type:existing.type??candidate.type,status:existing.status??candidate.status}}function toGraph(root){const nodesById=new Map,edgesByKey=new Map,pending=[root];for(;pending.length>0;){const node=pending.pop();nodesById.set(node.id,mergeGraphNode(nodesById.get(node.id),{id:node.id,title:node.title,type:node.type,status:node.status,missing:node.missing}));for(const child of node.dependencies){nodesById.set(child.id,mergeGraphNode(nodesById.get(child.id),{id:child.id,title:child.title,type:child.type,status:child.status,missing:child.missing}));const relationKind=child.via??"related",edgeKey=`${node.id}::${child.id}::${relationKind}`;edgesByKey.has(edgeKey)||edgesByKey.set(edgeKey,{from:node.id,to:child.id,kind:relationKind}),child.cycle||pending.push(child)}}const nodes=[...nodesById.values()].sort((left,right)=>left.id.localeCompare(right.id)),edges=[...edgesByKey.values()].sort((left,right)=>{const byFrom=left.from.localeCompare(right.from);if(byFrom!==0)return byFrom;const byTo=left.to.localeCompare(right.to);return byTo!==0?byTo:left.kind.localeCompare(right.kind)}),missingIds=nodes.filter(node=>node.missing).map(node=>node.id);return{root_id:root.id,nodes,edges,missing_ids:missingIds}}function countDependencyGraph(rootId,index,maxDepth){const nodeIds=new Set,edgeKeys=new Set,missingIds=new Set,expanded=new Set,pending=[{id:rootId,depth:0}];let pendingIndex=0;for(;pendingIndex<pending.length;){const current=pending[pendingIndex++],lookupId=current.id.trim().toLowerCase();nodeIds.add(lookupId);const item=index.get(lookupId);if(!item){missingIds.add(lookupId);continue}if(!(maxDepth!==void 0&¤t.depth>=maxDepth)&&!expanded.has(lookupId)){expanded.add(lookupId);for(const dependency of item.dependencies)edgeKeys.add(`${lookupId}::${dependency.id.trim().toLowerCase()}::${dependency.kind}`),pending.push({id:dependency.id,depth:current.depth+1})}}return{node_count:nodeIds.size,edge_count:edgeKeys.size,edge_basis:"deduplicated_directed",missing_count:missingIds.size}}function parseDepsContextOptions(options,registry=createRelationshipKindRegistry()){const maxDepth=parseMaxDepth(options.maxDepth),nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit"),edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit"),tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget"),kinds=parseKinds(options.kind,registry);return{direction:parseDirection(options.direction),...kinds===void 0?{}:{kinds},...maxDepth===void 0?{}:{maxDepth},...nodeLimit===void 0?{}:{nodeLimit},...edgeLimit===void 0?{}:{edgeLimit},...tokenBudget===void 0?{}:{tokenBudget},...options.cursor?.trim()?{cursor:options.cursor.trim()}:{}}}function buildContextFromAssembly(assembly,rootId,options,rootEvidence){return buildRelationshipContext(assembly.graph,rootId,assembly.details.map(detail=>detail.id===rootId&&rootEvidence.length>0?{...detail,evidence:rootEvidence}:detail),options)}function buildDepsRelationshipContext(rootId,items,options,rootEvidence=[]){const assembly=assembleWorkspaceRelationshipGraph(items);return buildContextFromAssembly(assembly,rootId,parseDepsContextOptions(options,assembly.graph.registry()),rootEvidence)}function appendEvidencePointers(evidence,label,values,limit){for(const value of values.slice(0,limit)){const trimmed=value?.trim();trimmed&&evidence.push(`${label}:${trimmed}`)}}async function collectRootEvidence(pmRoot,id,settings,typeToFolder){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)return[];const{document}=await readLocatedItem(located,{schema:settings.schema}),metadata=document.metadata,files=metadata.files??[],tests=metadata.tests??[],docs=metadata.docs??[],counts=[["files",files.length],["tests",tests.length],["docs",docs.length],["comments",(metadata.comments??[]).length],["notes",(metadata.notes??[]).length],["learnings",(metadata.learnings??[]).length]];if(counts.every(([,count])=>count===0))return[];const evidence=[`linked:${counts.map(([key,count])=>`${key}=${count}`).join(",")}`];return appendEvidencePointers(evidence,"file",files.map(file=>file.path),3),appendEvidencePointers(evidence,"test",tests.map(test=>test.command??test.path),2),appendEvidencePointers(evidence,"doc",docs.map(doc=>doc.path),2),evidence}function createContextDepsResult(params){const{canonicalId,context,missingCount,missingReferences,referenceLimit,summaryOnly}=params;return{id:canonicalId,format:"context",node_count:context.nodes.length+1,edge_count:context.edges.length,edge_basis:"deduplicated_directed",missing_count:missingCount,missing_scope:"traversal",missing_reference_count:missingReferences.length,...summaryOnly?{}:{missing_references:missingReferences.slice(0,referenceLimit),context}}}function includesContextMissingReference(params){const{row,missingReachableSet,packetIds,filteredKinds,registry}=params;if(row.no_active_blocker_sentinel||!missingReachableSet.has(row.target_id.trim().toLowerCase())||!packetIds.has(row.holder_id))return!1;if(filteredKinds===void 0)return!0;const definition=registry.resolve(row.kind);return definition!==void 0&&(filteredKinds.has(definition.kind)||definition.inverse!==void 0&&filteredKinds.has(definition.inverse))}function discloseDepsOutput(result,rendering){const activeCommand=getActiveCommandContext(),commandOptions=rendering.commandOptionsOverride??(activeCommand?.command==="deps"?activeCommand.options:rendering.commandOptions);return attachReadOutputContracts("deps",{...commandOptions,...rendering.global,resolvedOutputFormat:rendering.format},result)}function renderDepsOutput(result,rendering){const disclosed=discloseDepsOutput(result,rendering),render=value=>formatBuiltInOutput(value,rendering.format,rendering.global.lean===!0);return render(rendering.global.tokenAccounting===!0?attachOutputTokenAccounting(disclosed,render):disclosed)}function settleRenderedTokenCount(result,rendering,assign){let embeddedTokens;for(;;){const measuredTokens=estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(result,rendering)).byteLength);if(measuredTokens===embeddedTokens)return measuredTokens;assign(measuredTokens),embeddedTokens=measuredTokens}}function isContextBudgetFloorError(error){return error instanceof TypeError&&error.message.startsWith("Relationship context tokenBudget cannot fit ")}function enforceContextRenderedTokenBudget(params){const{assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,rendering,missingCount,missingReferences}=params,referenceLimit=contextOptions.edgeLimit??40;let emittedReferenceLimit=Math.min(referenceLimit,missingReferences.length),internalTokenBudget=contextOptions.tokenBudget,requestedTokenBudget;for(;;){const context=buildContextFromAssembly(assembly,canonicalId,{...contextOptions,...internalTokenBudget===void 0?{}:{tokenBudget:internalTokenBudget}},rootEvidence);requestedTokenBudget??=context.meta.tokenBudget,internalTokenBudget??=requestedTokenBudget;const result=createContextDepsResult({canonicalId,context,missingCount,missingReferences,referenceLimit:emittedReferenceLimit,summaryOnly});if(summaryOnly){if(estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(attachDepsProjection(result,!0,rendering.legacyAliasCounts),rendering)).byteLength)>requestedTokenBudget)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return result}if(context.meta.tokenBudget=requestedTokenBudget,context.meta.usedTokens=settleRenderedTokenCount(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering,tokens=>{context.meta.usedTokens=tokens}),context.meta.usedTokens<=requestedTokenBudget)return result;if(emittedReferenceLimit>0){emittedReferenceLimit-=1;continue}const currentInternalBudget=internalTokenBudget,scaledInternalBudget=currentInternalBudget*requestedTokenBudget/context.meta.usedTokens;internalTokenBudget=Math.min(currentInternalBudget-1,Math.max(1,Math.floor(scaledInternalBudget*.9)))}}function createContextRetryPlan(params,budget){const options=params.contextOptions,global2={...params.rendering.global,outputFormat:params.rendering.format},args=["--pm-path",params.pmRoot,"item","deps",params.canonicalId,"--format","context","--output-format",params.rendering.format,"--token-budget"],budgetIndex=args.length;args.push(String(budget));const provided=new Set(["--pm-path","--format","--output-format","--token-budget"]),commandOptions={format:"context",tokenBudget:budget,kind:options.kinds},values=[["--max-depth","maxDepth",options.maxDepth],["--node-limit","nodeLimit",options.nodeLimit],["--edge-limit","edgeLimit",options.edgeLimit],["--direction","direction",options.direction],["--cursor","cursor",options.cursor],["--output-include","outputInclude",global2.outputInclude],["--output-limit","outputLimit",global2.outputLimit],["--output-budget","outputBudget",global2.outputBudget],["--output-session","outputSession",global2.outputSession],["--output-cursor","outputCursor",global2.outputCursor]];for(const[flag,key,value]of values)value!==void 0&&(args.push(flag,String(value)),provided.add(flag),commandOptions[key]=value);for(const kind of options.kinds??[])args.push("--kind",kind),provided.add("--kind");const booleans=[["--summary","summary",params.summaryOnly],["--full","full",params.rendering.commandOptions.full],["--json","json",global2.json],["--lean","lean",global2.lean],["--output-row-contract","outputRowContract",global2.outputRowContract],["--token-accounting","tokenAccounting",global2.tokenAccounting],["--no-extensions","noExtensions",global2.noExtensions],["--no-pager","noPager",global2.noPager]];for(const[flag,key,enabled]of booleans)enabled===!0&&(args.push(flag),provided.add(flag),commandOptions[key]=!0);const contract=PM_READ_OUTPUT_SURFACE_CONTRACTS.find(candidate=>candidate.command==="deps");return Reflect.set(commandOptions,READ_OUTPUT_INVOCATION_PROVENANCE,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(contract.dimensions).flatMap(dimension=>dimension.legacy_aliases.flatMap(alias=>provided.has(alias.flag)?[alias.flag]:[]))}),normalizeReadOutputIncludeModeOptions("deps",commandOptions),assertProjectionModeChoice(commandOptions.summary===!0,commandOptions.full===!0,"--summary"),global2.outputInclude=commandOptions.outputInclude,{args,budgetIndex,summaryOnly:commandOptions.summary===!0,rendering:{...params.rendering,global:global2,commandOptionsOverride:commandOptions}}}function probeContextRetry(params,plan,budget){const rendering={...plan.rendering,commandOptionsOverride:{...plan.rendering.commandOptionsOverride,tokenBudget:budget}};let result;try{result=enforceContextRenderedTokenBudget({...params,contextOptions:{...params.contextOptions,tokenBudget:budget},summaryOnly:plan.summaryOnly,rootEvidence:plan.summaryOnly?[]:params.rootEvidence,rendering})}catch(error){if(!isContextBudgetFloorError(error))throw error;return"native_floor"}const disclosed=discloseDepsOutput(attachDepsProjection(result,plan.summaryOnly,rendering.legacyAliasCounts),rendering);return isReadOutputBudgetExceeded(disclosed)?"output_constraints":"fits"}async function createContextBudgetRefusal(params,cause){const requested=params.contextOptions.tokenBudget??DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,plan=createContextRetryPlan(params,requested),workUnits=(plan.summaryOnly?1:1+Math.min(params.contextOptions.edgeLimit??40,params.missingReferences.length))*(params.assembly.details.reduce((sum,node)=>sum+node.id.length+node.title.length+node.status.length+(node.type?.length??0),params.assembly.graph.edges().length+params.missingReferences.length)+(plan.summaryOnly?[]:params.rootEvidence).reduce((sum,pointer)=>sum+pointer.length,0)),{findContextBudgetRecovery}=await import("./dependencies/context-budget-recovery.js"),bounds=findContextBudgetRecovery({requested,initialBudget:DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,workUnits,probe:budget=>probeContextRetry(params,plan,budget)}),inspectionArgs=["--pm-path",params.pmRoot,"item","deps",params.canonicalId,"--format","tree","--summary"],inspection=renderPmCommand(inspectionArgs),retryArgs=bounds.feasible_tokens===null?inspectionArgs:[...plan.args];bounds.feasible_tokens!==null&&(retryArgs[plan.budgetIndex]=String(bounds.feasible_tokens));const retry=renderPmCommand(retryArgs);return createPmCliExpectedError("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:EXIT_CODE.USAGE,cause,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(requested),required:bounds.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+bounds.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[retry,inspection],nextSteps:[retry],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:bounds,suggested_retry_args:retryArgs,suggested_retry:retry,next_best_command:inspection,fallback_candidates:[{source:"relationship_summary",command:inspection,reason:"Inspect bounded counts separately from context rows."}]}}})}async function buildContextDepsResult(params){const{pmRoot,assembly,canonicalId,options,rootEvidence,summaryOnly,rendering}=params,contextOptions=parseDepsContextOptions(options,assembly.graph.registry()),reachable=assembly.graph.closure(canonicalId,{direction:contextOptions.direction,...contextOptions.kinds===void 0?{}:{kinds:contextOptions.kinds},maxDepth:contextOptions.maxDepth??3}),missingReachable=reachable.value.filter(nodeId=>assembly.missingIdSet.has(nodeId.toLowerCase())),missingReachableSet=new Set(missingReachable.map(nodeId=>nodeId.toLowerCase())),relationshipRegistry=assembly.graph.registry(),filteredKinds=contextOptions.kinds?new Set(contextOptions.kinds.map(kind=>relationshipRegistry.require(kind).kind)):void 0,packetIds=new Set([canonicalId,...reachable.value]),missingReferences=[...assembly.dangling.active,...assembly.dangling.legacy_terminal].filter(row=>includesContextMissingReference({row,missingReachableSet,packetIds,filteredKinds,registry:relationshipRegistry})),budgetParams={pmRoot,assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,rendering,missingCount:missingReachable.length,missingReferences};try{return enforceContextRenderedTokenBudget(budgetParams)}catch(error){if(error instanceof PmCliError&&error.code==="invalid_query_cursor"){const plan=createContextRetryPlan({...budgetParams,contextOptions:{...contextOptions,cursor:void 0},rendering:{...rendering,global:{...rendering.global,outputCursor:void 0}}},contextOptions.tokenBudget??DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET),retry=renderPmCommand(plan.args);throw new PmCliError(error.message,error.exitCode,{...error.context,nextSteps:[...error.context.nextSteps,retry],recovery:{suggested_retry:retry,suggested_retry_args:plan.args}})}throw isContextBudgetFloorError(error)?await createContextBudgetRefusal(budgetParams,error):error}}function trimDeepestDependency(tree){const pending=[tree];let parentToTrim;for(;pending.length>0;){const current=pending.pop();current.dependencies.length>0&&(parentToTrim=current,pending.push(...current.dependencies))}return parentToTrim?(parentToTrim.dependencies.pop(),parentToTrim.truncated=!0,!0):!1}function buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,rendering){const effectiveMaxDepth=maxDepth??DEFAULT_DEPS_TREE_MAX_DEPTH,nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit")??DEFAULT_DEPS_TREE_NODE_LIMIT,edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit")??DEFAULT_DEPS_TREE_EDGE_LIMIT,tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget")??DEFAULT_DEPS_TREE_TOKEN_BUDGET,budget={nodeLimit,edgeLimit,tokenBudget,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},tree=toTreeNode(id,index,new Set,effectiveMaxDepth,format==="graph"?"repeated":collapse,new Set,budget),totals=countDependencyGraph(id,index,void 0);let result;for(;;){const graph=toGraph(tree),truncation=budget.reasons.size===0?void 0:{reasons:[...budget.reasons].sort(),limits:{max_depth:effectiveMaxDepth,node_limit:nodeLimit,edge_limit:edgeLimit,token_budget:tokenBudget},estimated_tokens:0,total_node_count:totals.node_count,total_edge_count:totals.edge_count,omitted_node_count:Math.max(0,totals.node_count-graph.nodes.length),omitted_edge_count:Math.max(0,totals.edge_count-graph.edges.length)},baseResult={id,format,node_count:graph.nodes.length,edge_count:graph.edges.length,edge_basis:"deduplicated_directed",missing_count:graph.missing_ids.length,...truncation?{truncation}:{}};if(result=format==="tree"?{...baseResult,tree}:{...baseResult,graph},(result.truncation===void 0?estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering)).byteLength):settleRenderedTokenCount(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering,tokens=>{result.truncation.estimated_tokens=tokens}))<=tokenBudget)return result;if(!trimDeepestDependency(tree))return budget.reasons.add("token_budget"),result;budget.reasons.add("token_budget")}}function attachDepsProjection(result,summaryOnly,legacyAliasCounts={}){const group={name:result.format==="tree"?"dependency_tree":result.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"},boundedGroups=result.context?.meta.truncated?[{name:"relationship_context_bounds",restore_with:"--token-budget <n> --node-limit <n> --edge-limit <n> --max-depth <n>"}]:[];return{...result,legacy_alias_counts:legacyAliasCounts,projection:{mode:summaryOnly?"summary":"full",declared_field_groups:[group,...boundedGroups],included_field_groups:summaryOnly?[]:[group.name]}}}async function runDeps(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const format=parseFormat(options.format),maxDepth=parseMaxDepth(options.maxDepth),collapse=parseCollapse(options.collapse);assertProjectionModeChoice(options.summary===!0,options.full===!0,"--summary");const summaryOnly=options.summary===!0,settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,settings.schema),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),index=new Map(items.map(item=>[item.id.trim().toLowerCase(),toIndexedItem(item)])),dangling=collectDanglingDependencyReferences(items,status=>isTerminalStatus(status,statusRegistry));for(const reference of[...dangling.active,...dangling.legacy_terminal]){const holder=index.get(reference.holder_id.trim().toLowerCase()),referenceKind=reference.kind.trim().toLowerCase();holder&&!holder.dependencies.some(dependency=>dependency.id.trim().toLowerCase()===reference.target_id.trim().toLowerCase()&&dependency.kind===referenceKind)&&holder.dependencies.push({id:reference.target_id,kind:referenceKind})}if(!index.has(id.trim().toLowerCase()))throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const outputFormat=global2.outputFormat??(global2.json===!0||global2.json===void 0&&global2.defaultOutputFormat==="json"?"json":"toon");if(format==="context"){const canonicalId=index.get(id.trim().toLowerCase()).id,rootEvidence=summaryOnly?[]:await collectRootEvidence(pmRoot,canonicalId,settings,typeRegistry.type_to_folder),isTerminal=status=>isTerminalStatus(status,statusRegistry),relationshipRegistry=resolveWorkspaceRelationshipKindRegistry(),lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry));return attachDepsProjection(await buildContextDepsResult({pmRoot,assembly:lookup.assembly,canonicalId,options,rootEvidence,summaryOnly,rendering:{format:outputFormat,global:global2,commandOptions:options,legacyAliasCounts:lookup.assembly.legacyAliasCounts}}),summaryOnly,lookup.assembly.legacyAliasCounts)}const legacyAliasCounts=Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts));return summaryOnly?attachDepsProjection({id,format,...countDependencyGraph(id,index,maxDepth)},!0,legacyAliasCounts):attachDepsProjection(buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,{format:outputFormat,global:global2,commandOptions:options,legacyAliasCounts}),!1,legacyAliasCounts)}export{DEPS_COLLAPSE_VALUES,DEPS_DIRECTION_VALUES,DEPS_FORMAT_VALUES,buildDepsRelationshipContext,parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger,runDeps};
|
|
2
2
|
//# sourceMappingURL=dependencies.js.map
|