@unbrained/pm-cli 2026.11.4 → 2026.11.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/HARNESS_COMPATIBILITY.md +1 -1
- package/.agents/skills/README.md +14 -14
- package/.agents/skills/pm-developer/SKILL.md +16 -16
- package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +14 -14
- package/.agents/skills/pm-developer/references/SCRIPTING_COMPOSITION.md +10 -10
- package/.agents/skills/pm-extensions/SKILL.md +13 -13
- package/.agents/skills/pm-extensions/references/AUTHORING.md +12 -12
- package/.agents/skills/pm-sdk/SKILL.md +27 -27
- package/.agents/skills/pm-sdk/references/SURFACE_MAP.md +32 -32
- package/.agents/skills/pm-test-audit/references/AUDIT.md +1 -1
- package/.agents/skills/pm-user/SKILL.md +35 -35
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +9 -9
- package/CHANGELOG.md +9 -0
- package/README.md +13 -13
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2RPORE7M.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-NPEDFOVQ.js → chunk-335BZ75D.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-5GWEY4P6.js +122 -0
- package/dist/cli-bundle/chunks/chunk-6VRX2CM7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-7PGNAHNW.js → chunk-7DEKAXVA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3OXQGGRD.js → chunk-7ZRCYESH.js} +42 -41
- package/dist/cli-bundle/chunks/{chunk-BWAXA6S4.js → chunk-AUEKTX7V.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SRDO2NJU.js → chunk-D7KYPRK4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ODMJ3HIB.js → chunk-DAX3AOFI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-L4BKTPJ6.js → chunk-F6NDMKZ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-T56MB6SF.js → chunk-FRNMQM45.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5S6RT5LX.js → chunk-HNGLDMSZ.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-QN7VCOUU.js → chunk-HRCMORE7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BK2XAQVC.js → chunk-HRFGFIYU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CERNIZLB.js → chunk-JI2GDE4I.js} +42 -42
- package/dist/cli-bundle/chunks/{chunk-6T2V3UIK.js → chunk-LS3GI3H4.js} +53 -53
- package/dist/cli-bundle/chunks/chunk-OH6WQ7VT.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-BRIPGUAO.js → chunk-OJDMJT7Y.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7RCI7AAA.js → chunk-S4LPZ4TN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AQ5UHHQS.js → chunk-UEGXWXUZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5BVZ32G7.js → chunk-XLSHFYXZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2GW662DP.js → chunk-YKXATU2G.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-UAZOBP2Q.js → item-revision-OJJVPQY7.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-QEPBUCMY.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-QZQI2NN5.js → mutation-admission-INMM3HHG.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-P3NOKQUA.js → register-list-query-5Y5JKWU5.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-A6I5K5N6.js → register-mutation-WC7OSQID.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-SPKB3TNM.js → register-operations-PO63DBZH.js} +2 -2
- package/dist/cli-bundle/chunks/register-setup-RRFOS7IT.js +2 -0
- package/dist/cli-bundle/chunks/{stage-L3T725DS.js → stage-E3MMV4TV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5PMJOJCZ.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TFYTTDAK.js → chunk-7KK66ISG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Y5GOUUYJ.js → chunk-AHWJPZSJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-C7UX2ZI3.js → chunk-C6P6HPCX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Q4OIRSKL.js → chunk-CPMSL4HS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CZM75DE3.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-CO2DNPH7.js → chunk-D2TBEBNW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-E56OXRYH.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-FXFDVM5O.js → chunk-F62XGAAY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-G4QP365K.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-J7M52SCZ.js → chunk-G5PJCR7R.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GS3JC5UU.js +23 -0
- package/dist/cli-bundle/focused-chunks/{chunk-W3CSX6GI.js → chunk-LW64TINU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MEJKELWC.js → chunk-M6V7UMWL.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-CXTDEQ3N.js → chunk-MC7IE7D7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MG7C3JUY.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QEVJ3Y67.js → chunk-MK4HV4JO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-A2246ZM7.js → chunk-NQ7GYFOX.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-O7EI33NP.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-FFO7RBLN.js → chunk-RFTJZ5VB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PNPYQDHU.js → chunk-SNOXXRSJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JQS7TYQ6.js → chunk-UPJUTP2V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SDLIUZEL.js → chunk-VWWTIX5L.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-J6FDCAMH.js → chunk-XHOBYCVE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-J3YOATXR.js → chunk-YMGB2O4E.js} +25 -24
- package/dist/cli-bundle/focused-chunks/{item-revision-L6GVT42D.js → item-revision-CTDO4H3I.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-GYGP264N.js → item-transaction-AEAYVVHA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-UWTH56OD.js → mutation-admission-4WM7TNHZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-WRSNJ7VI.js → stage-WV7QXR4C.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 +1 -1
- 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 +9 -9
- package/dist/core/config/positional-value.d.ts +6 -0
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/item/literal-mutation-input.d.ts +17 -0
- package/dist/core/item/literal-mutation-input.js +1 -1
- package/dist/core/item/parent-reference-policy.d.ts +8 -4
- package/dist/core/item/parent-reference-policy.js +1 -1
- package/dist/core/item/sprint-release-format.d.ts +2 -1
- package/dist/core/item/sprint-release-format.js +1 -1
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/store/item-mutation-precondition.d.ts +3 -1
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/settings.d.ts +14 -0
- package/dist/core/store/settings.js +5 -4
- package/dist/core/telemetry/policy.d.ts +27 -1
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/runtime.d.ts +18 -7
- package/dist/core/telemetry/runtime.js +4 -4
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +8 -5
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/config.d.ts +2 -2
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/health.d.ts +2 -2
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/index.d.ts +4 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init.d.ts +4 -4
- package/dist/sdk/init.js +8 -8
- package/dist/sdk/lifecycle/claim.d.ts +4 -0
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close.d.ts +10 -0
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.d.ts +7 -5
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/shared-unset-fields.d.ts +628 -4
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +5 -4
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/telemetry.d.ts +1 -1
- package/dist/sdk/telemetry.js +2 -2
- package/docs/AGENT_GUIDE.md +48 -48
- package/docs/AGENT_OUTPUT_ENCODINGS.md +20 -20
- package/docs/ASSURANCE.md +10 -10
- package/docs/BOUNDED_CONTEXT_READS.md +3 -3
- package/docs/CLAUDE_CODE_PLUGIN.md +1 -1
- package/docs/CLI_GRAMMAR.md +2 -2
- package/docs/COMMANDS.md +56 -35
- package/docs/COMMAND_NAMESPACES.md +1 -1
- package/docs/CONFIGURATION.md +82 -71
- package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +2 -2
- package/docs/CONTEXT_INTEGRITY_CONTRACTS.md +5 -5
- package/docs/CORPUS_SHAPES.md +1 -1
- package/docs/DEPENDENCY_KIND_CONTRACT.md +6 -6
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +5 -5
- package/docs/ECOSYSTEM_PLANNING_REVIEW.md +3 -3
- package/docs/EXTENSION_AUTHOR_CONTRACTS.md +4 -4
- package/docs/HISTORY_ATTESTATION.md +1 -1
- package/docs/HISTORY_MAINTENANCE.md +1 -1
- package/docs/LIFECYCLE_COMMANDS.md +1 -1
- package/docs/MCP_2026_07_28.md +16 -16
- package/docs/MCP_2026_07_28_CONFORMANCE.md +19 -19
- package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +22 -22
- package/docs/MCP_SKILLS_AND_APPS.md +1 -1
- package/docs/MERGE_SAFETY.md +6 -6
- package/docs/MUTATION_INTEGRITY.md +5 -5
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +14 -14
- package/docs/PACKED_FIRST_RUN.md +1 -1
- package/docs/QUICKSTART.md +10 -10
- package/docs/README.md +21 -21
- package/docs/READ_OUTPUT_CONTRACTS.md +9 -9
- package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +1 -1
- package/docs/RELEASING.md +19 -10
- package/docs/SCRIPTING.md +10 -10
- package/docs/SDK.md +74 -38
- package/docs/SDK_ARTIFACT_OUTPUT.md +1 -1
- package/docs/SDK_PRIMITIVE_INVENTORY.md +2 -2
- package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +7 -7
- package/docs/TESTING.md +1 -1
- package/docs/WORKFLOW_POLICIES.md +2 -2
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +8 -8
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
- package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +1 -1
- package/docs/performance/cli-transport-overhead.md +7 -7
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/README.md +5 -5
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/GAP_REPORT.md +16 -16
- 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/README.md +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/GAP_REPORT.md +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/README.md +6 -6
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-5Z6LWFDL.js +0 -31
- package/dist/cli-bundle/chunks/chunk-DSCFJTHB.js +0 -122
- package/dist/cli-bundle/chunks/chunk-QQHMNUZT.js +0 -2
- package/dist/cli-bundle/chunks/chunk-TX2W6G37.js +0 -3
- package/dist/cli-bundle/chunks/item-transaction-N5F4LXYV.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-ZZRHJ4IS.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5NGNO54M.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-B6U44WPW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BAW3DGQO.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-BHNY3KPJ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CBG67HUP.js +0 -23
- package/dist/cli-bundle/focused-chunks/chunk-FEPE2CE4.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PMKR4MJI.js +0 -2
|
@@ -49,3 +49,9 @@ export type ConfigKey = "definition_of_done" | "item_format" | "history_missing_
|
|
|
49
49
|
* can fall back to the existing invalid-key path.
|
|
50
50
|
*/
|
|
51
51
|
export declare function resolveConfigPositionalValue(canonicalKeyOrAlias:string,value:string):ConfigPositionalResult;
|
|
52
|
+
/**
|
|
53
|
+
* The scope a config call without an explicit scope targets. Telemetry consent is
|
|
54
|
+
* read only from the global profile, so `telemetry-tracking` defaults there and the
|
|
55
|
+
* documented `pm config set telemetry-tracking off` opts out (GH-1660).
|
|
56
|
+
*/
|
|
57
|
+
export declare function defaultConfigScope(key:string | undefined):"project" | "global";
|
|
@@ -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]="7a401405-3370-53a5-811d-5e52287f1d2a")}catch{}})();const FORMAT_KEYS=new Set(["item_format"]),CRITERIA_KEYS=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),POLICY_KEYS=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_start_blocker_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),ENABLED_DISABLED_POLICY_KEYS=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),ENABLED_DISABLED_SYNONYMS={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function toCanonicalKey(keyOrAlias){const normalized=keyOrAlias.trim().toLowerCase().replaceAll("-","_");if(FORMAT_KEYS.has(normalized)||CRITERIA_KEYS.has(normalized)||POLICY_KEYS.has(normalized)||normalized==="context")return normalized}function normalizeEnabledDisabled(value){const normalized=value.trim().toLowerCase();return ENABLED_DISABLED_SYNONYMS[normalized]??value}function resolveConfigPositionalValue(canonicalKeyOrAlias,value){const key=toCanonicalKey(canonicalKeyOrAlias);return key===void 0?{routable:!1,reason:`Unknown config key "${canonicalKeyOrAlias}" cannot route a positional value.`}:key==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:FORMAT_KEYS.has(key)?{routable:!0,flag:"format",value}:CRITERIA_KEYS.has(key)?{routable:!0,flag:"criterion",values:[value]}:{routable:!0,flag:"policy",value:ENABLED_DISABLED_POLICY_KEYS.has(key)?normalizeEnabledDisabled(value):value}}function defaultConfigScope(key){return/^telemetry[-_]tracking$/u.test(key??"")?"global":"project"}export{defaultConfigScope,resolveConfigPositionalValue};
|
|
2
2
|
//# sourceMappingURL=positional-value.js.map
|
|
@@ -10,3 +10,20 @@ export declare function isLiteralMutationInput(input:object,field?:PropertyKey):
|
|
|
10
10
|
export declare function preserveLiteralMutationInputFields<T extends object>(input:T,fields:Iterable<PropertyKey>):T;
|
|
11
11
|
/** Preserve literal-data provenance when an internal adapter clones an option bag. */
|
|
12
12
|
export declare function transferLiteralMutationInput<T extends object>(source:object,target:T):T;
|
|
13
|
+
/** Vocabulary a mutation refusal uses: CLI flags, or the option keys a typed SDK or MCP caller passed (GH-1655). */
|
|
14
|
+
export type MutationInputAudience = "cli" | "sdk";
|
|
15
|
+
/**
|
|
16
|
+
* Who supplied a resolved option bag. Typed SDK and MCP input is marked literal
|
|
17
|
+
* before resolution and keeps that mark; a CLI adapter's bag never carries it.
|
|
18
|
+
*/
|
|
19
|
+
export declare function mutationInputAudience(input:object):MutationInputAudience;
|
|
20
|
+
/** Name an option for its caller: `--blocked-by` on the CLI, `blockedBy` for SDK and MCP callers. */
|
|
21
|
+
export declare function mutationOptionLabel(audience:MutationInputAudience,flag:string):string;
|
|
22
|
+
/**
|
|
23
|
+
* The remedy that clears one scalar field for typed SDK and MCP callers, named
|
|
24
|
+
* by its `unset` token: the one clear form both transports accept (MCP has no
|
|
25
|
+
* typed null). The CLI keeps its own wording at each call site.
|
|
26
|
+
*/
|
|
27
|
+
export declare function sdkClearRemedy(unsetToken:string):string;
|
|
28
|
+
/** Refusal text for an empty scalar option: the CLI wording unchanged, or the SDK option key and its clear remedy. */
|
|
29
|
+
export declare function emptyMutationOptionMessage(audience:MutationInputAudience,flag:string,cliRemedy?:string):string;
|
|
@@ -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]="8dd367eb-617e-5645-8f8a-57862f8385f7")}catch{}})();const literalInputs=new WeakSet,literalFields=new WeakMap,cliInputs=new WeakSet;function markCliMutationInput(input){return cliInputs.add(input),input}function isCliMutationInput(input){return cliInputs.has(input)}function preserveLiteralMutationInput(input){literalInputs.add(input);for(const[key,value]of Object.entries(input)){if(!Array.isArray(value))continue;const owned=[...value];Reflect.set(input,key,owned),literalInputs.add(owned)}return input}function isLiteralMutationInput(input,field){return literalInputs.has(input)||field!==void 0&&literalFields.get(input)?.has(field)===!0}function preserveLiteralMutationInputFields(input,fields){const selected=new Set(fields);literalFields.set(input,selected);for(const field of selected){const value=Reflect.get(input,field);if(!Array.isArray(value))continue;const owned=[...value];Reflect.set(input,field,owned),literalInputs.add(owned)}return input}function transferLiteralMutationInput(source,target){if(isCliMutationInput(source)&&markCliMutationInput(target),isLiteralMutationInput(source))return preserveLiteralMutationInput(target);const fields=literalFields.get(source);return fields?preserveLiteralMutationInputFields(target,fields):target}function mutationInputAudience(input){return isLiteralMutationInput(input)?"sdk":"cli"}function mutationOptionLabel(audience,flag){return audience==="cli"?`--${flag}`:flag.replace(/-([a-z])/gu,(_match,letter)=>letter.toUpperCase())}function sdkClearRemedy(unsetToken){return`Pass unset: ["${unsetToken}"] to clear it`}function emptyMutationOptionMessage(audience,flag,cliRemedy=""){return audience==="cli"?`--${flag} must not be empty${cliRemedy}`:`${mutationOptionLabel("sdk",flag)} must not be empty. ${sdkClearRemedy(flag)}, or omit ${mutationOptionLabel("sdk",flag)}.`}export{emptyMutationOptionMessage,isCliMutationInput,isLiteralMutationInput,markCliMutationInput,mutationInputAudience,mutationOptionLabel,preserveLiteralMutationInput,preserveLiteralMutationInputFields,sdkClearRemedy,transferLiteralMutationInput};
|
|
2
2
|
//# sourceMappingURL=literal-mutation-input.js.map
|
|
@@ -4,15 +4,19 @@
|
|
|
4
4
|
* Defines item parsing, formatting, and lifecycle helpers for Parent Reference Policy.
|
|
5
5
|
*/
|
|
6
6
|
import type { ParentReferencePolicy } from "../../types/index.js";
|
|
7
|
+
import { type MutationInputAudience } from "./literal-mutation-input.js";
|
|
7
8
|
/** Implements normalize parent reference policy for the public runtime surface of this module. */
|
|
8
9
|
export declare function normalizeParentReferencePolicy(value:string | undefined):ParentReferencePolicy;
|
|
9
|
-
/**
|
|
10
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Normalize a parent reference. `audience` selects the refusal vocabulary: CLI
|
|
12
|
+
* flags by default, or the SDK option and its `unset` remedy for typed callers.
|
|
13
|
+
*/
|
|
14
|
+
export declare function normalizeParentReferenceValue(rawValue:unknown,audience?:MutationInputAudience):string;
|
|
11
15
|
/** Detects parent-style placeholder tokens that should never become stored ids. */
|
|
12
16
|
export declare function isPlaceholderReferenceToken(value:string):boolean;
|
|
13
17
|
/** Implements validate missing parent reference for the public runtime surface of this module. */
|
|
14
|
-
export declare function validateMissingParentReference(parentId:string,policy:ParentReferencePolicy):{
|
|
18
|
+
export declare function validateMissingParentReference(parentId:string,policy:ParentReferencePolicy,audience?:MutationInputAudience):{
|
|
15
19
|
warnings:string[];
|
|
16
20
|
};
|
|
17
21
|
/** Rejects the one-node hierarchy cycle where an item points at itself. */
|
|
18
|
-
export declare function assertParentReferenceIsNotSelf(itemId:string,parentId:string,prefix:string):void;
|
|
22
|
+
export declare function assertParentReferenceIsNotSelf(itemId:string,parentId:string,prefix:string,audience?:MutationInputAudience):void;
|
|
@@ -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]="0394e0c1-ff68-5553-b022-1e8b6fff04f0")}catch{}})();import{normalizeItemId}from"./id.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{emptyMutationOptionMessage,sdkClearRemedy}from"./literal-mutation-input.js";const PLACEHOLDER_REFERENCE_TOKENS=new Set(["none","null","undefined"]);function normalizeParentReferencePolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="warn"||normalized==="strict_error")return normalized;if(normalized==="strict")return"strict_error";throw new PmCliError("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",EXIT_CODE.USAGE)}function normalizeParentReferenceValue(rawValue,audience="cli"){const sdk=audience==="sdk";if(typeof rawValue!="string")throw new PmCliError(sdk?`parent must be a string. ${sdkClearRemedy("parent")}.`:"--parent must be a string. Use --unset parent to clear this field.",EXIT_CODE.USAGE);const value=rawValue.trim();if(value.length===0)throw new PmCliError(emptyMutationOptionMessage(audience,"parent",". Use --parent none to unset."),EXIT_CODE.USAGE);if(isPlaceholderReferenceToken(value))throw new PmCliError(sdk?`parent must not be the placeholder "${value}". ${sdkClearRemedy("parent")}, or omit parent.`:`--parent must not use placeholder token "${value}". Use --unset parent to clear this field.`,EXIT_CODE.USAGE);return value}function isPlaceholderReferenceToken(value){return PLACEHOLDER_REFERENCE_TOKENS.has(value.trim().toLowerCase())}function validateMissingParentReference(parentId,policy,audience="cli"){if(policy==="strict_error")throw new PmCliError(`Parent item "${parentId}" was not found. Create it first or ${audience==="sdk"?"omit parent":"use --parent none"}.`,EXIT_CODE.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${parentId}`]}}function assertParentReferenceIsNotSelf(itemId,parentId,prefix,audience="cli"){const normalizedItemId=normalizeItemId(itemId,prefix),normalizedParentId=normalizeItemId(parentId,prefix);if(normalizedItemId!==normalizedParentId)return;const normalizationDetail=parentId!==normalizedParentId||itemId!==normalizedItemId?` (normalized from parent "${parentId}" and item "${itemId}")`:"";throw new PmCliError(`Parent item "${normalizedParentId}" cannot be the same as item "${normalizedItemId}"${normalizationDetail}. ${audience==="sdk"?`${sdkClearRemedy("parent")}.`:"Use --unset parent to clear this field."}`,EXIT_CODE.USAGE)}export{assertParentReferenceIsNotSelf,isPlaceholderReferenceToken,normalizeParentReferencePolicy,normalizeParentReferenceValue,validateMissingParentReference};
|
|
2
2
|
//# sourceMappingURL=parent-reference-policy.js.map
|
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
* Defines item parsing, formatting, and lifecycle helpers for Sprint Release Format.
|
|
5
5
|
*/
|
|
6
6
|
import type { SprintReleaseFormatPolicy } from "../../types/index.js";
|
|
7
|
+
import { type MutationInputAudience } from "./literal-mutation-input.js";
|
|
7
8
|
/** Implements normalize sprint release format policy for the public runtime surface of this module. */
|
|
8
9
|
export declare function normalizeSprintReleaseFormatPolicy(value:string | undefined):SprintReleaseFormatPolicy;
|
|
9
10
|
/** Implements validate sprint or release value for the public runtime surface of this module. */
|
|
10
|
-
export declare function validateSprintOrReleaseValue(field:"sprint" | "release",rawValue:string,policy:SprintReleaseFormatPolicy):{
|
|
11
|
+
export declare function validateSprintOrReleaseValue(field:"sprint" | "release",rawValue:string,policy:SprintReleaseFormatPolicy,audience?:MutationInputAudience):{
|
|
11
12
|
value:string;
|
|
12
13
|
warnings:string[];
|
|
13
14
|
};
|
|
@@ -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]="6012e77b-7cdd-5496-a668-c9240a811b1a")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{emptyMutationOptionMessage}from"./literal-mutation-input.js";const SPRINT_RELEASE_VALUE_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,SPRINT_RELEASE_MAX_LENGTH=64;function normalizeSprintReleaseFormatPolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="warn"||normalized==="strict_error")return normalized;if(normalized==="strict")return"strict_error";throw new PmCliError("Config set sprint-release-format-policy requires --policy with one of: warn, strict_error (alias: strict)",EXIT_CODE.USAGE)}function validateSprintOrReleaseValue(field,rawValue,policy,audience="cli"){const value=rawValue.trim();if(value.length===0)throw new PmCliError(emptyMutationOptionMessage(audience,field,`. Use --${field} none to unset.`),EXIT_CODE.USAGE);if(value.length<=SPRINT_RELEASE_MAX_LENGTH&&SPRINT_RELEASE_VALUE_PATTERN.test(value))return{value,warnings:[]};const guidance="Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._/-]* (no spaces).";if(policy==="strict_error")throw new PmCliError(`Invalid ${audience==="sdk"?field:`--${field}`} value "${value}". ${guidance}`,EXIT_CODE.USAGE);return{value,warnings:[`validation_warning:${field}_format:${value}`]}}export{normalizeSprintReleaseFormatPolicy,validateSprintOrReleaseValue};
|
|
2
2
|
//# sourceMappingURL=sprint-release-format.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]="
|
|
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]="2335ae7f-c7aa-5bdd-ac2e-e6d7a74be2e1")}catch{}})();import{unicodeSafePrefix}from"../shared/text-normalization.js";const CHANGED_FIELDS_KEY="changed_fields",CHANGED_FIELD_COUNT_KEY="changed_field_count",ROWS_KEY="rows",UPDATE_MANY_MUTATION_MODES=new Set(["apply","rollback"]),DELETE_OUTCOMES=new Set(["deleted","would_delete"]),COMPACT_RECURRENCE_TEXT_LIMIT=256,COMPOUND_MUTATION_STEPS={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function projectCompoundMutation(result,options){if(!isPlainObject(result)||typeof result.action!="string"||typeof result.id!="string"||result.id.length===0)return null;const steps=Object.hasOwn(COMPOUND_MUTATION_STEPS,result.action)?COMPOUND_MUTATION_STEPS[result.action]:void 0;if(!steps||!steps.every(step=>{const value=result[step];return isPlainObject(value)&&isPlainObject(value.item)&&value.item.id===result.id&&Array.isArray(value.changed_fields)&&value.changed_fields.every(field=>typeof field=="string")}))return null;const final=result[steps.at(-1)],identity=projectIdOnlyResult(final);return options.idOnly?identity:!options.compactEnvelope&&options.changedFields!=="compact"?null:{...result,...options.compactEnvelope?{...identity,changed_field_count:new Set(steps.flatMap(step=>result[step].changed_fields)).size}:{},...Object.fromEntries(steps.map(step=>[step,projectMutationResult(result[step],options)]))}}function truncateCompactRecurrenceText(value){return typeof value!="string"||value.length<=COMPACT_RECURRENCE_TEXT_LIMIT?value:`${unicodeSafePrefix(value,COMPACT_RECURRENCE_TEXT_LIMIT-1)}\u2026`}function projectCompactRecurrence(value){if(!isPlainObject(value))return null;const recurrence={...value};return recurrence.reason=truncateCompactRecurrenceText(recurrence.reason),isPlainObject(recurrence.previous_terminal)&&(recurrence.previous_terminal=Object.fromEntries(Object.entries(recurrence.previous_terminal).map(([key,entry])=>[key,truncateCompactRecurrenceText(entry)]))),recurrence}function isPlainObject(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function compactOwnChangedFields(envelope){const changedFields=envelope[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields))return null;const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};for(const[key,value]of Object.entries(envelope))key!==CHANGED_FIELDS_KEY&&(projected[key]=value);return projected[CHANGED_FIELD_COUNT_KEY]=changedFields.length,projected}function isMutationEnvelope(value){return"item"in value&&Array.isArray(value[CHANGED_FIELDS_KEY])}function isUpdateManyMutationEnvelope(value){return typeof value.mode=="string"&&UPDATE_MANY_MUTATION_MODES.has(value.mode)&&Array.isArray(value[ROWS_KEY])}function replaceRows(envelope,rows){const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};return Object.assign(projected,envelope),projected[ROWS_KEY]=rows,projected}function projectIdOnlyResult(result){if(!isPlainObject(result))return null;const subject=isPlainObject(result.item)?result.item:isPlainObject(result.plan)?result.plan:null;if(subject===null)return null;const id=typeof subject.id=="string"?subject.id:void 0,status=typeof result.outcome=="string"&&DELETE_OUTCOMES.has(result.outcome)?result.outcome:typeof subject.status=="string"?subject.status:void 0;return id?status?{id,status,...typeof result.deleted=="boolean"?{deleted:result.deleted}:{}}:{id}:null}function projectCompactMutationEnvelope(result,includeItem){if(!isPlainObject(result))return null;if(isPlainObject(result.plan)&&isPlainObject(result.mutation_receipt)&&result.mutation_receipt.kind==="plan_mutation"&&result.mutation_receipt.id===result.plan.id&&result.mutation_receipt.action===result.action)return result.mutation_receipt;if(!includeItem||!isPlainObject(result.item)||typeof result.item.id!="string")return null;const changedFields=result[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields))return null;const compact={id:result.item.id,...typeof result.outcome=="string"&&DELETE_OUTCOMES.has(result.outcome)?{status:result.outcome}:typeof result.item.status=="string"?{status:result.item.status}:{},...typeof result.deleted=="boolean"?{deleted:result.deleted}:{},...typeof result.previous_status=="string"?{previous_status:result.previous_status}:{},changed_field_count:changedFields.length};return appendCompactMutationEvidence(result,result.item,compact),compact}function appendCompactMutationEvidence(result,item,compact){const closeReason=typeof result.close_reason=="string"?result.close_reason:typeof item.close_reason=="string"?item.close_reason:void 0;closeReason!==void 0&&(compact.close_reason=closeReason);const recurrence=projectCompactRecurrence(result.recurrence);recurrence!==null&&(compact.recurrence=recurrence),Array.isArray(result.warnings)&&result.warnings.length>0&&(compact.warnings=result.warnings);for(const key of["recovery","follow_up","handoff","completion","start"])isPlainObject(result[key])&&(compact[key]=result[key]);if(typeof result.claimed_by=="string"||typeof result.released_by=="string")for(const key of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","start_refused","suggestions"])Object.hasOwn(result,key)&&(compact[key]=result[key])}function compactUpdateManyRows(envelope){const rows=isUpdateManyMutationEnvelope(envelope)?envelope[ROWS_KEY]:void 0;if(!Array.isArray(rows))return{projected:envelope,changed:!1};let rowsChanged=!1;const nextRows=rows.map(row=>{if(!isPlainObject(row))return row;const compactedRow=compactOwnChangedFields(row);return compactedRow?(rowsChanged=!0,compactedRow):row});return rowsChanged?{projected:replaceRows(envelope,nextRows),changed:!0}:{projected:envelope,changed:!1}}function projectMutationResult(result,options={}){const compound=projectCompoundMutation(result,options);if(compound!==null)return compound;if(options.idOnly===!0){const idOnly=projectIdOnlyResult(result);if(idOnly!==null)return idOnly}if(options.compactEnvelope===!0||options.changedFields==="compact"){const compact=projectCompactMutationEnvelope(result,options.compactEnvelope===!0);if(compact!==null)return compact}if((options.changedFields??"full")==="full"||!isPlainObject(result))return result;let changed=!1,projected=result;const compactedTop=isMutationEnvelope(result)?compactOwnChangedFields(result):null;compactedTop!==null&&(projected=compactedTop,changed=!0);const rowProjection=compactUpdateManyRows(projected);return rowProjection.changed&&(projected=rowProjection.projected,changed=!0),changed?projected:result}export{projectMutationResult};
|
|
2
2
|
//# sourceMappingURL=mutation-projection.js.map
|
|
@@ -76,8 +76,10 @@ export declare function assertItemMutationPreconditions(pmRoot:string,document:I
|
|
|
76
76
|
* Notify matching scoped guards of their own committed document (a tombstone
|
|
77
77
|
* after delete) before releasing the item lock. `aliasIds` carries identities
|
|
78
78
|
* the committed document no longer has, such as a deleted item's embedded id.
|
|
79
|
+
* `revision` overrides the document's hash when the stored state is not that
|
|
80
|
+
* document (a storage override persisted something the store cannot parse).
|
|
79
81
|
*/
|
|
80
|
-
export declare function advanceItemMutationPreconditions(pmRoot:string,document:ItemDocument,targetId?:string,aliasIds?:readonly string[]):void;
|
|
82
|
+
export declare function advanceItemMutationPreconditions(pmRoot:string,document:ItemDocument,targetId?:string,aliasIds?:readonly string[],revision?:string):void;
|
|
81
83
|
/** Collect target-scoped immutable attribution (keyed by either identity of the locked item) without attributing another caller's writes. */
|
|
82
84
|
export declare function itemMutationPreconditionHistoryContext(pmRoot:string,ids:readonly unknown[]):Record<string,unknown>;
|
|
83
85
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="82ccccc7-c505-51c2-b207-93afa945f718")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{realpathSync}from"node:fs";import path from"node:path";import{hashDocument}from"../history/history.js";import{sha256Hex}from"../shared/serialization.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const preconditions=new AsyncLocalStorage;function runWithItemMutationPrecondition(condition,operation){return preconditions.run([...preconditions.getStore()??[],{...condition,pmRoot:path.resolve(condition.pmRoot)}],operation)}const REVISION_SCOPES_KEY=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),revisionScopeRegistry=globalThis,revisionScopes=revisionScopeRegistry[REVISION_SCOPES_KEY]??=new AsyncLocalStorage;function canonicalTrackerRoot(pmRoot){const resolved=path.resolve(pmRoot);try{return realpathSync.native(resolved)}catch{return resolved}}function createItemRevisionScope(){return{entries:new Map}}function runWithItemRevisionScope(scope,operation){return revisionScopes.run([...revisionScopes.getStore()??[],scope],operation)}function bindItemRevisionScope(scope,pmRoot,expectations){const resolvedRoot=canonicalTrackerRoot(pmRoot);if(scope.pmRoot!==void 0&&scope.pmRoot!==resolvedRoot)throw new PmCliError("An expected-revision scope is already bound to another tracker.",EXIT_CODE.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});scope.pmRoot=resolvedRoot;for(const{id,itemHash}of expectations){const existing=scope.entries.get(id);if(existing!==void 0&&existing.declared!==itemHash)throw new PmCliError(`Item ${id} has two different expected revisions.`,EXIT_CODE.USAGE,{code:"expected_revision_duplicate",item_id:id,required:"Declare at most one expected revision per item."});scope.entries.set(id,existing??{declared:itemHash,expected:itemHash,checked:!1,committed:!1})}}function itemRevisionScopeReceipt(scope){const entries=[...scope.entries.entries()];return{checked:entries.filter(([,entry])=>entry.checked).map(([id])=>id),unchecked:entries.filter(([,entry])=>!entry.checked).map(([id])=>id)}}function matchingRevisionEntries(pmRoot,ids){const scopes=revisionScopes.getStore()??[];if(scopes.length===0)return[];const resolvedRoot=canonicalTrackerRoot(pmRoot),keys=new Set(ids.filter(id=>typeof id=="string"));return[...new Set(scopes.flatMap(scope=>scope.pmRoot===resolvedRoot?[...keys].flatMap(key=>scope.entries.get(key)??[]):[]))]}function hasActiveItemRevisionScope(pmRoot){const resolvedRoot=canonicalTrackerRoot(pmRoot);return(revisionScopes.getStore()??[]).some(scope=>scope.pmRoot===resolvedRoot&&scope.entries.size>0)}function assertItemRevisionExpectations(pmRoot,document,targetId){const entries=matchingRevisionEntries(pmRoot,[targetId,document.metadata.id]);entries.length>0&&assertRevisionEntries(entries,targetId,hashDocument(document),!1)}function assertItemRevisionExpectationsOnUnreadable(pmRoot,targetId,raw){const entries=matchingRevisionEntries(pmRoot,[targetId]);entries.length>0&&assertRevisionEntries(entries,targetId,sha256Hex(raw),!0)}function assertRevisionEntries(entries,targetId,current,unreadable){for(const entry of entries)if(entry.checked=!0,!(!unreadable&&entry.expected===current))throw new PmCliError(`Item ${targetId} is no longer at the expected revision ${entry.expected.slice(0,12)}${unreadable?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${entry.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,EXIT_CODE.CONFLICT,{code:"item_revision_conflict",item_id:targetId,expected_revision:entry.expected,current_revision:current,required:unreadable?`Recover ${targetId} without --expect-hash (pm restore ${targetId} <version>), since no declared revision describes an unreadable document.`:`Re-read ${targetId} (pm get ${targetId} --json reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",examples:[`pm get ${targetId} --fields item_hash --json`,`pm history ${targetId} --limit 5`],nextSteps:[`pm get ${targetId} --json`,`pm history ${targetId} --limit 5`]})}function assertItemMutationPreconditions(pmRoot,document,targetId=document.metadata.id){assertItemRevisionExpectations(pmRoot,document,targetId);for(const condition of conditionsFor(pmRoot,[targetId,document.metadata.id]))condition.validate(document)}function conditionsFor(pmRoot,ids){const resolvedRoot=path.resolve(pmRoot);return(preconditions.getStore()??[]).filter(condition=>condition.pmRoot===resolvedRoot&&ids.includes(condition.id))}function advanceItemMutationPreconditions(pmRoot,document,targetId=document.metadata.id,aliasIds=[],revision){const entries=matchingRevisionEntries(pmRoot,[targetId,document.metadata.id,...aliasIds]);if(entries.length>0){const committed=revision??hashDocument(document);for(const entry of entries)entry.expected=committed,entry.committed=!0}for(const condition of conditionsFor(pmRoot,[targetId,document.metadata.id,...aliasIds]))condition.committed?.(document)}function itemMutationPreconditionHistoryContext(pmRoot,ids){return Object.assign({},...conditionsFor(pmRoot,ids).map(condition=>condition.historyContext))}export{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable,bindItemRevisionScope,createItemRevisionScope,hasActiveItemRevisionScope,itemMutationPreconditionHistoryContext,itemRevisionScopeReceipt,runWithItemMutationPrecondition,runWithItemRevisionScope};
|
|
2
2
|
//# sourceMappingURL=item-mutation-precondition.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]="22232262-8057-5248-b462-1223d34a4570")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,itemMutationPreconditionHistoryContext}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext}from"../checkpoint/mutation-context.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease}from"../lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{code:"item_not_found",id:badId,nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const lease=await acquireLockLease(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),assigned=document.metadata.assignee?.trim(),assignedPrincipal=document.metadata.claim_principal?.trim()||assigned,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock,lease}}catch(error){throw await releaseLock(),error}}async function commitLockedItemWrite(lease,located,originalRaw,commit){return lease.fence(async()=>{let currentRaw;try{currentRaw=await fs.readFile(located.itemPath,"utf8")}catch(error){if(!isFileMissingError(error))throw error;currentRaw=null}if(currentRaw!==originalRaw)throw new PmCliError(`Item ${located.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,EXIT_CODE.CONFLICT,{code:"stale_revision",item_id:located.id,reason:currentRaw===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return commit()})}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function resolveItemStoreDeleteOverride(payload){const override=await runActiveServiceOverride("item_store_delete",payload),record=override.handled&&typeof override.result=="object"&&override.result!==null?override.result:{};return{effectiveItemPath:typeof record.item_path=="string"&&record.item_path.trim().length>0?record.item_path:payload.item_path,skipDelete:record.skip_delete===!0,warnings:override.warnings}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document,located.id);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument);if(params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext={...params.resolveHistoryContext?.(),...checkpointMutationHistoryContext(params.pmRoot,located.id),...itemMutationPreconditionHistoryContext(params.pmRoot,[located.id,document.metadata.id])},requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath:effectiveTargetItemPath2,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath2,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath2!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?Object.keys(historyContext).length===0?void 0:historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath:effectiveTargetItemPath2,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath2,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveTargetItemPath:effectiveTargetItemPath2,overrideWarnings:serviceWriteOverride.warnings}}),{derivedIndexWarnings,effectiveTargetItemPath}=committed;advanceItemMutationPreconditions(params.pmRoot,afterDocument,located.id);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document,located.id);const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}}),historyPath=getHistoryPath(params.pmRoot,located.id),runDeleteOverride=()=>resolveItemStoreDeleteOverride({op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});if(params.dryRun===!0){const preview=await runDeleteOverride();return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:preview.effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...preview.warnings]}}const committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const{effectiveItemPath:effectiveItemPath2,skipDelete,warnings}=await runDeleteOverride(),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipDelete||await fs.rm(effectiveItemPath2);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath2,originalRaw),error}skipDelete||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath2,document:null}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveItemPath:effectiveItemPath2,overrideWarnings:warnings}}),{derivedIndexWarnings,effectiveItemPath}=committed;advanceItemMutationPreconditions(params.pmRoot,tombstoneDocument,located.id,[document.metadata.id]);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
|
|
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]="2bc3df8a-c200-52a0-8227-0deda053a955")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,itemMutationPreconditionHistoryContext}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext}from"../checkpoint/mutation-context.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease}from"../lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{nowIso}from"../shared/time.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{code:"item_not_found",id:badId,nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const lease=await acquireLockLease(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),assigned=document.metadata.assignee?.trim(),assignedPrincipal=document.metadata.claim_principal?.trim()||assigned,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock,lease}}catch(error){throw await releaseLock(),error}}async function commitLockedItemWrite(lease,located,originalRaw,commit){return lease.fence(async()=>{let currentRaw;try{currentRaw=await fs.readFile(located.itemPath,"utf8")}catch(error){if(!isFileMissingError(error))throw error;currentRaw=null}if(currentRaw!==originalRaw)throw new PmCliError(`Item ${located.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,EXIT_CODE.CONFLICT,{code:"stale_revision",item_id:located.id,reason:currentRaw===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return commit()})}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function readOverriddenCommitRevision(params){try{const located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return{document:EMPTY_CANONICAL_DOCUMENT};const document=parseItemDocument(await fs.readFile(located.itemPath,"utf8"),{format:located.item_format,requireSupportedFormat:!0,schema:params.settings.schema,extensionFieldNames:resolveActiveExtensionFieldNames(params.extensionFieldNames)});return document.metadata.id===params.embeddedId?{document}:{document:params.fallback,revision:UNREADABLE_COMMIT_REVISION}}catch{return{document:params.fallback,revision:UNREADABLE_COMMIT_REVISION}}}const UNREADABLE_COMMIT_REVISION="unreadable-after-storage-override";async function resolveItemStoreDeleteOverride(payload){const override=await runActiveServiceOverride("item_store_delete",payload),record=override.handled&&typeof override.result=="object"&&override.result!==null?override.result:{};return{effectiveItemPath:typeof record.item_path=="string"&&record.item_path.trim().length>0?record.item_path:payload.item_path,skipDelete:record.skip_delete===!0,warnings:override.warnings}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document,located.id);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument);if(params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext={...params.resolveHistoryContext?.(),...checkpointMutationHistoryContext(params.pmRoot,located.id),...itemMutationPreconditionHistoryContext(params.pmRoot,[located.id,document.metadata.id])},requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath:effectiveTargetItemPath2,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath2,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath2!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:workflowPolicy.decisions.length===0?Object.keys(historyContext).length===0?void 0:historyContext:{...historyContext,workflow_policies:workflowPolicy.decisions}});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath:effectiveTargetItemPath2,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath2,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}const overridden=skipItemWrite||effectiveTargetItemPath2!==targetItemPath||effectiveSerializedAfter!==serializedAfter;return{derivedIndexWarnings:derivedIndexWarnings2,effectiveTargetItemPath:effectiveTargetItemPath2,overrideWarnings:serviceWriteOverride.warnings,stored:overridden?await readOverriddenCommitRevision({pmRoot:params.pmRoot,settings:params.settings,id:located.id,typeToFolder,extensionFieldNames:params.extensionFieldNames,fallback:afterDocument,embeddedId:afterDocument.metadata.id}):{document:afterDocument}}}),{derivedIndexWarnings,effectiveTargetItemPath,stored}=committed;advanceItemMutationPreconditions(params.pmRoot,stored.document,located.id,[afterDocument.metadata.id],stored.revision);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document,located.id);const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}}),historyPath=getHistoryPath(params.pmRoot,located.id),runDeleteOverride=()=>resolveItemStoreDeleteOverride({op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});if(params.dryRun===!0){const preview=await runDeleteOverride();return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:preview.effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...preview.warnings]}}const committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const{effectiveItemPath:effectiveItemPath2,skipDelete,warnings}=await runDeleteOverride(),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipDelete||await fs.rm(effectiveItemPath2);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath2,originalRaw),error}skipDelete||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath2,document:null}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveItemPath:effectiveItemPath2,overrideWarnings:warnings,stored:skipDelete||effectiveItemPath2!==located.itemPath?await readOverriddenCommitRevision({pmRoot:params.pmRoot,settings:params.settings,id:located.id,typeToFolder:prepared.typeToFolder,fallback:tombstoneDocument,embeddedId:document.metadata.id}):{document:tombstoneDocument}}}),{derivedIndexWarnings,effectiveItemPath,stored}=committed;advanceItemMutationPreconditions(params.pmRoot,stored.document,located.id,[document.metadata.id],stored.revision);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
|
|
2
2
|
//# sourceMappingURL=item-store.js.map
|
|
@@ -127,6 +127,20 @@ export interface WriteSettingsOptions {
|
|
|
127
127
|
* option (pm-4zpq71).
|
|
128
128
|
*/
|
|
129
129
|
assignedPaths?:readonly string[];
|
|
130
|
+
/**
|
|
131
|
+
* Top-level sections a full write (one without a stored-document snapshot)
|
|
132
|
+
* leaves out unless the stored document already has them. Snapshot writes
|
|
133
|
+
* keep the stored shape, so an omitted section stays absent (GH-1660: project
|
|
134
|
+
* files carry no telemetry block, which only the global profile governs).
|
|
135
|
+
*/
|
|
136
|
+
omitSections?:readonly "telemetry"[];
|
|
137
|
+
/**
|
|
138
|
+
* Compare-and-set, consulted under the settings lock with the stored
|
|
139
|
+
* document when one exists. Returning true writes nothing: the file, its
|
|
140
|
+
* history and the caller's snapshot stay unchanged, so a value another writer
|
|
141
|
+
* recorded after the caller's read stands (GH-1660).
|
|
142
|
+
*/
|
|
143
|
+
skipIfStored?:(stored:unknown) => boolean;
|
|
130
144
|
}
|
|
131
145
|
/** Implements read settings for the public runtime surface of this module. */
|
|
132
146
|
export declare function readSettings(pmRoot:string):Promise<PmSettings>;
|