@unbrained/pm-cli 2026.11.13 → 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-O6PBQMD7.js → chunk-25BUKX4W.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O6T24Z3M.js → chunk-27FG6ROB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5LG5YZYF.js → chunk-547OEGDR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FAYX6C7H.js → chunk-5TGFB34A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GWVP23RZ.js → chunk-65SBMIK6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LKVFPQNY.js → chunk-AXTUB74T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-L4F4ZHGR.js → chunk-BHH65KLL.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-C7M54YV6.js +122 -0
- package/dist/cli-bundle/chunks/{chunk-QSSENTXG.js → chunk-DMWL3K4A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-36E4L2R4.js → chunk-DVN7CD5B.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4WD4CHVH.js → chunk-DZ7CWUVM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GXGMMIZN.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-UYARS5XF.js → chunk-IDFRGH4X.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-URWNUZQZ.js → chunk-JSTBYDLL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UFZQPKQS.js → chunk-MELSYAFE.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-OQCVU2SG.js → chunk-OTM6PXZQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-COTC2QOR.js → chunk-PC5DGK3C.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6UXBWMEM.js → chunk-PF3V443A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CO7RWLCM.js → chunk-U2HVJVA5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PUU5DXSV.js → chunk-V2OAXGHK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-IYDIPXBO.js → chunk-VERRDW3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-G5OVYGZ5.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-SET4KY73.js → mutation-admission-LL6SGQYU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-JNJY2D3N.js → register-list-query-MCNOV6ML.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-WTHZHPOP.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-THFZP23A.js → register-setup-XGPOFFD3.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-JXJILTYE.js → stage-ZS7WNUD4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2A4JCFMI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-FNIX62V6.js → chunk-2T6MQ7NP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-32QYILXW.js +82 -0
- package/dist/cli-bundle/focused-chunks/{chunk-4LFE3FQL.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-RIMNSVFA.js → chunk-6C7NBJ7A.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JR75B6HU.js → chunk-7KNF6RCV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Q3OA5OAK.js → chunk-EAYRYXA6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VGFKTSGY.js → chunk-EH7JKGDH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZJF6ZA7B.js → chunk-EXCVUBAE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3MB47JLT.js → chunk-FNLOLNPQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-HRLGC3P7.js +28 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IYV3IPRF.js → chunk-I7A5VP5E.js} +56 -56
- package/dist/cli-bundle/focused-chunks/{chunk-CSKDIMQP.js → chunk-JHC3X43E.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VTOTZ5UC.js → chunk-MKYNDWT3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WFVZ7GGR.js → chunk-RDTHL44U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TVJ2PHAK.js → chunk-TA4EGVE6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ADBFVDTG.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-J3LQQP3N.js → chunk-YNYO7PMT.js} +4 -4
- package/dist/cli-bundle/focused-chunks/{item-revision-IF7E7BVY.js → item-revision-7J7WSCPC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-5TFWIOXI.js → item-transaction-F5YMCPRB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-KELM46JF.js → mutation-admission-2NRQEAOG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-UAKMQTCI.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/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/session/session-state.js +1 -1
- 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.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/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/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/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 -4793
- package/dist/cli-bundle/chunks/chunk-GIAJX2QJ.js +0 -9
- package/dist/cli-bundle/chunks/chunk-HQINCDF6.js +0 -116
- package/dist/cli-bundle/chunks/chunk-TCYIGAQG.js +0 -31
- package/dist/cli-bundle/chunks/item-transaction-I2X2P4TW.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-EZP3EG6A.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2ZPGEGTB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5KTOMFLR.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-5NTLNE54.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-QGQJBQCH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VGJDKDKA.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VGUQ4V47.js +0 -82
- package/dist/cli-bundle/focused-chunks/chunk-ZOGEQFGH.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,4 +1,42 @@
|
|
|
1
|
-
import type{GlobalOptions}from "../core/shared/command-types.js";import type{LinkScope}from "../types/index.js";import type{AnnotationOmissionReceipt}from "./annotations.js";
|
|
1
|
+
import type{GlobalOptions}from "../core/shared/command-types.js";import{PmCliError}from "../core/shared/errors.js";import type{LinkScope}from "../types/index.js";import type{AnnotationOmissionReceipt}from "./annotations.js";
|
|
2
|
+
/** How an add treats a stored link whose note differs from the requested one. */
|
|
3
|
+
export declare const LINKED_ARTIFACT_NOTE_CONFLICT_MODES:readonly["refuse","replace","append"];
|
|
4
|
+
/** One of {@link LINKED_ARTIFACT_NOTE_CONFLICT_MODES}; `refuse` is the default. */
|
|
5
|
+
export type LinkedArtifactNoteConflictMode=(typeof LINKED_ARTIFACT_NOTE_CONFLICT_MODES)[number];
|
|
6
|
+
/** What one requested link became in storage. */
|
|
7
|
+
export type LinkedArtifactLinkOutcome="added"|"note_added"|"note_replaced"|"note_appended"|"unchanged";
|
|
8
|
+
/** Per-link outcome a files or docs write reports in its mutation receipt. */
|
|
9
|
+
export interface LinkedArtifactLinkOutcomeEntry{
|
|
10
|
+
/** Linked path after anchoring and any path migration. */
|
|
11
|
+
path:string;
|
|
12
|
+
/** Scope of the requested link. */
|
|
13
|
+
scope:LinkScope;
|
|
14
|
+
/** What the write did to this link. */
|
|
15
|
+
outcome:LinkedArtifactLinkOutcome;}
|
|
16
|
+
/** A requested note that would overwrite a different stored note. */
|
|
17
|
+
export interface LinkedArtifactNoteConflict{
|
|
18
|
+
/** Linked path the conflict is on. */
|
|
19
|
+
path:string;
|
|
20
|
+
/** Scope of the stored link. */
|
|
21
|
+
scope:LinkScope;
|
|
22
|
+
/** The note already stored, which a refusal keeps. */
|
|
23
|
+
existing_note:string;
|
|
24
|
+
/** The note the add asked for. */
|
|
25
|
+
requested_note:string;
|
|
26
|
+
/** Whether the existing note was stored before this write or set by an earlier entry of the same write. */
|
|
27
|
+
source:"stored"|"this_write";}
|
|
28
|
+
/** Separator `append` places between the stored note and the requested one. */
|
|
29
|
+
export declare const LINKED_ARTIFACT_NOTE_JOINER="; ";
|
|
30
|
+
/** Parse the conflict mode, refusing a value outside the closed set and a mode with nothing to add. */
|
|
31
|
+
export declare function parseNoteConflictMode(raw:string|undefined,hasAddFlags:boolean):LinkedArtifactNoteConflictMode;
|
|
32
|
+
/**
|
|
33
|
+
* The note a stored link keeps after an add requests `requested`, and the
|
|
34
|
+
* outcome to report. A missing or identical requested note, and an append
|
|
35
|
+
* whose text is already one of the joined segments, leave the link unchanged.
|
|
36
|
+
*/
|
|
37
|
+
export declare function reviseLinkedNote(existing:string|undefined,requested:string|undefined,mode:LinkedArtifactNoteConflictMode):{note:string|undefined;outcome:LinkedArtifactLinkOutcome;conflict:boolean;};
|
|
38
|
+
/** Refuse a write whose adds would overwrite stored notes; nothing has been written when this throws. */
|
|
39
|
+
export declare function buildNoteConflictError(params:{itemId:string;noun:"file"|"doc";conflicts:readonly LinkedArtifactNoteConflict[];retryArgs:(mode:Exclude<LinkedArtifactNoteConflictMode,"refuse">)=> string[]|undefined;render:(args:string[])=> string;}):PmCliError;
|
|
2
40
|
/** Restricts linked artifact values accepted by command, SDK, and storage contracts. */
|
|
3
41
|
export type LinkedArtifact={
|
|
4
42
|
/** Filesystem path used for path resolution. */
|
|
@@ -27,6 +65,8 @@ remove?:string[];
|
|
|
27
65
|
migrate?:string[];
|
|
28
66
|
/** GH-170 (pm-pfnx): standalone note applied to every link added by --add / --add-glob in the same invocation. A per-entry embedded note (the `path=...,note=...` pair syntax) takes precedence over this flag. Requires at least one --add/--add-glob; rejected otherwise. */
|
|
29
67
|
note?:string;
|
|
68
|
+
/** How an add treats a stored link with a different note: refuse (default), replace or append (GH-1716). Requires --add or --add-glob. */
|
|
69
|
+
noteConflict?:LinkedArtifactNoteConflictMode|(string&{});
|
|
30
70
|
/** Value that configures or reports list for this contract. */
|
|
31
71
|
list?:boolean;
|
|
32
72
|
/** Value that configures or reports append stable for this contract. */
|
|
@@ -48,7 +88,9 @@ changed_count:number;
|
|
|
48
88
|
/** Stored entries this mutation removed. */
|
|
49
89
|
removed_count:number;
|
|
50
90
|
/** Whether the response includes the complete post-mutation collection. */
|
|
51
|
-
full_history_included:boolean;
|
|
91
|
+
full_history_included:boolean;
|
|
92
|
+
/** Files and docs writes: what each requested link became, so a note overwrite never reads as an add (GH-1716). */
|
|
93
|
+
link_outcomes?:LinkedArtifactLinkOutcomeEntry[];}
|
|
52
94
|
/** Counts and receipts a linked-collection mutation response carries beside its entries. */
|
|
53
95
|
export interface LinkedCollectionMutationProjection<TEntry>{
|
|
54
96
|
/** The written entries, or the whole collection when full history was requested. */
|
|
@@ -72,7 +114,7 @@ export declare function writtenLinkedEntries<TEntry>(before:readonly TEntry[],af
|
|
|
72
114
|
* MCP `full`) returns the whole collection, and the omission receipt names
|
|
73
115
|
* that selector whenever stored entries were withheld.
|
|
74
116
|
*/
|
|
75
|
-
export declare function projectLinkedCollectionMutation<TEntry>(params:{collectionKey:"files"|"docs"|"tests";stored:readonly TEntry[];written:readonly TEntry[];removedCount:number;fullHistory:boolean;}):LinkedCollectionMutationProjection<TEntry>;
|
|
117
|
+
export declare function projectLinkedCollectionMutation<TEntry>(params:{collectionKey:"files"|"docs"|"tests";stored:readonly TEntry[];written:readonly TEntry[];removedCount:number;fullHistory:boolean;linkOutcomes?:readonly LinkedArtifactLinkOutcomeEntry[];}):LinkedCollectionMutationProjection<TEntry>;
|
|
76
118
|
/** Documents the path migration payload exchanged by command, SDK, and package integrations. */
|
|
77
119
|
export interface PathMigration{
|
|
78
120
|
/** Value that configures or reports from for this contract. */
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw))return!0;const firstCommaIndex=raw.indexOf(","),leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length),equalsIndex=leadingSegment.indexOf("=");return equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))?!1:leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value)if(character==="("&&(depth+=1),character===")"&&(depth-=1),depth<0)return!1;return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed))return{path:trimmed,scope:"project",note:void 0};const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2))return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return;const label=trimmed.slice(0,delimiterIndex).trim(),destination=trimmed.slice(delimiterIndex+1).trim();if(!(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)))return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){return raw?raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};if(assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS),!kv.path)throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE);return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]}):[]}function parseAddGlobEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern)throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE);return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}}):[]}function parseRemoveEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove"),unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0)throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE);if(assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS),!kv.path)throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE);return kv.path}return trimmed}):[]}function parseMigrateEntries(raw){return raw?raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim(),to=kv.to?.trim();if(!from||!to)throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE);return{from,to}}):[]}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations)next.startsWith(migration.from)&&(next=`${migration.to}${next.slice(migration.from.length)}`);return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0)return;const addedPaths=new Set(adds.map(entry=>applyPathMigrations(entry.path,migrations))),conflicts=[...new Set(removes.map(entry=>applyPathMigrations(entry,migrations)).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length!==0)throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed))return trimmed;if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed))return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep));const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);return invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)?normalizeLinkedPath(path.normalize(trimmed)):normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){if(path.resolve(invocationRoot,entry.pattern)===path.resolve(invocationRoot))continue;const absolutePattern=path.isAbsolute(entry.pattern),matches=await glob(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches)expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0)return adds;if(!hasAddFlags)throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE);const trimmed=note.trim();return trimmed.length===0?adds:adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);return byPath!==0?byPath:left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right)),existingFiles=[],missingPaths=[],nonFilePaths=[],remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{(await fs.stat(resolvedPath)).isFile()?existingFiles.push(relativePath):nonFilePaths.push(relativePath)}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);migratedPath!==current[index].path&&(current[index]={...current[index],path:migratedPath},count+=1)}return{adds:adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);return migratedPath!==entry.path&&(count+=1),{...entry,path:migratedPath}}),removes:removes.map(entry=>applyPathMigrations(entry,migrations)),count}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable){const merged=dedupeLinkedArtifacts(current);for(const add of adds){const index=merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope);index<0?merged.push(add):add.note!==void 0&&(merged[index]={...merged[index],note:add.note})}if(removes.length>0)for(let index=merged.length-1;index>=0;index-=1)removes.includes(merged[index].path)&&merged.splice(index,1);return appendStable?merged:sortLinkedArtifacts(merged)}async function buildLinkedArtifactResult(params){const returned=params.mutation?.entries??params.artifacts,validated=params.options.validatePaths?params.artifacts:returned,{counts,receipts}=linkedCollectionMutationFields(params.mutation);return{id:params.id,artifacts:returned,changed:params.changed,count:returned.length,...counts,migrations_applied:params.migrationsApplied&¶ms.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed&&validated.length>0?await validateLinkedPaths(validated.map(entry=>entry.path),params.workspaceRoot):void 0,...receipts}}function countRemovedLinkedArtifacts(before,after,migrations){const remaining=new Map;for(const entry of after){const key=artifactKey(entry);remaining.set(key,(remaining.get(key)??0)+1)}let removed=0;for(const entry of before){const key=artifactKey({...entry,path:applyPathMigrations(entry.path,migrations)}),left=remaining.get(key)??0;left>0?remaining.set(key,left-1):removed+=1}return removed}function findMisreadNoteSegment(entry,bareNoun){const segments=/[\n\r]|^\s*[-*+`]/u.test(entry)?[]:splitStructuredEntrySegments(entry),noteIndex=segments.findIndex(segment=>segment.key?.toLowerCase()==="note");if(noteIndex<0)return;const fields=segments.slice(0,noteIndex).map(segment=>segment.raw.trim()),keys=new Set(segments.slice(0,noteIndex).map(segment=>segment.key?.toLowerCase())),prose=[segments[noteIndex].value];let misread;for(const segment of segments.slice(noteIndex+1)){const key=segment.key?.toLowerCase();if((key==="path"||key==="scope")&&!keys.has(key)){fields.push(segment.raw.trim()),keys.add(key);continue}misread??=segment.key===void 0?void 0:{segment:segment.text.trim(),key:segment.key},prose.push(segment.text)}if(misread===void 0)return;const note=prose.join(",").trim(),rewritten=[...fields,`note=${JSON.stringify(note)}`].join(",");try{parseAddEntries([rewritten],bareNoun)}catch{return}return{entry:rewritten,note,...misread}}function firstRefusedAddEntry(entries,bareNoun){return entries.findIndex(entry=>{try{return parseAddEntries([entry],bareNoun),!1}catch{return!0}})+1}function repeatFlag(flag,values){return(values??[]).flatMap(value=>[flag,value])}function noteRecoveryRetryArgs(params){const{options}=params;return[...resolvePmCommandScopeArgs(params.global),...params.guards.map(guard=>`--expect-hash=${guard}`),params.config.metadataKey,params.id,...repeatFlag("--add",params.entries.map((entry,index)=>index===params.position-1?params.rewritten:entry)),...repeatFlag("--add-glob",params.resolved.addGlob),...repeatFlag("--remove",params.resolved.remove),...repeatFlag("--migrate",params.resolved.migrate),...options.note===void 0?[]:["--note",options.note],...params.config.supportsAppendStable&&options.appendStable===!0?["--append-stable"]:[],...options.validatePaths===!0?["--validate-paths"]:[],...options.fullHistory===!0?["--full-history"]:[],...options.author?["--author",options.author]:[],...options.message?["--message",options.message]:[],...options.force===!0?["--force"]:[]]}function misreadKeyHint(key){return LINKED_ARTIFACT_ADD_KEYS.some(allowed=>allowed===key.toLowerCase())?`If "${key}" was meant as a key, give it once per entry.`:`If "${key}" was meant as a key, it is not one of: ${LINKED_ARTIFACT_ADD_KEYS.join(", ")}.`}function parseAddEntriesWithNoteRecovery(params){try{return parseAddEntries(params.entries,params.config.bareNoun)}catch(error){const entries=params.entries,cause=error,position=firstRefusedAddEntry(entries,params.config.bareNoun),misread=findMisreadNoteSegment(entries[position-1],params.config.bareNoun);if(misread===void 0)throw error;const guards=activeItemRevisionExpectations(params.pmRoot),retryArgs=guards===void 0?void 0:noteRecoveryRetryArgs({...params,entries,position,rewritten:misread.entry,guards});throw new PmCliError(`--add read the note segment "${misread.segment}" as a new key "${misread.key}", so the ${params.config.bareNoun} link was refused (${cause.message})`,EXIT_CODE.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:entries[position-1],required:`Retry with the note quoted so its commas stay prose (${retryArgs===void 0?`as ${misread.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${misreadKeyHint(misread.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...retryArgs===void 0?{}:{nextSteps:[renderPmCommand(retryArgs)]},details:{entry_index:position,misread_segment:misread.segment,misread_key:misread.key,note:misread.note,rewritten_entry:misread.entry,cause:cause.context.code??"invalid_argument_value"},...retryArgs===void 0?{}:{recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}}})}}function linkedCollectionMutationFields(mutation){return mutation===void 0?{counts:{},receipts:{}}:{counts:{total_count:mutation.total_count,returned_count:mutation.returned_count,has_more:mutation.has_more},receipts:{mutation_receipt:mutation.mutation_receipt,omission_receipt:mutation.omission_receipt}}}async function readLinkedArtifacts(params){const{settings,config}=params,located=await locateItem(params.pmRoot,params.id,settings.id_prefix,settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Item ${params.id} not found`,EXIT_CODE.NOT_FOUND);const artifacts=(await readLocatedItem(located,{schema:settings.schema})).document.metadata[config.metadataKey]??[],mutation=params.writeRequested?projectLinkedCollectionMutation({collectionKey:config.metadataKey,stored:artifacts,written:[],removedCount:0,fullHistory:params.options.fullHistory===!0}):void 0;return buildLinkedArtifactResult({id:located.id,artifacts,changed:!1,options:params.options,workspaceRoot:params.workspaceRoot,mutation})}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config,stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot),invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate"),parsedAdds=parseAddEntriesWithNoteRecovery({id,pmRoot,entries:resolvedAdds,resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config}).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)})),addGlobs=parseAddGlobEntries(resolvedAddGlobs),expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot),adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,parsedAdds.length>0||addGlobs.length>0),removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot)),migrations=parseMigrateEntries(resolvedMigrations);if(assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations),!(adds.length>0||removes.length>0||migrations.length>0))return readLinkedArtifacts({id,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,options,workspaceRoot,config,writeRequested:addGlobs.length>0});const author=resolveAuthor(options.author,settings.author_default);let before=[],removedCount=0;const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:!0,mutate(document){const metadata=document.metadata,current=metadata[metadataKey]??[],next=[...current],migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations),normalized=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===!0);normalized.length>0?metadata[metadataKey]=normalized:delete metadata[metadataKey];const changed=!stableValueEquals(current,normalized);return before=current,removedCount=countRemovedLinkedArtifacts(current,normalized,migrations),{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}}),artifacts=result.item[metadataKey]??[],migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:")),migrationCount=migrationWarning?Number(migrationWarning.slice(24)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot,mutation:projectLinkedCollectionMutation({collectionKey:metadataKey,stored:artifacts,written:writtenLinkedEntries(before,artifacts),removedCount,fullHistory:options.fullHistory===!0})})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result))out[field==="artifacts"?key:field]=value;return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,findMisreadNoteSegment,linkedCollectionMutationFields,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,projectLinkedCollectionMutation,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,writtenLinkedEntries};
|
|
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]="6c72ddef-c0fa-5d0b-9e35-20e3ba3c8d73")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{glob}from"tinyglobby";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,createStdinTokenResolver,looksLikeGenericKeyValueEntry,parseCsvKv,splitStructuredEntrySegments}from"../core/item/parse.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isRemoteLinkedArtifactReference}from"../core/validate/linked-artifact-reference.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{stableValueEquals}from"../core/shared/serialization.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{SCOPE_VALUES}from"../types/index.js";import{resolveAuthor}from"../core/shared/author.js";import{renderPmCommand,resolvePmCommandScopeArgs}from"./command-line.js";import{activeItemRevisionExpectations}from"../core/store/item-mutation-precondition.js";const LINKED_ARTIFACT_NOTE_CONFLICT_MODES=["refuse","replace","append"],LINKED_ARTIFACT_NOTE_JOINER="; ";function parseNoteConflictMode(raw,hasAddFlags){if(raw===void 0)return"refuse";const mode=raw.trim().toLowerCase();if(!LINKED_ARTIFACT_NOTE_CONFLICT_MODES.some(allowed=>allowed===mode))throw new PmCliError(`--note-conflict must be one of ${LINKED_ARTIFACT_NOTE_CONFLICT_MODES.join(", ")}; got "${raw}"`,EXIT_CODE.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:raw,required:`Pass --note-conflict ${LINKED_ARTIFACT_NOTE_CONFLICT_MODES.join("|")}.`});if(!hasAddFlags)throw new PmCliError("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",EXIT_CODE.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return mode}function reviseLinkedNote(existing,requested,mode){if(requested===void 0||requested===existing)return{note:existing,outcome:"unchanged",conflict:!1};if(existing===void 0)return{note:requested,outcome:"note_added",conflict:!1};if(mode==="replace")return{note:requested,outcome:"note_replaced",conflict:!1};if(mode==="append"){const joiner=LINKED_ARTIFACT_NOTE_JOINER;return`${joiner}${existing}${joiner}`.includes(`${joiner}${requested}${joiner}`)?{note:existing,outcome:"unchanged",conflict:!1}:{note:`${existing}${LINKED_ARTIFACT_NOTE_JOINER}${requested}`,outcome:"note_appended",conflict:!1}}return{note:existing,outcome:"unchanged",conflict:!0}}function buildNoteConflictError(params){const first=params.conflicts[0],more=params.conflicts.length>1?` and ${params.conflicts.length-1} more`:"",append=params.retryArgs("append"),replace=params.retryArgs("replace"),message=first.source==="stored"?`${params.itemId} already links ${params.noun} ${first.path} with the note "${first.existing_note}"${more}; the add was refused so that note is kept`:`The add names ${params.noun} ${first.path} on ${params.itemId} with two notes, "${first.existing_note}" and then "${first.requested_note}"${more}; the add was refused because they disagree`;return new PmCliError(message,EXIT_CODE.CONFLICT,{code:"linked_artifact_note_conflict",item_id:params.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...append===void 0||replace===void 0?{}:{nextSteps:[params.render(append),params.render(replace)],recovery:{suggested_retry:params.render(append),suggested_retry_args:append}},details:{conflicts:params.conflicts.map(conflict=>({...conflict}))}})}const LINKED_ARTIFACT_ADD_KEYS=["path","scope","note"],LINKED_ARTIFACT_ADD_GLOB_KEYS=["pattern","glob","path","scope","note"],LINKED_ARTIFACT_REMOVE_KEYS=["path"],LINKED_ARTIFACT_MIGRATE_KEYS=["from","to"],LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS=new Set(["note","scope"]);function persistedLinkedForm(entry){return JSON.parse(JSON.stringify(entry))}function writtenLinkedEntries(before,after){const unmatched=before.map(persistedLinkedForm);return after.filter(entry=>{const persisted=persistedLinkedForm(entry),index=unmatched.findIndex(candidate=>stableValueEquals(candidate,persisted));return index>=0&&unmatched.splice(index,1),index<0})}function projectLinkedCollectionMutation(params){const entries=params.fullHistory?[...params.stored]:[...params.written],withheld=entries.length<params.stored.length;return{entries,total_count:params.stored.length,returned_count:entries.length,has_more:withheld,mutation_receipt:{changed_count:params.written.length,removed_count:params.removedCount,full_history_included:!withheld,...params.linkOutcomes&¶ms.linkOutcomes.length>0?{link_outcomes:[...params.linkOutcomes]}:{}},omission_receipt:{has_omissions:withheld,omitted_field_group_count:withheld?1:0,omitted_field_groups:withheld?[{name:`${params.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value))throw new PmCliError(`Invalid scope "${raw}". Valid scopes: ${SCOPE_VALUES.join(", ")} (default: project).`,EXIT_CODE.USAGE);return value}function looksLikeStructuredPathEntry(raw){if(raw.startsWith("```")||raw.includes(`
|
|
2
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw))return!0;const firstCommaIndex=raw.indexOf(","),leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length),equalsIndex=leadingSegment.indexOf("=");return equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))?!1:leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value)if(character==="("&&(depth+=1),character===")"&&(depth-=1),depth<0)return!1;return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed))return{path:trimmed,scope:"project",note:void 0};const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2))return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return;const label=trimmed.slice(0,delimiterIndex).trim(),destination=trimmed.slice(delimiterIndex+1).trim();if(!(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)))return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){return raw?raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};if(assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS),!kv.path)throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE);return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]}):[]}function parseAddGlobEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern)throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE);return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}}):[]}function parseRemoveEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE);if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove"),unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0)throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE);if(assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS),!kv.path)throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE);return kv.path}return trimmed}):[]}function parseMigrateEntries(raw){return raw?raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim(),to=kv.to?.trim();if(!from||!to)throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE);return{from,to}}):[]}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations)next.startsWith(migration.from)&&(next=`${migration.to}${next.slice(migration.from.length)}`);return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0)return;const addedPaths=new Set(adds.map(entry=>storedLinkedPath(applyPathMigrations(entry.path,migrations)))),conflicts=[...new Set(removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length!==0)throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed))return trimmed;if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed))return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep));const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);return invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)?normalizeLinkedPath(path.normalize(trimmed)):normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){if(path.resolve(invocationRoot,entry.pattern)===path.resolve(invocationRoot))continue;const absolutePattern=path.isAbsolute(entry.pattern),matches=await glob(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches)expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0)return adds;if(!hasAddFlags)throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE);const trimmed=note.trim();return trimmed.length===0?adds:adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);return byPath!==0?byPath:left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right)),existingFiles=[],missingPaths=[],nonFilePaths=[],remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{(await fs.stat(resolvedPath)).isFile()?existingFiles.push(relativePath):nonFilePaths.push(relativePath)}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);migratedPath!==current[index].path&&(count+=1);const storedPath=storedLinkedPath(migratedPath);storedPath!==current[index].path&&(current[index]={...current[index],path:storedPath})}return{adds:adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);return migratedPath!==entry.path&&(count+=1),{...entry,path:storedLinkedPath(migratedPath)}}),removes:removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))),count}}function storedLinkedPath(value){return value.replaceAll("\\","/")}function storedLinkKey(entry){return`${entry.scope}\0${storedLinkedPath(entry.path)}`}function linkedArtifactOutcomes(baseline,merged,adds){const before=new Map(baseline.map(entry=>[storedLinkKey(entry),entry.note])),after=new Map(merged.map(entry=>[storedLinkKey(entry),entry.note])),outcomes=new Map;for(const add of adds){const key=storedLinkKey(add);outcomes.has(key)||outcomes.set(key,{path:storedLinkedPath(add.path),scope:add.scope,outcome:classifyLinkOutcome(before.has(key),before.get(key),after.get(key))})}return[...outcomes.values()]}function classifyLinkOutcome(existed,prior,final){return existed?final===prior?"unchanged":prior===void 0?"note_added":final?.startsWith(`${prior}${LINKED_ARTIFACT_NOTE_JOINER}`)?"note_appended":"note_replaced":"added"}function applyLinkedArtifactAdd(state,add,noteConflict){const index=state.merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope),stored=state.merged[index];if(stored===void 0){state.merged.push(add),add.note!==void 0&&state.notedHere.add(add);return}const revision=reviseLinkedNote(stored.note,add.note,noteConflict);if(revision.conflict)state.conflicts.push({path:add.path,scope:add.scope,existing_note:stored.note,requested_note:add.note,source:state.notedHere.has(stored)?"this_write":"stored"});else if(revision.note!==stored.note){const revised={...stored,note:revision.note};state.merged[index]=revised,state.notedHere.add(revised)}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable,noteConflict){const baseline=dedupeLinkedArtifacts(current),state={merged:[...baseline],notedHere:new Set,conflicts:[]};for(const add of adds)applyLinkedArtifactAdd(state,add,noteConflict);const{merged}=state,outcomes=linkedArtifactOutcomes(baseline,merged,adds);if(removes.length>0)for(let index=merged.length-1;index>=0;index-=1)removes.includes(merged[index].path)&&merged.splice(index,1);return{entries:appendStable?merged:sortLinkedArtifacts(merged),outcomes,conflicts:state.conflicts}}async function buildLinkedArtifactResult(params){const returned=params.mutation?.entries??params.artifacts,validated=params.options.validatePaths?params.artifacts:returned,{counts,receipts}=linkedCollectionMutationFields(params.mutation);return{id:params.id,artifacts:returned,changed:params.changed,count:returned.length,...counts,migrations_applied:params.migrationsApplied&¶ms.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed&&validated.length>0?await validateLinkedPaths(validated.map(entry=>entry.path),params.workspaceRoot):void 0,...receipts}}function countRemovedLinkedArtifacts(before,after,migrations){const remaining=new Map;for(const entry of after){const key=artifactKey(entry);remaining.set(key,(remaining.get(key)??0)+1)}let removed=0;for(const entry of before){const key=artifactKey({...entry,path:storedLinkedPath(applyPathMigrations(entry.path,migrations))}),left=remaining.get(key)??0;left>0?remaining.set(key,left-1):removed+=1}return removed}function findMisreadNoteSegment(entry,bareNoun){const segments=/[\n\r]|^\s*[-*+`]/u.test(entry)?[]:splitStructuredEntrySegments(entry),noteIndex=segments.findIndex(segment=>segment.key?.toLowerCase()==="note");if(noteIndex<0)return;const fields=segments.slice(0,noteIndex).map(segment=>segment.raw.trim()),keys=new Set(segments.slice(0,noteIndex).map(segment=>segment.key?.toLowerCase())),prose=[segments[noteIndex].value];let misread;for(const segment of segments.slice(noteIndex+1)){const key=segment.key?.toLowerCase();if((key==="path"||key==="scope")&&!keys.has(key)){fields.push(segment.raw.trim()),keys.add(key);continue}misread??=segment.key===void 0?void 0:{segment:segment.text.trim(),key:segment.key},prose.push(segment.text)}if(misread===void 0)return;const note=prose.join(",").trim(),rewritten=[...fields,`note=${JSON.stringify(note)}`].join(",");try{parseAddEntries([rewritten],bareNoun)}catch{return}return{entry:rewritten,note,...misread}}function firstRefusedAddEntry(entries,bareNoun){return entries.findIndex(entry=>{try{return parseAddEntries([entry],bareNoun),!1}catch{return!0}})+1}function repeatFlag(flag,values,literalKey){return(values??[]).flatMap(value=>[flag,literalKey!==void 0&&value.trim()==="-"?`${literalKey}=-`:value])}function noteRecoveryRetryArgs(params){const{options}=params,noteConflict=params.noteConflict??options.noteConflict;return[...resolvePmCommandScopeArgs(params.global),...params.guards.map(guard=>`--expect-hash=${guard}`),params.config.metadataKey,params.id,...repeatFlag("--add",params.entries.map((entry,index)=>index===params.position-1?params.rewritten:entry),"path"),...repeatFlag("--add-glob",params.resolved.addGlob,"pattern"),...repeatFlag("--remove",params.resolved.remove,"path"),...repeatFlag("--migrate",params.resolved.migrate),...options.note===void 0?[]:["--note",options.note],...noteConflict===void 0?[]:["--note-conflict",noteConflict],...params.config.supportsAppendStable&&options.appendStable===!0?["--append-stable"]:[],...options.validatePaths===!0?["--validate-paths"]:[],...options.fullHistory===!0?["--full-history"]:[],...options.author?["--author",options.author]:[],...options.message?["--message",options.message]:[],...options.force===!0?["--force"]:[]]}function misreadKeyHint(key){return LINKED_ARTIFACT_ADD_KEYS.some(allowed=>allowed===key.toLowerCase())?`If "${key}" was meant as a key, give it once per entry.`:`If "${key}" was meant as a key, it is not one of: ${LINKED_ARTIFACT_ADD_KEYS.join(", ")}.`}function parseAddEntriesWithNoteRecovery(params){try{return parseAddEntries(params.entries,params.config.bareNoun)}catch(error){const entries=params.entries,cause=error,position=firstRefusedAddEntry(entries,params.config.bareNoun),misread=findMisreadNoteSegment(entries[position-1],params.config.bareNoun);if(misread===void 0)throw error;const guards=activeItemRevisionExpectations(params.pmRoot),retryArgs=guards===void 0?void 0:noteRecoveryRetryArgs({...params,entries,position,rewritten:misread.entry,guards});throw new PmCliError(`--add read the note segment "${misread.segment}" as a new key "${misread.key}", so the ${params.config.bareNoun} link was refused (${cause.message})`,EXIT_CODE.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:entries[position-1],required:`Retry with the note quoted so its commas stay prose (${retryArgs===void 0?`as ${misread.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${misreadKeyHint(misread.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...retryArgs===void 0?{}:{nextSteps:[renderPmCommand(retryArgs)]},details:{entry_index:position,misread_segment:misread.segment,misread_key:misread.key,note:misread.note,rewritten_entry:misread.entry,cause:cause.context.code??"invalid_argument_value"},...retryArgs===void 0?{}:{recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}}})}}function linkedCollectionMutationFields(mutation){return mutation===void 0?{counts:{},receipts:{}}:{counts:{total_count:mutation.total_count,returned_count:mutation.returned_count,has_more:mutation.has_more},receipts:{mutation_receipt:mutation.mutation_receipt,omission_receipt:mutation.omission_receipt}}}async function readLinkedArtifacts(params){const{settings,config}=params,located=await locateItem(params.pmRoot,params.id,settings.id_prefix,settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Item ${params.id} not found`,EXIT_CODE.NOT_FOUND);const artifacts=(await readLocatedItem(located,{schema:settings.schema})).document.metadata[config.metadataKey]??[],mutation=params.writeRequested?projectLinkedCollectionMutation({collectionKey:config.metadataKey,stored:artifacts,written:[],removedCount:0,fullHistory:params.options.fullHistory===!0}):void 0;return buildLinkedArtifactResult({id:located.id,artifacts,changed:!1,options:params.options,workspaceRoot:params.workspaceRoot,mutation})}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config,stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot),invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate"),parsedAdds=parseAddEntriesWithNoteRecovery({id,pmRoot,entries:resolvedAdds,resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config}).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)})),addGlobs=parseAddGlobEntries(resolvedAddGlobs),expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot),hasAddFlags=parsedAdds.length>0||addGlobs.length>0,adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,hasAddFlags),noteConflict=parseNoteConflictMode(options.noteConflict,hasAddFlags),removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot)),migrations=parseMigrateEntries(resolvedMigrations);if(assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations),!(adds.length>0||removes.length>0||migrations.length>0))return readLinkedArtifacts({id,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,options,workspaceRoot,config,writeRequested:addGlobs.length>0});const author=resolveAuthor(options.author,settings.author_default);let before=[],removedCount=0,linkOutcomes=[];const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:!0,mutate(document){const metadata=document.metadata,current=metadata[metadataKey]??[],next=[...current],migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations),merge=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===!0,noteConflict);if(merge.conflicts.length>0){const guards=activeItemRevisionExpectations(pmRoot);throw buildNoteConflictError({itemId:document.metadata.id,noun:config.bareNoun,conflicts:merge.conflicts,retryArgs:mode=>guards===void 0?void 0:noteRecoveryRetryArgs({id:document.metadata.id,entries:resolvedAdds??[],position:0,rewritten:"",resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config,guards,noteConflict:mode}),render:renderPmCommand})}const normalized=merge.entries;linkOutcomes=merge.outcomes,normalized.length>0?metadata[metadataKey]=normalized:delete metadata[metadataKey];const changed=!stableValueEquals(current,normalized);return before=current,removedCount=countRemovedLinkedArtifacts(current,normalized,migrations),{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}}),artifacts=result.item[metadataKey]??[],migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:")),migrationCount=migrationWarning?Number(migrationWarning.slice(24)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot,mutation:projectLinkedCollectionMutation({collectionKey:metadataKey,stored:artifacts,written:writtenLinkedEntries(before,artifacts),removedCount,fullHistory:options.fullHistory===!0,linkOutcomes})})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result))out[field==="artifacts"?key:field]=value;return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_NOTE_CONFLICT_MODES,LINKED_ARTIFACT_NOTE_JOINER,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,buildNoteConflictError,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,findMisreadNoteSegment,linkedCollectionMutationFields,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseNoteConflictMode,parseRemoveEntries,projectLinkedCollectionMutation,renameArtifactsResultKey,reviseLinkedNote,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,writtenLinkedEntries};
|
|
3
3
|
//# sourceMappingURL=linked-artifacts.js.map
|
|
@@ -24,6 +24,20 @@ null_column_index?:number[];
|
|
|
24
24
|
column_order?:string[];
|
|
25
25
|
/** Missing field coordinates, expressed as [zero-based row, column name]. */
|
|
26
26
|
absent:Array<[number,string]>;}
|
|
27
|
+
/**
|
|
28
|
+
* An encoding block in the form the TOON host renders it (GH-1684). Empty
|
|
29
|
+
* `json_columns` and `absent` arrays are left out, and missing cells are
|
|
30
|
+
* grouped by column in `absent_rows`, so consumers recognize the block by its
|
|
31
|
+
* reserved `<collection>_encoding` key rather than by the arrays it carries.
|
|
32
|
+
* {@link decodePmTableRows} accepts this form and every earlier one.
|
|
33
|
+
*/
|
|
34
|
+
export interface PmRenderedTableCellEncoding extends Omit<PmTableCellEncoding,"json_columns"|"absent">{
|
|
35
|
+
/** Columns whose every present cell contains a JSON-serialized value; omitted when none. */
|
|
36
|
+
json_columns?:string[];
|
|
37
|
+
/** Missing field coordinates as [zero-based row, column name] pairs, as earlier releases rendered them. */
|
|
38
|
+
absent?:Array<[number,string]>;
|
|
39
|
+
/** Missing field coordinates grouped by column: column name to its zero-based row indexes. */
|
|
40
|
+
absent_rows?:Record<string,number[]>;}
|
|
27
41
|
/** Primitive rows accepted by the standard TOON tabular encoder. */
|
|
28
42
|
export interface PmEncodedTableRows{
|
|
29
43
|
/** Key-hoisted rows with primitive cells and null padding for absent keys. */
|
|
@@ -40,8 +54,18 @@ encoding:PmTableCellEncoding;}
|
|
|
40
54
|
*/
|
|
41
55
|
export declare function encodePmTableRows(rows:readonly Record<string,JsonValue>[],options?:{compact?:boolean;}):PmEncodedTableRows;
|
|
42
56
|
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
57
|
+
* Project an encoding for TOON delivery without losing a fact: empty
|
|
58
|
+
* `json_columns` and `absent` arrays are dropped, and absent coordinates are
|
|
59
|
+
* grouped by column. Grouping writes each column name once, so it is smaller
|
|
60
|
+
* whenever a column misses more than one cell, which is the shape of sparse
|
|
61
|
+
* focus rows such as unblocked `pm context` rows.
|
|
62
|
+
*/
|
|
63
|
+
export declare function projectPmTableEncodingForToon(encoding:PmTableCellEncoding):PmRenderedTableCellEncoding;
|
|
64
|
+
/**
|
|
65
|
+
* Restore rows emitted by {@link encodePmTableRows}, including the TOON form
|
|
66
|
+
* that omits empty metadata and groups absent cells by column. Metadata is
|
|
67
|
+
* explicit, so strings resembling JSON stay strings unless their column
|
|
68
|
+
* declares JSON. Malformed JSON cells throw instead of silently changing their
|
|
69
|
+
* meaning.
|
|
46
70
|
*/
|
|
47
|
-
export declare function decodePmTableRows(table:PmEncodedTableRows):Record<string,JsonValue>[];
|
|
71
|
+
export declare function decodePmTableRows(table:{rows:PmEncodedTableRows["rows"];encoding:PmRenderedTableCellEncoding;}):Record<string,JsonValue>[];
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bafcd4e4-ec0f-5340-89ce-b85d822b2323")}catch{}})();function encodePmTableRows(rows,options={}){const columns=[...new Set(rows.flatMap(row=>Object.keys(row)))],nullColumns=options.compact?columns.filter(column=>rows.every(row=>Object.hasOwn(row,column)&&row[column]===null)):[],listColumns=options.compact?columns.filter(column=>rows.every(row=>{if(!Object.hasOwn(row,column))return!0;const cell=row[column];return Array.isArray(cell)&&cell.every(value=>typeof value=="string"&&value!==""&&!value.includes(";"))})):[],lists=new Set(listColumns),nulls=new Set(nullColumns),jsonColumns=columns.filter(column=>!lists.has(column)&&rows.some(row=>{const cell=row[column];return cell!==null&&typeof cell=="object"})),nested=new Set(jsonColumns),absent=[];return{rows:rows.map((row,index)=>Object.fromEntries(columns.filter(column=>!nulls.has(column)).map(column=>{if(!Object.hasOwn(row,column))return absent.push([index,column]),[column,null];const cell=row[column];return lists.has(column)?[column,cell.join(";")]:[column,nested.has(column)?JSON.stringify(cell):cell]}))),encoding:{json_columns:jsonColumns,absent,...listColumns.length?{list_columns:Object.fromEntries(listColumns.map(column=>[column,";"]))}:{},...nullColumns.length?{null_columns:nullColumns,null_column_index:nullColumns.map(column=>columns.indexOf(column))}:{}}}}function projectPmTableEncodingForToon(encoding){const{json_columns:jsonColumns,absent,...declarations}=encoding,absentRows=new Map;for(const[row,column]of absent){const rows=absentRows.get(column)??[];rows.push(row),absentRows.set(column,rows)}return{...jsonColumns.length>0?{json_columns:jsonColumns}:{},...absentRows.size>0?{absent_rows:Object.fromEntries(absentRows)}:{},...declarations}}function restoreColumnOrder(encodedColumns,encoding){const nullColumns=encoding.null_columns??[],positions=encoding.null_column_index??[],columns=[...encodedColumns],insertions=nullColumns.map((column,index)=>({column,position:positions[index]})).filter(entry=>typeof entry.position=="number").sort((left,right)=>left.position-right.position);for(const{column,position}of insertions)columns.splice(Math.min(position,columns.length),0,column);for(const column of nullColumns)columns.includes(column)||columns.push(column);return columns}function decodePmTableRows(table){const nested=new Set(table.encoding.json_columns??[]),delimiters=new Map(Object.entries(table.encoding.list_columns??{})),absent=new Set([...(table.encoding.absent??[]).map(([row,column])=>JSON.stringify([row,column])),...Object.entries(table.encoding.absent_rows??{}).flatMap(([column,rows])=>rows.map(row=>JSON.stringify([row,column])))]);return table.rows.map((row,index)=>{const cells=new Map(Object.entries(row).flatMap(([column,cell])=>{if(absent.has(JSON.stringify([index,column])))return[];const delimiter=delimiters.get(column),value=delimiter!==void 0?cell===""?[]:String(cell).split(delimiter):nested.has(column)?JSON.parse(String(cell)):cell;return[[column,value]]}));for(const column of table.encoding.null_columns??[])cells.set(column,null);const columns=table.encoding.column_order??restoreColumnOrder(Object.keys(row),table.encoding);return Object.fromEntries(columns.filter(column=>cells.has(column)).map(column=>[column,cells.get(column)]))})}export{decodePmTableRows,encodePmTableRows,projectPmTableEncodingForToon};
|
|
2
2
|
//# sourceMappingURL=table-rows.js.map
|
package/dist/sdk/output.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Defines public output-control primitives for extension commands, exporters,
|
|
5
5
|
* renderers, and custom SDK-built hosts.
|
|
6
6
|
*/
|
|
7
|
-
export{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput,type SuppressedHostOutput,}from "../core/output/output-control.js";export{encodePmTableRows,decodePmTableRows,type PmTableCellEncoding,type PmEncodedTableRows,}from "./output/table-rows.js";export{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,}from "./output/list-envelope.js";export{assertWellFormedOutputText,toWellFormedText}from "../core/shared/output-unicode.js";
|
|
7
|
+
export{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput,type SuppressedHostOutput,}from "../core/output/output-control.js";export{encodePmTableRows,decodePmTableRows,type PmTableCellEncoding,type PmRenderedTableCellEncoding,type PmEncodedTableRows,}from "./output/table-rows.js";export{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,}from "./output/list-envelope.js";export{assertWellFormedOutputText,toWellFormedText}from "../core/shared/output-unicode.js";
|
|
8
8
|
/**
|
|
9
9
|
* Serialize object rows as newline-delimited JSON without adding a trailing
|
|
10
10
|
* newline. CLI hosts can append their final newline while SDK consumers can
|
package/dist/sdk/output.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="e6c590de-c83e-59ca-9fdb-9a68cc88d545")}catch{}})();import{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput}from"../core/output/output-control.js";import{encodePmTableRows,decodePmTableRows}from"./output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"./output/list-envelope.js";import{assertWellFormedOutputText,toWellFormedText}from"../core/shared/output-unicode.js";function serializeNdjsonRows(rows){return rows.map((row,index)=>{if(typeof row!="object"||row===null||Array.isArray(row))throw new TypeError(`NDJSON row ${index} must be a non-null object.`);const serialized=JSON.stringify(row);if(serialized===void 0)throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);const projected=JSON.parse(serialized);if(typeof projected!="object"||projected===null||Array.isArray(projected))throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);return serialized}).join(`
|
|
2
2
|
`)}function serializeNdjsonStream(rows,trailer){if(trailer.count!==rows.length)throw new TypeError(`NDJSON trailer count ${trailer.count} does not match ${rows.length} ${rows.length===1?"row":"rows"}.`);for(const[index,row]of rows.entries())if(typeof row=="object"&&row!==null&&!Array.isArray(row)&&Reflect.get(row,"record_type")==="pm.stream.trailer")throw new TypeError(`NDJSON row ${index} uses reserved record_type pm.stream.trailer`);return serializeNdjsonRows([...rows,{...trailer,record_type:"pm.stream.trailer"}])}export{SUPPRESS_HOST_OUTPUT_MARKER,assertWellFormedOutputText,decodePmTableRows,encodePmTableRows,isHostOutputSuppressed,projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,serializeNdjsonRows,serializeNdjsonStream,suppressHostOutput,toWellFormedText};
|
|
3
3
|
//# sourceMappingURL=output.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]="0f06f072-47a7-560e-9291-72e47225a73c")}catch{}})();import{appendHistoryEntry,createHistoryEntry}from"../core/history/history.js";import{acquireLock}from"../core/lock/lock.js";import{enforceWorkflowMutation}from"../core/policy/workflow-policy-store.js";import{parseTags}from"../core/item/parse.js";import{normalizeStatusInput}from"../core/item/status.js";import{serializeItemDocument}from"../core/item/item-format.js";import{getHistoryPath}from"../core/store/paths.js";import{removeFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolveAuthor}from"../core/shared/author.js";import{nowIso}from"../core/shared/time.js";import{assertInitializedTracker}from"./environment/tracker-preflight.js";function toNonEmptyImportString(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function toEstimatedMinutesValue(value){if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}function toImportPriority(value){if(typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=4)return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(Number.isInteger(parsed)&&parsed>=0&&parsed<=4)return parsed}return 2}function toImportTags(value){if(Array.isArray(value)){const tags=value.filter(entry=>typeof entry=="string").map(entry=>entry.trim().toLowerCase()).filter(entry=>entry.length>0);return Array.from(new Set(tags)).sort((left,right)=>left.localeCompare(right))}return typeof value=="string"?parseTags(value):[]}function toImportStatus(value){const normalized=toNonEmptyImportString(value);if(normalized){const canonical=normalizeStatusInput(normalized);if(canonical)return canonical}return"open"}function toImportInteger(value){if(typeof value=="number"&&Number.isInteger(value))return value;if(typeof value!="string"||value.trim().length===0)return;const parsed=Number(value);return Number.isInteger(parsed)?parsed:void 0}function toImportBoolean(value){if(typeof value=="boolean")return value;if(typeof value=="number")return value===1?!0:value===0?!1:void 0;if(typeof value!="string")return;const normalized=value.trim().toLowerCase();return normalized==="true"||normalized==="1"?!0:normalized==="false"||normalized==="0"?!1:void 0}function toImportStringList(value){if(!Array.isArray(value))return;const entries=value.map(entry=>toNonEmptyImportString(entry)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportStringMap(value){return toImportValueMap(value,toNonEmptyImportString)}function toImportNumberMap(value){return toImportValueMap(value,toImportFiniteNumber)}function toImportConfidence(value,allowedTextValues){if(typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=100)return value;const normalized=toNonEmptyImportString(value)?.toLowerCase();if(!normalized)return;const candidate=normalized==="med"?"medium":normalized;if(allowedTextValues.some(entry=>entry===candidate))return candidate;const parsed=Number(candidate);return Number.isInteger(parsed)&&parsed>=0&&parsed<=100?parsed:void 0}function toImportNormalizedEnum(value,allowed){const normalized=toNonEmptyImportString(value)?.toLowerCase();if(!normalized)return;const candidate=normalized==="med"?"medium":normalized;return allowed.includes(candidate)?candidate:void 0}function toImportLinkScope(value){return toNonEmptyImportString(value)?.toLowerCase()==="global"?"global":"project"}function toImportLogEntries(value,options){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const entries=values.map(entry=>toImportLogEntry(entry,options)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportLinkedFiles(value,options={}){return toImportLinkedArtifacts(value,options,(pathValue,record)=>({path:pathValue,scope:toImportLinkScope(record?.scope),note:toNonEmptyImportString(record?.note)}))}function toImportLinkedDocs(value,options={}){return toImportLinkedArtifacts(value,options,(pathValue,record)=>({path:pathValue,scope:toImportLinkScope(record?.scope),note:toNonEmptyImportString(record?.note)}))}function toImportLinkedTests(value,options={}){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const entries=values.map(entry=>toImportLinkedTest(entry,options)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function selectImportAuthor(explicitAuthor,settingsAuthor){return resolveAuthor(explicitAuthor,settingsAuthor)}function isImportRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function normalizeImportCollection(value,allowScalar){return Array.isArray(value)?value:allowScalar?[value]:void 0}function firstNonEmptyImportString(record,keys){for(const key of keys){const value=toNonEmptyImportString(record[key]);if(value)return value}}function toImportValueMap(value,coerce){if(!isImportRecord(value))return;const entries=Object.entries(value).map(([key,entryValue])=>[key.trim(),coerce(entryValue)]).filter(entry=>entry[0].length>0&&entry[1]!==void 0);return entries.length>0?Object.fromEntries(entries):void 0}function toImportLogEntry(entry,options){if(typeof entry=="string")return toImportLogEntryFromText(entry,options);if(!isImportRecord(entry))return;const text=firstNonEmptyImportString(entry,options.textKeys??["text"]);if(!text)return;const createdAtKey=options.createdAtKey??"created_at",authorKey=options.authorKey??"author";return{created_at:(options.toIsoString?options.toIsoString(entry[createdAtKey]):toNonEmptyImportString(entry[createdAtKey]))??options.fallbackCreatedAt,author:toNonEmptyImportString(entry[authorKey])??options.fallbackAuthor,text}}function toImportLogEntryFromText(entry,options){const text=toNonEmptyImportString(entry);return text?{created_at:options.fallbackCreatedAt,author:options.fallbackAuthor,text}:void 0}function toImportLinkedArtifacts(value,options,build){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const pathKeys=options.pathKeys??["path"],entries=values.map(entry=>toImportLinkedArtifact(entry,pathKeys,build)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportLinkedArtifact(entry,pathKeys,build){if(typeof entry=="string"){const pathValue2=toNonEmptyImportString(entry);return pathValue2?build(pathValue2):void 0}if(!isImportRecord(entry))return;const pathValue=firstNonEmptyImportString(entry,pathKeys);return pathValue?build(pathValue,entry):void 0}function toImportLinkedTest(entry,options){if(typeof entry=="string"){const command2=toNonEmptyImportString(entry);return command2?{command:command2,scope:"project"}:void 0}if(!isImportRecord(entry))return;const command=firstNonEmptyImportString(entry,options.commandKeys??["command"]),testPath=firstNonEmptyImportString(entry,options.pathKeys??["path"]);if(!(!command&&(options.requireCommand===!0||!testPath)))return{...command?{command}:{},...testPath?{path:testPath}:{},scope:toImportLinkScope(entry.scope),timeout_seconds:toImportLinkedTestTimeout(entry.timeout_seconds,options),note:toNonEmptyImportString(entry.note),...options.includeExtendedAssertions===!0?toImportLinkedTestAssertions(entry):{}}}function toImportLinkedTestTimeout(value,options){const parsed=options.integerTimeout===!0?toImportInteger(value):toImportFiniteNumber(value);if(parsed===void 0)return;const minimum=options.timeoutMinimum??0;return options.timeoutExclusiveMinimum===!0?parsed>minimum?parsed:void 0:parsed>=minimum?parsed:void 0}function toImportFiniteNumber(value){if(typeof value=="number"&&Number.isFinite(value))return value;if(typeof value!="string"||value.trim().length===0)return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}function toImportLinkedTestAssertions(entry){return{pm_context_mode:toImportNormalizedEnum(entry.pm_context_mode,["schema","tracker","auto"]),env_set:toImportStringMap(entry.env_set),env_clear:toImportStringList(entry.env_clear),shared_host_safe:toImportBoolean(entry.shared_host_safe),assert_stdout_contains:toImportStringList(entry.assert_stdout_contains),assert_stdout_regex:toImportStringList(entry.assert_stdout_regex),assert_stderr_contains:toImportStringList(entry.assert_stderr_contains),assert_stderr_regex:toImportStringList(entry.assert_stderr_regex),assert_stdout_min_lines:toImportInteger(entry.assert_stdout_min_lines),assert_json_field_equals:toImportStringMap(entry.assert_json_field_equals),assert_json_field_gte:toImportNumberMap(entry.assert_json_field_gte)}}async function ensureTrackerInitialized(pmRoot){await assertInitializedTracker(pmRoot)}function emptyImportedDocument(){return{metadata:{},body:""}}async function commitImportedItem(params){const{pmRoot,id,itemPath,document,author,message,settings,conflictWarningPrefix}=params,historyPath=getHistoryPath(pmRoot,id),beforeDocument=emptyImportedDocument();try{const releaseLock=await acquireLock(pmRoot,id,settings.locks.ttl_seconds,author,!1,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms);try{const workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"import",author,before:null,after:document});await writeFileAtomic(itemPath,serializeItemDocument(document,{format:"toon"}));try{const entry=createHistoryEntry({nowIso:nowIso(),author,op:"import",before:beforeDocument,after:document,message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});return await appendHistoryEntry(historyPath,entry),{committed:!0,writeWarnings:[...workflowPolicy.warnings,...await runActiveOnWriteHooks({path:itemPath,scope:"project",op:"import",item_id:document.metadata.id,item_type:document.metadata.type,before:beforeDocument,after:document,changed_fields:["imported"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"import:history",item_id:document.metadata.id,item_type:document.metadata.type,before:beforeDocument,after:document,changed_fields:["imported"]})]}}catch(error){throw await removeFileIfExists(itemPath),error}}finally{await releaseLock()}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.CONFLICT&&!error.code?.startsWith("workflow_policy_"))return{committed:!1,conflictWarning:`${conflictWarningPrefix}:${id}`};throw error}}export{commitImportedItem,emptyImportedDocument,ensureTrackerInitialized,selectImportAuthor,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkScope,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString};
|
|
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]="2eb50875-5603-5474-bb1f-f1f983c5e29e")}catch{}})();import{appendHistoryEntry,createHistoryEntry}from"../core/history/history.js";import{acquireLock}from"../core/lock/lock.js";import{enforceWorkflowMutation}from"../core/policy/workflow-policy-store.js";import{parseTags}from"../core/item/parse.js";import{normalizeStatusInput}from"../core/item/status.js";import{serializeItemDocument}from"../core/item/item-format.js";import{getHistoryPath}from"../core/store/paths.js";import{removeFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolveAuthor}from"../core/shared/author.js";import{nowIso}from"../core/shared/time.js";import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{stampRequiredItemFormat}from"./environment/project-runtime-compatibility.js";function toNonEmptyImportString(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function toEstimatedMinutesValue(value){if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}function toImportPriority(value){if(typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=4)return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(Number.isInteger(parsed)&&parsed>=0&&parsed<=4)return parsed}return 2}function toImportTags(value){if(Array.isArray(value)){const tags=value.filter(entry=>typeof entry=="string").map(entry=>entry.trim().toLowerCase()).filter(entry=>entry.length>0);return Array.from(new Set(tags)).sort((left,right)=>left.localeCompare(right))}return typeof value=="string"?parseTags(value):[]}function toImportStatus(value){const normalized=toNonEmptyImportString(value);if(normalized){const canonical=normalizeStatusInput(normalized);if(canonical)return canonical}return"open"}function toImportInteger(value){if(typeof value=="number"&&Number.isInteger(value))return value;if(typeof value!="string"||value.trim().length===0)return;const parsed=Number(value);return Number.isInteger(parsed)?parsed:void 0}function toImportBoolean(value){if(typeof value=="boolean")return value;if(typeof value=="number")return value===1?!0:value===0?!1:void 0;if(typeof value!="string")return;const normalized=value.trim().toLowerCase();return normalized==="true"||normalized==="1"?!0:normalized==="false"||normalized==="0"?!1:void 0}function toImportStringList(value){if(!Array.isArray(value))return;const entries=value.map(entry=>toNonEmptyImportString(entry)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportStringMap(value){return toImportValueMap(value,toNonEmptyImportString)}function toImportNumberMap(value){return toImportValueMap(value,toImportFiniteNumber)}function toImportConfidence(value,allowedTextValues){if(typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=100)return value;const normalized=toNonEmptyImportString(value)?.toLowerCase();if(!normalized)return;const candidate=normalized==="med"?"medium":normalized;if(allowedTextValues.some(entry=>entry===candidate))return candidate;const parsed=Number(candidate);return Number.isInteger(parsed)&&parsed>=0&&parsed<=100?parsed:void 0}function toImportNormalizedEnum(value,allowed){const normalized=toNonEmptyImportString(value)?.toLowerCase();if(!normalized)return;const candidate=normalized==="med"?"medium":normalized;return allowed.includes(candidate)?candidate:void 0}function toImportLinkScope(value){return toNonEmptyImportString(value)?.toLowerCase()==="global"?"global":"project"}function toImportLogEntries(value,options){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const entries=values.map(entry=>toImportLogEntry(entry,options)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportLinkedFiles(value,options={}){return toImportLinkedArtifacts(value,options,(pathValue,record)=>({path:pathValue,scope:toImportLinkScope(record?.scope),note:toNonEmptyImportString(record?.note)}))}function toImportLinkedDocs(value,options={}){return toImportLinkedArtifacts(value,options,(pathValue,record)=>({path:pathValue,scope:toImportLinkScope(record?.scope),note:toNonEmptyImportString(record?.note)}))}function toImportLinkedTests(value,options={}){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const entries=values.map(entry=>toImportLinkedTest(entry,options)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function selectImportAuthor(explicitAuthor,settingsAuthor){return resolveAuthor(explicitAuthor,settingsAuthor)}function isImportRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function normalizeImportCollection(value,allowScalar){return Array.isArray(value)?value:allowScalar?[value]:void 0}function firstNonEmptyImportString(record,keys){for(const key of keys){const value=toNonEmptyImportString(record[key]);if(value)return value}}function toImportValueMap(value,coerce){if(!isImportRecord(value))return;const entries=Object.entries(value).map(([key,entryValue])=>[key.trim(),coerce(entryValue)]).filter(entry=>entry[0].length>0&&entry[1]!==void 0);return entries.length>0?Object.fromEntries(entries):void 0}function toImportLogEntry(entry,options){if(typeof entry=="string")return toImportLogEntryFromText(entry,options);if(!isImportRecord(entry))return;const text=firstNonEmptyImportString(entry,options.textKeys??["text"]);if(!text)return;const createdAtKey=options.createdAtKey??"created_at",authorKey=options.authorKey??"author";return{created_at:(options.toIsoString?options.toIsoString(entry[createdAtKey]):toNonEmptyImportString(entry[createdAtKey]))??options.fallbackCreatedAt,author:toNonEmptyImportString(entry[authorKey])??options.fallbackAuthor,text}}function toImportLogEntryFromText(entry,options){const text=toNonEmptyImportString(entry);return text?{created_at:options.fallbackCreatedAt,author:options.fallbackAuthor,text}:void 0}function toImportLinkedArtifacts(value,options,build){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const pathKeys=options.pathKeys??["path"],entries=values.map(entry=>toImportLinkedArtifact(entry,pathKeys,build)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportLinkedArtifact(entry,pathKeys,build){if(typeof entry=="string"){const pathValue2=toNonEmptyImportString(entry);return pathValue2?build(pathValue2):void 0}if(!isImportRecord(entry))return;const pathValue=firstNonEmptyImportString(entry,pathKeys);return pathValue?build(pathValue,entry):void 0}function toImportLinkedTest(entry,options){if(typeof entry=="string"){const command2=toNonEmptyImportString(entry);return command2?{command:command2,scope:"project"}:void 0}if(!isImportRecord(entry))return;const command=firstNonEmptyImportString(entry,options.commandKeys??["command"]),testPath=firstNonEmptyImportString(entry,options.pathKeys??["path"]);if(!(!command&&(options.requireCommand===!0||!testPath)))return{...command?{command}:{},...testPath?{path:testPath}:{},scope:toImportLinkScope(entry.scope),timeout_seconds:toImportLinkedTestTimeout(entry.timeout_seconds,options),note:toNonEmptyImportString(entry.note),...typeof entry.phase=="string"&&entry.phase.trim().toLowerCase()==="setup"?{phase:"setup"}:{},...options.includeExtendedAssertions===!0?toImportLinkedTestAssertions(entry):{}}}function toImportLinkedTestTimeout(value,options){const parsed=options.integerTimeout===!0?toImportInteger(value):toImportFiniteNumber(value);if(parsed===void 0)return;const minimum=options.timeoutMinimum??0;return options.timeoutExclusiveMinimum===!0?parsed>minimum?parsed:void 0:parsed>=minimum?parsed:void 0}function toImportFiniteNumber(value){if(typeof value=="number"&&Number.isFinite(value))return value;if(typeof value!="string"||value.trim().length===0)return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}function toImportLinkedTestAssertions(entry){return{pm_context_mode:toImportNormalizedEnum(entry.pm_context_mode,["schema","tracker","auto"]),env_set:toImportStringMap(entry.env_set),env_clear:toImportStringList(entry.env_clear),shared_host_safe:toImportBoolean(entry.shared_host_safe),assert_stdout_contains:toImportStringList(entry.assert_stdout_contains),assert_stdout_regex:toImportStringList(entry.assert_stdout_regex),assert_stderr_contains:toImportStringList(entry.assert_stderr_contains),assert_stderr_regex:toImportStringList(entry.assert_stderr_regex),assert_stdout_min_lines:toImportInteger(entry.assert_stdout_min_lines),assert_json_field_equals:toImportStringMap(entry.assert_json_field_equals),assert_json_field_gte:toImportNumberMap(entry.assert_json_field_gte)}}async function ensureTrackerInitialized(pmRoot){await assertInitializedTracker(pmRoot)}function emptyImportedDocument(){return{metadata:{},body:""}}async function commitImportedItem(params){const{pmRoot,id,itemPath,author,message,settings,conflictWarningPrefix}=params,document={...params.document,metadata:{...params.document.metadata}};stampRequiredItemFormat(document.metadata,pmRoot);const historyPath=getHistoryPath(pmRoot,id),beforeDocument=emptyImportedDocument();try{const releaseLock=await acquireLock(pmRoot,id,settings.locks.ttl_seconds,author,!1,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms);try{const workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"import",author,before:null,after:document});await writeFileAtomic(itemPath,serializeItemDocument(document,{format:"toon"}));try{const entry=createHistoryEntry({nowIso:nowIso(),author,op:"import",before:beforeDocument,after:document,message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});return await appendHistoryEntry(historyPath,entry),{committed:!0,writeWarnings:[...workflowPolicy.warnings,...await runActiveOnWriteHooks({path:itemPath,scope:"project",op:"import",item_id:document.metadata.id,item_type:document.metadata.type,before:beforeDocument,after:document,changed_fields:["imported"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"import:history",item_id:document.metadata.id,item_type:document.metadata.type,before:beforeDocument,after:document,changed_fields:["imported"]})]}}catch(error){throw await removeFileIfExists(itemPath),error}}finally{await releaseLock()}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.CONFLICT&&!error.code?.startsWith("workflow_policy_"))return{committed:!1,conflictWarning:`${conflictWarningPrefix}:${id}`};throw error}}export{commitImportedItem,emptyImportedDocument,ensureTrackerInitialized,selectImportAuthor,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkScope,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString};
|
|
2
2
|
//# sourceMappingURL=package-import-adapters.js.map
|