@unbrained/pm-cli 2026.11.12 → 2026.11.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-MR3CRLA7.js → chunk-25BUKX4W.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5NY6EQSX.js → chunk-27FG6ROB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OBTU2BHJ.js → chunk-547OEGDR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6ESY4Y2B.js → chunk-5TGFB34A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GLPUIQDB.js → chunk-65SBMIK6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-T4UC3ZKL.js → chunk-AXTUB74T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KJL42AN5.js → chunk-BHH65KLL.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-C7M54YV6.js +122 -0
- package/dist/cli-bundle/chunks/chunk-DMWL3K4A.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-3DWEBVIK.js → chunk-DVN7CD5B.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FJNHTBJ2.js → chunk-DZ7CWUVM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GDS4DC5A.js → chunk-EXO4PM5J.js} +50 -44
- package/dist/cli-bundle/chunks/chunk-FRCNYOTG.js +9 -0
- package/dist/cli-bundle/chunks/chunk-HXECILIE.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-2K6GJUW7.js → chunk-IDFRGH4X.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-EALO2FPM.js → chunk-JSTBYDLL.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-MELSYAFE.js +124 -0
- package/dist/cli-bundle/chunks/{chunk-L3SA3354.js → chunk-OTM6PXZQ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-PC5DGK3C.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-UY7Z3ZHQ.js → chunk-PF3V443A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OFIXSWJS.js → chunk-U2HVJVA5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2DUUL53Z.js → chunk-V2OAXGHK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-U7MZIX3D.js → chunk-VERRDW3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-SYJT6TVZ.js → item-revision-VGIHIWZM.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-6OB6BGTD.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-T57TAVWI.js → mutation-admission-LL6SGQYU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-5XZXTPNG.js → register-list-query-MCNOV6ML.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-V6WJFL77.js → register-mutation-KYXLYHOK.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-6RQF6IAE.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-HCKCSQWQ.js → register-setup-XGPOFFD3.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-VIDXGF3T.js → stage-ZS7WNUD4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2A4JCFMI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IPIFI4NT.js → chunk-2T6MQ7NP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-32QYILXW.js +82 -0
- package/dist/cli-bundle/focused-chunks/{chunk-5OCUNAQN.js → chunk-3SUKWYR2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4WOF3Q6R.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-5IQPFV4Y.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GB2N4OM7.js → chunk-6C7NBJ7A.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BHYGUVAU.js → chunk-7KNF6RCV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NP5C2TQM.js → chunk-EAYRYXA6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LAIN47EJ.js → chunk-EH7JKGDH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3FN4ON2Z.js → chunk-EXCVUBAE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NSOXVVQX.js → chunk-FNLOLNPQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-HRLGC3P7.js +28 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VUNX6NBR.js → chunk-I7A5VP5E.js} +56 -56
- package/dist/cli-bundle/focused-chunks/{chunk-AXPRCCYM.js → chunk-JHC3X43E.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MKYNDWT3.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SPAEZKVA.js → chunk-RDTHL44U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GBW2EAAG.js → chunk-TA4EGVE6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-P6KYUJD4.js → chunk-UCCLV5GJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-W3RWCLEU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-W57DSFSU.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KN7RBRRH.js → chunk-YNYO7PMT.js} +22 -22
- package/dist/cli-bundle/focused-chunks/{item-revision-PWJNBW3F.js → item-revision-7J7WSCPC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-T6HXC3NS.js → item-transaction-F5YMCPRB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-CLPOLSXZ.js → mutation-admission-2NRQEAOG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-EKYWEU2Y.js → stage-2KVCKOGC.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/item/item-format-version.d.ts +6 -5
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +1 -1
- package/dist/core/lock/lock.js +3 -3
- package/dist/core/output/linked-test-projection.js +6 -0
- package/dist/core/output/output.js +7 -5
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/author.js +2 -2
- package/dist/core/shared/secret-rules.d.ts +8 -2
- package/dist/core/shared/secret-rules.js +3 -3
- package/dist/core/shared/text-normalization.d.ts +24 -0
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/url-credentials.d.ts +33 -5
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/test/run-selectors.d.ts +3 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/completion/bash.js +1 -1
- package/dist/sdk/completion/fish.js +4 -1
- package/dist/sdk/completion/zsh.js +4 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/docs.d.ts +3 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.d.ts +8 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
- package/dist/sdk/files.d.ts +3 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/claim.d.ts +5 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/linked-artifacts.d.ts +45 -3
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/output/table-rows.d.ts +28 -4
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output.d.ts +1 -1
- package/dist/sdk/output.js +1 -1
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/test/batch.d.ts +5 -2
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution.d.ts +10 -7
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/prerequisites.d.ts +1 -1
- package/dist/sdk/test/prerequisites.js +1 -1
- package/dist/sdk/test/run-phases.d.ts +44 -0
- package/dist/sdk/test/run-phases.js +2 -0
- package/dist/types.d.ts +3 -1
- package/dist/types.js +1 -1
- package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -4
- package/docs/COMMANDS.md +22 -4
- package/docs/LINKED_TEST_EDITS.md +2 -1
- package/docs/MUTATION_INTEGRITY.md +56 -6
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +6 -3
- package/docs/README.md +2 -2
- package/docs/READ_OUTPUT_CONTRACTS.md +23 -2
- package/docs/SDK.md +18 -1
- package/docs/TESTING.md +64 -1
- package/docs/WORKSPACE_CONCURRENCY.md +5 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +8 -8
- package/marketplace.json +1 -1
- package/package.json +1 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/CHANGELOG.md +0 -4782
- package/dist/cli-bundle/chunks/chunk-5NGGI7JC.js +0 -6
- package/dist/cli-bundle/chunks/chunk-A7L5IEYV.js +0 -20
- package/dist/cli-bundle/chunks/chunk-FOT5K5OM.js +0 -124
- package/dist/cli-bundle/chunks/chunk-PS2YAPXC.js +0 -9
- package/dist/cli-bundle/chunks/chunk-PZI6CR24.js +0 -116
- package/dist/cli-bundle/chunks/chunk-UTNPDAID.js +0 -31
- package/dist/cli-bundle/chunks/item-transaction-YXZ27UC6.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-5RAWXY2F.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AIYJHVKV.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-BB2GMKRB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GAXO2UQX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HIKZYZ26.js +0 -82
- package/dist/cli-bundle/focused-chunks/chunk-MK7UQEE5.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-NY65XTX7.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-RXY6BFRW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TZO6L523.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="164daf80-c7f0-5707-bd7d-df96b52a1904")}catch{}})();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{PLAN_SHOW_DEPTH_VALUES}from"../query/projection-contracts.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"],STEP_ID_PREFIX="plan-step-",DEFAULT_PLAN_MODE="draft",PLAN_TEMPLATE_NAMES=["bug-investigation","feature-implementation","refactoring-sprint"],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(),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){return(Array.isArray(value)?value:value==null?[]:[value]).filter(entry=>entry!=null).map(entry=>(typeof entry=="string"?entry:String(entry)).trim()).filter(entry=>entry.length>0)}function toArray(value){return Array.isArray(value)?value.flatMap(entry=>splitCommaList(entry,{unique:!1})):typeof value=="string"&&value.trim().length>0?splitCommaList(value,{unique:!1}):[]}function toSpecArray(value){return Array.isArray(value)?value.map(entry=>entry.trim()).filter(Boolean):typeof value=="string"&&value.trim().length>0?[value.trim()]:[]}function asPlanMode(value,fallback=DEFAULT_PLAN_MODE){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase(),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(),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(),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;const normalized=value.trim().toLowerCase();if(normalized.length===0)return;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(),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,projected={},unknownFields=[];for(const field of fields){const normalized=field.startsWith("plan.")?field.slice(5):field;if(normalized.length!==0){if(!PLAN_FIELD_KEYS.has(normalized)){unknownFields.push(field);continue}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};return(fields.scope==="global"||fields.scope==="project")&&(file.scope=fields.scope),fields.note&&(file.note=fields.note),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={};return fields.command&&(test.command=fields.command),fields.path&&(test.path=fields.path),fields.note&&(test.note=fields.note),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};return(fields.scope==="global"||fields.scope==="project")&&(doc.scope=fields.scope),fields.note&&(doc.note=fields.note),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;return summary.completion_pct=planCompletionPct(summary.completed,summary.total),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),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}}function resolveMaterializeTargets(steps,refs){const allRefs=refs.filter(ref=>ref.trim().toLowerCase()==="all"),targets=[],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,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),summary=summarizeSteps(steps),current=findCurrentStep(steps),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}))};return(depth==="standard"||depth==="deep")&&(projection.steps=steps),depth==="deep"&&(projection.decisions=item.plan_decisions??[],projection.discoveries=item.plan_discoveries??[],projection.validation=item.plan_validation??[]),projection}function nextActionsFor(planId,plan){const tips=[];return plan.steps_summary.total===0&&tips.push(`pm plan add-step ${planId} --step-title "First step"`),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 "..."`),plan.steps_summary.blocked>0&&tips.push(`pm plan show ${planId} --depth standard`),(plan.mode==="draft"||plan.mode==="research")&&tips.push(`pm plan approve ${planId} --message "ready to execute"`),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"`),tips}function ensurePlanItem(item){if((item.type??"").trim().toLowerCase()!=="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()),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});return ensurePlanItem(loaded.document.metadata),{document:loaded.document,itemId:located.id}}function buildPlanCreateDependencies(options){const deps=[];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(),command=options.validationCommand?.trim(),expected=options.validationExpected?.trim();if(!(!text&&!command&&!expected))return{text:text||command||"Validation check",command:command||void 0,expected:expected||void 0}}function hasPlanStepDetailOptions(options){return!!options.stepBody?.trim()||!!options.stepOwner?.trim()||!!options.stepStatus?.trim()||!!options.stepEvidence?.trim()||!!options.stepBlockedReason?.trim()||!!options.stepReplacement?.trim()||toArray(options.dependsOn).length>0||toArray(options.link).length>0}function resolveInitialStepSeed(options){const stepTitleFlag=options.stepTitle?.trim()||void 0,repeatedStepTitles=toOrderedStepTitles(options.step),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"),linkedItems=buildLinkInputs(options,"depends_on"),files=toSpecArray(options.file).map(parseStepFile),tests=toSpecArray(options.test).map(parseStepTest),docs=toSpecArray(options.doc).map(parseStepDoc),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),hasDetailOptions=hasPlanStepDetailOptions(options);if(assertInitialStepSeedAllowed(seed,hasDetailOptions),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),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),harness=asHarness(options.harness),fromSearch=options.fromSearch?.trim(),initialValidation=buildInitialValidation(options),{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,requestedAssignee=options.claim?resolveAuthor(options.author,ctx.settings.author_default):options.assignee?.trim()||void 0,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),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,harness&&(doc.metadata.plan_harness=harness,changedFields.push("plan_harness"));const scope=options.scope?.trim();scope&&(doc.metadata.plan_scope=scope,changedFields.push("plan_scope"));const resumeContext=options.resumeContext?.trim();return resumeContext&&(doc.metadata.plan_resume_context=resumeContext,changedFields.push("plan_resume_context")),doc.metadata.plan_steps=initialSteps,changedFields.push("plan_steps"),initialValidation&&(doc.metadata.plan_validation=[...doc.metadata.plan_validation??[],initialValidation],changedFields.push("plan_validation")),requestedAssignee&&(doc.metadata.assignee=requestedAssignee,changedFields.push("assignee")),{changedFields}}}),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),fields=parsePlanFields(options.fields),{document,itemId}=await readPlanItem(ctx,id),fullPlan=projectPlan(document.metadata,fields===null?depth:"deep");return{action:"show",plan:fields===null?fullPlan:projectPlanForFields(fullPlan,fields),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(),beforePlanFields=new Map(Object.entries(doc.metadata).filter(([key])=>key.startsWith("plan_")).map(([key,value])=>[key,JSON.stringify(value)])),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);return changedFields.length===0&&outcome.changedSteps.length===0?{changedFields:[]}:{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"),allowMultipleActive=options.allowMultipleActive===!0,{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});return steps.push(step),{changedSteps:[step.id],resultStep:step}}}),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)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"),files=toSpecArray(options.file).map(parseStepFile),tests=toSpecArray(options.test).map(parseStepTest),docs=toSpecArray(options.doc).map(parseStepDoc),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})),related=toArray(options.related).map(id=>({id,kind:"related"})),blocks=toArray(options.blocks).map(id=>({id,kind:"blocks"})),blockedBy=toArray(options.blockedBy).map(id=>({id,kind:"blocked_by"})),explicit=toArray(options.link),explicitKind=asLinkKind(options.linkKind,fallbackKind),note=options.linkNote?.trim(),explicitLinks=explicit.map(id=>{const link={id,kind:explicitKind};return note&&(link.note=note),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),now=nowIso(),desiredStatus=args.finalStatus??asStepStatus(options.stepStatus,step.status),allowMultipleActive=options.allowMultipleActive===!0||args.allowMultipleActive===!0;return assertInProgressStepAllowed(steps,step.status==="in_progress"?step.id:void 0,desiredStatus,allowMultipleActive),applyStepUpdates(step,options,desiredStatus,now),doc.metadata.updated_at=now,{changedSteps:[step.id],resultStep:step}}}),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))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();title&&(step.title=title),options.stepBody!==void 0&&(step.body=options.stepBody.trim()||void 0),options.stepOwner!==void 0&&(step.owner=options.stepOwner.trim()||void 0),options.stepEvidence!==void 0&&(step.evidence=options.stepEvidence.trim()||void 0),options.stepBlockedReason!==void 0&&(step.blocked_reason=options.stepBlockedReason.trim()||void 0),options.stepReplacement!==void 0&&(step.superseded_by=options.stepReplacement.trim()||void 0);const files=toSpecArray(options.file).map(parseStepFile),tests=toSpecArray(options.test).map(parseStepTest),docs=toSpecArray(options.doc).map(parseStepDoc);files.length>0&&(step.files=mergePlanStepEvidence(step.files,files)),tests.length>0&&(step.tests=mergePlanStepEvidence(step.tests,tests)),docs.length>0&&(step.docs=mergePlanStepEvidence(step.docs,docs))}function mergePlanStepEvidence(existing,added){const merged=[...existing??[]],seen=new Set(merged.map(entry=>JSON.stringify(entry)));for(const entry of added){const key=JSON.stringify(entry);seen.has(key)||(seen.add(key),merged.push(entry))}return merged}function applyStepCompletionTimestamp(step,desiredStatus,now){if(desiredStatus==="completed"&&!step.completed_at){step.completed_at=now;return}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),filtered=steps.filter(entry=>entry.id!==step.id),clamped=Math.max(1,Math.min(newOrder,filtered.length+1));return filtered.splice(clamped-1,0,step),filtered.forEach((entry,index)=>{entry.order=index+1,entry.updated_at=nowIso()}),steps.length=0,steps.push(...filtered),{changedSteps:[step.id],resultStep:step}}}),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),remaining=steps.filter(entry=>entry.id!==step.id);return remaining.forEach((entry,index)=>{entry.order=index+1}),steps.length=0,steps.push(...remaining),{changedSteps:[step.id],resultStep:step}}}),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===!0,{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),existing=step.linked_items??[],dedupKey=link=>`${link.kind}:${link.id}`,seen=new Set(existing.map(dedupKey));for(const link of newLinks){const key=dedupKey(link);seen.has(key)||(existing.push(link),seen.add(key))}if(step.linked_items=existing,step.updated_at=nowIso(),promoteToItemDep){const deps=doc.metadata.dependencies??[],depKey=dep=>`${dep.kind}:${dep.id}`,seenDeps=new Set(deps.map(depKey));for(const link of newLinks){const promotedKind=link.kind==="depends_on"?"blocked_by":link.kind,candidate={id:link.id,kind:promotedKind,created_at:nowIso(),author:resolveAuthor(options.author,ctx.settings.author_default)};seenDeps.has(depKey(candidate))||(deps.push(candidate),seenDeps.add(depKey(candidate)))}doc.metadata.dependencies=deps}return{changedSteps:[step.id],resultStep:step}}}),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),filtered=(step.linked_items??[]).filter(link=>!removeIds.includes(link.id));return step.linked_items=filtered.length>0?filtered:void 0,step.updated_at=nowIso(),{changedSteps:[step.id],resultStep:step}}}),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`,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),{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??[];return list2.push({ts:now,author,decision:logText,rationale:options.decisionRationale?.trim()||void 0,evidence:options.decisionEvidence?.trim()||void 0}),doc.metadata.plan_decisions=list2,{changedSteps:[]}}if(kind==="discovery"){const list2=doc.metadata.plan_discoveries??[];return list2.push({ts:now,author,text:logText}),doc.metadata.plan_discoveries=list2,{changedSteps:[]}}const list=doc.metadata.plan_validation??[];return list.push({text:logText,command:options.validationCommand?.trim()||void 0,expected:options.validationExpected?.trim()||void 0}),doc.metadata.plan_validation=list,{changedSteps:[]}}}),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();return scope&&(doc.metadata.plan_scope=scope),{changedSteps:[]}}}),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"),{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();return scope&&(doc.metadata.plan_scope=scope),{changedSteps:[]}}}),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=[],materializeFields={},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(),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,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",typeRegistry=resolveItemTypeRegistry(ctx.settings,getActiveExtensionRegistrations()),resolvedTypeName=resolveTypeName(targetType,typeRegistry);if(!resolvedTypeName)throw new PmCliError(`Invalid --materialize-type "${targetType}"`,EXIT_CODE.USAGE);const parent=options.materializeParent?.trim()||id,tags=options.materializeTags,planRead=await readPlanItem(ctx,id),steps=(planRead.document.metadata.plan_steps??[]).slice(),{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}),{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_materialize",message:options.message??`plan materialize ${stepRefs.join(",")}`,mutator(currentSteps){return linkMaterializedStepItems(currentSteps,targets,materialized),{changedSteps:targets.map(entry=>entry.id)}}}),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);return stepValues.length===1&&!input.options.stepTitle?.trim()?{...input,options:transferMutationStdinTokenPolicy(input.options,{...input.options,stepTitle:stepValues[0]})}: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),normalizedInput=normalizePlanStepAliasInput(input),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};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="caead750-d1ce-5727-a028-5d310494f6ea")}catch{}})();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{parseIdentityOption}from"../../core/shared/url-credentials.js";import{PLAN_SHOW_DEPTH_VALUES}from"../query/projection-contracts.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"],STEP_ID_PREFIX="plan-step-",DEFAULT_PLAN_MODE="draft",PLAN_TEMPLATE_NAMES=["bug-investigation","feature-implementation","refactoring-sprint"],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(),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){return(Array.isArray(value)?value:value==null?[]:[value]).filter(entry=>entry!=null).map(entry=>(typeof entry=="string"?entry:String(entry)).trim()).filter(entry=>entry.length>0)}function toArray(value){return Array.isArray(value)?value.flatMap(entry=>splitCommaList(entry,{unique:!1})):typeof value=="string"&&value.trim().length>0?splitCommaList(value,{unique:!1}):[]}function toSpecArray(value){return Array.isArray(value)?value.map(entry=>entry.trim()).filter(Boolean):typeof value=="string"&&value.trim().length>0?[value.trim()]:[]}function asPlanMode(value,fallback=DEFAULT_PLAN_MODE){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase(),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(),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(),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;const normalized=value.trim().toLowerCase();if(normalized.length===0)return;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(),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,projected={},unknownFields=[];for(const field of fields){const normalized=field.startsWith("plan.")?field.slice(5):field;if(normalized.length!==0){if(!PLAN_FIELD_KEYS.has(normalized)){unknownFields.push(field);continue}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};return(fields.scope==="global"||fields.scope==="project")&&(file.scope=fields.scope),fields.note&&(file.note=fields.note),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={};return fields.command&&(test.command=fields.command),fields.path&&(test.path=fields.path),fields.note&&(test.note=fields.note),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};return(fields.scope==="global"||fields.scope==="project")&&(doc.scope=fields.scope),fields.note&&(doc.note=fields.note),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;return summary.completion_pct=planCompletionPct(summary.completed,summary.total),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),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}}function resolveMaterializeTargets(steps,refs){const allRefs=refs.filter(ref=>ref.trim().toLowerCase()==="all"),targets=[],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,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),summary=summarizeSteps(steps),current=findCurrentStep(steps),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}))};return(depth==="standard"||depth==="deep")&&(projection.steps=steps),depth==="deep"&&(projection.decisions=item.plan_decisions??[],projection.discoveries=item.plan_discoveries??[],projection.validation=item.plan_validation??[]),projection}function nextActionsFor(planId,plan){const tips=[];return plan.steps_summary.total===0&&tips.push(`pm plan add-step ${planId} --step-title "First step"`),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 "..."`),plan.steps_summary.blocked>0&&tips.push(`pm plan show ${planId} --depth standard`),(plan.mode==="draft"||plan.mode==="research")&&tips.push(`pm plan approve ${planId} --message "ready to execute"`),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"`),tips}function ensurePlanItem(item){if((item.type??"").trim().toLowerCase()!=="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()),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});return ensurePlanItem(loaded.document.metadata),{document:loaded.document,itemId:located.id}}function buildPlanCreateDependencies(options){const deps=[];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(),command=options.validationCommand?.trim(),expected=options.validationExpected?.trim();if(!(!text&&!command&&!expected))return{text:text||command||"Validation check",command:command||void 0,expected:expected||void 0}}function hasPlanStepDetailOptions(options){return!!options.stepBody?.trim()||!!options.stepOwner?.trim()||!!options.stepStatus?.trim()||!!options.stepEvidence?.trim()||!!options.stepBlockedReason?.trim()||!!options.stepReplacement?.trim()||toArray(options.dependsOn).length>0||toArray(options.link).length>0}function resolveInitialStepSeed(options){const stepTitleFlag=options.stepTitle?.trim()||void 0,repeatedStepTitles=toOrderedStepTitles(options.step),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"),linkedItems=buildLinkInputs(options,"depends_on"),files=toSpecArray(options.file).map(parseStepFile),tests=toSpecArray(options.test).map(parseStepTest),docs=toSpecArray(options.doc).map(parseStepDoc),now=nowIso();return{id:"plan-step-001",order:1,title,body:options.stepBody?.trim()||void 0,status,owner:resolveStepOwner(options.stepOwner),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),hasDetailOptions=hasPlanStepDetailOptions(options);if(assertInitialStepSeedAllowed(seed,hasDetailOptions),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),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),harness=asHarness(options.harness),fromSearch=options.fromSearch?.trim(),initialValidation=buildInitialValidation(options),{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,requestedAssignee=options.claim?resolveAuthor(options.author,ctx.settings.author_default):options.assignee?.trim()||void 0,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),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,harness&&(doc.metadata.plan_harness=harness,changedFields.push("plan_harness"));const scope=options.scope?.trim();scope&&(doc.metadata.plan_scope=scope,changedFields.push("plan_scope"));const resumeContext=options.resumeContext?.trim();return resumeContext&&(doc.metadata.plan_resume_context=resumeContext,changedFields.push("plan_resume_context")),doc.metadata.plan_steps=initialSteps,changedFields.push("plan_steps"),initialValidation&&(doc.metadata.plan_validation=[...doc.metadata.plan_validation??[],initialValidation],changedFields.push("plan_validation")),requestedAssignee&&(doc.metadata.assignee=requestedAssignee,changedFields.push("assignee")),{changedFields}}}),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),fields=parsePlanFields(options.fields),{document,itemId}=await readPlanItem(ctx,id),fullPlan=projectPlan(document.metadata,fields===null?depth:"deep");return{action:"show",plan:fields===null?fullPlan:projectPlanForFields(fullPlan,fields),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(),beforePlanFields=new Map(Object.entries(doc.metadata).filter(([key])=>key.startsWith("plan_")).map(([key,value])=>[key,JSON.stringify(value)])),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);return changedFields.length===0&&outcome.changedSteps.length===0?{changedFields:[]}:{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"),allowMultipleActive=options.allowMultipleActive===!0,{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});return steps.push(step),{changedSteps:[step.id],resultStep:step}}}),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)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"),files=toSpecArray(options.file).map(parseStepFile),tests=toSpecArray(options.test).map(parseStepTest),docs=toSpecArray(options.doc).map(parseStepDoc),now=nowIso();return{id:newStepId(existingSteps),order:seed.order,title:seed.title,body:options.stepBody?.trim()||void 0,status:seed.status,owner:resolveStepOwner(options.stepOwner),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})),related=toArray(options.related).map(id=>({id,kind:"related"})),blocks=toArray(options.blocks).map(id=>({id,kind:"blocks"})),blockedBy=toArray(options.blockedBy).map(id=>({id,kind:"blocked_by"})),explicit=toArray(options.link),explicitKind=asLinkKind(options.linkKind,fallbackKind),note=options.linkNote?.trim(),explicitLinks=explicit.map(id=>{const link={id,kind:explicitKind};return note&&(link.note=note),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),now=nowIso(),desiredStatus=args.finalStatus??asStepStatus(options.stepStatus,step.status),allowMultipleActive=options.allowMultipleActive===!0||args.allowMultipleActive===!0;return assertInProgressStepAllowed(steps,step.status==="in_progress"?step.id:void 0,desiredStatus,allowMultipleActive),applyStepUpdates(step,options,desiredStatus,now),doc.metadata.updated_at=now,{changedSteps:[step.id],resultStep:step}}}),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 resolveStepOwner(value){return parseIdentityOption(value?.trim(),"--step-owner")||void 0}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))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();title&&(step.title=title),options.stepBody!==void 0&&(step.body=options.stepBody.trim()||void 0),options.stepOwner!==void 0&&(step.owner=resolveStepOwner(options.stepOwner)),options.stepEvidence!==void 0&&(step.evidence=options.stepEvidence.trim()||void 0),options.stepBlockedReason!==void 0&&(step.blocked_reason=options.stepBlockedReason.trim()||void 0),options.stepReplacement!==void 0&&(step.superseded_by=options.stepReplacement.trim()||void 0);const files=toSpecArray(options.file).map(parseStepFile),tests=toSpecArray(options.test).map(parseStepTest),docs=toSpecArray(options.doc).map(parseStepDoc);files.length>0&&(step.files=mergePlanStepEvidence(step.files,files)),tests.length>0&&(step.tests=mergePlanStepEvidence(step.tests,tests)),docs.length>0&&(step.docs=mergePlanStepEvidence(step.docs,docs))}function mergePlanStepEvidence(existing,added){const merged=[...existing??[]],seen=new Set(merged.map(entry=>JSON.stringify(entry)));for(const entry of added){const key=JSON.stringify(entry);seen.has(key)||(seen.add(key),merged.push(entry))}return merged}function applyStepCompletionTimestamp(step,desiredStatus,now){if(desiredStatus==="completed"&&!step.completed_at){step.completed_at=now;return}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),filtered=steps.filter(entry=>entry.id!==step.id),clamped=Math.max(1,Math.min(newOrder,filtered.length+1));return filtered.splice(clamped-1,0,step),filtered.forEach((entry,index)=>{entry.order=index+1,entry.updated_at=nowIso()}),steps.length=0,steps.push(...filtered),{changedSteps:[step.id],resultStep:step}}}),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),remaining=steps.filter(entry=>entry.id!==step.id);return remaining.forEach((entry,index)=>{entry.order=index+1}),steps.length=0,steps.push(...remaining),{changedSteps:[step.id],resultStep:step}}}),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===!0,{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),existing=step.linked_items??[],dedupKey=link=>`${link.kind}:${link.id}`,seen=new Set(existing.map(dedupKey));for(const link of newLinks){const key=dedupKey(link);seen.has(key)||(existing.push(link),seen.add(key))}if(step.linked_items=existing,step.updated_at=nowIso(),promoteToItemDep){const deps=doc.metadata.dependencies??[],depKey=dep=>`${dep.kind}:${dep.id}`,seenDeps=new Set(deps.map(depKey));for(const link of newLinks){const promotedKind=link.kind==="depends_on"?"blocked_by":link.kind,candidate={id:link.id,kind:promotedKind,created_at:nowIso(),author:resolveAuthor(options.author,ctx.settings.author_default)};seenDeps.has(depKey(candidate))||(deps.push(candidate),seenDeps.add(depKey(candidate)))}doc.metadata.dependencies=deps}return{changedSteps:[step.id],resultStep:step}}}),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),filtered=(step.linked_items??[]).filter(link=>!removeIds.includes(link.id));return step.linked_items=filtered.length>0?filtered:void 0,step.updated_at=nowIso(),{changedSteps:[step.id],resultStep:step}}}),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`,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),{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??[];return list2.push({ts:now,author,decision:logText,rationale:options.decisionRationale?.trim()||void 0,evidence:options.decisionEvidence?.trim()||void 0}),doc.metadata.plan_decisions=list2,{changedSteps:[]}}if(kind==="discovery"){const list2=doc.metadata.plan_discoveries??[];return list2.push({ts:now,author,text:logText}),doc.metadata.plan_discoveries=list2,{changedSteps:[]}}const list=doc.metadata.plan_validation??[];return list.push({text:logText,command:options.validationCommand?.trim()||void 0,expected:options.validationExpected?.trim()||void 0}),doc.metadata.plan_validation=list,{changedSteps:[]}}}),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();return scope&&(doc.metadata.plan_scope=scope),{changedSteps:[]}}}),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"),{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();return scope&&(doc.metadata.plan_scope=scope),{changedSteps:[]}}}),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=[],materializeFields={},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(),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,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",typeRegistry=resolveItemTypeRegistry(ctx.settings,getActiveExtensionRegistrations()),resolvedTypeName=resolveTypeName(targetType,typeRegistry);if(!resolvedTypeName)throw new PmCliError(`Invalid --materialize-type "${targetType}"`,EXIT_CODE.USAGE);const parent=options.materializeParent?.trim()||id,tags=options.materializeTags,planRead=await readPlanItem(ctx,id),steps=(planRead.document.metadata.plan_steps??[]).slice(),{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}),{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_materialize",message:options.message??`plan materialize ${stepRefs.join(",")}`,mutator(currentSteps){return linkMaterializedStepItems(currentSteps,targets,materialized),{changedSteps:targets.map(entry=>entry.id)}}}),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);return stepValues.length===1&&!input.options.stepTitle?.trim()?{...input,options:transferMutationStdinTokenPolicy(input.options,{...input.options,stepTitle:stepValues[0]})}: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),normalizedInput=normalizePlanStepAliasInput(input),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=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="89278323-311b-567b-b7ba-d51d3bec7a69")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../environment/project-runtime-compatibility.js";import{enforceWorkflowMutation}from"../../core/policy/workflow-policy-store.js";import jsonPatch from"fast-json-patch";import fs from"node:fs/promises";import{readLocatedItemSnapshot}from"../../core/store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable}from"../../core/store/item-mutation-precondition.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{readHistorySnapshot}from"../../core/history/read.js";import{verifyHistoryRewriteNoDrift}from"../../core/history/history-rewrite.js";import{resolveHistorySubject}from"../history/subject.js";import{historyVersionOffset}from"../../core/history/version-address.js";import{writeFileAtomic,appendHistoryEntry,createHistoryEntry,replayToCanonicalItemDocument,replayToItemDocument,toReplayDocument,enforceHistoryStreamPolicyForItem,canonicalDocument,serializeItemDocument,resolveItemTypeRegistry,acquireLockLease,EXIT_CODE,PmCliError,nowIso,getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnWriteHooks,runActiveBeforeMutationHooks,createMutationGuardSdk,getItemPath,resolvePmRoot,resolveWorkspaceRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{applyHistoryPatch,ensureMaterializedHistoryTarget as ensureMaterializedRestoreTarget,extractPatchFailureContext,replayHistoryToTarget as replayToTarget,resolveHistoryTarget}from"../history-read.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../item-metadata-index.js";async function readRestoreItem(located,settings,history){const snapshot=await readLocatedItemSnapshot(located,{schema:settings.schema});return snapshot.error===null?{raw:snapshot.raw,document:snapshot.document}:{raw:snapshot.raw,document:replayCurrentDocument(history),recovered:!0}}function ensureReplayTarget(target,history){return resolveHistoryTarget(target,history,{errorSubject:"restore",allowFutureTimestamp:!0})}function replayCurrentDocument(history){const currentReplay=replayToTarget(history,history.length-1);return Object.keys(currentReplay.metadata).length===0?{metadata:{},body:currentReplay.body}:canonicalDocument(replayToItemDocument(currentReplay))}async function resolveRestoreSubject(pmRoot,id,settings,typeToFolder){const subject=await resolveHistorySubject(pmRoot,id,settings,typeToFolder),historyPolicy=subject.located?await enforceHistoryStreamPolicyForItem({pmRoot,settings,itemId:subject.id,commandLabel:"restore"}):{warnings:[]};return{...subject,historyPolicyWarnings:historyPolicy.warnings}}function changedFields(beforeDocument,afterDocument){const beforeReplay=toReplayDocument(beforeDocument),afterReplay=toReplayDocument(afterDocument),patch=jsonPatch.compare(beforeReplay,afterReplay),fields=new Set;for(const op of patch){if(op.path==="/body"||op.path.startsWith("/body/")){fields.add("body");continue}const segment=op.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];fields.add(segment.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(fields).sort((a,b)=>a.localeCompare(b))}async function loadRestoreStateUnderLock(params){const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:"restore",readItem:located=>readRestoreItem(located,params.settings,params.history)});return{loadedItemUnderLock:verified.loadedItemUnderLock,existingItemPath:verified.locatedUnderLock?.itemPath??null}}function resolveRestoreCurrentState(loadedItemUnderLock,history){return loadedItemUnderLock?{document:loadedItemUnderLock.document,originalRaw:loadedItemUnderLock.raw}:{document:replayCurrentDocument(history),originalRaw:null}}function collectRestoreOwnershipWarnings(params){const assigned=params.document.metadata.assignee?.trim();if(!(assigned&&assigned!==params.author&&!params.force))return[];if(params.enforcement==="strict")throw new PmCliError(`Item ${params.resolvedId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return params.enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.resolvedId}:${assigned}`]:[]}async function restorePreviousItemAfterHistoryFailure(params){if(params.existingItemPath&¶ms.resolvedOriginalRaw!==null&¶ms.restoredItemPath!==params.existingItemPath){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw),await fs.rm(params.restoredItemPath,{force:!0});return}if(params.existingItemPath&¶ms.resolvedOriginalRaw!==null){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw);return}await fs.rm(params.restoredItemPath,{force:!0})}async function runRestoreWriteHooks(params){return[...await runActiveOnWriteHooks({path:params.restoredItemPath,scope:"project",op:"restore",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]}),...await runActiveOnWriteHooks({path:params.historyPath,scope:"project",op:"restore:history",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]})]}async function runRestore(id,target,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),subject=await resolveRestoreSubject(pmRoot,id,settings,typeRegistry.type_to_folder),resolvedId=subject.id,{raw:historyRawBeforeLock,entries:history}=await readHistorySnapshot(subject.historyPath,resolvedId);if(history.length===0)throw new PmCliError(`No history exists for ${resolvedId}; restore is unavailable.`,EXIT_CODE.NOT_FOUND);const resolvedTarget=ensureReplayTarget(target,history),replayDocument=ensureMaterializedRestoreTarget(replayToTarget(history,resolvedTarget.historyIndex),resolvedTarget),restoredDocument=replayToCanonicalItemDocument(replayDocument,{schema:settings.schema});if(restoredDocument.metadata.id!==resolvedId)throw new PmCliError(`Restore target resolved to item ${restoredDocument.metadata.id}, expected ${resolvedId}.`,EXIT_CODE.GENERIC_FAILURE);const currentItemRawBeforeLock=(subject.located?await readRestoreItem(subject.located,settings,history):null)?.raw??null,author=resolveAuthor(options.author,settings.author_default),lease=await acquireLockLease(pmRoot,resolvedId,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const{loadedItemUnderLock,existingItemPath}=await loadRestoreStateUnderLock({pmRoot,subject,settings,typeRegistry,historyRawBeforeLock,currentItemRawBeforeLock,history}),itemFormat="toon",currentState=resolveRestoreCurrentState(loadedItemUnderLock,history);loadedItemUnderLock?.recovered===!0&&assertItemRevisionExpectationsOnUnreadable(pmRoot,resolvedId,loadedItemUnderLock.raw),assertItemMutationPreconditions(pmRoot,loadedItemUnderLock?.document??EMPTY_CANONICAL_DOCUMENT,resolvedId),restoredDocument.metadata.pm_format_version=normalizeItemFormatVersion(Math.max(requiredItemFormatVersion(restoredDocument.metadata),requiredItemFormatVersion(currentState.document.metadata))),assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(pmRoot),requiredItemFormatVersion(restoredDocument.metadata));const ownershipWarnings=collectRestoreOwnershipWarnings({document:currentState.document,author,force:options.force,enforcement:settings.governance.ownership_enforcement,resolvedId}),restoreChangedFields=changedFields(currentState.document,restoredDocument),workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"restore",author,before:currentState.document,after:restoredDocument});await runActiveBeforeMutationHooks({pm_root:pmRoot,operation:"restore",before:currentState.document,after:restoredDocument,changed_fields:restoreChangedFields,sdk:createMutationGuardSdk({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder})});const serializedRestore=serializeItemDocument(restoredDocument,{format:itemFormat,schema:settings.schema}),restoredItemPath=getItemPath(pmRoot,restoredDocument.metadata.type,resolvedId,itemFormat,typeRegistry.type_to_folder),derivedIndexWarnings=await lease.fence(async()=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(pmRoot,author);let derivedIndexWarnings2;try{await writeFileAtomic(restoredItemPath,serializedRestore),existingItemPath&&restoredItemPath!==existingItemPath&&await fs.rm(existingItemPath);const historyEntry=createHistoryEntry({nowIso:nowIso(),author,op:"restore",before:currentState.document,after:restoredDocument,message:options.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(subject.historyPath,historyEntry)}catch(error){throw await restorePreviousItemAfterHistoryFailure({existingItemPath,resolvedOriginalRaw:currentState.originalRaw,restoredItemPath}),error}derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot,preferredFormat:settings.item_format,typeToFolder:typeRegistry.type_to_folder,schema:settings.schema,itemPath:restoredItemPath,previousItemPath:existingItemPath??void 0,document:restoredDocument})}finally{await releaseDerivedIndexLock()}return derivedIndexWarnings2});advanceItemMutationPreconditions(pmRoot,restoredDocument,resolvedId);const hookWarnings=await runRestoreWriteHooks({restoredItemPath,historyPath:subject.historyPath,before:currentState.document,after:restoredDocument});recordAfterCommandAffectedItem({id:restoredDocument.metadata.id,op:"restore",item_type:restoredDocument.metadata.type,previous_status:currentState.document.metadata.status,status:restoredDocument.metadata.status,previous:projectAfterCommandItemSnapshot(currentState.document.metadata,restoreChangedFields),current:projectAfterCommandItemSnapshot(restoredDocument.metadata,restoreChangedFields),changed_fields:restoreChangedFields});const targetEntry=history[resolvedTarget.historyIndex],offset=historyVersionOffset(history,!0);return{item:restoredDocument.metadata,restored_from:{kind:resolvedTarget.kind,target:resolvedTarget.raw,history_index:resolvedTarget.historyIndex+1,version:offset===null?null:offset+resolvedTarget.historyIndex+1,entry_ts:targetEntry.ts,entry_op:targetEntry.op},changed_fields:restoreChangedFields,warnings:[...workflowPolicy.warnings,...loadedItemUnderLock?.recovered?["restore_unreadable_item_recovered"]:[],...subject.historyPolicyWarnings,...ownershipWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}const _testOnlyRestoreCommand={applyHistoryPatch,changedFields,ensureMaterializedRestoreTarget,ensureReplayTarget,extractPatchFailureContext,replayCurrentDocument,replayToTarget,resolveRestoreSubject};export{_testOnlyRestoreCommand,runRestore};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b8f7423c-972b-57a6-b524-d7fbc36f6f58")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../environment/project-runtime-compatibility.js";import{enforceWorkflowMutation}from"../../core/policy/workflow-policy-store.js";import jsonPatch from"fast-json-patch";import fs from"node:fs/promises";import{readLocatedItemSnapshot}from"../../core/store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable}from"../../core/store/item-mutation-precondition.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{readHistorySnapshot}from"../../core/history/read.js";import{verifyHistoryRewriteNoDrift}from"../../core/history/history-rewrite.js";import{resolveHistorySubject}from"../history/subject.js";import{historyVersionOffset}from"../../core/history/version-address.js";import{writeFileAtomic,appendHistoryEntry,createHistoryEntry,replayToCanonicalItemDocument,replayToItemDocument,toReplayDocument,enforceHistoryStreamPolicyForItem,canonicalDocument,serializeItemDocument,resolveItemTypeRegistry,acquireLockLease,EXIT_CODE,PmCliError,nowIso,getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnWriteHooks,runActiveBeforeMutationHooks,createMutationGuardSdk,getItemPath,resolvePmRoot,resolveWorkspaceRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{applyHistoryPatch,ensureMaterializedHistoryTarget as ensureMaterializedRestoreTarget,extractPatchFailureContext,replayHistoryToTarget as replayToTarget,resolveHistoryTarget}from"../history-read.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../item-metadata-index.js";import{redactOptionalIdentityCredentials}from"../../core/shared/url-credentials.js";async function readRestoreItem(located,settings,history){const snapshot=await readLocatedItemSnapshot(located,{schema:settings.schema});return snapshot.error===null?{raw:snapshot.raw,document:snapshot.document}:{raw:snapshot.raw,document:replayCurrentDocument(history),recovered:!0}}function ensureReplayTarget(target,history){return resolveHistoryTarget(target,history,{errorSubject:"restore",allowFutureTimestamp:!0})}function replayCurrentDocument(history){const currentReplay=replayToTarget(history,history.length-1);return Object.keys(currentReplay.metadata).length===0?{metadata:{},body:currentReplay.body}:canonicalDocument(replayToItemDocument(currentReplay))}async function resolveRestoreSubject(pmRoot,id,settings,typeToFolder){const subject=await resolveHistorySubject(pmRoot,id,settings,typeToFolder),historyPolicy=subject.located?await enforceHistoryStreamPolicyForItem({pmRoot,settings,itemId:subject.id,commandLabel:"restore"}):{warnings:[]};return{...subject,historyPolicyWarnings:historyPolicy.warnings}}function changedFields(beforeDocument,afterDocument){const beforeReplay=toReplayDocument(beforeDocument),afterReplay=toReplayDocument(afterDocument),patch=jsonPatch.compare(beforeReplay,afterReplay),fields=new Set;for(const op of patch){if(op.path==="/body"||op.path.startsWith("/body/")){fields.add("body");continue}const segment=op.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];fields.add(segment.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(fields).sort((a,b)=>a.localeCompare(b))}async function loadRestoreStateUnderLock(params){const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:"restore",readItem:located=>readRestoreItem(located,params.settings,params.history)});return{loadedItemUnderLock:verified.loadedItemUnderLock,existingItemPath:verified.locatedUnderLock?.itemPath??null}}function resolveRestoreCurrentState(loadedItemUnderLock,history){return loadedItemUnderLock?{document:loadedItemUnderLock.document,originalRaw:loadedItemUnderLock.raw}:{document:replayCurrentDocument(history),originalRaw:null}}function collectRestoreOwnershipWarnings(params){const stored=params.document.metadata.assignee?.trim(),hasOwnershipConflict=stored&&stored!==params.author&&!params.force,assigned=redactOptionalIdentityCredentials(stored);if(!hasOwnershipConflict)return[];if(params.enforcement==="strict")throw new PmCliError(`Item ${params.resolvedId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return params.enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.resolvedId}:${assigned}`]:[]}async function restorePreviousItemAfterHistoryFailure(params){if(params.existingItemPath&¶ms.resolvedOriginalRaw!==null&¶ms.restoredItemPath!==params.existingItemPath){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw),await fs.rm(params.restoredItemPath,{force:!0});return}if(params.existingItemPath&¶ms.resolvedOriginalRaw!==null){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw);return}await fs.rm(params.restoredItemPath,{force:!0})}async function runRestoreWriteHooks(params){return[...await runActiveOnWriteHooks({path:params.restoredItemPath,scope:"project",op:"restore",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]}),...await runActiveOnWriteHooks({path:params.historyPath,scope:"project",op:"restore:history",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]})]}async function runRestore(id,target,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),subject=await resolveRestoreSubject(pmRoot,id,settings,typeRegistry.type_to_folder),resolvedId=subject.id,{raw:historyRawBeforeLock,entries:history}=await readHistorySnapshot(subject.historyPath,resolvedId);if(history.length===0)throw new PmCliError(`No history exists for ${resolvedId}; restore is unavailable.`,EXIT_CODE.NOT_FOUND);const resolvedTarget=ensureReplayTarget(target,history),replayDocument=ensureMaterializedRestoreTarget(replayToTarget(history,resolvedTarget.historyIndex),resolvedTarget),restoredDocument=replayToCanonicalItemDocument(replayDocument,{schema:settings.schema});if(restoredDocument.metadata.id!==resolvedId)throw new PmCliError(`Restore target resolved to item ${restoredDocument.metadata.id}, expected ${resolvedId}.`,EXIT_CODE.GENERIC_FAILURE);const currentItemRawBeforeLock=(subject.located?await readRestoreItem(subject.located,settings,history):null)?.raw??null,author=resolveAuthor(options.author,settings.author_default),lease=await acquireLockLease(pmRoot,resolvedId,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const{loadedItemUnderLock,existingItemPath}=await loadRestoreStateUnderLock({pmRoot,subject,settings,typeRegistry,historyRawBeforeLock,currentItemRawBeforeLock,history}),itemFormat="toon",currentState=resolveRestoreCurrentState(loadedItemUnderLock,history);loadedItemUnderLock?.recovered===!0&&assertItemRevisionExpectationsOnUnreadable(pmRoot,resolvedId,loadedItemUnderLock.raw),assertItemMutationPreconditions(pmRoot,loadedItemUnderLock?.document??EMPTY_CANONICAL_DOCUMENT,resolvedId),restoredDocument.metadata.pm_format_version=normalizeItemFormatVersion(Math.max(requiredItemFormatVersion(restoredDocument.metadata),requiredItemFormatVersion(currentState.document.metadata))),assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(pmRoot),requiredItemFormatVersion(restoredDocument.metadata));const ownershipWarnings=collectRestoreOwnershipWarnings({document:currentState.document,author,force:options.force,enforcement:settings.governance.ownership_enforcement,resolvedId}),restoreChangedFields=changedFields(currentState.document,restoredDocument),workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"restore",author,before:currentState.document,after:restoredDocument});await runActiveBeforeMutationHooks({pm_root:pmRoot,operation:"restore",before:currentState.document,after:restoredDocument,changed_fields:restoreChangedFields,sdk:createMutationGuardSdk({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder})});const serializedRestore=serializeItemDocument(restoredDocument,{format:itemFormat,schema:settings.schema}),restoredItemPath=getItemPath(pmRoot,restoredDocument.metadata.type,resolvedId,itemFormat,typeRegistry.type_to_folder),derivedIndexWarnings=await lease.fence(async()=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(pmRoot,author);let derivedIndexWarnings2;try{await writeFileAtomic(restoredItemPath,serializedRestore),existingItemPath&&restoredItemPath!==existingItemPath&&await fs.rm(existingItemPath);const historyEntry=createHistoryEntry({nowIso:nowIso(),author,op:"restore",before:currentState.document,after:restoredDocument,message:options.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(subject.historyPath,historyEntry)}catch(error){throw await restorePreviousItemAfterHistoryFailure({existingItemPath,resolvedOriginalRaw:currentState.originalRaw,restoredItemPath}),error}derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot,preferredFormat:settings.item_format,typeToFolder:typeRegistry.type_to_folder,schema:settings.schema,itemPath:restoredItemPath,previousItemPath:existingItemPath??void 0,document:restoredDocument})}finally{await releaseDerivedIndexLock()}return derivedIndexWarnings2});advanceItemMutationPreconditions(pmRoot,restoredDocument,resolvedId);const hookWarnings=await runRestoreWriteHooks({restoredItemPath,historyPath:subject.historyPath,before:currentState.document,after:restoredDocument});recordAfterCommandAffectedItem({id:restoredDocument.metadata.id,op:"restore",item_type:restoredDocument.metadata.type,previous_status:currentState.document.metadata.status,status:restoredDocument.metadata.status,previous:projectAfterCommandItemSnapshot(currentState.document.metadata,restoreChangedFields),current:projectAfterCommandItemSnapshot(restoredDocument.metadata,restoreChangedFields),changed_fields:restoreChangedFields});const targetEntry=history[resolvedTarget.historyIndex],offset=historyVersionOffset(history,!0);return{item:restoredDocument.metadata,restored_from:{kind:resolvedTarget.kind,target:resolvedTarget.raw,history_index:resolvedTarget.historyIndex+1,version:offset===null?null:offset+resolvedTarget.historyIndex+1,entry_ts:targetEntry.ts,entry_op:targetEntry.op},changed_fields:restoreChangedFields,warnings:[...workflowPolicy.warnings,...loadedItemUnderLock?.recovered?["restore_unreadable_item_recovered"]:[],...subject.historyPolicyWarnings,...ownershipWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}const _testOnlyRestoreCommand={applyHistoryPatch,changedFields,ensureMaterializedRestoreTarget,ensureReplayTarget,extractPatchFailureContext,replayCurrentDocument,replayToTarget,resolveRestoreSubject};export{_testOnlyRestoreCommand,runRestore};
|
|
2
2
|
//# sourceMappingURL=restore.js.map
|