@unbrained/pm-cli 2026.9.27 → 2026.9.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +7 -6
- package/.agents/skills/pm-user/references/BACKLOG_SHAPING.md +1 -1
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +26 -3
- package/.claude-plugin/marketplace.json +4 -6
- package/CHANGELOG.md +43 -0
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/help-json-payload.js +2 -2
- package/dist/cli/main.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/runtime/invocation-options.d.ts +3 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +151 -151
- package/dist/cli-bundle/chunks/{chunk-6OJVQ7SW.js → chunk-2AQKVJMW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TSF2LPIH.js → chunk-4DOL43PF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7TAGYNFP.js → chunk-5KEPG36D.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-IEP3VAT5.js → chunk-D32HVIB2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AUS6USO4.js → chunk-GP6QTYSD.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-OTLIM22J.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-LKGQUZ5M.js → chunk-P75SO5HO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4SLLCDFL.js → chunk-PJSQAWWQ.js} +64 -64
- package/dist/cli-bundle/chunks/{chunk-V5UGBYHN.js → chunk-S5A2UIRV.js} +62 -62
- package/dist/cli-bundle/chunks/chunk-SC6JHXFT.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-3BTJ66CB.js → chunk-SEJ53XDN.js} +55 -55
- package/dist/cli-bundle/chunks/{chunk-OKVDVERQ.js → chunk-SJI55O65.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JX6WCCHL.js → chunk-U3QJGJYN.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-6PAJ4PBU.js → register-list-query-R3ELWWPY.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-RZCXZXYS.js → register-mutation-WHXJXIHJ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-GK6VU2H2.js → register-operations-7ASWBYQG.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-ASEMNMBF.js → register-setup-FDRTUG54.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QO4MTAEA.js → chunk-2O3QFI3G.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LBDWUHQD.js → chunk-4A4DO5ZT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5MC57KRC.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NWRVNHAD.js → chunk-6OXJVE74.js} +17 -17
- package/dist/cli-bundle/focused-chunks/{chunk-MILJCOFJ.js → chunk-7URX7FMY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OJRX6G22.js → chunk-AVP5C674.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SMADBUPL.js → chunk-AZE7KUHG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GZD4ZYIB.js → chunk-DZVOCJFY.js} +14 -14
- package/dist/cli-bundle/focused-chunks/chunk-FBIRNSYP.js +75 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NETVXIH5.js → chunk-IFBA3ZAT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OJKJFDIG.js → chunk-K3AIMRIK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-DQ3MB7BO.js → chunk-KLKKCHWM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PDVL7QYU.js → chunk-MRH4A542.js} +15 -15
- package/dist/cli-bundle/focused-chunks/{chunk-6UNKK3UH.js → chunk-NXQZMKW5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NY6FLQTN.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NZAG7OKB.js → chunk-T4H6Q44B.js} +2 -2
- package/dist/cli-bundle/main.js +22 -22
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +22 -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 +51 -51
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +2 -2
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/history/replay.js +1 -1
- package/dist/core/item/item-format.js +1 -1
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/store/settings.js +3 -3
- package/dist/core/telemetry/runtime.js +2 -2
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/completion/fish.js +3 -3
- package/dist/sdk/completion/zsh.js +3 -3
- package/dist/sdk/extension/copy-scope.d.ts +2 -2
- package/dist/sdk/extension/copy-scope.js +1 -1
- package/dist/sdk/extension/install-plan.js +1 -1
- package/dist/sdk/extension/install-runtime.js +2 -2
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.d.ts +18 -0
- package/dist/sdk/governance/health-merge-evidence.js +2 -0
- package/dist/sdk/governance/health.js +1 -1
- package/dist/sdk/index.d.ts +1 -0
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/plan-mutation-receipt.d.ts +53 -0
- package/dist/sdk/lifecycle/plan-mutation-receipt.js +2 -0
- package/dist/sdk/lifecycle/plan.d.ts +3 -0
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/linked-artifacts.js +1 -1
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/output-projection.d.ts +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-budget.d.ts +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/similarity-scoring.js +1 -1
- package/dist/sdk/telemetry.d.ts +2 -0
- package/dist/sdk/telemetry.js +3 -1
- package/dist/sdk/test/execution.d.ts +11 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/test/parsers.d.ts +1 -1
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/types.js +1 -1
- package/docs/AGENT_READ_AND_TEST_RECEIPTS.md +21 -0
- package/docs/CLAUDE_CODE_PLUGIN.md +12 -7
- package/docs/CLI_GRAMMAR.md +18 -1
- package/docs/CONFIGURATION.md +2 -0
- package/docs/ECOSYSTEM_PLANNING_REVIEW.md +270 -0
- package/docs/PACKAGE_EVIDENCE.md +18 -7
- package/docs/README.md +2 -0
- package/docs/SDK_EVIDENCE_TRACEABILITY.md +34 -0
- package/docs/TESTING.md +14 -3
- package/docs/agent-task-token-baseline.json +28 -2
- package/docs/agent-task-transcripts.json +137 -14
- package/docs/ecosystem-review-2026-09-28.json +3159 -0
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +7 -3
- package/marketplace.json +4 -6
- package/package.json +5 -5
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +4 -2
- package/plugins/pm-claude/.mcp.json +1 -2
- package/plugins/pm-claude/README.md +7 -7
- package/plugins/pm-claude/package.json +2 -2
- package/plugins/pm-claude/{commands/pm-calendar.md → skills/pm-calendar/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-close-task.md → skills/pm-close-task/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-init.md → skills/pm-init/SKILL.md} +2 -1
- package/plugins/pm-claude/{commands/pm-list.md → skills/pm-list/SKILL.md} +2 -1
- package/plugins/pm-claude/{commands/pm-new.md → skills/pm-new/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-search.md → skills/pm-search/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-start-task.md → skills/pm-start-task/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-status.md → skills/pm-status/SKILL.md} +1 -0
- package/plugins/pm-claude/{commands/pm-triage.md → skills/pm-triage/SKILL.md} +1 -0
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4UPZLUT2.js +0 -29
- package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6J2YCGSN.js +0 -75
- package/dist/cli-bundle/focused-chunks/chunk-E7LYK7V5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +0 -2
- package/plugins/pm-claude/commands/pm-audit.md +0 -38
- package/plugins/pm-claude/commands/pm-developer.md +0 -38
- package/plugins/pm-claude/commands/pm-planner.md +0 -54
- package/plugins/pm-claude/commands/pm-release.md +0 -41
- package/plugins/pm-claude/commands/pm-workflow.md +0 -49
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module sdk/lifecycle/plan-mutation-receipt
|
|
3
|
+
* Bounded mutation acknowledgements; full Plan state remains a separate read.
|
|
4
|
+
*/
|
|
5
|
+
import type { PlanCommandResult, PlanStepSummary, PlanSubcommand } from "./plan.js";
|
|
6
|
+
import type { PlanMode, PlanStepStatus } from "../../types/index.js";
|
|
7
|
+
/** Stable mutation facts whose size does not grow with unrelated Plan content. */
|
|
8
|
+
export interface PlanMutationReceipt {
|
|
9
|
+
/** Discriminator used by CLI and MCP mutation projection. */
|
|
10
|
+
kind: "plan_mutation";
|
|
11
|
+
/** Operation that completed successfully. */
|
|
12
|
+
action: PlanSubcommand;
|
|
13
|
+
/** Persisted Plan identifier. */
|
|
14
|
+
id: string;
|
|
15
|
+
/** Persisted item lifecycle state. */
|
|
16
|
+
status: string;
|
|
17
|
+
/** Persisted execution mode. */
|
|
18
|
+
mode: PlanMode;
|
|
19
|
+
/** Counts over the complete persisted step collection. */
|
|
20
|
+
steps_summary: PlanStepSummary;
|
|
21
|
+
/** Affected step identity when the operation returns a step. */
|
|
22
|
+
step?: Pick<NonNullable<PlanCommandResult["step"]>, "id" | "order"> & {
|
|
23
|
+
status: PlanStepStatus;
|
|
24
|
+
};
|
|
25
|
+
/** Number of items created by this materialization. */
|
|
26
|
+
materialized_count: number;
|
|
27
|
+
/** Number of already completed or materialized steps skipped. */
|
|
28
|
+
skipped_count: number;
|
|
29
|
+
/** Number of warnings in the full SDK result. */
|
|
30
|
+
warning_count: number;
|
|
31
|
+
/** Up to three warning previews, each bounded to 160 characters. */
|
|
32
|
+
warnings: string[];
|
|
33
|
+
/** Whether any warning content is absent from the previews. */
|
|
34
|
+
warnings_truncated: boolean;
|
|
35
|
+
/** First applicable next action, falling back to read-only inspection. */
|
|
36
|
+
next_action: string;
|
|
37
|
+
/** Read-only recovery for complete steps, evidence and resume context. */
|
|
38
|
+
inspection_command: string;
|
|
39
|
+
/** Explicitly declares that this acknowledgement is not complete Plan state. */
|
|
40
|
+
omission_receipt: {
|
|
41
|
+
/** Full Plan content is intentionally withheld. */
|
|
42
|
+
has_omissions: true;
|
|
43
|
+
/** Projection group count. */
|
|
44
|
+
omitted_field_group_count: 1;
|
|
45
|
+
/** Named omitted group and its safe read-only recovery. */
|
|
46
|
+
omitted_field_groups: {
|
|
47
|
+
name: "plan_detail";
|
|
48
|
+
restore_with: string;
|
|
49
|
+
}[];
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** Project completed work; omit the root for MCP recovery in the caller's existing workspace context. */
|
|
53
|
+
export declare function buildPlanMutationReceipt(result: PlanCommandResult, pmRoot: string | undefined): PlanMutationReceipt;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="fc60339e-561c-5ac3-bdb3-116bd55e35b5")}catch(e2){}})();import{quoteCommandArg,renderPmCommand}from"../command-line.js";function buildPlanMutationReceipt(result,pmRoot){const inspectionCommand=renderPmCommand(["plan","show",result.plan.id,"--depth","deep",...pmRoot===void 0?[]:["--pm-path",pmRoot]]);return{kind:"plan_mutation",action:result.action,id:result.plan.id,status:result.plan.status,mode:result.plan.mode,steps_summary:result.plan.steps_summary,...result.step===void 0?{}:{step:{id:result.step.id,order:result.step.order,status:result.step.status}},materialized_count:result.materialized?.length??0,skipped_count:result.materialize_skipped?.length??0,warning_count:result.warnings.length,warnings:result.warnings.slice(0,3).map(warning=>warning.slice(0,160)),warnings_truncated:result.warnings.length>3||result.warnings.some(warning=>warning.length>160),next_action:result.next_actions?.[0]===void 0?inspectionCommand:pmRoot===void 0?result.next_actions[0]:`${result.next_actions[0]} --pm-path ${quoteCommandArg(pmRoot)}`,inspection_command:inspectionCommand,omission_receipt:{has_omissions:true,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:inspectionCommand}]}}}export{buildPlanMutationReceipt};
|
|
2
|
+
//# sourceMappingURL=plan-mutation-receipt.js.map
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type GlobalOptions } from "../runtime-primitives.js";
|
|
2
2
|
import type { DependencyKind, ItemMetadata, PlanDecision, PlanDiscovery, PlanHarness, PlanMode, PlanStep, PlanStepStatus, PlanValidationCheck } from "../../types/index.js";
|
|
3
3
|
import type { MutationMetadataCommandOptions, SharedLinkedResourceOptions } from "./mutation-command-options.js";
|
|
4
|
+
import { type PlanMutationReceipt } from "./plan-mutation-receipt.js";
|
|
4
5
|
/** Public contract for plan subcommands, shared by SDK and presentation-layer consumers. */
|
|
5
6
|
export declare const PLAN_SUBCOMMANDS: readonly ["create", "show", "add-step", "update-step", "complete-step", "block-step", "reorder-step", "remove-step", "link", "unlink", "decision", "discovery", "validation", "resume", "approve", "materialize"];
|
|
6
7
|
/** Restricts plan subcommand values accepted by command, SDK, and storage contracts. */
|
|
@@ -126,6 +127,8 @@ export interface PlanCommandOptions extends Omit<MutationMetadataCommandOptions,
|
|
|
126
127
|
export type PlanOperationOptions = PlanCommandOptions;
|
|
127
128
|
/** Documents the plan command result payload exchanged by command, SDK, and package integrations. */
|
|
128
129
|
export interface PlanCommandResult {
|
|
130
|
+
/** Bounded acknowledgement for mutations; full typed Plan state remains available alongside it. */
|
|
131
|
+
mutation_receipt?: PlanMutationReceipt;
|
|
129
132
|
/** Value that configures or reports action for this contract. */
|
|
130
133
|
action: PlanSubcommand;
|
|
131
134
|
/** Value that configures or reports plan for this contract. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="374c7cb8-9fd0-5a2d-8aaf-9d09b63abaf0")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,isTerminalStatus,resolveItemTypeRegistry,resolveRuntimeStatusRegistry,resolveTypeName,EXIT_CODE,PmCliError,splitCommaList,nowIso,locateItem,mutateItem,readLocatedItem,resolvePmRoot,readSettings,resolveAuthor,isTerminalPlanMode,preserveMutationStdinTokenFields,transferMutationStdinTokenPolicy}from"../runtime-primitives.js";import{PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES}from"../../types/index.js";import{runCreate}from"./create.js";import{createUnknownSubcommandError}from"../agent/subcommand-recovery.js";const PLAN_SUBCOMMANDS=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"];const PLAN_SHOW_DEPTH_VALUES=["brief","standard","deep"];const STEP_ID_PREFIX="plan-step-";const DEFAULT_PLAN_MODE="draft";const PLAN_TEMPLATE_NAMES=["bug-investigation","feature-implementation","refactoring-sprint"];const PLAN_TEMPLATES={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function resolvePlanTemplateSteps(raw){const normalized=raw.trim().toLowerCase();const template=Object.prototype.hasOwnProperty.call(PLAN_TEMPLATES,normalized)?PLAN_TEMPLATES[normalized]:void 0;if(!template){throw new PmCliError(`Unknown plan template "${raw}". Allowed: ${PLAN_TEMPLATE_NAMES.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${PLAN_TEMPLATE_NAMES[0]}`]})}return template.map(step=>({...step}))}function planCompletionPct(completed,total){return total>0?Math.round(completed/total*100):0}function toOrderedStepTitles(value){const values=Array.isArray(value)?value:value===void 0||value===null?[]:[value];return values.filter(entry=>entry!==void 0&&entry!==null).map(entry=>(typeof entry==="string"?entry:String(entry)).trim()).filter(entry=>entry.length>0)}function toArray(value){if(Array.isArray(value))return value.flatMap(entry=>splitCommaList(entry,{unique:false}));if(typeof value==="string"&&value.trim().length>0){return splitCommaList(value,{unique:false})}return[]}function toSpecArray(value){if(Array.isArray(value))return value.map(entry=>entry.trim()).filter(Boolean);if(typeof value==="string"&&value.trim().length>0)return[value.trim()];return[]}function asPlanMode(value,fallback=DEFAULT_PLAN_MODE){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_MODE_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid plan mode "${value}". Allowed: ${PLAN_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asStepStatus(value,fallback="pending"){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_STEP_STATUS_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid step status "${value}". Allowed: ${PLAN_STEP_STATUS_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asLinkKind(value,fallback="related"){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_STEP_LINK_KIND_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid step link kind "${value}". Allowed: ${PLAN_STEP_LINK_KIND_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asHarness(value){if(value===void 0)return void 0;const normalized=value.trim().toLowerCase();if(normalized.length===0)return void 0;const found=PLAN_HARNESS_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid plan harness "${value}". Allowed: ${PLAN_HARNESS_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asDepth(value){if(value===void 0)return"brief";const normalized=value.trim().toLowerCase();const found=PLAN_SHOW_DEPTH_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid --depth "${value}". Allowed: ${PLAN_SHOW_DEPTH_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function parsePlanFields(raw){if(raw===void 0){return null}const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0){throw new PmCliError("Plan --fields requires a comma-separated list of plan field names",EXIT_CODE.USAGE)}return fields}const PLAN_FIELD_KEYS=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function projectPlanForFields(plan,fields){const source=plan;const projected={};const unknownFields=[];for(const field of fields){const normalized=field.startsWith("plan.")?field.slice("plan.".length):field;if(normalized.length===0){continue}if(!PLAN_FIELD_KEYS.has(normalized)){unknownFields.push(field);continue}if(Object.prototype.hasOwnProperty.call(source,normalized)){projected[normalized]=source[normalized]}}if(unknownFields.length>0){throw new PmCliError(`Unknown Plan --fields value(s): ${unknownFields.join(", ")}`,EXIT_CODE.USAGE,{nextSteps:[`Use --fields ${[...PLAN_FIELD_KEYS].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:unknownFields,suggested_retry:`pm plan show <id> --fields ${[...PLAN_FIELD_KEYS].join(",")}`}})}return projected}function parsePairList(raw,label){const out={};for(const entry of raw.split(",")){const trimmed=entry.trim();if(trimmed.length===0)continue;const equalsIndex=trimmed.indexOf("=");if(equalsIndex<=0){throw new PmCliError(`Invalid ${label} entry "${trimmed}"; expected key=value`,EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:`${label} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']})}out[trimmed.slice(0,equalsIndex).trim().toLowerCase()]=trimmed.slice(equalsIndex+1).trim()}return out}function parseStepFile(spec){const fields=parsePairList(spec,"--file");if(!fields.path){throw new PmCliError("--file requires path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."})}const file={path:fields.path};if(fields.scope==="global"||fields.scope==="project")file.scope=fields.scope;if(fields.note)file.note=fields.note;return file}function parseStepTest(spec){const fields=parsePairList(spec,"--test");if(!fields.command&&!fields.path){throw new PmCliError("--test requires at least command=<value> or path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."})}const test={};if(fields.command)test.command=fields.command;if(fields.path)test.path=fields.path;if(fields.note)test.note=fields.note;return test}function parseStepDoc(spec){const fields=parsePairList(spec,"--doc");if(!fields.path){throw new PmCliError("--doc requires path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."})}const doc={path:fields.path};if(fields.scope==="global"||fields.scope==="project")doc.scope=fields.scope;if(fields.note)doc.note=fields.note;return doc}function summarizeSteps(steps){const summary={total:steps.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(const step of steps){summary[step.status]+=1}summary.completion_pct=planCompletionPct(summary.completed,summary.total);return summary}function newStepId(existing){const used=new Set(existing.map(step=>step.id));for(let cursor=existing.length+1;cursor<existing.length+1024;cursor+=1){const candidate=`${STEP_ID_PREFIX}${String(cursor).padStart(3,"0")}`;if(!used.has(candidate))return candidate}throw new PmCliError("Could not allocate step id (limit reached)",EXIT_CODE.GENERIC_FAILURE)}function resolveStepRef(steps,ref){const trimmed=ref.trim();if(trimmed.length===0){throw new PmCliError("Step reference cannot be empty",EXIT_CODE.USAGE)}const direct=steps.find(step=>step.id===trimmed);if(direct)return direct;if(/^\d+$/.test(trimmed)){const order=Number.parseInt(trimmed,10);const byOrder=steps.find(step=>step.order===order);if(byOrder)return byOrder}throw new PmCliError(`Step "${ref}" not found in plan`,EXIT_CODE.NOT_FOUND)}function classifyMaterializeSkip(step){if(step.status==="completed"){return{reason:"already_completed"}}const existingImplements=(step.linked_items??[]).find(link=>link.kind==="implements");if(existingImplements){return{reason:"already_materialized",existing_id:existingImplements.id}}return void 0}function resolveMaterializeTargets(steps,refs){const allRefs=refs.filter(ref=>ref.trim().toLowerCase()==="all");const targets=[];const skipped=[];if(allRefs.length>0){if(refs.length>allRefs.length){throw new PmCliError("pm plan materialize --steps all cannot be combined with other step refs",EXIT_CODE.USAGE)}for(const step of steps.slice().sort((left,right)=>left.order-right.order)){const skip=classifyMaterializeSkip(step);if(skip){skipped.push({from_step:step.id,...skip});continue}targets.push(step)}return{targets,skipped}}const seen=new Set;for(const ref of refs){const step=resolveStepRef(steps,ref);if(seen.has(step.id))continue;seen.add(step.id);const skip=classifyMaterializeSkip(step);if(skip){skipped.push({from_step:step.id,...skip});continue}targets.push(step)}return{targets,skipped}}function resolvePlanLogText(kind,options){const canonical=kind==="decision"?options.decisionText:kind==="discovery"?options.discoveryText:options.validationText;const shorthand=kind==="decision"?options.decision:kind==="discovery"?options.discovery:options.validation;return canonical?.trim()||shorthand?.trim()||void 0}function findCurrentStep(steps){return steps.find(step=>step.status==="in_progress")??steps.find(step=>step.status==="pending")}function blockedSteps(steps){return steps.filter(step=>step.status==="blocked").map(step=>({id:step.id,order:step.order,title:step.title,blocked_reason:step.blocked_reason}))}function projectPlan(item,depth="brief"){const steps=(item.plan_steps??[]).slice().sort((left,right)=>left.order-right.order);const summary=summarizeSteps(steps);const current=findCurrentStep(steps);const projection={id:item.id,title:item.title,status:item.status,mode:item.plan_mode??DEFAULT_PLAN_MODE,scope:item.plan_scope,harness:item.plan_harness,parent:item.parent,resume_context:item.plan_resume_context,steps_summary:summary,current_step:current?{id:current.id,order:current.order,title:current.title,status:current.status}:void 0,blocked_steps:blockedSteps(steps),linked_items:(item.dependencies??[]).map(dep=>({id:dep.id,kind:dep.kind}))};if(depth==="standard"||depth==="deep"){projection.steps=steps}if(depth==="deep"){projection.decisions=item.plan_decisions??[];projection.discoveries=item.plan_discoveries??[];projection.validation=item.plan_validation??[]}return projection}function nextActionsFor(planId,plan){const tips=[];if(plan.steps_summary.total===0){tips.push(`pm plan add-step ${planId} --step-title "First step"`)}if(plan.current_step){tips.push(`pm plan update-step ${planId} ${plan.current_step.id} --step-status in_progress`,`pm plan complete-step ${planId} ${plan.current_step.id} --step-evidence "..."`)}if(plan.steps_summary.blocked>0){tips.push(`pm plan show ${planId} --depth standard`)}if(plan.mode==="draft"||plan.mode==="research"){tips.push(`pm plan approve ${planId} --message "ready to execute"`)}if(plan.steps_summary.completed===plan.steps_summary.total&&plan.steps_summary.total>0&&!isTerminalPlanMode(plan.mode)&&plan.status!=="closed"&&plan.status!=="canceled"){tips.push(`pm close ${planId} "plan complete"`)}return tips}function ensurePlanItem(item){const normalizedType=(item.type??"").trim().toLowerCase();if(normalizedType!=="plan"){throw new PmCliError(`Item ${item.id} is type ${item.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,EXIT_CODE.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${item.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}}async function loadContext(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);return{pmRoot,settings}}async function readPlanItem(ctx,id){const typeRegistry=resolveItemTypeRegistry(ctx.settings,getActiveExtensionRegistrations());const located=await locateItem(ctx.pmRoot,id,ctx.settings.id_prefix,ctx.settings.item_format,typeRegistry.type_to_folder);if(!located){throw new PmCliError(`Plan ${id} not found`,EXIT_CODE.NOT_FOUND)}const loaded=await readLocatedItem(located,{schema:ctx.settings.schema});ensurePlanItem(loaded.document.metadata);return{document:loaded.document,itemId:located.id}}function buildPlanCreateDependencies(options){const deps=[];if(options.parent){deps.push(`id=${options.parent.trim()},kind=parent`)}for(const ref of toArray(options.related))deps.push(`id=${ref},kind=related`);for(const ref of toArray(options.blocks))deps.push(`id=${ref},kind=blocks`);for(const ref of toArray(options.blockedBy))deps.push(`id=${ref},kind=blocked_by`);return deps.length>0?deps:void 0}function buildInitialValidation(options){const text=options.validationText?.trim();const command=options.validationCommand?.trim();const expected=options.validationExpected?.trim();if(!text&&!command&&!expected){return void 0}return{text:text||command||"Validation check",command:command||void 0,expected:expected||void 0}}function hasPlanStepDetailOptions(options){return Boolean(options.stepBody?.trim())||Boolean(options.stepOwner?.trim())||Boolean(options.stepStatus?.trim())||Boolean(options.stepEvidence?.trim())||Boolean(options.stepBlockedReason?.trim())||Boolean(options.stepReplacement?.trim())||toArray(options.dependsOn).length>0||toArray(options.link).length>0}function resolveInitialStepSeed(options){const stepTitleFlag=options.stepTitle?.trim()||void 0;const repeatedStepTitles=toOrderedStepTitles(options.step);const templateSteps=options.template?.trim()?resolvePlanTemplateSteps(options.template):[];return{repeatedStepTitles,stepTitleFlag,stepTitles:[...stepTitleFlag?[stepTitleFlag]:[],...repeatedStepTitles,...templateSteps.map(step=>step.title)],templateSteps}}function assertInitialStepSeedAllowed(seed,hasPerStepDetailOptions){if((seed.stepTitleFlag||seed.repeatedStepTitles.length>0)&&seed.templateSteps.length>0){throw new PmCliError("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${PLAN_TEMPLATE_NAMES[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']})}if(seed.stepTitles.length>1&&hasPerStepDetailOptions){throw new PmCliError("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}}function buildSingleInitialStep(options,title){const status=asStepStatus(options.stepStatus,"pending");const linkedItems=buildLinkInputs(options,"depends_on");const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);const now=nowIso();return{id:"plan-step-001",order:1,title,body:options.stepBody?.trim()||void 0,status,owner:options.stepOwner?.trim()||void 0,evidence:options.stepEvidence?.trim()||void 0,blocked_reason:status==="blocked"?options.stepBlockedReason?.trim()||"":void 0,linked_items:linkedItems.length>0?linkedItems:void 0,files:files.length>0?files:void 0,tests:tests.length>0?tests:void 0,docs:docs.length>0?docs:void 0,created_at:now,updated_at:now,completed_at:status==="completed"?now:void 0}}function buildInitialSteps(options){const seed=resolveInitialStepSeed(options);const hasDetailOptions=hasPlanStepDetailOptions(options);assertInitialStepSeedAllowed(seed,hasDetailOptions);if(seed.stepTitles.length===0){return{steps:[],hasPerStepDetailOptions:hasDetailOptions}}if(seed.stepTitles.length===1){return{steps:[buildSingleInitialStep(options,seed.stepTitles[0])],hasPerStepDetailOptions:hasDetailOptions}}const now=nowIso();return{steps:seed.stepTitles.map((stepTitle,index)=>({id:`${STEP_ID_PREFIX}${String(index+1).padStart(3,"0")}`,order:index+1,title:stepTitle,body:seed.templateSteps[index]?.body,status:"pending",created_at:now,updated_at:now})),hasPerStepDetailOptions:hasDetailOptions}}function preservePlanCreateStdinPolicy(source,createOptions,derivedLiteralFields=[]){transferMutationStdinTokenPolicy(source,createOptions);if(derivedLiteralFields.length>0){preserveMutationStdinTokenFields(createOptions,derivedLiteralFields)}}async function planCreate(options,global2,ctx){const title=options.title?.trim();if(!title){throw new PmCliError("pm plan create requires --title",EXIT_CODE.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']})}const mode=asPlanMode(options.mode,DEFAULT_PLAN_MODE);const harness=asHarness(options.harness);const fromSearch=options.fromSearch?.trim();const initialValidation=buildInitialValidation(options);const{steps:initialSteps,hasPerStepDetailOptions}=buildInitialSteps(options);if(initialSteps.length===0&&hasPerStepDetailOptions){throw new PmCliError("pm plan create step options require --step-title (or a single --step)",EXIT_CODE.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']})}const description=options.description?.trim()??options.scope?.trim()??title;const requestedAssignee=options.claim?resolveAuthor(options.author,ctx.settings.author_default):options.assignee?.trim()||void 0;const createOptions={...options,title,description,type:"Plan",template:void 0,file:toSpecArray(options.file),test:toSpecArray(options.test),doc:toSpecArray(options.doc),field:toSpecArray(options.field),assignee:resolveAuthor(options.author,ctx.settings.author_default),blockedBy:void 0,dep:buildPlanCreateDependencies(options),message:options.message??(fromSearch?`plan create (search: ${fromSearch})`:`plan create`)};preservePlanCreateStdinPolicy(options,createOptions);const createResult=await runCreate(createOptions,global2);const seedResult=await mutateItem({pmRoot:ctx.pmRoot,settings:ctx.settings,id:createResult.item.id,op:"plan_create_metadata",author:resolveAuthor(options.author,ctx.settings.author_default),message:"seed plan metadata",mutate(doc){const changedFields=["plan_mode"];doc.metadata.plan_mode=mode;if(harness){doc.metadata.plan_harness=harness;changedFields.push("plan_harness")}const scope=options.scope?.trim();if(scope){doc.metadata.plan_scope=scope;changedFields.push("plan_scope")}const resumeContext=options.resumeContext?.trim();if(resumeContext){doc.metadata.plan_resume_context=resumeContext;changedFields.push("plan_resume_context")}doc.metadata.plan_steps=initialSteps;changedFields.push("plan_steps");if(initialValidation){doc.metadata.plan_validation=[...doc.metadata.plan_validation??[],initialValidation];changedFields.push("plan_validation")}if(requestedAssignee){doc.metadata.assignee=requestedAssignee;changedFields.push("assignee")}return{changedFields}}});const plan=projectPlan(seedResult.item,"brief");return{action:"create",plan,step:initialSteps[0],next_actions:nextActionsFor(createResult.item.id,plan),warnings:[...createResult.warnings],generated_at:nowIso()}}async function planShow(id,options,ctx){const depth=asDepth(options.depth);const fields=parsePlanFields(options.fields);const{document,itemId}=await readPlanItem(ctx,id);const fullPlan=projectPlan(document.metadata,fields===null?depth:"deep");const plan=fields===null?fullPlan:projectPlanForFields(fullPlan,fields);return{action:"show",plan,next_actions:nextActionsFor(itemId,fullPlan),warnings:[],generated_at:nowIso()}}function changedPlanMetadataFields(beforePlanFields,metadata){const afterPlanFields=new Map(Object.entries(metadata).filter(([key])=>key.startsWith("plan_")).map(([key,value])=>[key,JSON.stringify(value)]));return[...new Set([...beforePlanFields.keys(),...afterPlanFields.keys()])].filter(key=>beforePlanFields.get(key)!==afterPlanFields.get(key))}async function mutatePlanSteps(args){const author=resolveAuthor(args.options.author,args.ctx.settings.author_default);let resultStep;const result=await mutateItem({pmRoot:args.ctx.pmRoot,settings:args.ctx.settings,id:args.id,op:args.op,author,message:args.options.message??args.message,force:args.options.force,mutate(doc){ensurePlanItem(doc.metadata);const statusRegistry=resolveRuntimeStatusRegistry(args.ctx.settings.schema);if(isTerminalStatus(doc.metadata.status,statusRegistry)||isTerminalPlanMode(doc.metadata.plan_mode)){throw new PmCliError(`Plan ${doc.metadata.id} is terminal (status=${doc.metadata.status}, plan_mode=${doc.metadata.plan_mode??"unset"}) and cannot be mutated.`,EXIT_CODE.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."})}const steps=(doc.metadata.plan_steps??[]).slice();const beforePlanFields=new Map(Object.entries(doc.metadata).filter(([key])=>key.startsWith("plan_")).map(([key,value])=>[key,JSON.stringify(value)]));const outcome=args.mutator(steps,doc);resultStep=outcome.resultStep;const sorted=steps.slice().sort((left,right)=>left.order-right.order).map((step,index)=>({...step,order:index+1}));doc.metadata.plan_steps=sorted;const changedFields=changedPlanMetadataFields(beforePlanFields,doc.metadata);if(changedFields.length===0&&outcome.changedSteps.length===0){return{changedFields:[]}}return{changedFields:changedFields.length>0?changedFields:["plan_steps"]}}});return{document:{metadata:result.item,body:result.body},resultStep,itemId:result.item.id}}async function planAddStep(id,options,ctx){const title=options.stepTitle?.trim();if(!title){throw new PmCliError("pm plan add-step requires --step-title",EXIT_CODE.USAGE)}const status=asStepStatus(options.stepStatus,"pending");const allowMultipleActive=options.allowMultipleActive===true;const{document,resultStep,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_add_step",message:`plan add-step "${title}"`,mutator(steps){const order=steps.length+1;assertInProgressStepAllowed(steps,void 0,status,allowMultipleActive);const step=buildAddedPlanStep(steps,options,{order,title,status});steps.push(step);return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"add-step",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function assertInProgressStepAllowed(steps,currentStepId,desiredStatus,allowMultipleActive){if(desiredStatus!=="in_progress"||allowMultipleActive){return}const activeStep=steps.find(step=>step.id!==currentStepId&&step.status==="in_progress");if(!activeStep){return}throw new PmCliError(`Plan already has step ${activeStep.id} in_progress. Pass --allow-multiple-active or update that step first.`,EXIT_CODE.CONFLICT)}function buildAddedPlanStep(existingSteps,options,seed){const linkedItems=buildLinkInputs(options,"depends_on");const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);const now=nowIso();return{id:newStepId(existingSteps),order:seed.order,title:seed.title,body:options.stepBody?.trim()||void 0,status:seed.status,owner:options.stepOwner?.trim()||void 0,evidence:options.stepEvidence?.trim()||void 0,blocked_reason:seed.status==="blocked"?options.stepBlockedReason?.trim()||"":void 0,linked_items:linkedItems.length>0?linkedItems:void 0,files:files.length>0?files:void 0,tests:tests.length>0?tests:void 0,docs:docs.length>0?docs:void 0,created_at:now,updated_at:now,completed_at:seed.status==="completed"?now:void 0}}function buildLinkInputs(options,fallbackKind){const dependsOn=toArray(options.dependsOn).map(id=>({id,kind:fallbackKind}));const related=toArray(options.related).map(id=>({id,kind:"related"}));const blocks=toArray(options.blocks).map(id=>({id,kind:"blocks"}));const blockedBy=toArray(options.blockedBy).map(id=>({id,kind:"blocked_by"}));const explicit=toArray(options.link);const explicitKind=asLinkKind(options.linkKind,fallbackKind);const note=options.linkNote?.trim();const explicitLinks=explicit.map(id=>{const link={id,kind:explicitKind};if(note)link.note=note;return link});return[...dependsOn,...related,...blocks,...blockedBy,...explicitLinks]}async function planUpdateStep(id,options,ctx,args){const{document,resultStep,itemId}=await mutatePlanSteps({id,options,ctx,op:args.op,message:options.message??`${args.op} ${args.stepRef}`,mutator(steps,doc){const step=resolveStepRef(steps,args.stepRef);const now=nowIso();const desiredStatus=args.finalStatus??asStepStatus(options.stepStatus,step.status);const allowMultipleActive=options.allowMultipleActive===true||args.allowMultipleActive===true;assertInProgressStepAllowed(steps,step.status==="in_progress"?step.id:void 0,desiredStatus,allowMultipleActive);applyStepUpdates(step,options,desiredStatus,now);doc.metadata.updated_at=now;return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:args.op==="plan_complete_step"?"complete-step":args.op==="plan_block_step"?"block-step":"update-step",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function applyStepUpdates(step,options,desiredStatus,now){assertBlockedStepReason(step,options,desiredStatus);applyStepFieldUpdates(step,options);step.status=desiredStatus;step.updated_at=now;applyStepCompletionTimestamp(step,desiredStatus,now)}function assertBlockedStepReason(step,options,desiredStatus){if(desiredStatus!=="blocked"||options.stepBlockedReason?.trim()||step.blocked_reason){return}throw new PmCliError("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",EXIT_CODE.USAGE)}function applyStepFieldUpdates(step,options){const title=options.stepTitle?.trim();if(title){step.title=title}if(options.stepBody!==void 0){step.body=options.stepBody.trim()||void 0}if(options.stepOwner!==void 0){step.owner=options.stepOwner.trim()||void 0}if(options.stepEvidence!==void 0){step.evidence=options.stepEvidence.trim()||void 0}if(options.stepBlockedReason!==void 0){step.blocked_reason=options.stepBlockedReason.trim()||void 0}if(options.stepReplacement!==void 0){step.superseded_by=options.stepReplacement.trim()||void 0}const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);if(files.length>0){step.files=mergePlanStepEvidence(step.files,files)}if(tests.length>0){step.tests=mergePlanStepEvidence(step.tests,tests)}if(docs.length>0){step.docs=mergePlanStepEvidence(step.docs,docs)}}function mergePlanStepEvidence(existing,added){const merged=[...existing??[]];const seen=new Set(merged.map(entry=>JSON.stringify(entry)));for(const entry of added){const key=JSON.stringify(entry);if(seen.has(key))continue;seen.add(key);merged.push(entry)}return merged}function applyStepCompletionTimestamp(step,desiredStatus,now){if(desiredStatus==="completed"&&!step.completed_at){step.completed_at=now;return}if(desiredStatus!=="completed"){step.completed_at=void 0}}async function planReorderStep(id,options,ctx,stepRef,newOrder){const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_reorder_step",message:options.message??`plan reorder-step ${stepRef} -> ${newOrder}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const filtered=steps.filter(entry=>entry.id!==step.id);const clamped=Math.max(1,Math.min(newOrder,filtered.length+1));filtered.splice(clamped-1,0,step);filtered.forEach((entry,index)=>{entry.order=index+1;entry.updated_at=nowIso()});steps.length=0;steps.push(...filtered);return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"reorder-step",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planRemoveStep(id,options,ctx,stepRef){const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_remove_step",message:options.message??`plan remove-step ${stepRef}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const remaining=steps.filter(entry=>entry.id!==step.id);remaining.forEach((entry,index)=>{entry.order=index+1});steps.length=0;steps.push(...remaining);return{changedSteps:[step.id]}}});const plan=projectPlan(document.metadata,"standard");return{action:"remove-step",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planLink(id,options,ctx,stepRef){const newLinks=buildLinkInputs(options,asLinkKind(options.linkKind,"related"));if(newLinks.length===0){throw new PmCliError("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",EXIT_CODE.USAGE)}const promoteToItemDep=options.promoteToItemDep===true;const{document,itemId,resultStep}=await mutatePlanSteps({id,options,ctx,op:"plan_link_step",message:options.message??`plan link ${stepRef}`,mutator(steps,doc){const step=resolveStepRef(steps,stepRef);const existing=step.linked_items??[];const dedupKey=link=>`${link.kind}:${link.id}`;const seen=new Set(existing.map(dedupKey));for(const link of newLinks){const key=dedupKey(link);if(seen.has(key))continue;existing.push(link);seen.add(key)}step.linked_items=existing;step.updated_at=nowIso();if(promoteToItemDep){const deps=doc.metadata.dependencies??[];const depKey=dep=>`${dep.kind}:${dep.id}`;const seenDeps=new Set(deps.map(depKey));for(const link of newLinks){const promotedKind=link.kind==="depends_on"?"blocked_by":link.kind;const candidate={id:link.id,kind:promotedKind,created_at:nowIso(),author:resolveAuthor(options.author,ctx.settings.author_default)};if(seenDeps.has(depKey(candidate)))continue;deps.push(candidate);seenDeps.add(depKey(candidate))}doc.metadata.dependencies=deps}return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"link",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planUnlink(id,options,ctx,stepRef){const removeIds=toArray(options.link);if(removeIds.length===0){throw new PmCliError("pm plan unlink requires --link <id> to remove",EXIT_CODE.USAGE)}const{document,itemId,resultStep}=await mutatePlanSteps({id,options,ctx,op:"plan_unlink_step",message:options.message??`plan unlink ${stepRef}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const filtered=(step.linked_items??[]).filter(link=>!removeIds.includes(link.id));step.linked_items=filtered.length>0?filtered:void 0;step.updated_at=nowIso();return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"unlink",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planAppendLog(id,options,ctx,kind){const logText=resolvePlanLogText(kind,options);if(!logText){const canonical=`--${kind}-text`;const shorthand=`--${kind}`;throw new PmCliError(`pm plan ${kind} requires ${canonical}`,EXIT_CODE.USAGE,{code:"missing_required_option",examples:[`pm plan ${kind} <plan-id> ${canonical} "..."`,`pm plan ${kind} <plan-id> ${shorthand} "..."`],recovery:{suggested_retry:`pm plan ${kind} <plan-id> ${canonical} <value>`}})}const author=resolveAuthor(options.author,ctx.settings.author_default);const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:`plan_append_${kind}`,message:options.message??`plan ${kind} append`,mutator(_steps,doc){const now=nowIso();if(kind==="decision"){const list2=doc.metadata.plan_decisions??[];list2.push({ts:now,author,decision:logText,rationale:options.decisionRationale?.trim()||void 0,evidence:options.decisionEvidence?.trim()||void 0});doc.metadata.plan_decisions=list2;return{changedSteps:[]}}if(kind==="discovery"){const list2=doc.metadata.plan_discoveries??[];list2.push({ts:now,author,text:logText});doc.metadata.plan_discoveries=list2;return{changedSteps:[]}}const list=doc.metadata.plan_validation??[];list.push({text:logText,command:options.validationCommand?.trim()||void 0,expected:options.validationExpected?.trim()||void 0});doc.metadata.plan_validation=list;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"deep");return{action:kind,plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planResume(id,options,ctx){const text=options.resumeContext?.trim();if(!text){throw new PmCliError("pm plan resume requires --resume-context <text>",EXIT_CODE.USAGE)}const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_resume",message:options.message??"plan resume context update",mutator(_steps,doc){doc.metadata.plan_resume_context=text;const scope=options.scope?.trim();if(scope)doc.metadata.plan_scope=scope;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"brief");return{action:"resume",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planApprove(id,options,ctx){const mode=asPlanMode(options.mode??"approved","approved");const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_approve",message:options.message??`plan approve mode=${mode}`,mutator(_steps,doc){doc.metadata.plan_mode=mode;const scope=options.scope?.trim();if(scope)doc.metadata.plan_scope=scope;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"brief");return{action:"approve",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function buildMaterializeSkippedWarnings(materializeSkipped){return materializeSkipped.map(entry=>`plan_materialize_skipped:${entry.from_step}:${entry.reason}${entry.existing_id?`:${entry.existing_id}`:""}`)}function buildMaterializeNoopResult(planRead,materializeSkipped){const plan=projectPlan(planRead.document.metadata,"standard");return{action:"materialize",plan,materialized:[],materialize_skipped:materializeSkipped,next_actions:nextActionsFor(planRead.itemId,plan),warnings:buildMaterializeSkippedWarnings(materializeSkipped),generated_at:nowIso()}}function buildMaterializeDependencies(parent,planItemId,step){const deps=[`id=${parent},kind=parent`,`id=${planItemId},kind=discovered_from`];for(const link of step.linked_items??[]){const realKind=link.kind==="blocked_by"||link.kind==="blocks"||link.kind==="related"||link.kind==="discovered_from"?link.kind:"related";deps.push(`id=${link.id},kind=${realKind}`)}return deps}async function createMaterializedStepItems(params){const materialized=[];const materializeFields={};const reservedMaterializeKeys=new Set(["title","description","type","parent","tags","author","message","dep"]);for(const specification of toSpecArray(params.options.field)){const separator=specification.indexOf("=");if(separator<=0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const name=specification.slice(0,separator).trim();const value=specification.slice(separator+1).trim();if(name.length===0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const segments=name.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(segment=>segment.toLowerCase());if(segments.length===0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const[first,...rest]=segments;const fieldKey=`${first}${rest.map(segment=>`${segment.slice(0,1).toUpperCase()}${segment.slice(1)}`).join("")}`;if(reservedMaterializeKeys.has(fieldKey)){throw new PmCliError(`Invalid --field entry "${specification}"; "${fieldKey}" is reserved by materialize and cannot be overridden`,EXIT_CODE.USAGE)}materializeFields[fieldKey]=value}for(const step of params.targets){const createOptions={...materializeFields,title:step.title,description:step.body?.trim()||step.title,type:params.resolvedTypeName,parent:params.parent,tags:params.tags,author:params.options.author,message:params.options.message??`materialized from plan ${params.planItemId} step ${step.id}`,dep:buildMaterializeDependencies(params.parent,params.planItemId,step)};preservePlanCreateStdinPolicy(params.options,createOptions,["description",...Object.keys(materializeFields)]);const created=await runCreate(createOptions,{...{},path:params.pmRoot});materialized.push({id:created.item.id,title:created.item.title,type:params.resolvedTypeName,parent:created.item.parent,tags:created.item.tags??[],from_step:step.id})}return materialized}function linkMaterializedStepItems(currentSteps,targets,materialized){for(const target of targets){const matched=materialized.find(entry=>entry.from_step===target.id);if(!matched){continue}const step=currentSteps.find(entry=>entry.id===target.id);if(!step){continue}const links=step.linked_items??[];links.push({id:matched.id,kind:"implements",note:`materialized as ${matched.type}`});step.linked_items=links;step.updated_at=nowIso()}}async function planMaterialize(id,options,ctx){const stepRefs=toArray(options.steps);if(stepRefs.length===0){throw new PmCliError("pm plan materialize requires --steps <ids|orders|all>",EXIT_CODE.USAGE)}const targetType=options.materializeType?.trim()||"Task";const typeRegistry=resolveItemTypeRegistry(ctx.settings,getActiveExtensionRegistrations());const resolvedTypeName=resolveTypeName(targetType,typeRegistry);if(!resolvedTypeName){throw new PmCliError(`Invalid --materialize-type "${targetType}"`,EXIT_CODE.USAGE)}const parent=options.materializeParent?.trim()||id;const tags=options.materializeTags;const planRead=await readPlanItem(ctx,id);const steps=(planRead.document.metadata.plan_steps??[]).slice();const{targets,skipped:materializeSkipped}=resolveMaterializeTargets(steps,stepRefs);if(targets.length===0){if(materializeSkipped.length>0){return buildMaterializeNoopResult(planRead,materializeSkipped)}throw new PmCliError("No matching plan steps found for --steps",EXIT_CODE.NOT_FOUND)}const materialized=await createMaterializedStepItems({targets,parent,planItemId:planRead.itemId,resolvedTypeName,tags,options,pmRoot:ctx.pmRoot});const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_materialize",message:options.message??`plan materialize ${stepRefs.join(",")}`,mutator(currentSteps){linkMaterializedStepItems(currentSteps,targets,materialized);return{changedSteps:targets.map(entry=>entry.id)}}});const plan=projectPlan(document.metadata,"standard");return{action:"materialize",plan,materialized,...materializeSkipped.length>0?{materialize_skipped:materializeSkipped}:{},next_actions:nextActionsFor(itemId,plan),warnings:buildMaterializeSkippedWarnings(materializeSkipped),generated_at:nowIso()}}function normalizePlanStepAliasInput(input){if(input.subcommand==="create"){return input}const stepValues=toOrderedStepTitles(input.options.step);if(stepValues.length>1){throw new PmCliError(`pm plan ${input.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,EXIT_CODE.USAGE)}if(stepValues.length===1&&!input.options.stepTitle?.trim()){return{...input,options:transferMutationStdinTokenPolicy(input.options,{...input.options,stepTitle:stepValues[0]})}}return input}function requirePlanId(input,label){if(!input.id){throw new PmCliError(`pm plan ${label} requires a plan id`,EXIT_CODE.USAGE)}return input.id}function requirePlanStepRef(input,label){const id=requirePlanId(input,label);if(!input.stepRef){throw new PmCliError(`pm plan ${label} requires <plan-id> <step>`,EXIT_CODE.USAGE)}return{id,stepRef:input.stepRef}}function requireReorderTarget(input){const target=requirePlanStepRef(input,"reorder-step");if(input.reorderTo===void 0){throw new PmCliError("pm plan reorder-step requires <plan-id> <step> <new-order>",EXIT_CODE.USAGE)}return{...target,reorderTo:input.reorderTo}}const PLAN_DISPATCHERS={create:(input,ctx)=>planCreate(input.options,input.global,ctx),show:(input,ctx)=>planShow(requirePlanId(input,"show"),input.options,ctx),"add-step":(input,ctx)=>planAddStep(requirePlanId(input,"add-step"),input.options,ctx),"update-step":(input,ctx)=>{const target=requirePlanStepRef(input,"update-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,op:"plan_update_step"})},"complete-step":(input,ctx)=>{const target=requirePlanStepRef(input,"complete-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(input,ctx)=>{const target=requirePlanStepRef(input,"block-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(input,ctx)=>{const target=requireReorderTarget(input);return planReorderStep(target.id,input.options,ctx,target.stepRef,target.reorderTo)},"remove-step":(input,ctx)=>{const target=requirePlanStepRef(input,"remove-step");return planRemoveStep(target.id,input.options,ctx,target.stepRef)},link:(input,ctx)=>{const target=requirePlanStepRef(input,"link");return planLink(target.id,input.options,ctx,target.stepRef)},unlink:(input,ctx)=>{const target=requirePlanStepRef(input,"unlink");return planUnlink(target.id,input.options,ctx,target.stepRef)},decision:(input,ctx)=>planAppendLog(requirePlanId(input,"decision"),input.options,ctx,"decision"),discovery:(input,ctx)=>planAppendLog(requirePlanId(input,"discovery"),input.options,ctx,"discovery"),validation:(input,ctx)=>planAppendLog(requirePlanId(input,"validation"),input.options,ctx,"validation"),resume:(input,ctx)=>planResume(requirePlanId(input,"resume"),input.options,ctx),approve:(input,ctx)=>planApprove(requirePlanId(input,"approve"),input.options,ctx),materialize:(input,ctx)=>planMaterialize(requirePlanId(input,"materialize"),input.options,ctx)};function resolvePlanDispatcher(subcommand){const dispatcher=PLAN_DISPATCHERS[subcommand];if(!dispatcher){throw createUnknownSubcommandError({command_path:"plan",token:subcommand,allowed:PLAN_SUBCOMMANDS})}return dispatcher}async function runPlan(input){const ctx=await loadContext(input.global);const normalizedInput=normalizePlanStepAliasInput(input);return resolvePlanDispatcher(normalizedInput.subcommand)(normalizedInput,ctx)}const _testOnlyPlanCommand={changedPlanMetadataFields};export{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,_testOnlyPlanCommand,resolvePlanTemplateSteps,runPlan};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d9a4fa9f-2f70-5ce9-b9c0-24e58b120420")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,isTerminalStatus,resolveItemTypeRegistry,resolveRuntimeStatusRegistry,resolveTypeName,EXIT_CODE,PmCliError,splitCommaList,nowIso,locateItem,mutateItem,readLocatedItem,resolvePmRoot,readSettings,resolveAuthor,isTerminalPlanMode,preserveMutationStdinTokenFields,transferMutationStdinTokenPolicy}from"../runtime-primitives.js";import{PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES}from"../../types/index.js";import{runCreate}from"./create.js";import{createUnknownSubcommandError}from"../agent/subcommand-recovery.js";import{buildPlanMutationReceipt}from"./plan-mutation-receipt.js";const PLAN_SUBCOMMANDS=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"];const PLAN_SHOW_DEPTH_VALUES=["brief","standard","deep"];const STEP_ID_PREFIX="plan-step-";const DEFAULT_PLAN_MODE="draft";const PLAN_TEMPLATE_NAMES=["bug-investigation","feature-implementation","refactoring-sprint"];const PLAN_TEMPLATES={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function resolvePlanTemplateSteps(raw){const normalized=raw.trim().toLowerCase();const template=Object.prototype.hasOwnProperty.call(PLAN_TEMPLATES,normalized)?PLAN_TEMPLATES[normalized]:void 0;if(!template){throw new PmCliError(`Unknown plan template "${raw}". Allowed: ${PLAN_TEMPLATE_NAMES.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${PLAN_TEMPLATE_NAMES[0]}`]})}return template.map(step=>({...step}))}function planCompletionPct(completed,total){return total>0?Math.round(completed/total*100):0}function toOrderedStepTitles(value){const values=Array.isArray(value)?value:value===void 0||value===null?[]:[value];return values.filter(entry=>entry!==void 0&&entry!==null).map(entry=>(typeof entry==="string"?entry:String(entry)).trim()).filter(entry=>entry.length>0)}function toArray(value){if(Array.isArray(value))return value.flatMap(entry=>splitCommaList(entry,{unique:false}));if(typeof value==="string"&&value.trim().length>0){return splitCommaList(value,{unique:false})}return[]}function toSpecArray(value){if(Array.isArray(value))return value.map(entry=>entry.trim()).filter(Boolean);if(typeof value==="string"&&value.trim().length>0)return[value.trim()];return[]}function asPlanMode(value,fallback=DEFAULT_PLAN_MODE){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_MODE_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid plan mode "${value}". Allowed: ${PLAN_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asStepStatus(value,fallback="pending"){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_STEP_STATUS_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid step status "${value}". Allowed: ${PLAN_STEP_STATUS_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asLinkKind(value,fallback="related"){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_STEP_LINK_KIND_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid step link kind "${value}". Allowed: ${PLAN_STEP_LINK_KIND_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asHarness(value){if(value===void 0)return void 0;const normalized=value.trim().toLowerCase();if(normalized.length===0)return void 0;const found=PLAN_HARNESS_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid plan harness "${value}". Allowed: ${PLAN_HARNESS_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asDepth(value){if(value===void 0)return"brief";const normalized=value.trim().toLowerCase();const found=PLAN_SHOW_DEPTH_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid --depth "${value}". Allowed: ${PLAN_SHOW_DEPTH_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function parsePlanFields(raw){if(raw===void 0){return null}const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0){throw new PmCliError("Plan --fields requires a comma-separated list of plan field names",EXIT_CODE.USAGE)}return fields}const PLAN_FIELD_KEYS=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function projectPlanForFields(plan,fields){const source=plan;const projected={};const unknownFields=[];for(const field of fields){const normalized=field.startsWith("plan.")?field.slice("plan.".length):field;if(normalized.length===0){continue}if(!PLAN_FIELD_KEYS.has(normalized)){unknownFields.push(field);continue}if(Object.prototype.hasOwnProperty.call(source,normalized)){projected[normalized]=source[normalized]}}if(unknownFields.length>0){throw new PmCliError(`Unknown Plan --fields value(s): ${unknownFields.join(", ")}`,EXIT_CODE.USAGE,{nextSteps:[`Use --fields ${[...PLAN_FIELD_KEYS].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:unknownFields,suggested_retry:`pm plan show <id> --fields ${[...PLAN_FIELD_KEYS].join(",")}`}})}return projected}function parsePairList(raw,label){const out={};for(const entry of raw.split(",")){const trimmed=entry.trim();if(trimmed.length===0)continue;const equalsIndex=trimmed.indexOf("=");if(equalsIndex<=0){throw new PmCliError(`Invalid ${label} entry "${trimmed}"; expected key=value`,EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:`${label} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']})}out[trimmed.slice(0,equalsIndex).trim().toLowerCase()]=trimmed.slice(equalsIndex+1).trim()}return out}function parseStepFile(spec){const fields=parsePairList(spec,"--file");if(!fields.path){throw new PmCliError("--file requires path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."})}const file={path:fields.path};if(fields.scope==="global"||fields.scope==="project")file.scope=fields.scope;if(fields.note)file.note=fields.note;return file}function parseStepTest(spec){const fields=parsePairList(spec,"--test");if(!fields.command&&!fields.path){throw new PmCliError("--test requires at least command=<value> or path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."})}const test={};if(fields.command)test.command=fields.command;if(fields.path)test.path=fields.path;if(fields.note)test.note=fields.note;return test}function parseStepDoc(spec){const fields=parsePairList(spec,"--doc");if(!fields.path){throw new PmCliError("--doc requires path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."})}const doc={path:fields.path};if(fields.scope==="global"||fields.scope==="project")doc.scope=fields.scope;if(fields.note)doc.note=fields.note;return doc}function summarizeSteps(steps){const summary={total:steps.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(const step of steps){summary[step.status]+=1}summary.completion_pct=planCompletionPct(summary.completed,summary.total);return summary}function newStepId(existing){const used=new Set(existing.map(step=>step.id));for(let cursor=existing.length+1;cursor<existing.length+1024;cursor+=1){const candidate=`${STEP_ID_PREFIX}${String(cursor).padStart(3,"0")}`;if(!used.has(candidate))return candidate}throw new PmCliError("Could not allocate step id (limit reached)",EXIT_CODE.GENERIC_FAILURE)}function resolveStepRef(steps,ref){const trimmed=ref.trim();if(trimmed.length===0){throw new PmCliError("Step reference cannot be empty",EXIT_CODE.USAGE)}const direct=steps.find(step=>step.id===trimmed);if(direct)return direct;if(/^\d+$/.test(trimmed)){const order=Number.parseInt(trimmed,10);const byOrder=steps.find(step=>step.order===order);if(byOrder)return byOrder}throw new PmCliError(`Step "${ref}" not found in plan`,EXIT_CODE.NOT_FOUND)}function classifyMaterializeSkip(step){if(step.status==="completed"){return{reason:"already_completed"}}const existingImplements=(step.linked_items??[]).find(link=>link.kind==="implements");if(existingImplements){return{reason:"already_materialized",existing_id:existingImplements.id}}return void 0}function resolveMaterializeTargets(steps,refs){const allRefs=refs.filter(ref=>ref.trim().toLowerCase()==="all");const targets=[];const skipped=[];if(allRefs.length>0){if(refs.length>allRefs.length){throw new PmCliError("pm plan materialize --steps all cannot be combined with other step refs",EXIT_CODE.USAGE)}for(const step of steps.slice().sort((left,right)=>left.order-right.order)){const skip=classifyMaterializeSkip(step);if(skip){skipped.push({from_step:step.id,...skip});continue}targets.push(step)}return{targets,skipped}}const seen=new Set;for(const ref of refs){const step=resolveStepRef(steps,ref);if(seen.has(step.id))continue;seen.add(step.id);const skip=classifyMaterializeSkip(step);if(skip){skipped.push({from_step:step.id,...skip});continue}targets.push(step)}return{targets,skipped}}function resolvePlanLogText(kind,options){const canonical=kind==="decision"?options.decisionText:kind==="discovery"?options.discoveryText:options.validationText;const shorthand=kind==="decision"?options.decision:kind==="discovery"?options.discovery:options.validation;return canonical?.trim()||shorthand?.trim()||void 0}function findCurrentStep(steps){return steps.find(step=>step.status==="in_progress")??steps.find(step=>step.status==="pending")}function blockedSteps(steps){return steps.filter(step=>step.status==="blocked").map(step=>({id:step.id,order:step.order,title:step.title,blocked_reason:step.blocked_reason}))}function projectPlan(item,depth="brief"){const steps=(item.plan_steps??[]).slice().sort((left,right)=>left.order-right.order);const summary=summarizeSteps(steps);const current=findCurrentStep(steps);const projection={id:item.id,title:item.title,status:item.status,mode:item.plan_mode??DEFAULT_PLAN_MODE,scope:item.plan_scope,harness:item.plan_harness,parent:item.parent,resume_context:item.plan_resume_context,steps_summary:summary,current_step:current?{id:current.id,order:current.order,title:current.title,status:current.status}:void 0,blocked_steps:blockedSteps(steps),linked_items:(item.dependencies??[]).map(dep=>({id:dep.id,kind:dep.kind}))};if(depth==="standard"||depth==="deep"){projection.steps=steps}if(depth==="deep"){projection.decisions=item.plan_decisions??[];projection.discoveries=item.plan_discoveries??[];projection.validation=item.plan_validation??[]}return projection}function nextActionsFor(planId,plan){const tips=[];if(plan.steps_summary.total===0){tips.push(`pm plan add-step ${planId} --step-title "First step"`)}if(plan.current_step){tips.push(`pm plan update-step ${planId} ${plan.current_step.id} --step-status in_progress`,`pm plan complete-step ${planId} ${plan.current_step.id} --step-evidence "..."`)}if(plan.steps_summary.blocked>0){tips.push(`pm plan show ${planId} --depth standard`)}if(plan.mode==="draft"||plan.mode==="research"){tips.push(`pm plan approve ${planId} --message "ready to execute"`)}if(plan.steps_summary.completed===plan.steps_summary.total&&plan.steps_summary.total>0&&!isTerminalPlanMode(plan.mode)&&plan.status!=="closed"&&plan.status!=="canceled"){tips.push(`pm close ${planId} "plan complete"`)}return tips}function ensurePlanItem(item){const normalizedType=(item.type??"").trim().toLowerCase();if(normalizedType!=="plan"){throw new PmCliError(`Item ${item.id} is type ${item.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,EXIT_CODE.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${item.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}}async function loadContext(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);return{pmRoot,settings}}async function readPlanItem(ctx,id){const typeRegistry=resolveItemTypeRegistry(ctx.settings,getActiveExtensionRegistrations());const located=await locateItem(ctx.pmRoot,id,ctx.settings.id_prefix,ctx.settings.item_format,typeRegistry.type_to_folder);if(!located){throw new PmCliError(`Plan ${id} not found`,EXIT_CODE.NOT_FOUND)}const loaded=await readLocatedItem(located,{schema:ctx.settings.schema});ensurePlanItem(loaded.document.metadata);return{document:loaded.document,itemId:located.id}}function buildPlanCreateDependencies(options){const deps=[];if(options.parent){deps.push(`id=${options.parent.trim()},kind=parent`)}for(const ref of toArray(options.related))deps.push(`id=${ref},kind=related`);for(const ref of toArray(options.blocks))deps.push(`id=${ref},kind=blocks`);for(const ref of toArray(options.blockedBy))deps.push(`id=${ref},kind=blocked_by`);return deps.length>0?deps:void 0}function buildInitialValidation(options){const text=options.validationText?.trim();const command=options.validationCommand?.trim();const expected=options.validationExpected?.trim();if(!text&&!command&&!expected){return void 0}return{text:text||command||"Validation check",command:command||void 0,expected:expected||void 0}}function hasPlanStepDetailOptions(options){return Boolean(options.stepBody?.trim())||Boolean(options.stepOwner?.trim())||Boolean(options.stepStatus?.trim())||Boolean(options.stepEvidence?.trim())||Boolean(options.stepBlockedReason?.trim())||Boolean(options.stepReplacement?.trim())||toArray(options.dependsOn).length>0||toArray(options.link).length>0}function resolveInitialStepSeed(options){const stepTitleFlag=options.stepTitle?.trim()||void 0;const repeatedStepTitles=toOrderedStepTitles(options.step);const templateSteps=options.template?.trim()?resolvePlanTemplateSteps(options.template):[];return{repeatedStepTitles,stepTitleFlag,stepTitles:[...stepTitleFlag?[stepTitleFlag]:[],...repeatedStepTitles,...templateSteps.map(step=>step.title)],templateSteps}}function assertInitialStepSeedAllowed(seed,hasPerStepDetailOptions){if((seed.stepTitleFlag||seed.repeatedStepTitles.length>0)&&seed.templateSteps.length>0){throw new PmCliError("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${PLAN_TEMPLATE_NAMES[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']})}if(seed.stepTitles.length>1&&hasPerStepDetailOptions){throw new PmCliError("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}}function buildSingleInitialStep(options,title){const status=asStepStatus(options.stepStatus,"pending");const linkedItems=buildLinkInputs(options,"depends_on");const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);const now=nowIso();return{id:"plan-step-001",order:1,title,body:options.stepBody?.trim()||void 0,status,owner:options.stepOwner?.trim()||void 0,evidence:options.stepEvidence?.trim()||void 0,blocked_reason:status==="blocked"?options.stepBlockedReason?.trim()||"":void 0,linked_items:linkedItems.length>0?linkedItems:void 0,files:files.length>0?files:void 0,tests:tests.length>0?tests:void 0,docs:docs.length>0?docs:void 0,created_at:now,updated_at:now,completed_at:status==="completed"?now:void 0}}function buildInitialSteps(options){const seed=resolveInitialStepSeed(options);const hasDetailOptions=hasPlanStepDetailOptions(options);assertInitialStepSeedAllowed(seed,hasDetailOptions);if(seed.stepTitles.length===0){return{steps:[],hasPerStepDetailOptions:hasDetailOptions}}if(seed.stepTitles.length===1){return{steps:[buildSingleInitialStep(options,seed.stepTitles[0])],hasPerStepDetailOptions:hasDetailOptions}}const now=nowIso();return{steps:seed.stepTitles.map((stepTitle,index)=>({id:`${STEP_ID_PREFIX}${String(index+1).padStart(3,"0")}`,order:index+1,title:stepTitle,body:seed.templateSteps[index]?.body,status:"pending",created_at:now,updated_at:now})),hasPerStepDetailOptions:hasDetailOptions}}function preservePlanCreateStdinPolicy(source,createOptions,derivedLiteralFields=[]){transferMutationStdinTokenPolicy(source,createOptions);if(derivedLiteralFields.length>0){preserveMutationStdinTokenFields(createOptions,derivedLiteralFields)}}async function planCreate(options,global2,ctx){const title=options.title?.trim();if(!title){throw new PmCliError("pm plan create requires --title",EXIT_CODE.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']})}const mode=asPlanMode(options.mode,DEFAULT_PLAN_MODE);const harness=asHarness(options.harness);const fromSearch=options.fromSearch?.trim();const initialValidation=buildInitialValidation(options);const{steps:initialSteps,hasPerStepDetailOptions}=buildInitialSteps(options);if(initialSteps.length===0&&hasPerStepDetailOptions){throw new PmCliError("pm plan create step options require --step-title (or a single --step)",EXIT_CODE.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']})}const description=options.description?.trim()??options.scope?.trim()??title;const requestedAssignee=options.claim?resolveAuthor(options.author,ctx.settings.author_default):options.assignee?.trim()||void 0;const createOptions={...options,title,description,type:"Plan",template:void 0,file:toSpecArray(options.file),test:toSpecArray(options.test),doc:toSpecArray(options.doc),field:toSpecArray(options.field),assignee:resolveAuthor(options.author,ctx.settings.author_default),blockedBy:void 0,dep:buildPlanCreateDependencies(options),message:options.message??(fromSearch?`plan create (search: ${fromSearch})`:`plan create`)};preservePlanCreateStdinPolicy(options,createOptions);const createResult=await runCreate(createOptions,global2);const seedResult=await mutateItem({pmRoot:ctx.pmRoot,settings:ctx.settings,id:createResult.item.id,op:"plan_create_metadata",author:resolveAuthor(options.author,ctx.settings.author_default),message:"seed plan metadata",mutate(doc){const changedFields=["plan_mode"];doc.metadata.plan_mode=mode;if(harness){doc.metadata.plan_harness=harness;changedFields.push("plan_harness")}const scope=options.scope?.trim();if(scope){doc.metadata.plan_scope=scope;changedFields.push("plan_scope")}const resumeContext=options.resumeContext?.trim();if(resumeContext){doc.metadata.plan_resume_context=resumeContext;changedFields.push("plan_resume_context")}doc.metadata.plan_steps=initialSteps;changedFields.push("plan_steps");if(initialValidation){doc.metadata.plan_validation=[...doc.metadata.plan_validation??[],initialValidation];changedFields.push("plan_validation")}if(requestedAssignee){doc.metadata.assignee=requestedAssignee;changedFields.push("assignee")}return{changedFields}}});const plan=projectPlan(seedResult.item,"brief");return{action:"create",plan,step:initialSteps[0],next_actions:nextActionsFor(createResult.item.id,plan),warnings:[...createResult.warnings],generated_at:nowIso()}}async function planShow(id,options,ctx){const depth=asDepth(options.depth);const fields=parsePlanFields(options.fields);const{document,itemId}=await readPlanItem(ctx,id);const fullPlan=projectPlan(document.metadata,fields===null?depth:"deep");const plan=fields===null?fullPlan:projectPlanForFields(fullPlan,fields);return{action:"show",plan,next_actions:nextActionsFor(itemId,fullPlan),warnings:[],generated_at:nowIso()}}function changedPlanMetadataFields(beforePlanFields,metadata){const afterPlanFields=new Map(Object.entries(metadata).filter(([key])=>key.startsWith("plan_")).map(([key,value])=>[key,JSON.stringify(value)]));return[...new Set([...beforePlanFields.keys(),...afterPlanFields.keys()])].filter(key=>beforePlanFields.get(key)!==afterPlanFields.get(key))}async function mutatePlanSteps(args){const author=resolveAuthor(args.options.author,args.ctx.settings.author_default);let resultStep;const result=await mutateItem({pmRoot:args.ctx.pmRoot,settings:args.ctx.settings,id:args.id,op:args.op,author,message:args.options.message??args.message,force:args.options.force,mutate(doc){ensurePlanItem(doc.metadata);const statusRegistry=resolveRuntimeStatusRegistry(args.ctx.settings.schema);if(isTerminalStatus(doc.metadata.status,statusRegistry)||isTerminalPlanMode(doc.metadata.plan_mode)){throw new PmCliError(`Plan ${doc.metadata.id} is terminal (status=${doc.metadata.status}, plan_mode=${doc.metadata.plan_mode??"unset"}) and cannot be mutated.`,EXIT_CODE.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."})}const steps=(doc.metadata.plan_steps??[]).slice();const beforePlanFields=new Map(Object.entries(doc.metadata).filter(([key])=>key.startsWith("plan_")).map(([key,value])=>[key,JSON.stringify(value)]));const outcome=args.mutator(steps,doc);resultStep=outcome.resultStep;const sorted=steps.slice().sort((left,right)=>left.order-right.order).map((step,index)=>({...step,order:index+1}));doc.metadata.plan_steps=sorted;const changedFields=changedPlanMetadataFields(beforePlanFields,doc.metadata);if(changedFields.length===0&&outcome.changedSteps.length===0){return{changedFields:[]}}return{changedFields:changedFields.length>0?changedFields:["plan_steps"]}}});return{document:{metadata:result.item,body:result.body},resultStep,itemId:result.item.id}}async function planAddStep(id,options,ctx){const title=options.stepTitle?.trim();if(!title){throw new PmCliError("pm plan add-step requires --step-title",EXIT_CODE.USAGE)}const status=asStepStatus(options.stepStatus,"pending");const allowMultipleActive=options.allowMultipleActive===true;const{document,resultStep,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_add_step",message:`plan add-step "${title}"`,mutator(steps){const order=steps.length+1;assertInProgressStepAllowed(steps,void 0,status,allowMultipleActive);const step=buildAddedPlanStep(steps,options,{order,title,status});steps.push(step);return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"add-step",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function assertInProgressStepAllowed(steps,currentStepId,desiredStatus,allowMultipleActive){if(desiredStatus!=="in_progress"||allowMultipleActive){return}const activeStep=steps.find(step=>step.id!==currentStepId&&step.status==="in_progress");if(!activeStep){return}throw new PmCliError(`Plan already has step ${activeStep.id} in_progress. Pass --allow-multiple-active or update that step first.`,EXIT_CODE.CONFLICT)}function buildAddedPlanStep(existingSteps,options,seed){const linkedItems=buildLinkInputs(options,"depends_on");const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);const now=nowIso();return{id:newStepId(existingSteps),order:seed.order,title:seed.title,body:options.stepBody?.trim()||void 0,status:seed.status,owner:options.stepOwner?.trim()||void 0,evidence:options.stepEvidence?.trim()||void 0,blocked_reason:seed.status==="blocked"?options.stepBlockedReason?.trim()||"":void 0,linked_items:linkedItems.length>0?linkedItems:void 0,files:files.length>0?files:void 0,tests:tests.length>0?tests:void 0,docs:docs.length>0?docs:void 0,created_at:now,updated_at:now,completed_at:seed.status==="completed"?now:void 0}}function buildLinkInputs(options,fallbackKind){const dependsOn=toArray(options.dependsOn).map(id=>({id,kind:fallbackKind}));const related=toArray(options.related).map(id=>({id,kind:"related"}));const blocks=toArray(options.blocks).map(id=>({id,kind:"blocks"}));const blockedBy=toArray(options.blockedBy).map(id=>({id,kind:"blocked_by"}));const explicit=toArray(options.link);const explicitKind=asLinkKind(options.linkKind,fallbackKind);const note=options.linkNote?.trim();const explicitLinks=explicit.map(id=>{const link={id,kind:explicitKind};if(note)link.note=note;return link});return[...dependsOn,...related,...blocks,...blockedBy,...explicitLinks]}async function planUpdateStep(id,options,ctx,args){const{document,resultStep,itemId}=await mutatePlanSteps({id,options,ctx,op:args.op,message:options.message??`${args.op} ${args.stepRef}`,mutator(steps,doc){const step=resolveStepRef(steps,args.stepRef);const now=nowIso();const desiredStatus=args.finalStatus??asStepStatus(options.stepStatus,step.status);const allowMultipleActive=options.allowMultipleActive===true||args.allowMultipleActive===true;assertInProgressStepAllowed(steps,step.status==="in_progress"?step.id:void 0,desiredStatus,allowMultipleActive);applyStepUpdates(step,options,desiredStatus,now);doc.metadata.updated_at=now;return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:args.op==="plan_complete_step"?"complete-step":args.op==="plan_block_step"?"block-step":"update-step",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function applyStepUpdates(step,options,desiredStatus,now){assertBlockedStepReason(step,options,desiredStatus);applyStepFieldUpdates(step,options);step.status=desiredStatus;step.updated_at=now;applyStepCompletionTimestamp(step,desiredStatus,now)}function assertBlockedStepReason(step,options,desiredStatus){if(desiredStatus!=="blocked"||options.stepBlockedReason?.trim()||step.blocked_reason){return}throw new PmCliError("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",EXIT_CODE.USAGE)}function applyStepFieldUpdates(step,options){const title=options.stepTitle?.trim();if(title){step.title=title}if(options.stepBody!==void 0){step.body=options.stepBody.trim()||void 0}if(options.stepOwner!==void 0){step.owner=options.stepOwner.trim()||void 0}if(options.stepEvidence!==void 0){step.evidence=options.stepEvidence.trim()||void 0}if(options.stepBlockedReason!==void 0){step.blocked_reason=options.stepBlockedReason.trim()||void 0}if(options.stepReplacement!==void 0){step.superseded_by=options.stepReplacement.trim()||void 0}const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);if(files.length>0){step.files=mergePlanStepEvidence(step.files,files)}if(tests.length>0){step.tests=mergePlanStepEvidence(step.tests,tests)}if(docs.length>0){step.docs=mergePlanStepEvidence(step.docs,docs)}}function mergePlanStepEvidence(existing,added){const merged=[...existing??[]];const seen=new Set(merged.map(entry=>JSON.stringify(entry)));for(const entry of added){const key=JSON.stringify(entry);if(seen.has(key))continue;seen.add(key);merged.push(entry)}return merged}function applyStepCompletionTimestamp(step,desiredStatus,now){if(desiredStatus==="completed"&&!step.completed_at){step.completed_at=now;return}if(desiredStatus!=="completed"){step.completed_at=void 0}}async function planReorderStep(id,options,ctx,stepRef,newOrder){const{document,itemId,resultStep}=await mutatePlanSteps({id,options,ctx,op:"plan_reorder_step",message:options.message??`plan reorder-step ${stepRef} -> ${newOrder}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const filtered=steps.filter(entry=>entry.id!==step.id);const clamped=Math.max(1,Math.min(newOrder,filtered.length+1));filtered.splice(clamped-1,0,step);filtered.forEach((entry,index)=>{entry.order=index+1;entry.updated_at=nowIso()});steps.length=0;steps.push(...filtered);return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"reorder-step",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planRemoveStep(id,options,ctx,stepRef){const{document,itemId,resultStep}=await mutatePlanSteps({id,options,ctx,op:"plan_remove_step",message:options.message??`plan remove-step ${stepRef}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const remaining=steps.filter(entry=>entry.id!==step.id);remaining.forEach((entry,index)=>{entry.order=index+1});steps.length=0;steps.push(...remaining);return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"remove-step",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planLink(id,options,ctx,stepRef){const newLinks=buildLinkInputs(options,asLinkKind(options.linkKind,"related"));if(newLinks.length===0){throw new PmCliError("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",EXIT_CODE.USAGE)}const promoteToItemDep=options.promoteToItemDep===true;const{document,itemId,resultStep}=await mutatePlanSteps({id,options,ctx,op:"plan_link_step",message:options.message??`plan link ${stepRef}`,mutator(steps,doc){const step=resolveStepRef(steps,stepRef);const existing=step.linked_items??[];const dedupKey=link=>`${link.kind}:${link.id}`;const seen=new Set(existing.map(dedupKey));for(const link of newLinks){const key=dedupKey(link);if(seen.has(key))continue;existing.push(link);seen.add(key)}step.linked_items=existing;step.updated_at=nowIso();if(promoteToItemDep){const deps=doc.metadata.dependencies??[];const depKey=dep=>`${dep.kind}:${dep.id}`;const seenDeps=new Set(deps.map(depKey));for(const link of newLinks){const promotedKind=link.kind==="depends_on"?"blocked_by":link.kind;const candidate={id:link.id,kind:promotedKind,created_at:nowIso(),author:resolveAuthor(options.author,ctx.settings.author_default)};if(seenDeps.has(depKey(candidate)))continue;deps.push(candidate);seenDeps.add(depKey(candidate))}doc.metadata.dependencies=deps}return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"link",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planUnlink(id,options,ctx,stepRef){const removeIds=toArray(options.link);if(removeIds.length===0){throw new PmCliError("pm plan unlink requires --link <id> to remove",EXIT_CODE.USAGE)}const{document,itemId,resultStep}=await mutatePlanSteps({id,options,ctx,op:"plan_unlink_step",message:options.message??`plan unlink ${stepRef}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const filtered=(step.linked_items??[]).filter(link=>!removeIds.includes(link.id));step.linked_items=filtered.length>0?filtered:void 0;step.updated_at=nowIso();return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"unlink",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planAppendLog(id,options,ctx,kind){const logText=resolvePlanLogText(kind,options);if(!logText){const canonical=`--${kind}-text`;const shorthand=`--${kind}`;throw new PmCliError(`pm plan ${kind} requires ${canonical}`,EXIT_CODE.USAGE,{code:"missing_required_option",examples:[`pm plan ${kind} <plan-id> ${canonical} "..."`,`pm plan ${kind} <plan-id> ${shorthand} "..."`],recovery:{suggested_retry:`pm plan ${kind} <plan-id> ${canonical} <value>`}})}const author=resolveAuthor(options.author,ctx.settings.author_default);const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:`plan_append_${kind}`,message:options.message??`plan ${kind} append`,mutator(_steps,doc){const now=nowIso();if(kind==="decision"){const list2=doc.metadata.plan_decisions??[];list2.push({ts:now,author,decision:logText,rationale:options.decisionRationale?.trim()||void 0,evidence:options.decisionEvidence?.trim()||void 0});doc.metadata.plan_decisions=list2;return{changedSteps:[]}}if(kind==="discovery"){const list2=doc.metadata.plan_discoveries??[];list2.push({ts:now,author,text:logText});doc.metadata.plan_discoveries=list2;return{changedSteps:[]}}const list=doc.metadata.plan_validation??[];list.push({text:logText,command:options.validationCommand?.trim()||void 0,expected:options.validationExpected?.trim()||void 0});doc.metadata.plan_validation=list;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"deep");return{action:kind,plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planResume(id,options,ctx){const text=options.resumeContext?.trim();if(!text){throw new PmCliError("pm plan resume requires --resume-context <text>",EXIT_CODE.USAGE)}const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_resume",message:options.message??"plan resume context update",mutator(_steps,doc){doc.metadata.plan_resume_context=text;const scope=options.scope?.trim();if(scope)doc.metadata.plan_scope=scope;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"brief");return{action:"resume",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planApprove(id,options,ctx){const mode=asPlanMode(options.mode??"approved","approved");const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_approve",message:options.message??`plan approve mode=${mode}`,mutator(_steps,doc){doc.metadata.plan_mode=mode;const scope=options.scope?.trim();if(scope)doc.metadata.plan_scope=scope;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"brief");return{action:"approve",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function buildMaterializeSkippedWarnings(materializeSkipped){return materializeSkipped.map(entry=>`plan_materialize_skipped:${entry.from_step}:${entry.reason}${entry.existing_id?`:${entry.existing_id}`:""}`)}function buildMaterializeNoopResult(planRead,materializeSkipped){const plan=projectPlan(planRead.document.metadata,"standard");return{action:"materialize",plan,materialized:[],materialize_skipped:materializeSkipped,next_actions:nextActionsFor(planRead.itemId,plan),warnings:buildMaterializeSkippedWarnings(materializeSkipped),generated_at:nowIso()}}function buildMaterializeDependencies(parent,planItemId,step){const deps=[`id=${parent},kind=parent`,`id=${planItemId},kind=discovered_from`];for(const link of step.linked_items??[]){const realKind=link.kind==="blocked_by"||link.kind==="blocks"||link.kind==="related"||link.kind==="discovered_from"?link.kind:"related";deps.push(`id=${link.id},kind=${realKind}`)}return deps}async function createMaterializedStepItems(params){const materialized=[];const materializeFields={};const reservedMaterializeKeys=new Set(["title","description","type","parent","tags","author","message","dep"]);for(const specification of toSpecArray(params.options.field)){const separator=specification.indexOf("=");if(separator<=0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const name=specification.slice(0,separator).trim();const value=specification.slice(separator+1).trim();if(name.length===0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const segments=name.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(segment=>segment.toLowerCase());if(segments.length===0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const[first,...rest]=segments;const fieldKey=`${first}${rest.map(segment=>`${segment.slice(0,1).toUpperCase()}${segment.slice(1)}`).join("")}`;if(reservedMaterializeKeys.has(fieldKey)){throw new PmCliError(`Invalid --field entry "${specification}"; "${fieldKey}" is reserved by materialize and cannot be overridden`,EXIT_CODE.USAGE)}materializeFields[fieldKey]=value}for(const step of params.targets){const createOptions={...materializeFields,title:step.title,description:step.body?.trim()||step.title,type:params.resolvedTypeName,parent:params.parent,tags:params.tags,author:params.options.author,message:params.options.message??`materialized from plan ${params.planItemId} step ${step.id}`,dep:buildMaterializeDependencies(params.parent,params.planItemId,step)};preservePlanCreateStdinPolicy(params.options,createOptions,["description",...Object.keys(materializeFields)]);const created=await runCreate(createOptions,{...{},path:params.pmRoot});materialized.push({id:created.item.id,title:created.item.title,type:params.resolvedTypeName,parent:created.item.parent,tags:created.item.tags??[],from_step:step.id})}return materialized}function linkMaterializedStepItems(currentSteps,targets,materialized){for(const target of targets){const matched=materialized.find(entry=>entry.from_step===target.id);if(!matched){continue}const step=currentSteps.find(entry=>entry.id===target.id);if(!step){continue}const links=step.linked_items??[];links.push({id:matched.id,kind:"implements",note:`materialized as ${matched.type}`});step.linked_items=links;step.updated_at=nowIso()}}async function planMaterialize(id,options,ctx){const stepRefs=toArray(options.steps);if(stepRefs.length===0){throw new PmCliError("pm plan materialize requires --steps <ids|orders|all>",EXIT_CODE.USAGE)}const targetType=options.materializeType?.trim()||"Task";const typeRegistry=resolveItemTypeRegistry(ctx.settings,getActiveExtensionRegistrations());const resolvedTypeName=resolveTypeName(targetType,typeRegistry);if(!resolvedTypeName){throw new PmCliError(`Invalid --materialize-type "${targetType}"`,EXIT_CODE.USAGE)}const parent=options.materializeParent?.trim()||id;const tags=options.materializeTags;const planRead=await readPlanItem(ctx,id);const steps=(planRead.document.metadata.plan_steps??[]).slice();const{targets,skipped:materializeSkipped}=resolveMaterializeTargets(steps,stepRefs);if(targets.length===0){if(materializeSkipped.length>0){return buildMaterializeNoopResult(planRead,materializeSkipped)}throw new PmCliError("No matching plan steps found for --steps",EXIT_CODE.NOT_FOUND)}const materialized=await createMaterializedStepItems({targets,parent,planItemId:planRead.itemId,resolvedTypeName,tags,options,pmRoot:ctx.pmRoot});const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_materialize",message:options.message??`plan materialize ${stepRefs.join(",")}`,mutator(currentSteps){linkMaterializedStepItems(currentSteps,targets,materialized);return{changedSteps:targets.map(entry=>entry.id)}}});const plan=projectPlan(document.metadata,"standard");return{action:"materialize",plan,materialized,...materializeSkipped.length>0?{materialize_skipped:materializeSkipped}:{},next_actions:nextActionsFor(itemId,plan),warnings:buildMaterializeSkippedWarnings(materializeSkipped),generated_at:nowIso()}}function normalizePlanStepAliasInput(input){if(input.subcommand==="create"){return input}const stepValues=toOrderedStepTitles(input.options.step);if(stepValues.length>1){throw new PmCliError(`pm plan ${input.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,EXIT_CODE.USAGE)}if(stepValues.length===1&&!input.options.stepTitle?.trim()){return{...input,options:transferMutationStdinTokenPolicy(input.options,{...input.options,stepTitle:stepValues[0]})}}return input}function requirePlanId(input,label){if(!input.id){throw new PmCliError(`pm plan ${label} requires a plan id`,EXIT_CODE.USAGE)}return input.id}function requirePlanStepRef(input,label){const id=requirePlanId(input,label);if(!input.stepRef){throw new PmCliError(`pm plan ${label} requires <plan-id> <step>`,EXIT_CODE.USAGE)}return{id,stepRef:input.stepRef}}function requireReorderTarget(input){const target=requirePlanStepRef(input,"reorder-step");if(input.reorderTo===void 0){throw new PmCliError("pm plan reorder-step requires <plan-id> <step> <new-order>",EXIT_CODE.USAGE)}return{...target,reorderTo:input.reorderTo}}const PLAN_DISPATCHERS={create:(input,ctx)=>planCreate(input.options,input.global,ctx),show:(input,ctx)=>planShow(requirePlanId(input,"show"),input.options,ctx),"add-step":(input,ctx)=>planAddStep(requirePlanId(input,"add-step"),input.options,ctx),"update-step":(input,ctx)=>{const target=requirePlanStepRef(input,"update-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,op:"plan_update_step"})},"complete-step":(input,ctx)=>{const target=requirePlanStepRef(input,"complete-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(input,ctx)=>{const target=requirePlanStepRef(input,"block-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(input,ctx)=>{const target=requireReorderTarget(input);return planReorderStep(target.id,input.options,ctx,target.stepRef,target.reorderTo)},"remove-step":(input,ctx)=>{const target=requirePlanStepRef(input,"remove-step");return planRemoveStep(target.id,input.options,ctx,target.stepRef)},link:(input,ctx)=>{const target=requirePlanStepRef(input,"link");return planLink(target.id,input.options,ctx,target.stepRef)},unlink:(input,ctx)=>{const target=requirePlanStepRef(input,"unlink");return planUnlink(target.id,input.options,ctx,target.stepRef)},decision:(input,ctx)=>planAppendLog(requirePlanId(input,"decision"),input.options,ctx,"decision"),discovery:(input,ctx)=>planAppendLog(requirePlanId(input,"discovery"),input.options,ctx,"discovery"),validation:(input,ctx)=>planAppendLog(requirePlanId(input,"validation"),input.options,ctx,"validation"),resume:(input,ctx)=>planResume(requirePlanId(input,"resume"),input.options,ctx),approve:(input,ctx)=>planApprove(requirePlanId(input,"approve"),input.options,ctx),materialize:(input,ctx)=>planMaterialize(requirePlanId(input,"materialize"),input.options,ctx)};function resolvePlanDispatcher(subcommand){const dispatcher=PLAN_DISPATCHERS[subcommand];if(!dispatcher){throw createUnknownSubcommandError({command_path:"plan",token:subcommand,allowed:PLAN_SUBCOMMANDS})}return dispatcher}async function runPlan(input){const ctx=await loadContext(input.global);const normalizedInput=normalizePlanStepAliasInput(input);const result=await resolvePlanDispatcher(normalizedInput.subcommand)(normalizedInput,ctx);return result.action==="show"?result:{...result,mutation_receipt:buildPlanMutationReceipt(result,ctx.pmRoot)}}const _testOnlyPlanCommand={changedPlanMetadataFields};export{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,_testOnlyPlanCommand,resolvePlanTemplateSteps,runPlan};
|
|
2
2
|
//# sourceMappingURL=plan.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="02743545-3a44-565d-932c-7fe736d17eb8")}catch(e2){}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import fg from"fast-glob";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,createStdinTokenResolver,looksLikeGenericKeyValueEntry,parseCsvKv}from"../core/item/parse.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isRemoteLinkedArtifactReference}from"../core/validate/linked-artifact-reference.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{stableValueEquals}from"../core/shared/serialization.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{SCOPE_VALUES}from"../types/index.js";import{resolveAuthor}from"../core/shared/author.js";const LINKED_ARTIFACT_ADD_KEYS=["path","scope","note"];const LINKED_ARTIFACT_ADD_GLOB_KEYS=["pattern","glob","path","scope","note"];const LINKED_ARTIFACT_REMOVE_KEYS=["path"];const LINKED_ARTIFACT_MIGRATE_KEYS=["from","to"];const LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS=new Set(["note","scope"]);function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value)){throw new PmCliError(`Invalid scope "${raw}". Valid scopes: ${SCOPE_VALUES.join(", ")} (default: project).`,EXIT_CODE.USAGE)}return value}function looksLikeStructuredPathEntry(raw){if(raw.startsWith("```")||raw.includes("\n")){return true}if(/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw)){return true}const firstCommaIndex=raw.indexOf(",");const leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length);const equalsIndex=leadingSegment.indexOf("=");if(equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))){return false}return leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value){if(character==="(")depth+=1;if(character===")")depth-=1;if(depth<0)return false}return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed)){return{path:trimmed,scope:"project",note:void 0}}const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2)){return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return void 0;const label=trimmed.slice(0,delimiterIndex).trim();const destination=trimmed.slice(delimiterIndex+1).trim();if(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)){return void 0}return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){if(!raw)return[];return raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS);if(!kv.path){throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE)}return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]})}function parseAddGlobEntries(raw){if(!raw)return[];return raw.map(entry=>{const trimmed=entry.trim();if(!trimmed){throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE)}if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern){throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE)}return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}})}function parseRemoveEntries(raw){if(!raw)return[];return raw.map(entry=>{const trimmed=entry.trim();if(!trimmed){throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE)}if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove");const unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0){throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE)}assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS);if(!kv.path){throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE)}return kv.path}return trimmed})}function parseMigrateEntries(raw){if(!raw)return[];return raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim();const to=kv.to?.trim();if(!from||!to){throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE)}return{from,to}})}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations){if(next.startsWith(migration.from)){next=`${migration.to}${next.slice(migration.from.length)}`}}return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0){return}const addedPaths=new Set(adds.map(entry=>applyPathMigrations(entry.path,migrations)));const conflicts=[...new Set(removes.map(entry=>applyPathMigrations(entry,migrations)).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length===0){return}throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed)){return trimmed}if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed)){return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep))}const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);if(invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)){return normalizeLinkedPath(path.normalize(trimmed))}return normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){const absolutePattern=path.isAbsolute(entry.pattern);const matches=await fg(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:true,dot:true,unique:true,followSymbolicLinks:true});const sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches){expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0){return adds}if(!hasAddFlags){throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE)}const trimmed=note.trim();if(trimmed.length===0){return adds}return adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);if(byPath!==0)return byPath;return left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right));const existingFiles=[];const missingPaths=[];const nonFilePaths=[];const remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{const stats=await fs.stat(resolvedPath);if(stats.isFile()){existingFiles.push(relativePath)}else{nonFilePaths.push(relativePath)}}catch(error){if(typeof error==="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);if(migratedPath!==current[index].path){current[index]={...current[index],path:migratedPath};count+=1}}const migratedAdds=adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);if(migratedPath!==entry.path)count+=1;return{...entry,path:migratedPath}});return{adds:migratedAdds,removes:removes.map(entry=>applyPathMigrations(entry,migrations)),count}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable){for(const add of adds){if(!current.some(entry=>entry.path===add.path&&entry.scope===add.scope)){current.push(add)}}if(removes.length>0){for(let index=current.length-1;index>=0;index-=1){if(removes.includes(current[index].path))current.splice(index,1)}}const deduped=dedupeLinkedArtifacts(current);return appendStable?deduped:sortLinkedArtifacts(deduped)}async function buildLinkedArtifactResult(params){const paths=params.artifacts.map(entry=>entry.path);return{id:params.id,artifacts:params.artifacts,changed:params.changed,count:params.artifacts.length,migrations_applied:params.migrationsApplied&¶ms.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed?await validateLinkedPaths(paths,params.workspaceRoot):void 0}}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config;const stdinResolver=createStdinTokenResolver();const pmRoot=resolvePmRoot(process.cwd(),global2.path);const workspaceRoot=resolveWorkspaceRoot(pmRoot);const invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const resolvedAdds=await stdinResolver.resolveList(options.add,"--add");const resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob");const resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove");const resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate");const parsedAdds=parseAddEntries(resolvedAdds,config.bareNoun).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)}));const addGlobs=parseAddGlobEntries(resolvedAddGlobs);const expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot);const adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,parsedAdds.length>0||addGlobs.length>0);const removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot));const migrations=parseMigrateEntries(resolvedMigrations);assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations);const shouldMutate=adds.length>0||removes.length>0||migrations.length>0;if(!shouldMutate){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located){throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND)}const loaded=await readLocatedItem(located,{schema:settings.schema});const artifacts2=loaded.document.metadata[metadataKey]??[];return buildLinkedArtifactResult({id:located.id,artifacts:artifacts2,changed:false,options,workspaceRoot})}const author=resolveAuthor(options.author,settings.author_default);const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:true,mutate(document){const metadata=document.metadata;const current=metadata[metadataKey]??[];const next=[...current];const migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations);const normalized=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===true);if(normalized.length>0){metadata[metadataKey]=normalized}else{delete metadata[metadataKey]}const changed=!stableValueEquals(current,normalized);return{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}});const artifacts=result.item[metadataKey]??[];const migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:"));const migrationCount=migrationWarning?Number(migrationWarning.slice("path_migrations_applied:".length)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result)){out[field==="artifacts"?key:field]=value}return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bb855f72-341c-5dc3-ade5-dd3102275cd8")}catch(e2){}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import fg from"fast-glob";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,createStdinTokenResolver,looksLikeGenericKeyValueEntry,parseCsvKv}from"../core/item/parse.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isRemoteLinkedArtifactReference}from"../core/validate/linked-artifact-reference.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{stableValueEquals}from"../core/shared/serialization.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{SCOPE_VALUES}from"../types/index.js";import{resolveAuthor}from"../core/shared/author.js";const LINKED_ARTIFACT_ADD_KEYS=["path","scope","note"];const LINKED_ARTIFACT_ADD_GLOB_KEYS=["pattern","glob","path","scope","note"];const LINKED_ARTIFACT_REMOVE_KEYS=["path"];const LINKED_ARTIFACT_MIGRATE_KEYS=["from","to"];const LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS=new Set(["note","scope"]);function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value)){throw new PmCliError(`Invalid scope "${raw}". Valid scopes: ${SCOPE_VALUES.join(", ")} (default: project).`,EXIT_CODE.USAGE)}return value}function looksLikeStructuredPathEntry(raw){if(raw.startsWith("```")||raw.includes("\n")){return true}if(/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw)){return true}const firstCommaIndex=raw.indexOf(",");const leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length);const equalsIndex=leadingSegment.indexOf("=");if(equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))){return false}return leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value){if(character==="(")depth+=1;if(character===")")depth-=1;if(depth<0)return false}return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed)){return{path:trimmed,scope:"project",note:void 0}}const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2)){return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return void 0;const label=trimmed.slice(0,delimiterIndex).trim();const destination=trimmed.slice(delimiterIndex+1).trim();if(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)){return void 0}return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){if(!raw)return[];return raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS);if(!kv.path){throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE)}return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]})}function parseAddGlobEntries(raw){if(!raw)return[];return raw.map(entry=>{const trimmed=entry.trim();if(!trimmed){throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE)}if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern){throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE)}return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}})}function parseRemoveEntries(raw){if(!raw)return[];return raw.map(entry=>{const trimmed=entry.trim();if(!trimmed){throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE)}if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove");const unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0){throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE)}assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS);if(!kv.path){throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE)}return kv.path}return trimmed})}function parseMigrateEntries(raw){if(!raw)return[];return raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim();const to=kv.to?.trim();if(!from||!to){throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE)}return{from,to}})}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations){if(next.startsWith(migration.from)){next=`${migration.to}${next.slice(migration.from.length)}`}}return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0){return}const addedPaths=new Set(adds.map(entry=>applyPathMigrations(entry.path,migrations)));const conflicts=[...new Set(removes.map(entry=>applyPathMigrations(entry,migrations)).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length===0){return}throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed)){return trimmed}if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed)){return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep))}const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);if(invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)){return normalizeLinkedPath(path.normalize(trimmed))}return normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){const absolutePattern=path.isAbsolute(entry.pattern);const matches=await fg(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:true,dot:true,unique:true,followSymbolicLinks:true});const sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches){expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0){return adds}if(!hasAddFlags){throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE)}const trimmed=note.trim();if(trimmed.length===0){return adds}return adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);if(byPath!==0)return byPath;return left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right));const existingFiles=[];const missingPaths=[];const nonFilePaths=[];const remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{const stats=await fs.stat(resolvedPath);if(stats.isFile()){existingFiles.push(relativePath)}else{nonFilePaths.push(relativePath)}}catch(error){if(typeof error==="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);if(migratedPath!==current[index].path){current[index]={...current[index],path:migratedPath};count+=1}}const migratedAdds=adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);if(migratedPath!==entry.path)count+=1;return{...entry,path:migratedPath}});return{adds:migratedAdds,removes:removes.map(entry=>applyPathMigrations(entry,migrations)),count}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable){const merged=dedupeLinkedArtifacts(current);for(const add of adds){const index=merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope);if(index<0){merged.push(add)}else if(add.note!==void 0){merged[index]={...merged[index],note:add.note}}}if(removes.length>0){for(let index=merged.length-1;index>=0;index-=1){if(removes.includes(merged[index].path))merged.splice(index,1)}}return appendStable?merged:sortLinkedArtifacts(merged)}async function buildLinkedArtifactResult(params){const paths=params.artifacts.map(entry=>entry.path);return{id:params.id,artifacts:params.artifacts,changed:params.changed,count:params.artifacts.length,migrations_applied:params.migrationsApplied&¶ms.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed?await validateLinkedPaths(paths,params.workspaceRoot):void 0}}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config;const stdinResolver=createStdinTokenResolver();const pmRoot=resolvePmRoot(process.cwd(),global2.path);const workspaceRoot=resolveWorkspaceRoot(pmRoot);const invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const resolvedAdds=await stdinResolver.resolveList(options.add,"--add");const resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob");const resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove");const resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate");const parsedAdds=parseAddEntries(resolvedAdds,config.bareNoun).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)}));const addGlobs=parseAddGlobEntries(resolvedAddGlobs);const expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot);const adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,parsedAdds.length>0||addGlobs.length>0);const removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot));const migrations=parseMigrateEntries(resolvedMigrations);assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations);const shouldMutate=adds.length>0||removes.length>0||migrations.length>0;if(!shouldMutate){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located){throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND)}const loaded=await readLocatedItem(located,{schema:settings.schema});const artifacts2=loaded.document.metadata[metadataKey]??[];return buildLinkedArtifactResult({id:located.id,artifacts:artifacts2,changed:false,options,workspaceRoot})}const author=resolveAuthor(options.author,settings.author_default);const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:true,mutate(document){const metadata=document.metadata;const current=metadata[metadataKey]??[];const next=[...current];const migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations);const normalized=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===true);if(normalized.length>0){metadata[metadataKey]=normalized}else{delete metadata[metadataKey]}const changed=!stableValueEquals(current,normalized);return{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}});const artifacts=result.item[metadataKey]??[];const migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:"));const migrationCount=migrationWarning?Number(migrationWarning.slice("path_migrations_applied:".length)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result)){out[field==="artifacts"?key:field]=value}return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths};
|
|
2
2
|
//# sourceMappingURL=linked-artifacts.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8f999825-ace7-55cd-b83c-8c6c4b94fd9f")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";import{access,readFile,realpath,writeFile}from"node:fs/promises";import{constants}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{pathExists}from"../../core/fs/fs-utils.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{acquireLock}from"../../core/lock/lock.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{resolveAuthor}from"../../core/shared/author.js";import{nowIso}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings,resolveGovernanceKnobs}from"../../core/store/settings.js";import{isPathOutsideRoot}from"../workspace.js";import{resolveSourceContextWritePolicy}from"../environment/source-context.js";import{gitWorkspaceEnvironment,resolveMergeDriverConfigScope}from"./worktree-config.js";import{discoverProjectRuntimeVersionPins}from"../environment/project-runtime-compatibility.js";const execFileAsync=promisify(execFile);const PM_GITATTRIBUTES_START="# pm-cli:merge-drivers:start";const PM_GITATTRIBUTES_END="# pm-cli:merge-drivers:end";const PM_GITATTRIBUTES_V2_START="# pm-cli:merge-drivers:v2:start";const PM_GITATTRIBUTES_V2_END="# pm-cli:merge-drivers:v2:end";const MERGE_FENCE_LOCK_ID="merge-fence";function quoteMergeDriverArgument(value){return`'${value.replaceAll("'",`'"'"'`)}'`}async function resolveMergeDriverCliCommand(){const packageRoot=resolvePmPackageRootFromModule(import.meta.url,["../../.."]);let executable=process.execPath;const runtimeIdentity=await realpath(process.execPath);for(const directory of(process.env.PATH??"").split(path.delimiter)){if(!path.isAbsolute(directory))continue;const candidate=path.join(directory,path.basename(process.execPath));try{await access(candidate,constants.X_OK);if(candidate!==runtimeIdentity&&await realpath(candidate)===runtimeIdentity){executable=candidate;break}}catch{}}return`${quoteMergeDriverArgument(executable)} ${quoteMergeDriverArgument(path.join(packageRoot,"dist","cli.js"))}`}const MERGE_DRIVER_DEFINITIONS=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function resolveMergeInstallContext(options){const explicitPath=options.explicitPath?.trim();const sourceWorkspaceRoot=options.environment.PM_SOURCE_WORKSPACE_ROOT?.trim();const sourcePmRoot=options.environment.PM_SOURCE_PM_PATH?.trim();const sourcePolicy=resolveSourceContextWritePolicy(options.environment);const sourceCoordinatesAvailable=Boolean(sourceWorkspaceRoot&&sourcePmRoot);const sourceContextSelected=explicitPath===void 0&&sourceCoordinatesAvailable&&(options.dryRun||sourcePolicy.source_writes_allowed);if(explicitPath!==void 0){const pmRoot=resolvePmRoot(options.cwd,explicitPath);return{pm_root:pmRoot,workspace_start:pmRoot,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:false,source_policy:sourcePolicy}}if(sourceContextSelected){return{pm_root:path.resolve(sourcePmRoot),workspace_start:path.resolve(sourceWorkspaceRoot),source_coordinates_available:true,source_context_selected:true,source_policy:sourcePolicy}}return{pm_root:sourceCoordinatesAvailable?resolvePmRoot(options.cwd,".agents/pm"):resolvePmRoot(options.cwd),workspace_start:options.cwd,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:false,source_policy:sourcePolicy}}async function findGitWorkspaceRoot(cwd){try{const{stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:true,timeout:1e4});return await realpath(stdout.trim())}catch{return null}}async function resolveGitWorkspaceRoot(cwd){const workspaceRoot=await findGitWorkspaceRoot(cwd);if(workspaceRoot===null){throw new PmCliError("pm merge install requires a git repository (merge drivers are git configuration).",EXIT_CODE.USAGE)}return workspaceRoot}function toPosixRelative(fromPath,toPath){return path.relative(fromPath,toPath).replaceAll("\\","/")}function quoteGitAttributePattern(value){return`"${value.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function readSingleQuotedArgument(command,offset){if(command[offset]!=="'"){return null}let value="";for(let index=offset+1;index<command.length;index+=1){if(command.startsWith(`'"'"'`,index)){value+="'";index+=4;continue}if(command[index]==="'"){return{value,nextOffset:index+1}}value+=command[index]}return null}async function isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,version){const exactPins=discoverProjectRuntimeVersionPins(workspaceRoot).filter(pin=>pin.constraint==="exact");if(exactPins.some(pin=>pin.version!==version))return false;const driverWorkspace=await findGitWorkspaceRoot(packageRoot);if(driverWorkspace!==null&&driverWorkspace!==await realpath(workspaceRoot)){const commonDirectories=await Promise.all([driverWorkspace,workspaceRoot].map(async cwd=>{const result=await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,env:gitWorkspaceEnvironment(),timeout:1e4});return realpath(result.stdout.trim())}));if(commonDirectories[0]===commonDirectories[1])return false}return true}async function isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot){const nodeArgument=readSingleQuotedArgument(configured,0);if(nodeArgument===null||configured[nodeArgument.nextOffset]!==" "){return false}const cliArgument=readSingleQuotedArgument(configured,nodeArgument.nextOffset+1);if(cliArgument===null||configured.slice(cliArgument.nextOffset)!==expectedSuffix||!/^node(?:\.exe)?$/iu.test(path.basename(nodeArgument.value))||path.basename(cliArgument.value)!=="cli.js"||path.basename(path.dirname(cliArgument.value))!=="dist"){return false}if(!await pathExists(nodeArgument.value)||!await pathExists(cliArgument.value)){return false}try{const packageRoot=path.dirname(path.dirname(cliArgument.value));const manifest=JSON.parse(await readFile(path.join(packageRoot,"package.json"),"utf8"));const pmBin=typeof manifest.bin==="string"?manifest.bin:manifest.bin?.pm;if(!await isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,manifest.version))return false;return manifest.name==="@unbrained/pm-cli"&&pmBin==="dist/cli.js"}catch{return false}}function buildMergeAttributePatterns(trackerRelativeRoot,typeFolders){const prefix=trackerRelativeRoot.length>0?`${trackerRelativeRoot}/`:"";const patterns=[`${quoteGitAttributePattern(`${prefix}**/*.toon`)} merge=pm-item-toon`,`${quoteGitAttributePattern(`${prefix}**/*.md`)} merge=pm-item-markdown`];for(const folder of typeFolders){patterns.push(`${quoteGitAttributePattern(`${prefix}${folder}/*.toon`)} merge=pm-item-toon`);patterns.push(`${quoteGitAttributePattern(`${prefix}${folder}/*.md`)} merge=pm-item-markdown`)}patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.jsonl`)} merge=pm-relationship`);patterns.push(`${quoteGitAttributePattern(`${prefix}history/*.jsonl`)} merge=pm-history`);patterns.push(`${quoteGitAttributePattern(`${prefix}settings.json`)} merge=pm-json`);patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.json`)} merge=pm-json`);patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/**`)} -merge`);patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/.managed-extensions.json`)} merge=pm-json`);return patterns}function removeManagedBlock(content,startMarker,endMarker){const start=content.indexOf(startMarker);const end=content.indexOf(endMarker);return start>=0&&end>start?`${content.slice(0,start)}${content.slice(end+endMarker.length)}`:content.replace(startMarker,"").replace(endMarker,"")}async function reconcileGitattributesBlock(workspaceRoot,patterns,dryRun){const gitattributesPath=path.join(workspaceRoot,".gitattributes");let current="";try{current=await readFile(gitattributesPath,"utf8")}catch(error){if(!(error instanceof Error&&"code"in error&&isFileMissingError(error))){throw error}}const block=[PM_GITATTRIBUTES_V2_START,...patterns,PM_GITATTRIBUTES_V2_END].join("\n");const withoutManagedBlock=removeManagedBlock(removeManagedBlock(current,PM_GITATTRIBUTES_V2_START,PM_GITATTRIBUTES_V2_END),PM_GITATTRIBUTES_START,PM_GITATTRIBUTES_END);const prefix=withoutManagedBlock.trimEnd();const next=`${prefix.length>0?`${prefix}
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0e36ac30-62c1-57ee-b2c6-16f7fce5cd4d")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError,readFileIfExists,writeFileAtomic}from"../../core/fs/fs-utils.js";import{access,readFile,realpath}from"node:fs/promises";import{constants}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{pathExists}from"../../core/fs/fs-utils.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{acquireLock}from"../../core/lock/lock.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{resolveAuthor}from"../../core/shared/author.js";import{nowIso}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings,resolveGovernanceKnobs}from"../../core/store/settings.js";import{isPathOutsideRoot}from"../workspace.js";import{resolveSourceContextWritePolicy}from"../environment/source-context.js";import{gitWorkspaceEnvironment,resolveMergeDriverConfigScope}from"./worktree-config.js";import{discoverProjectRuntimeVersionPins}from"../environment/project-runtime-compatibility.js";const execFileAsync=promisify(execFile);const PM_GITATTRIBUTES_START="# pm-cli:merge-drivers:start";const PM_GITATTRIBUTES_END="# pm-cli:merge-drivers:end";const PM_GITATTRIBUTES_V2_START="# pm-cli:merge-drivers:v2:start";const PM_GITATTRIBUTES_V2_END="# pm-cli:merge-drivers:v2:end";const MERGE_FENCE_LOCK_ID="merge-fence";const MERGE_ATTRIBUTES_LOCK_ID="merge-attributes";function quoteMergeDriverArgument(value){return`'${value.replaceAll("'",`'"'"'`)}'`}async function resolveMergeDriverCliCommand(){const packageRoot=resolvePmPackageRootFromModule(import.meta.url,["../../.."]);let executable=process.execPath;const runtimeIdentity=await realpath(process.execPath);for(const directory of(process.env.PATH??"").split(path.delimiter)){if(!path.isAbsolute(directory))continue;const candidate=path.join(directory,path.basename(process.execPath));try{await access(candidate,constants.X_OK);if(candidate!==runtimeIdentity&&await realpath(candidate)===runtimeIdentity){executable=candidate;break}}catch{}}return`${quoteMergeDriverArgument(executable)} ${quoteMergeDriverArgument(path.join(packageRoot,"dist","cli.js"))}`}const MERGE_DRIVER_DEFINITIONS=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function resolveMergeInstallContext(options){const explicitPath=options.explicitPath?.trim();const sourceWorkspaceRoot=options.environment.PM_SOURCE_WORKSPACE_ROOT?.trim();const sourcePmRoot=options.environment.PM_SOURCE_PM_PATH?.trim();const sourcePolicy=resolveSourceContextWritePolicy(options.environment);const sourceCoordinatesAvailable=Boolean(sourceWorkspaceRoot&&sourcePmRoot);const sourceContextSelected=explicitPath===void 0&&sourceCoordinatesAvailable&&(options.dryRun||sourcePolicy.source_writes_allowed);if(explicitPath!==void 0){const pmRoot=resolvePmRoot(options.cwd,explicitPath);return{pm_root:pmRoot,workspace_start:pmRoot,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:false,source_policy:sourcePolicy}}if(sourceContextSelected){return{pm_root:path.resolve(sourcePmRoot),workspace_start:path.resolve(sourceWorkspaceRoot),source_coordinates_available:true,source_context_selected:true,source_policy:sourcePolicy}}return{pm_root:sourceCoordinatesAvailable?resolvePmRoot(options.cwd,".agents/pm"):resolvePmRoot(options.cwd),workspace_start:options.cwd,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:false,source_policy:sourcePolicy}}async function findGitWorkspaceRoot(cwd){try{const{stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:true,timeout:1e4});return await realpath(stdout.trim())}catch{return null}}async function resolveGitWorkspaceRoot(cwd){const workspaceRoot=await findGitWorkspaceRoot(cwd);if(workspaceRoot===null){throw new PmCliError("pm merge install requires a git repository (merge drivers are git configuration).",EXIT_CODE.USAGE)}return workspaceRoot}function toPosixRelative(fromPath,toPath){return path.relative(fromPath,toPath).replaceAll("\\","/")}function quoteGitAttributePattern(value){return`"${value.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function readSingleQuotedArgument(command,offset){if(command[offset]!=="'"){return null}let value="";for(let index=offset+1;index<command.length;index+=1){if(command.startsWith(`'"'"'`,index)){value+="'";index+=4;continue}if(command[index]==="'"){return{value,nextOffset:index+1}}value+=command[index]}return null}async function isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,version){const exactPins=discoverProjectRuntimeVersionPins(workspaceRoot).filter(pin=>pin.constraint==="exact");if(exactPins.some(pin=>pin.version!==version))return false;const driverWorkspace=await findGitWorkspaceRoot(packageRoot);if(driverWorkspace!==null&&driverWorkspace!==await realpath(workspaceRoot)){const commonDirectories=await Promise.all([driverWorkspace,workspaceRoot].map(async cwd=>{const result=await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,env:gitWorkspaceEnvironment(),timeout:1e4});return realpath(result.stdout.trim())}));if(commonDirectories[0]===commonDirectories[1])return false}return true}async function isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot){const nodeArgument=readSingleQuotedArgument(configured,0);if(nodeArgument===null||configured[nodeArgument.nextOffset]!==" "){return false}const cliArgument=readSingleQuotedArgument(configured,nodeArgument.nextOffset+1);if(cliArgument===null||configured.slice(cliArgument.nextOffset)!==expectedSuffix||!/^node(?:\.exe)?$/iu.test(path.basename(nodeArgument.value))||path.basename(cliArgument.value)!=="cli.js"||path.basename(path.dirname(cliArgument.value))!=="dist"){return false}if(!await pathExists(nodeArgument.value)||!await pathExists(cliArgument.value)){return false}try{const packageRoot=path.dirname(path.dirname(cliArgument.value));const manifest=JSON.parse(await readFile(path.join(packageRoot,"package.json"),"utf8"));const pmBin=typeof manifest.bin==="string"?manifest.bin:manifest.bin?.pm;if(!await isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,manifest.version))return false;return manifest.name==="@unbrained/pm-cli"&&pmBin==="dist/cli.js"}catch{return false}}function buildMergeAttributePatterns(trackerRelativeRoot,typeFolders){const prefix=trackerRelativeRoot.length>0?`${trackerRelativeRoot}/`:"";const patterns=[`${quoteGitAttributePattern(`${prefix}**/*.toon`)} merge=pm-item-toon`,`${quoteGitAttributePattern(`${prefix}**/*.md`)} merge=pm-item-markdown`];for(const folder of typeFolders){patterns.push(`${quoteGitAttributePattern(`${prefix}${folder}/*.toon`)} merge=pm-item-toon`);patterns.push(`${quoteGitAttributePattern(`${prefix}${folder}/*.md`)} merge=pm-item-markdown`)}patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.jsonl`)} merge=pm-relationship`);patterns.push(`${quoteGitAttributePattern(`${prefix}history/*.jsonl`)} merge=pm-history`);patterns.push(`${quoteGitAttributePattern(`${prefix}settings.json`)} merge=pm-json`);patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.json`)} merge=pm-json`);patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/**`)} -merge`);patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/.managed-extensions.json`)} merge=pm-json`);return patterns}function managedMergeBlocks(content){const blocks=[];let cursor=0;while(cursor<content.length){const legacyStart=content.indexOf(PM_GITATTRIBUTES_START,cursor);const versionedStart=content.indexOf(PM_GITATTRIBUTES_V2_START,cursor);const start=legacyStart===-1?versionedStart:versionedStart===-1?legacyStart:Math.min(legacyStart,versionedStart);if(start===-1)break;const versioned=start===versionedStart;const startMarker=versioned?PM_GITATTRIBUTES_V2_START:PM_GITATTRIBUTES_START;const endMarker=versioned?PM_GITATTRIBUTES_V2_END:PM_GITATTRIBUTES_END;const closing=content.indexOf(endMarker,start+startMarker.length);const end=closing===-1?content.length:closing+endMarker.length;blocks.push({start,end,closed:closing!==-1,lines:content.slice(start+startMarker.length,closing===-1?end:closing).split("\n").map(line=>line.trim()).filter(Boolean)});cursor=end}return blocks}function blockBelongsToTracker(lines,patterns,trackerRelativeRoot){const ownedPatterns=new Set(patterns);const prefix=quoteGitAttributePattern(trackerRelativeRoot.length>0?`${trackerRelativeRoot}/`:"").slice(0,-1);return lines.some(line=>ownedPatterns.has(line)||line.startsWith(prefix)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(line.slice(prefix.length)))}async function reconcileGitattributesBlock(workspaceRoot,trackerRelativeRoot,patterns,dryRun){const gitattributesPath=path.join(workspaceRoot,".gitattributes");const gitDirectory=dryRun?null:(await execFileAsync("git",["rev-parse","--absolute-git-dir"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:true,timeout:1e4})).stdout.trim();const releaseLock=gitDirectory===null?null:await acquireLock(gitDirectory,MERGE_ATTRIBUTES_LOCK_ID,120,"merge-fence",false,true,5e3);try{const current=await readFileIfExists(gitattributesPath)??"";const block=[PM_GITATTRIBUTES_V2_START,...patterns,PM_GITATTRIBUTES_V2_END].join("\n");const blocks=managedMergeBlocks(current);const owned=blocks.filter(candidate=>blockBelongsToTracker(candidate.lines,patterns,trackerRelativeRoot));if(owned.length===0&&trackerRelativeRoot===".agents/pm"&&blocks.length===1&&blocks[0].lines.every(line=>!line.includes(".agents/pm/"))){owned.push(blocks[0])}let next;if(owned.length>0){const first=owned[0];next=current;for(const duplicate of owned.slice(1).reverse()){next=`${next.slice(0,duplicate.start)}${next.slice(duplicate.end)}`}next=`${next.slice(0,first.start)}${block}${next.slice(first.end)}`}else{const prefix=current.trimEnd();next=`${prefix.length>0?`${prefix}
|
|
2
2
|
|
|
3
3
|
`:""}${block}
|
|
4
|
-
|
|
4
|
+
`}if(next===current){return{path:gitattributesPath,changed:false}}if(!dryRun){await writeFileAtomic(gitattributesPath,next)}return{path:gitattributesPath,changed:true}}finally{await releaseLock?.()}}function resolveProjectMergeTypeFolders(settings){const registry=resolveItemTypeRegistry(settings,null);return[...new Set(Object.values(registry.type_to_folder))].sort((left,right)=>left.localeCompare(right))}async function auditMergeAttributeFence(pmRoot,typeFolders){const resolvedRoot=path.resolve(pmRoot);let fenceDirectory=null;let fenceContent="";let directory=resolvedRoot;for(let depth=0;depth<8;depth+=1){const candidate=path.join(directory,".gitattributes");try{const raw=await readFile(candidate,"utf8");if(raw.includes(PM_GITATTRIBUTES_V2_START)||raw.includes(PM_GITATTRIBUTES_START)){fenceDirectory=directory;fenceContent=raw;break}}catch{}const parent=path.dirname(directory);if(parent===directory){break}directory=parent}if(fenceDirectory===null){return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"}}const fencePath=path.join(fenceDirectory,".gitattributes");const relativeRoot=toPosixRelative(fenceDirectory,resolvedRoot);const blocks=managedMergeBlocks(fenceContent);const expected=buildMergeAttributePatterns(relativeRoot,typeFolders);const owned=blocks.filter(block=>blockBelongsToTracker(block.lines,expected,relativeRoot));const committed=owned.flatMap(block=>block.closed?block.lines:[]);const committedSet=new Set(committed);const expectedSet=new Set(expected);const missing=expected.filter(line=>!committedSet.has(line));const stale=committed.filter(line=>!expectedSet.has(line));return{status:owned.length!==1||!owned[0].closed||missing.length>0||stale.length>0?"drift":"ok",path:fencePath,missing_patterns:missing,stale_patterns:stale,schema_scope:"project"}}async function auditMergeDriverConfiguration(workspaceRoot){const missingKeys=[];const driftedKeys=[];for(const definition of MERGE_DRIVER_DEFINITIONS){const key=`merge.${definition.key}.driver`;const expectedSuffix=` merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`;try{const{stdout}=await execFileAsync("git",["config","--get",key],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:true,timeout:1e4});const configured=stdout.trim();if(!await isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot)){driftedKeys.push(key)}}catch{missingKeys.push(key)}}return{status:missingKeys.length>0?"missing":driftedKeys.length>0?"drift":"ok",missing_keys:missingKeys,drifted_keys:driftedKeys}}async function refreshMergeAttributeFenceIfInstalled(pmRoot){let workspaceRoot;try{workspaceRoot=await resolveGitWorkspaceRoot(path.resolve(pmRoot))}catch{return{status:"no_git"}}const trackerRelativeRoot=toPosixRelative(workspaceRoot,path.resolve(pmRoot));const lockSettings=await readSettings(pmRoot);const owner=resolveAuthor(void 0,lockSettings.author_default);const releaseLock=await acquireLock(pmRoot,MERGE_FENCE_LOCK_ID,lockSettings.locks.ttl_seconds,owner,false,resolveGovernanceKnobs(lockSettings).force_required_for_stale_lock,lockSettings.locks.wait_ms);try{const gitattributesPath=path.join(workspaceRoot,".gitattributes");let current;try{current=await readFile(gitattributesPath,"utf8")}catch(error){if(error instanceof Error&&"code"in error&&isFileMissingError(error)){return{status:"not_installed",path:gitattributesPath}}throw error}if(!current.includes(PM_GITATTRIBUTES_V2_START)&&!current.includes(PM_GITATTRIBUTES_START)){return{status:"not_installed",path:gitattributesPath}}const settings=await readSettings(pmRoot);const typeFolders=resolveProjectMergeTypeFolders(settings);const outcome=await reconcileGitattributesBlock(workspaceRoot,trackerRelativeRoot,buildMergeAttributePatterns(trackerRelativeRoot,typeFolders),false);return{status:outcome.changed?"refreshed":"unchanged",path:outcome.path}}finally{await releaseLock()}}async function runMergeInstall(options,global2){const context=resolveMergeInstallContext({cwd:process.cwd(),explicitPath:global2.path,dryRun:options.dryRun===true,environment:process.env});const pmRoot=context.pm_root;await assertInitializedTracker(pmRoot);const workspaceRoot=await resolveGitWorkspaceRoot(context.workspace_start);return installMergeFence({pmRoot,workspaceRoot,dryRun:options.dryRun===true})}async function installMergeFence(options){const pmRoot=path.resolve(options.pmRoot);const workspaceRoot=path.resolve(options.workspaceRoot);const dryRun=options.dryRun===true;let canonicalPmRoot;let canonicalWorkspaceRoot;try{[canonicalPmRoot,canonicalWorkspaceRoot]=await Promise.all([realpath(pmRoot),realpath(workspaceRoot)])}catch(error){throw new PmCliError(`Cannot resolve tracker root ${pmRoot} or workspace root ${workspaceRoot}: ${String(error)}`,EXIT_CODE.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}const trackerRelativeRoot=toPosixRelative(canonicalWorkspaceRoot,canonicalPmRoot);if(isPathOutsideRoot(trackerRelativeRoot)){throw new PmCliError(`Tracker root ${pmRoot} is outside the git repository ${workspaceRoot}; there is nothing to configure for this repository.`,EXIT_CODE.USAGE)}const settings=await readSettings(canonicalPmRoot);const typeFolders=resolveProjectMergeTypeFolders(settings);const patterns=buildMergeAttributePatterns(trackerRelativeRoot,typeFolders);const gitConfigEntries=[];const cliCommand=await resolveMergeDriverCliCommand();for(const definition of MERGE_DRIVER_DEFINITIONS){gitConfigEntries.push({key:`merge.${definition.key}.name`,value:definition.name});gitConfigEntries.push({key:`merge.${definition.key}.driver`,value:`${cliCommand} merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`})}if(!dryRun){try{const configScope=await resolveMergeDriverConfigScope(canonicalWorkspaceRoot);for(const entry of gitConfigEntries){await execFileAsync("git",["config",configScope,entry.key,entry.value],{cwd:canonicalWorkspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:true,timeout:1e4})}}catch{throw new PmCliError(`Cannot install repository-local merge drivers in ${canonicalWorkspaceRoot}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,EXIT_CODE.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}}const gitattributes=await reconcileGitattributesBlock(canonicalWorkspaceRoot,trackerRelativeRoot,patterns,dryRun);return{ok:true,dry_run:dryRun,workspace_root:canonicalWorkspaceRoot,pm_root:canonicalPmRoot,gitattributes:{path:gitattributes.path,changed:gitattributes.changed,patterns,schema_scope:"project"},git_config:gitConfigEntries,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:nowIso()}}export{PM_GITATTRIBUTES_END,PM_GITATTRIBUTES_START,PM_GITATTRIBUTES_V2_END,PM_GITATTRIBUTES_V2_START,auditMergeAttributeFence,auditMergeDriverConfiguration,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall};
|
|
5
5
|
//# sourceMappingURL=install.js.map
|
|
@@ -73,7 +73,7 @@ export declare const PM_READ_ROW_CONTRACTS: {
|
|
|
73
73
|
readonly fields: "unsupported";
|
|
74
74
|
};
|
|
75
75
|
readonly history: {
|
|
76
|
-
readonly row_keys: readonly ["compact_history", "provenance_history", "history"];
|
|
76
|
+
readonly row_keys: readonly ["compact_history", "provenance_history", "history", "diff"];
|
|
77
77
|
readonly fields: "unsupported";
|
|
78
78
|
};
|
|
79
79
|
readonly deps: {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6c87b004-3647-531a-9599-d37fd91c2807")}catch(e2){}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const MATERIAL_FIELD_GROUPS_BY_RESULT=new WeakMap;function registerOutputMaterialFieldGroups(result,fieldGroups){MATERIAL_FIELD_GROUPS_BY_RESULT.set(result,new Set(fieldGroups))}const PM_READ_ROW_JQ_SELECTOR='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end';const PM_READ_ROW_CONTRACTS={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}};const PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function assertProjectionModeChoice(compactRequested,fullRequested,compactFlag){if(compactRequested&&fullRequested){throw new PmCliError(`${compactFlag} cannot be combined with --full`,EXIT_CODE.USAGE)}}function createOutputOmissionReceipt(declaredGroups,includedGroupNames=new Set){const omittedFieldGroups=declaredGroups.filter(group=>!includedGroupNames.has(group.name)).map(group=>({...group}));return{has_omissions:omittedFieldGroups.length>0,omitted_field_group_count:omittedFieldGroups.length,omitted_field_groups:omittedFieldGroups}}function resolveModePairedOutputOmissionReceipt(command,mode){const contract=PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS.find(candidate=>candidate.command===command);if(contract===void 0){throw new TypeError(`Unknown mode-paired output command: ${command}`)}if(mode===contract.complete_mode){return createOutputOmissionReceipt([])}const groups=contract.omissions_by_mode[mode];if(groups===void 0){throw new TypeError(`Unknown ${command} output mode: ${mode}`)}return createOutputOmissionReceipt(groups)}const CONTEXT_FIELD_GROUPS=[{name:"hierarchy",restore_with:"--depth standard"},{name:"activity",restore_with:"--depth standard"},{name:"progress",restore_with:"--depth standard"},{name:"blockers",restore_with:"--depth standard"},{name:"recently_created",restore_with:"--depth standard"},{name:"unparented",restore_with:"--depth standard"},{name:"files",restore_with:"--depth deep"},{name:"workload",restore_with:"--depth standard"},{name:"staleness",restore_with:"--depth deep"},{name:"tests",restore_with:"--depth deep"},{name:"workspace_memory",restore_with:"--depth deep"}];function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}const READ_ROW_TOON_ENCODINGS=new Set([void 0,"tabular_when_uniform"]);const READ_ROW_KINDS=new Set(["collection","none"]);const READ_ROW_FIELD_MODES=new Set(["supported","unsupported"]);function isUniqueNonEmptyStringArray(value,allowEmpty){return Array.isArray(value)&&(allowEmpty||value.length>0)&&value.every(entry=>typeof entry==="string"&&entry.length>0)&&new Set(value).size===value.length}function isReadRowContract(value){return isRecord(value)&&typeof value.command==="string"&&value.command.trim().length>0&&READ_ROW_KINDS.has(value.row_kind)&&isUniqueNonEmptyStringArray(value.row_keys,true)&&(value.continuation_row_keys===void 0||isUniqueNonEmptyStringArray(value.continuation_row_keys,false))&&READ_ROW_FIELD_MODES.has(value.fields)&&READ_ROW_TOON_ENCODINGS.has(value.toon_encoding)&&(value.row_kind==="collection"?value.row_keys.length>0&&typeof value.jq_selector==="string"&&value.jq_selector.trim().length>0:value.row_keys.length===0&&value.jq_selector===void 0)}const GRAPH_ROW_KEYS={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]};const READ_RESULT_SENTINEL_KEYS={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function resolveReadRowContract(command,result){const rawRootCommand=command.trim().toLowerCase().split(/\s+/u,1)[0];const rootCommand=rawRootCommand?.startsWith("list-")?"list":rawRootCommand;if(rootCommand==="graph"){const subcommand=typeof result.subcommand==="string"?result.subcommand:"";if(subcommand.length===0)return void 0;const rowKeys=GRAPH_ROW_KEYS[subcommand];if(rowKeys===void 0)return void 0;const activeRowKeys=rowKeys.filter(key=>Array.isArray(result[key])||isRecord(result[key]));return{command:"graph",row_kind:activeRowKeys.length>0?"collection":"none",row_keys:activeRowKeys,fields:"unsupported",...activeRowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}}const declaration=PM_READ_ROW_CONTRACTS[rootCommand];const sentinelKeys=READ_RESULT_SENTINEL_KEYS[rootCommand];return declaration===void 0||sentinelKeys===void 0||!sentinelKeys.some(key=>Object.hasOwn(result,key))?void 0:(()=>{const rowKeys=declaration.row_keys.filter(key=>{const value=key.split(".").reduce((current,segment)=>isRecord(current)?current[segment]:void 0,result);return Array.isArray(value)||isRecord(value)});return{command:rootCommand,row_kind:rowKeys.length>0?"collection":"none",row_keys:rowKeys,fields:declaration.fields,...rowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}})()}function resolveDeclaredProjectionReceipt(result){if(!isRecord(result.projection))return void 0;if(typeof result.projection.mode!=="string"||result.projection.mode.trim().length===0){return void 0}const declared=result.projection.declared_field_groups;const included=result.projection.included_field_groups;if(!Array.isArray(declared)||!Array.isArray(included))return void 0;const declaredGroups=declared.filter(entry=>isRecord(entry)&&typeof entry.name==="string"&&entry.name.trim().length>0&&typeof entry.restore_with==="string"&&entry.restore_with.trim().length>0);const includedNames=included.filter(entry=>typeof entry==="string");if(declaredGroups.length!==declared.length||includedNames.length!==included.length){return void 0}const declaredNames=new Set(declaredGroups.map(group=>group.name));if(declaredNames.size!==declaredGroups.length||new Set(includedNames).size!==includedNames.length||includedNames.some(name=>!declaredNames.has(name))){return void 0}return createOutputOmissionReceipt(declaredGroups,new Set(includedNames))}function resolveContextReceipt(result){if(!Array.isArray(result.sections_included))return void 0;const receipt=createOutputOmissionReceipt(CONTEXT_FIELD_GROUPS,new Set(result.sections_included.filter(section=>typeof section==="string")));if(isRecord(result.summary)&&result.summary.scope==="matching_items"){receipt.summary_scope="matching_items"}return receipt}function resolveGetReceipt(result){if(!isRecord(result.item))return void 0;const item=result.item;const itemGroups=["comments","notes","learnings","files","tests","docs","reminders","events"];const resultGroups=["body","children","claim_state","linked","schedule"];const materialGroups=MATERIAL_FIELD_GROUPS_BY_RESULT.get(result);const ownerFor=name=>itemGroups.includes(name)||name==="body"?item:result;const groups=["body",...itemGroups,...resultGroups.slice(1)].filter(name=>materialGroups===void 0||materialGroups.has(name)||Object.hasOwn(ownerFor(name),name)).map(name=>({name,restore_with:`--fields ${name}`}));return createOutputOmissionReceipt(groups,new Set(groups.flatMap(({name})=>!Object.hasOwn(ownerFor(name),name)?[]:[name])))}function resolveListOrSearchReceipt(result){if(!isRecord(result.projection))return void 0;return createOutputOmissionReceipt([{name:"full_item_fields",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_item_fields"]:[]))}function resolveHealthReceipt(result){if(!isRecord(result.projection))return createOutputOmissionReceipt([]);if(typeof result.projection.mode!=="string")return void 0;return createOutputOmissionReceipt([{name:"full_check_details",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_check_details"]:[]))}function resolveContractsReceipt(result){if(!isRecord(result.selected)||typeof result.selected.summary!=="boolean"){return void 0}return createOutputOmissionReceipt([{name:"full_contract_catalog",restore_with:"--full"}],new Set(result.selected.summary?[]:["full_contract_catalog"]))}function resolveOutputOmissionReceipt(command,result){const declaredReceipt=resolveDeclaredProjectionReceipt(result);if(declaredReceipt!==void 0)return declaredReceipt;const[rootCommand]=command.split(/\s+/u,1);if(rootCommand==="context")return resolveContextReceipt(result);if(rootCommand==="get")return resolveGetReceipt(result);if(rootCommand==="list"||rootCommand.startsWith("list-")){return resolveListOrSearchReceipt(result)}if(rootCommand==="search"){return resolveListOrSearchReceipt(result)??createOutputOmissionReceipt([{name:"projection_metadata",restore_with:"--full"}])}if(rootCommand==="health")return resolveHealthReceipt(result);if(rootCommand==="contracts")return resolveContractsReceipt(result);return void 0}function attachOutputOmissionReceipt(command,result){if(command===void 0||!isRecord(result)){return result}const receipt=resolveOutputOmissionReceipt(command,result);const declaredRowContract=result.row_contract;const rowContract=isReadRowContract(declaredRowContract)?declaredRowContract:resolveReadRowContract(command,result);const disclosedResult=rowContract!==void 0?{...result,row_contract:rowContract}:Object.hasOwn(result,"row_contract")?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result;if(isRecord(disclosedResult.omission_receipt))return disclosedResult;return receipt===void 0?disclosedResult:{...disclosedResult,omission_receipt:receipt}}export{PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,PM_READ_ROW_CONTRACTS,PM_READ_ROW_JQ_SELECTOR,assertProjectionModeChoice,attachOutputOmissionReceipt,createOutputOmissionReceipt,isReadRowContract,registerOutputMaterialFieldGroups,resolveModePairedOutputOmissionReceipt,resolveOutputOmissionReceipt,resolveReadRowContract};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d248fcfa-d007-526a-9849-9ea8352acaa1")}catch(e2){}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const MATERIAL_FIELD_GROUPS_BY_RESULT=new WeakMap;function registerOutputMaterialFieldGroups(result,fieldGroups){MATERIAL_FIELD_GROUPS_BY_RESULT.set(result,new Set(fieldGroups))}const PM_READ_ROW_JQ_SELECTOR='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end';const PM_READ_ROW_CONTRACTS={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}};const PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function assertProjectionModeChoice(compactRequested,fullRequested,compactFlag){if(compactRequested&&fullRequested){throw new PmCliError(`${compactFlag} cannot be combined with --full`,EXIT_CODE.USAGE)}}function createOutputOmissionReceipt(declaredGroups,includedGroupNames=new Set){const omittedFieldGroups=declaredGroups.filter(group=>!includedGroupNames.has(group.name)).map(group=>({...group}));return{has_omissions:omittedFieldGroups.length>0,omitted_field_group_count:omittedFieldGroups.length,omitted_field_groups:omittedFieldGroups}}function resolveModePairedOutputOmissionReceipt(command,mode){const contract=PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS.find(candidate=>candidate.command===command);if(contract===void 0){throw new TypeError(`Unknown mode-paired output command: ${command}`)}if(mode===contract.complete_mode){return createOutputOmissionReceipt([])}const groups=contract.omissions_by_mode[mode];if(groups===void 0){throw new TypeError(`Unknown ${command} output mode: ${mode}`)}return createOutputOmissionReceipt(groups)}const CONTEXT_FIELD_GROUPS=[{name:"hierarchy",restore_with:"--depth standard"},{name:"activity",restore_with:"--depth standard"},{name:"progress",restore_with:"--depth standard"},{name:"blockers",restore_with:"--depth standard"},{name:"recently_created",restore_with:"--depth standard"},{name:"unparented",restore_with:"--depth standard"},{name:"files",restore_with:"--depth deep"},{name:"workload",restore_with:"--depth standard"},{name:"staleness",restore_with:"--depth deep"},{name:"tests",restore_with:"--depth deep"},{name:"workspace_memory",restore_with:"--depth deep"}];function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}const READ_ROW_TOON_ENCODINGS=new Set([void 0,"tabular_when_uniform"]);const READ_ROW_KINDS=new Set(["collection","none"]);const READ_ROW_FIELD_MODES=new Set(["supported","unsupported"]);function isUniqueNonEmptyStringArray(value,allowEmpty){return Array.isArray(value)&&(allowEmpty||value.length>0)&&value.every(entry=>typeof entry==="string"&&entry.length>0)&&new Set(value).size===value.length}function isReadRowContract(value){return isRecord(value)&&typeof value.command==="string"&&value.command.trim().length>0&&READ_ROW_KINDS.has(value.row_kind)&&isUniqueNonEmptyStringArray(value.row_keys,true)&&(value.continuation_row_keys===void 0||isUniqueNonEmptyStringArray(value.continuation_row_keys,false))&&READ_ROW_FIELD_MODES.has(value.fields)&&READ_ROW_TOON_ENCODINGS.has(value.toon_encoding)&&(value.row_kind==="collection"?value.row_keys.length>0&&typeof value.jq_selector==="string"&&value.jq_selector.trim().length>0:value.row_keys.length===0&&value.jq_selector===void 0)}const GRAPH_ROW_KEYS={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]};const READ_RESULT_SENTINEL_KEYS={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function resolveReadRowContract(command,result){const rawRootCommand=command.trim().toLowerCase().split(/\s+/u,1)[0];const rootCommand=rawRootCommand?.startsWith("list-")?"list":rawRootCommand;if(rootCommand==="graph"){const subcommand=typeof result.subcommand==="string"?result.subcommand:"";if(subcommand.length===0)return void 0;const rowKeys=GRAPH_ROW_KEYS[subcommand];if(rowKeys===void 0)return void 0;const activeRowKeys=rowKeys.filter(key=>Array.isArray(result[key])||isRecord(result[key]));return{command:"graph",row_kind:activeRowKeys.length>0?"collection":"none",row_keys:activeRowKeys,fields:"unsupported",...activeRowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}}const declaration=PM_READ_ROW_CONTRACTS[rootCommand];const sentinelKeys=READ_RESULT_SENTINEL_KEYS[rootCommand];return declaration===void 0||sentinelKeys===void 0||!sentinelKeys.some(key=>Object.hasOwn(result,key))?void 0:(()=>{const rowKeys=declaration.row_keys.filter(key=>{const value=key.split(".").reduce((current,segment)=>isRecord(current)?current[segment]:void 0,result);return Array.isArray(value)||isRecord(value)});return{command:rootCommand,row_kind:rowKeys.length>0?"collection":"none",row_keys:rowKeys,fields:declaration.fields,...rowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}})()}function resolveDeclaredProjectionReceipt(result){if(!isRecord(result.projection))return void 0;if(typeof result.projection.mode!=="string"||result.projection.mode.trim().length===0){return void 0}const declared=result.projection.declared_field_groups;const included=result.projection.included_field_groups;if(!Array.isArray(declared)||!Array.isArray(included))return void 0;const declaredGroups=declared.filter(entry=>isRecord(entry)&&typeof entry.name==="string"&&entry.name.trim().length>0&&typeof entry.restore_with==="string"&&entry.restore_with.trim().length>0);const includedNames=included.filter(entry=>typeof entry==="string");if(declaredGroups.length!==declared.length||includedNames.length!==included.length){return void 0}const declaredNames=new Set(declaredGroups.map(group=>group.name));if(declaredNames.size!==declaredGroups.length||new Set(includedNames).size!==includedNames.length||includedNames.some(name=>!declaredNames.has(name))){return void 0}return createOutputOmissionReceipt(declaredGroups,new Set(includedNames))}function resolveContextReceipt(result){if(!Array.isArray(result.sections_included))return void 0;const receipt=createOutputOmissionReceipt(CONTEXT_FIELD_GROUPS,new Set(result.sections_included.filter(section=>typeof section==="string")));if(isRecord(result.summary)&&result.summary.scope==="matching_items"){receipt.summary_scope="matching_items"}return receipt}function resolveGetReceipt(result){if(!isRecord(result.item))return void 0;const item=result.item;const itemGroups=["comments","notes","learnings","files","tests","docs","reminders","events"];const resultGroups=["body","children","claim_state","linked","schedule"];const materialGroups=MATERIAL_FIELD_GROUPS_BY_RESULT.get(result);const ownerFor=name=>itemGroups.includes(name)||name==="body"?item:result;const groups=["body",...itemGroups,...resultGroups.slice(1)].filter(name=>materialGroups===void 0||materialGroups.has(name)||Object.hasOwn(ownerFor(name),name)).map(name=>({name,restore_with:`--fields ${name}`}));return createOutputOmissionReceipt(groups,new Set(groups.flatMap(({name})=>!Object.hasOwn(ownerFor(name),name)?[]:[name])))}function resolveListOrSearchReceipt(result){if(!isRecord(result.projection))return void 0;return createOutputOmissionReceipt([{name:"full_item_fields",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_item_fields"]:[]))}function resolveHealthReceipt(result){if(!isRecord(result.projection))return createOutputOmissionReceipt([]);if(typeof result.projection.mode!=="string")return void 0;return createOutputOmissionReceipt([{name:"full_check_details",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_check_details"]:[]))}function resolveContractsReceipt(result){if(!isRecord(result.selected)||typeof result.selected.summary!=="boolean"){return void 0}return createOutputOmissionReceipt([{name:"full_contract_catalog",restore_with:"--full"}],new Set(result.selected.summary?[]:["full_contract_catalog"]))}function resolveOutputOmissionReceipt(command,result){const declaredReceipt=resolveDeclaredProjectionReceipt(result);if(declaredReceipt!==void 0)return declaredReceipt;const[rootCommand]=command.split(/\s+/u,1);if(rootCommand==="context")return resolveContextReceipt(result);if(rootCommand==="get")return resolveGetReceipt(result);if(rootCommand==="list"||rootCommand.startsWith("list-")){return resolveListOrSearchReceipt(result)}if(rootCommand==="search"){return resolveListOrSearchReceipt(result)??createOutputOmissionReceipt([{name:"projection_metadata",restore_with:"--full"}])}if(rootCommand==="health")return resolveHealthReceipt(result);if(rootCommand==="contracts")return resolveContractsReceipt(result);return void 0}function attachOutputOmissionReceipt(command,result){if(command===void 0||!isRecord(result)){return result}const receipt=resolveOutputOmissionReceipt(command,result);const declaredRowContract=result.row_contract;const rowContract=isReadRowContract(declaredRowContract)?declaredRowContract:resolveReadRowContract(command,result);const disclosedResult=rowContract!==void 0?{...result,row_contract:rowContract}:Object.hasOwn(result,"row_contract")?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result;if(isRecord(disclosedResult.omission_receipt))return disclosedResult;return receipt===void 0?disclosedResult:{...disclosedResult,omission_receipt:receipt}}export{PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,PM_READ_ROW_CONTRACTS,PM_READ_ROW_JQ_SELECTOR,assertProjectionModeChoice,attachOutputOmissionReceipt,createOutputOmissionReceipt,isReadRowContract,registerOutputMaterialFieldGroups,resolveModePairedOutputOmissionReceipt,resolveOutputOmissionReceipt,resolveReadRowContract};
|
|
2
2
|
//# sourceMappingURL=output-projection.js.map
|