@unbrained/pm-cli 2026.9.28 → 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.
Files changed (101) hide show
  1. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +7 -6
  2. package/.agents/skills/pm-user/references/BACKLOG_SHAPING.md +1 -1
  3. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +26 -3
  4. package/.claude-plugin/marketplace.json +2 -2
  5. package/CHANGELOG.md +17 -0
  6. package/dist/cli/error-guidance.js +1 -1
  7. package/dist/cli/help-json-payload.js +2 -2
  8. package/dist/cli/main.js +2 -2
  9. package/dist/cli/runtime/invocation-options.d.ts +3 -1
  10. package/dist/cli/runtime/invocation-options.js +1 -1
  11. package/dist/cli-bundle/bundle-manifest.json +153 -153
  12. package/dist/cli-bundle/chunks/{chunk-OYCCWPBM.js → chunk-2AQKVJMW.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-UT7GRGHY.js → chunk-4DOL43PF.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-GLH2LNRH.js → chunk-5KEPG36D.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-YERBAGQD.js → chunk-D32HVIB2.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-A2G5OG6W.js → chunk-GP6QTYSD.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-CPOWTIIS.js → chunk-OTLIM22J.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-PLNNUAFZ.js → chunk-P75SO5HO.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-PR4UAMI5.js → chunk-PJSQAWWQ.js} +60 -60
  20. package/dist/cli-bundle/chunks/{chunk-VMJLM7P2.js → chunk-S5A2UIRV.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-ZFHJP7YD.js → chunk-SC6JHXFT.js} +31 -29
  22. package/dist/cli-bundle/chunks/{chunk-NBDB3SRC.js → chunk-SEJ53XDN.js} +48 -48
  23. package/dist/cli-bundle/chunks/{chunk-35DME35A.js → chunk-SJI55O65.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-NEUIVBFO.js → chunk-U3QJGJYN.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-list-query-N6RP6PSP.js → register-list-query-R3ELWWPY.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-mutation-CY7JGQE6.js → register-mutation-WHXJXIHJ.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-operations-53HAD3QP.js → register-operations-7ASWBYQG.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-setup-NVX6374E.js → register-setup-FDRTUG54.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-YZB7IPR6.js → chunk-2O3QFI3G.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-Y5Z3XNGY.js → chunk-4A4DO5ZT.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-K7GSZ7YZ.js → chunk-5MC57KRC.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-IWLMQLBO.js → chunk-6OXJVE74.js} +17 -17
  33. package/dist/cli-bundle/focused-chunks/{chunk-6IVQPNYN.js → chunk-7URX7FMY.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-5KJXX2TZ.js → chunk-AVP5C674.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-DTLRXY77.js → chunk-AZE7KUHG.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-V7OPZRL6.js → chunk-DZVOCJFY.js} +14 -14
  37. package/dist/cli-bundle/focused-chunks/{chunk-AZA4AEOR.js → chunk-FBIRNSYP.js} +6 -6
  38. package/dist/cli-bundle/focused-chunks/{chunk-A5O3VYWV.js → chunk-IFBA3ZAT.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-ONDNR3VU.js → chunk-K3AIMRIK.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-ZMQTIS3L.js → chunk-KLKKCHWM.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-BRLXKRI2.js → chunk-MRH4A542.js} +4 -4
  42. package/dist/cli-bundle/focused-chunks/{chunk-IJXZQE3D.js → chunk-NXQZMKW5.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-BGWF6CMP.js → chunk-NY6FLQTN.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-OVVCXTIE.js → chunk-T4H6Q44B.js} +2 -2
  45. package/dist/cli-bundle/main.js +22 -22
  46. package/dist/cli-bundle/sdk-authoring.js +1 -1
  47. package/dist/cli-bundle/sdk-contracts.js +1 -1
  48. package/dist/cli-bundle/sdk-core.js +22 -21
  49. package/dist/cli-bundle/sdk-governance.js +1 -1
  50. package/dist/cli-bundle/sdk-graph.js +1 -1
  51. package/dist/cli-bundle/sdk-merge.js +28 -28
  52. package/dist/cli-bundle/sdk-query.js +1 -1
  53. package/dist/cli-bundle/sdk-runtime.js +1 -1
  54. package/dist/cli-bundle/sdk-testing.js +1 -1
  55. package/dist/cli-bundle/sdk.js +2 -2
  56. package/dist/core/history/replay.js +1 -1
  57. package/dist/core/output/mutation-projection.js +1 -1
  58. package/dist/core/telemetry/runtime.js +2 -2
  59. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  60. package/dist/sdk/index.d.ts +1 -0
  61. package/dist/sdk/index.js +1 -1
  62. package/dist/sdk/lifecycle/plan-mutation-receipt.d.ts +53 -0
  63. package/dist/sdk/lifecycle/plan-mutation-receipt.js +2 -0
  64. package/dist/sdk/lifecycle/plan.d.ts +3 -0
  65. package/dist/sdk/lifecycle/plan.js +1 -1
  66. package/dist/sdk/linked-artifacts.js +1 -1
  67. package/dist/sdk/public-surface.json +1 -1
  68. package/dist/sdk/runtime/actions.js +1 -1
  69. package/dist/sdk/runtime-input.d.ts +2 -0
  70. package/dist/sdk/runtime-input.js +1 -1
  71. package/dist/sdk/runtime.js +1 -1
  72. package/dist/sdk/similarity-scoring.js +1 -1
  73. package/dist/sdk/telemetry.d.ts +2 -0
  74. package/dist/sdk/telemetry.js +3 -1
  75. package/docs/CLI_GRAMMAR.md +18 -1
  76. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +270 -0
  77. package/docs/README.md +1 -0
  78. package/docs/SDK_EVIDENCE_TRACEABILITY.md +34 -0
  79. package/docs/agent-task-token-baseline.json +28 -2
  80. package/docs/agent-task-transcripts.json +137 -14
  81. package/docs/ecosystem-review-2026-09-28.json +3159 -0
  82. package/marketplace.json +2 -2
  83. package/package.json +1 -1
  84. package/packages/pm-beads/package.json +1 -1
  85. package/packages/pm-calendar/package.json +1 -1
  86. package/packages/pm-command-kit/package.json +1 -1
  87. package/packages/pm-digital-twin/package.json +1 -1
  88. package/packages/pm-governance-audit/package.json +1 -1
  89. package/packages/pm-guide-shell/package.json +1 -1
  90. package/packages/pm-kanban/package.json +1 -1
  91. package/packages/pm-lifecycle-hooks/package.json +1 -1
  92. package/packages/pm-linked-test-adapters/package.json +1 -1
  93. package/packages/pm-search-advanced/package.json +1 -1
  94. package/packages/pm-templates/package.json +1 -1
  95. package/packages/pm-todos/package.json +1 -1
  96. package/packages/pm-vcs/package.json +1 -1
  97. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  98. package/plugins/pm-claude/package.json +2 -2
  99. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  100. package/plugins/pm-codex/package.json +2 -2
  101. package/plugins/pm-codex/plugin.json +1 -1
@@ -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&&params.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&&params.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