@unbrained/pm-cli 2026.11.21 → 2026.11.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/pm-developer/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-PJXKA4QU.js → chunk-4TB5D6HL.js} +37 -37
- package/dist/cli-bundle/chunks/{chunk-WELSVDPU.js → chunk-5ZMVLWE3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +33 -0
- package/dist/cli-bundle/chunks/{chunk-JVGRFU5H.js → chunk-AR4NP5HI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XHJ3H5PL.js → chunk-B4PPFOPY.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-5647LU3A.js → chunk-B76TFRO2.js} +47 -45
- package/dist/cli-bundle/chunks/{chunk-YJEBK7HU.js → chunk-CAR2L5NW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D6ILFXZY.js → chunk-EIGUKEV6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XWHJIRNV.js → chunk-GTPCAJMZ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-CASX6SFI.js → chunk-HC2OPETM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NCFCBKIP.js → chunk-HKUV74K3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-S6HB3WL2.js → chunk-J2LABXBL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BKSVHOWI.js → chunk-J52BEBSS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NT5AKFE5.js → chunk-OJTMGDON.js} +31 -31
- package/dist/cli-bundle/chunks/{chunk-SRVTCYAU.js → chunk-TC6XLIYO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AHQB7W2H.js → chunk-U7EL3AYA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-CIKGG34F.js → chunk-X6MIWTTT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-RMIRNYRG.js → chunk-XFHPKXAE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6QLEXRUG.js → chunk-YHVLVSEZ.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-4QBMZXKX.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-3TG636XG.js → mutation-actor-FWLYWJ37.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-LICSDNNO.js → mutation-admission-7ZDCK3G2.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-RR5KACJ3.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-WWVECKFQ.js → register-mutation-57AJQWFV.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-L6HFJNWD.js → register-operations-RKWST7CU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-K7UFG5TD.js → register-setup-CMI23PC5.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-57KH3KAC.js → stage-4KDVXC5Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YOAYY3HE.js → chunk-2ZD7275J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-532WZV65.js → chunk-324AHXJO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QGKLRXP7.js → chunk-4JZITIJB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-CU2BRAOX.js → chunk-4KTFKSS3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MKM5NKD7.js → chunk-BRZV7BFV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RPE6IX26.js → chunk-HDEKFSOK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LNHUE4VV.js → chunk-IWOXAUDU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-J63D6QST.js → chunk-ML3JHCC6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JMQJBZQ5.js → chunk-OPGOOP25.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XCJSHNXK.js → chunk-RE7ZWT7D.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-WXMI4AV5.js → chunk-RQ252B6V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7A4QWNZX.js → chunk-URGHTTT3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IQK5NPMG.js → chunk-USPYKWQG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-UOC6257J.js → chunk-WZWXGDYY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NP72ZDXE.js → chunk-YKSLZPLT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +2 -0
- package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-2O6MLPEX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-actor-62HKR5IO.js → mutation-actor-TCYDPUGG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-X4PF2SG3.js → mutation-admission-LY73EJWM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-O7T7CXBB.js → stage-DQ7RQQ52.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +70 -58
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/history/bridge.js +2 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history.d.ts +12 -0
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.d.ts +9 -0
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.d.ts +46 -5
- package/dist/core/history/replay.js +2 -2
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
- package/dist/sdk/completion/fish.js +3 -2
- package/dist/sdk/completion/zsh.js +3 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/history/append-only-repair.d.ts +30 -0
- package/dist/sdk/history/append-only-repair.js +6 -0
- package/dist/sdk/history/maintenance.d.ts +8 -2
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +2 -0
- package/dist/sdk/history/reseed.d.ts +15 -0
- package/dist/sdk/history/reseed.js +2 -0
- package/dist/sdk/history/salvage.d.ts +19 -8
- package/dist/sdk/history/salvage.js +5 -3
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.d.ts +8 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/merge/three-way.d.ts +22 -3
- package/dist/sdk/merge/three-way.js +8 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +6 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +7 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +5 -5
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/transactions/item-finalization.js +2 -0
- package/dist/types.d.ts +20 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
- package/docs/COMMANDS.md +6 -2
- package/docs/HISTORY_RECOVERY.md +229 -5
- package/docs/README.md +2 -2
- package/docs/SDK.md +103 -4
- package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
- package/marketplace.json +1 -1
- package/node_modules/tar/package.json +2 -3
- package/package.json +30 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
- package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
- package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
- package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
- package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
- package/dist/sdk/agent/refusal-closure.js +0 -2
- package/dist/sdk/agent/refusal-reachability.js +0 -4
- package/dist/sdk/agent/task-transcript-contracts.js +0 -2
- package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
- package/dist/sdk/authoring.js +0 -2
- package/dist/sdk/compose.js +0 -2
- package/dist/sdk/contracts.js +0 -2
- package/dist/sdk/core-governance.js +0 -2
- package/dist/sdk/core.js +0 -2
- package/dist/sdk/corpus-shape.js +0 -2
- package/dist/sdk/define.js +0 -2
- package/dist/sdk/environment/agent-environment.js +0 -2
- package/dist/sdk/governance/artifact-ledgers.js +0 -2
- package/dist/sdk/governance/coverage-assurance.js +0 -2
- package/dist/sdk/governance/reliability.js +0 -2
- package/dist/sdk/governance.js +0 -2
- package/dist/sdk/graph/adapter.js +0 -2
- package/dist/sdk/graph/conformance.js +0 -2
- package/dist/sdk/graph/index.js +0 -2
- package/dist/sdk/graph.js +0 -2
- package/dist/sdk/index.js +0 -2
- package/dist/sdk/query.js +0 -2
- package/dist/sdk/relationship-migration.js +0 -2
- package/dist/sdk/testing.js +0 -8
- package/dist/sdk/workspace-recipe.js +0 -2
- package/docs/AGENT_PROVENANCE_ADR.md +0 -206
- package/docs/DEFECT_RECURRENCE.md +0 -257
- package/docs/PERFORMANCE.md +0 -204
package/dist/sdk/index.d.ts
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Defines public SDK APIs and package-author helpers for Index.
|
|
5
5
|
*/
|
|
6
|
-
export type{CompletionRuntimeConfig}from "./completion.js";export{isItemAlreadyExistsError,type PmItemAlreadyExistsError,isPmTokenBudgetRecovery,type PmTokenBudgetRecovery,PM_CLI_ERROR_DETAILS_LIMITS,isPmCliErrorDetails,projectPmCliErrorDetails,projectPmCliErrorContextDetails,snapshotPmCliErrorContext,type PmCliErrorDetails,type PmCliErrorDetailValue,type PmCliErrorDetailsOmission,type PmCliErrorDetailsRejection}from "./errors.js";export{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,renderPmCommandVisibilityMarkdown,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier,}from "./agent-capability-contracts.js";export * from "./mcp/protocol.js";export * from "./mcp/executable.js";export * from "./mcp/interactions.js";export * from "./mcp/tasks.js";export * from "./mcp/subscriptions.js";export * from "./mcp/transport.js";export * from "./mcp/authorization.js";export * from "./mcp/apps.js";export * from "./mcp/skills.js";export * from "./cli-contracts/grammar-contracts.js";export * from "./agent-session-context.js";export * from "./environment/agent-environment.js";export type{PmCommandCapabilityContract,PmCommandCapabilityFamily,PmCommandVisibilityContract,PmCommandVisibilityTier,PmMcpPromptArgumentContract,PmMcpPromptContract,PmMcpResourceContract,PmMcpToolProfile,}from "./agent-capability-contracts.js";export{isErrnoError,limitAnnotationEntries,parseAnnotationTextInput,readAnnotationEntries,normalizeAnnotationTransportOptions,resolveAnnotationInput,resolveAnnotationIndex,runAnnotationCommand,wrapOwnershipConflict,type AnnotationCommandConfig,type AnnotationCommandOptions,type AnnotationCommandResult,type AnnotationEntry,type AnnotationInput,type AnnotationHistoryRestoration,type AnnotationMutationReceipt,type AnnotationOmissionReceipt,type AnnotationSourceOptions,type IndexedAnnotationEntry,type OwnershipConflictGuidance,}from "./annotations.js";export{acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,inspectHistoryAuthorStream,parseUnknownAuthorHistoryEventCoordinates,planUnknownAuthorHistoryAcknowledgment,resolveUnknownAuthorAcknowledgmentSelector,scanHistoryAuthorAttribution,type AcknowledgeUnknownAuthorEventsOptions,type HistoryAuthorAttributionScan,type UnknownAuthorAcknowledgmentPlan,type UnknownAuthorAcknowledgmentPlanCoordinate,type UnknownAuthorAcknowledgmentResult,type UnknownAuthorHistoryEvent,}from "./author-attribution.js";export{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape,type BuiltinCorpusShapeName,type CorpusShape,type CorpusShapeEdgeWeight,type CorpusShapeItemPlan,type CorpusShapeMeasurement,type CorpusShapeProfile,}from "./corpus-shape.js";export * from "./core-governance.js";export{createPmCliProgram}from "./cli-program.js";export{runSearchRefreshWorkerEntrypoint}from "./search-refresh-worker.js";export{PM_REPRODUCIBLE_PROCESS_ENV,createReproducibleProcessRunner,resolveReproducibleProcessEnvironment,runWithReproducibleProcessEnvironment,type ReproducibleExecutionSettings,type ReproducibleProcessEnvironment,type ReproducibleProcessRunner,}from "./reproducibility/process.js";export{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe,type WorkspaceRecipe,type WorkspaceRecipeJsonValue,type WorkspaceRecipeOperation,}from "./workspace-recipe.js";export{SNAPSHOT_SCHEMA,WORKSPACE_SNAPSHOT_ACTIONS,createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery,type CreateWorkspaceSnapshotResult,type RestoreWorkspaceSnapshotOptions,type RestoreWorkspaceSnapshotResult,type WorkspaceSnapshotHistoryImpact,type WorkspaceSnapshotManifest,type WorkspaceSnapshotReference,type WorkspaceSnapshotRestorePlan,}from "./workspace-snapshot.js";export{flushTelemetryQueue}from "./telemetry-flush.js";export{PM_HISTORY_COMMAND_ALIASES,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,findPmNamespacedCommand,resolvePmCommandOperation,resolvePmHistoryOperation}from "./cli-contracts.js";export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,type PmCommandAliasContract,type PmCommandAliasLifecycle,type PmCommandAliasRegistration,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,stripGlobalBootstrapTokens,type BootstrapGlobalOptions,type BootstrapHelpRequest,type BootstrapInvocationNormalizationResult,type BootstrapNormalizationEvent,}from "./cli-bootstrap.js";export{quoteCommandArg,quoteWindowsCommandArg,redactUrlCredentialsInText,redactUrlCredentialsInToken,renderPmCommand,resolvePmCommandScopeArgs,URL_CREDENTIAL_PLACEHOLDER,}from "./command-line.js";export * from "./agent/command-recovery.js";export * from "./agent/linked-resource-recovery.js";export * from "./agent/command-suggestions.js";export * from "./agent/item-addressing.js";export * from "./agent/create-option-policy.js";export{runGc,type GcCheckpointsSummary,type GcLocksSummary,}from "./governance/gc.js";export{PM_EXACT_COVERAGE_METRICS,findCoverageDeficits,type PmCoverageDeficit,type PmExactCoverageMetric,}from "./governance/coverage-assurance.js";export{_testOnlyHealthCommand,runHealth,type HealthCheck,}from "./governance/health.js";export{_testOnlyValidateCommand,projectValidateCounts,runValidate,type ValidateCheck,type ValidateCountsFixesSummary,type ValidateCountsResult,type ValidateFixesSummary,type ValidateMutationServices,}from "./governance/validate.js";export{runExtension,type ExtensionCommandAction}from "./extension.js";export{inspectStaticExtensionInventory,type StaticExtensionInventoryEntry,type StaticExtensionInventoryError,type StaticExtensionInventoryResult}from "./extension/static-inventory.js";export{buildExtensionInstallPlan,planExtensionDirectoryCopy,type ExtensionCopyPlan,type ExtensionCopyPlanOptions,type ExtensionInstallPlan,}from "./extension/install-plan.js";export{resolveExtensionInstallSourceIdentity,type ExtensionInstallSourceCandidate,type ExtensionInstallSourceResolution,type ExtensionInstallSourceSelection,type ResolvedExtensionInstallSource,}from "./extension/source-resolution.js";export{applyStoredExtensionMigrationState,readExtensionMigrationState,resolveExtensionMigrationStatePath,runExtensionMigrateAction,runExtensionMigrations,type ExtensionMigrationActionContext,type ExtensionMigrationOutcomeStatus,type ExtensionMigrationReceipt,type ExtensionMigrationRunResult,type ExtensionMigrationState,type ExtensionMigrationStateEntry,type RunExtensionMigrationsOptions,}from "./extension/migrations.js";export{findInstalledNpmPackageCandidate,type GithubInstallSource,type InstalledNpmPackageCandidate,type InstallSource,type LocalInstallSource,type NpmInstallSource,type ResolvedInstallSource,}from "./extension/install-sources.js";export{buildExtensionDescribeResult,renderExtensionDescribeMarkdown,type ExtensionCommandClaimant,type ExtensionCommandOwnership,type ExtensionDescribeActivationStatus,type ExtensionDescribeResult,type ExtensionSurfaceDescription,}from "./extension/describe.js";export{runEvent,runMeet,runRemind,type MeetingEventShortcutOptions,type ReminderShortcutOptions,type SchedulingShortcutCommonOptions,}from "./scheduling-shortcuts.js";export{createExtensionCommandSdk}from "./extension-command-context.js";export{isRuntimeRecord}from "./runtime-input.js";export{resolveStartTaskInProgressStatus}from "./start-task-status.js";export{auditMergeAttributeFence,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall,type MergeFenceAuditOptions,type MergeFenceAuditResult,type MergeFenceRefreshOutcome,type MergeInstallOptions,type MergeInstallContextResolution,type MergeInstallResult,}from "./merge/install.js";export{deriveSchemaEvolutionMigrationId,formatSchemaEvolutionMigrationHuman,planSchemaEvolutionMigration,runSchemaEvolutionMigration,type PlanSchemaEvolutionMigrationOptions,type SchemaEvolutionFieldChange,type SchemaEvolutionItemPlan,type SchemaEvolutionMigrationPlan,}from "./schema-migration.js";export type{RuntimeFieldDefinition,RuntimeFieldValueSchema,}from "./schema.js";export{runWithActiveExtensions,type ActiveExtensionScopeOptions,}from "./runtime.js";export{applyInvocationAuthorOverride}from "./invocation-author.js";export{describeItemRevisionChanges,isItemRevisionConflict,ITEM_REVISION_CONFLICT_CHANGE_LIMIT,ITEM_REVISION_CONFLICT_CODE,normalizeExpectedItemHash,parseExpectHashSpecs,readItemRevision,withExpectedItemRevisions,type ExpectedItemRevision,type ExpectedItemRevisionsOutcome,type ExpectHashSpec,type ItemRevision,type ItemRevisionChange,type ItemRevisionConflictRowFields,type ItemRevisionContext,}from "./lifecycle/item-revision.js";export type{CreateNullClearableOptionKey,NullClearableOptionKey,UpdateNullClearableOptionKey,WithNullClears,}from "./lifecycle/shared-unset-fields.js";export type{MutationInputAudience}from "../core/item/literal-mutation-input.js";export{admitStartWithOpenBlockers,isStartTransition,START_BLOCKED_REFUSAL_CODE,START_BLOCKER_ENFORCEMENT_DEFAULT,}from "./lifecycle/start-blockers.js";export{resolveDeclaredBlockers}from "./query/declared-blockers.js";export{evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,PM_MUTATION_ACTION_CONTRACTS,scanMutationSecrets,decideSecretGuardFinding,SECRET_GUARD_RULE_CATEGORIES,secretGuardRuleCategory,type EvaluateMutationGuardOptions,type MutationActionContract,type MutationGuardResult,type MutationGuardSettings,type MutationHistoryScope,type SecretGuardFinding,type SecretGuardMode,type SecretGuardPolicy,type SecretGuardPolicyDecision,type SecretGuardRule,type SecretGuardRuleCategory,type SecretNormalizationKind,}from "./mutation-guard.js";export{findSimilarItems,findDuplicateClusters,evaluateSimilarityGovernance,similarityAdvisoryWarnings,jaccardSimilarity,normalizeSimilarityText,prepareSimilarityText,scoreItemSimilarity,scorePreparedItemSimilarity,tokenizeSimilarityText,type FindSimilarItemsOptions,type FindDuplicateClustersOptions,type DuplicateCluster,type DuplicateClusterMatch,type DuplicateClustersResult,type SimilarItemCandidate,type SimilarItemMatch,type SimilarItemsResult,type SimilarityAdvisory,type SimilarityRecovery,type PreparedSimilarityText,}from "./similarity.js";export{STALE_WORK_THRESHOLD_SETTING,inspectInProgressWork,inspectStaleInProgressItems,resolveLastActivityAt,scanInProgressWork,scanStaleInProgressItems,type InProgressWorkGroup,type InProgressWorkItem,type InProgressWorkScan,type InspectStaleInProgressOptions,type StaleInProgressItem,type StaleInProgressScan,}from "./governance/stale-work.js";export{buildInProgressSweepCommands,type InProgressSweepCommands,}from "./governance/in-progress-work-health.js";export{describeItemOwnershipConflict,evaluateClaimActivity,resolveItemOwnershipActivity,resolveItemOwnershipConflict,type ClaimActivityEvidence,type ClaimActivityOptions,type ItemOwnershipActivity,type ItemOwnershipConflict,}from "./ownership-source.js";export{discoverNearbyPmRoot}from "./tracker-root-discovery.js";export{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery,}from "./environment/tracker-preflight.js";export{_testOnly as _testOnlyTemplates,type TemplateSource,}from "./templates.js";export{runConfig,_testOnlyConfigCommand,type NestedSettingResultValue,}from "./config.js";export * from "./agent/identity-config.js";export{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance,_testOnly as _testOnlyInitAgentGuidance,type InitAgentGuidanceMode,type InitAgentGuidanceSummary,type RunInitAgentGuidanceOptions,type RunInitAgentGuidanceResult,}from "./init-agent-guidance.js";export{runInit,summarizeInitResult,_testOnly as _testOnlyInit,type InitAgentGuidanceResult,type InitConciseResult,type InitDisplayResult,type InitInstalledPackagesSummary,type InitRegisteredTypePresetSummary,type InitTargetResolution,type InitTypePresetName,}from "./init.js";export{PROFILE_SUBCOMMANDS,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,runProfileApply,runProfileLint,runProfileList,runProfileShow,type ProfileApplyDimension,type ProfileComposition,type ProfileListEntry,}from "./profile.js";export * from "./extension-contracts.js";export{RESERVED_ITEM_FIELD_NAMES}from "../core/extensions/item-fields.js";export type{LocatedItem}from "../core/store/item-store.js";export{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest,type PmPackageCatalogLinkMap,type PmPackageCatalogMediaMap,type PmPackageCatalogMetadata,type PmPackageManifest,type PmPackageResourceKind,type PmPackageResourceMap,}from "../core/packages/manifest.js";export type{CommanderOptionAliasContract,CommanderOptionRegistrationContract,}from "./cli-contracts.js";export{ACTIVITY_FLAG_CONTRACTS,ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_CORE_COMMAND_NAMES,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_ITEM_ACTION_SUBCOMMANDS,PM_DEPRECATED_TOOL_ACTIONS,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTIONS,analyzePmToolActionParity,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PROFILE_FLAG_CONTRACTS,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,verifyToolOptionCliParity,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,buildPmActionToolInputSchema,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,compactFlagAliasContracts,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,projectPmDiagnosticOutput,projectPmDiagnosticText,PM_GENERIC_REFUSAL_GUIDANCE,PM_RECOVERY_ECHO_FIELDS,isGenericRefusalRequired,isGenericRefusalWhy,projectLeanRecoveryPayload,withoutGenericRefusalExamples,analyzeSdkCliParameterCompleteness,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,hasSubcommandFlagContractsForCommand,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions,resolvePmPositionalActionFlagContracts,resolveSubcommandFlagContractsForCommand,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget,resolvePmToolCustomFieldCollision,toCompletionFlagString,withFlagAliasMetadata,}from "./cli-contracts.js";export type{CliFlagContract,OptionsFromContracts,PmActionSchemaContract,PmActionToolInputSchemaOptions,PmToolCustomFieldCollision,PmBulkMutationControlOptions,PmBulkMutationFilterOptions,PmCloseActionOptions,PmCloseManyActionOptions,PmCreateActionOptions,PmMutationAttributionOptions,PmOptionScalar,PmCommandOutputBudgetContract,PmDiagnosticDegradationStep,PmDiagnosticOutputBudgetContract,PmDiagnosticOutputClass,PmDiagnosticOutputReceipt,PmOutputBudgetClass,PmOutputDegradationStep,PmProjectedDiagnostic,PmProjectedTextDiagnostic,PmUpdateActionFields,PmUpdateActionOptions,PmUpdateManyActionOptions,PmExtensionCapabilityContract,PmExtensionPolicyModeContract,PmExtensionPolicySurfaceContract,PmExtensionSandboxProfileContract,PmExtensionServiceNameContract,PmExtensionTrustModeContract,MergeSubcommand,PmToolAction,SdkCliActionParameterCoverage,SdkCliCompletenessContractSource,SdkCliParameterCoverageEntry,SdkCliParameterDisposition,ToolOptionFlagContract,ToolOptionCliParityFinding,ToolOptionCliParityReport,}from "./cli-contracts.js";export * from "./compose.js";export * from "./governance/assurance.js";export * from "./governance/assurance-action.js";export * from "./governance/assurance-runtime.js";export * from "./governance/assurance-presets.js";export * from "./governance/boundary-fixtures.js";export * from "./governance/defect-recurrence.js";export * from "./governance/merge-receipt-history.js";export * from "./compile-cache.js";export * from "./environment/project-runtime-compatibility.js";export * from "./environment/source-context.js";export * from "./environment/host-environment-errors.js";export * from "./cli-contracts/command-exit-contracts.js";export * from "./context-relevance.js";export * from "./context/recency.js";export * from "./context-intent-contracts.js";export * from "./context-intent-runtime.js";export * from "./context-signal-store.js";export * from "./workspace-memory.js";export * from "./lifecycle-completion.js";export * from "./lifecycle-policy.js";export * from "./output-projection.js";export * from "./read-output-contracts.js";export * from "./read-output-rows.js";export * from "./read-output-session.js";export * from "./output-token-accounting.js";export * from "./output/fit-envelope.js";export * from "./context-packing.js";export * from "./context-usage.js";export{classifyHistoryEvent,HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS,type HistoryEventClass,}from "../core/history/event-classification.js";export * from "./dependency-provenance.js";export * from "./duplicates.js";export * from "./lifecycle/reopen.js";export * from "./history-compact.js";export * from "./history-read.js";export * from "../core/history/operation-contract.js";export * from "./history/maintenance.js";export{readHistorySnapshot,type HistoryStreamSnapshot}from "../core/history/read.js";export * from "./history-provenance.js";export * from "./mutation-events.js";export * from "./history-redact.js";export{_testOnly}from "./history-redact.js";export * from "./history-repair.js";export * from "./item-children.js";export * from "./item-schedule.js";export * from "./merge/index.js";export{runDeps,type DepsCollapseMode,type DepsFormat,type DepsGraphEdge,type DepsGraphNode,type DepsGraphResult,type DepsTreeNode,}from "./dependencies.js";export * from "./graph/index.js";export{runDocs}from "./docs.js";export{runFiles,runFilesDiscover,runFilesLookup,type FilesDiscoveryCandidate,type FilesLookupItem,type FilesLookupMatch,}from "./files.js";export{applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,type AddGlobEntry,type LinkedArtifact,type LinkedArtifactCommandOptions,type LinkedArtifactKindConfig,type LinkedArtifactResult,type LinkedCollectionMutationProjection,type LinkedCollectionMutationReceipt,type LinkedPathValidation,type PathMigration,projectLinkedCollectionMutation,writtenLinkedEntries,}from "./linked-artifacts.js";export{LINKED_ARTIFACT_NOTE_CONFLICT_MODES,reviseLinkedNote,type LinkedArtifactLinkOutcome,type LinkedArtifactLinkOutcomeEntry,type LinkedArtifactNoteConflict,type LinkedArtifactNoteConflictMode,}from "./linked-artifacts.js";export * from "./pagination.js";export * from "./query/item-filter-options.js";export * from "./query/parsers.js";export * from "./output.js";export * from "./output-contracts.js";export * from "./agent/task-transcript-contracts.js";export * from "./relationship-analytics.js";export * from "./relationship-context.js";export * from "./relationship-history.js";export * from "./relationship-migration.js";export * from "./workspace-transaction.js";export * from "./workspace-transaction-gc.js";export * from "./item-transaction.js";export * from "./item-metadata-index.js";export * from "./structured-mutations.js";export * from "./lifecycle/structured-mutation-plan.js";export * from "./runtime-primitives.js";export * from "./error-runtime.js";export * from "./error-code-catalog.js";export * from "./generated-error-code-catalog.js";export * from "./agent/refusal-reachability.js";export * from "./agent/refusal-closure-census.js";export * from "./agent/refusal-closure.js";export * from "./agent/closed-domain-contracts.js";export * from "./agent/refusal-corpus-contracts.js";export{MERGE_SUBCOMMAND_VALUES}from "./cli-contracts.js";export * from "./agent/tracker-preflight-contracts.js";export * from "./agent/subcommand-recovery.js";export * from "./flag-invocation-contracts.js";export * from "./cli-contracts/flag-lexicon-contracts.js";export * from "./relationships.js";export * from "./actionability.js";export type{PlanCommandOptions,PlanOperationOptions,PlanCommandResult,PlanDispatchInput,PlanResultPlan,PlanShowDepth,PlanStepSummary,PlanSubcommand,PlanTemplateName,}from "./lifecycle/plan.js";export type{CreateOperationOptions}from "./lifecycle/create.js";export type{PlanMutationReceipt}from "./lifecycle/plan-mutation-receipt.js";export type{UpdateOperationOptions}from "./lifecycle/update.js";export type{AppendOperationOptions}from "./lifecycle/append.js";export type{CloseManyOperationOptions}from "./lifecycle/close-many.js";export type{UpdateManyOperationOptions}from "./lifecycle/update-many.js";export{runCreate}from "./lifecycle/create.js";export{runPlan}from "./lifecycle/plan.js";export{runAppend}from "./lifecycle/append.js";export{STALE_CLAIM_TAKEOVER_REFUSED_CODE,isAlreadyClaimedError,runClaim,runClaimNext,runRelease,type StaleClaimTakeoverReceipt,}from "./lifecycle/claim.js";export{runStartTask,runPauseTask,runCloseTask,type TaskCompositionOptions}from "./lifecycle/task-composition.js";export{runCloseMany}from "./lifecycle/close-many.js";export{runUpdateMany}from "./lifecycle/update-many.js";export{runComments}from "./comments.js";export{runNotes}from "./notes.js";export{runLearnings}from "./learnings.js";export{runUpgrade}from "./governance/upgrade.js";export{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,}from "./lifecycle/plan.js";export * from "./define.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,acquireLock,acquireLockLease,appendHistoryEntry,canonicalDocument,classifyItemFormatVersion,clearWorkspaceContractsCache,commitImportedItem,createHistoryEntry,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,ensureTrackerInitialized,generateItemId,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getSettingsPath,getWorkspaceContracts,isPmCliExpectedError,isTimestampLiteral,listAllItemMetadata,loadCreateTemplateOptions,locateItem,normalizeItemMetadata,normalizeItemFormatVersion,normalizeItemId,normalizeRawItemId,normalizeStatusInput,nowIso,parseTags,pathExists,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString,readSettings,readStringOption,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveItemTypeRegistry,resolveImplicitPmRoot,resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runCalendar,runCompletion,runGuide,runList,runReindex,runSearch,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,scanItemFormatVersions,selectImportAuthor,serializeItemDocument,splitFrontMatter,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportDeferredFields,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,writeFileAtomic,aggregate,append,claim,claimNext,close,reopen,closeTask,comments,config,context,copy,create,deleteItem,deps,docs,duplicates,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,get,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,learnings,list,listAllComplete,next,notes,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,pauseTask,profile,profileApply,profileLint,profileList,profileShow,release,restore,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaShow,schemaShowField,schemaShowStatus,schemaRenameField,schemaRenameType,search,startTask,stats,update,upgrade,validate,type AggregateOptions,type AggregateResult,type AggregateRow,type AppendCommandOptions,type AppendResult,type BlockerEntry,type CalendarOptions,type CalendarResult,type ClaimResult,type ClaimStartReceipt,type CloseResult,type CloseTaskResult,type CommitImportedItemParams,type CommitImportedItemResult,type CommentsCommandOptions,type CommentsResult,type ConfigCommandOptions,type ConfigResult,type CompletionResult,type CompletionShell,type ContractsCommandOptions,type ContractsResult,type ContextFocusItem,type ContextOptions,type ContextOutputFormat,type ContextResult,type CopyResult,type CreatePmCliExpectedErrorOptions,type CreateResult,type CreateTemplateOptions,type Dependency,type DeleteResult,type DepsCommandOptions,type DepsResult,type DocsCommandOptions,type DocsResult,type ExtensionCommandOptions,type ExtensionCommandResult,type FilesCommandOptions,type FilesDiscoverOptions,type FilesDiscoverResult,type FilesLookupOptions,type FilesLookupResult,type FilesResult,type FocusResult,type GcCommandOptions,type GcResult,type GetContractsOptions,type GetOptions,type GetResult,type GuideDepth,type GuideOptions,type GuideOutputFormat,type GuideResult,type HealthResult,type ImportLinkedScope,type InitCommandOptions,type InitResult,type ItemFormatVersionScanEntry,type ItemFormatVersionScanResult,type ItemFormatVersionStatus,type LearningsCommandOptions,type LearningsResult,type LinkedDoc,type LinkedFile,type LinkedTest,type ListedItem,type ListCompactResult,type ListFullResult,type ListOptions,type ListProjectedItem,type ListProjectedItemCore,type ListResult,type ListResultItem,type ListSortField,type ListSortOrder,type ListTreeItem,type ListTreeMetadata,type ListVerboseResult,type PmCompleteListCertificate,type PmCompleteListFailureReceipt,type PmCompleteListFinding,type PmCompleteListFindingCode,type PmCompleteListInspection,type PmCompleteListOptions,type PmCompleteListResult,type LogNote,type NextActionableItem,type NextBlockerRef,type NextOptions,type NextOutputFormat,type NextRecommendation,type NextResult,type NotesCommandOptions,type NotesResult,type PackageCommandOptions,type PackageCommandResult,type PauseTaskResult,type PmActionInput,type PmActionName,type PmActionOptions,type PmClientCloseActionOptions,type PmClientFullMutationOptions,type PmClientMutationOptions,type PmClientOptions,type PmClientRunArgs,type PmCliExpectedError,type ProfileApplyCommandOptions,type ProfileApplyResult,type ProfileLintResult,type ProfileListResult,type ProfileResult,type ProfileShowResult,type ProfileSubcommand,type ReindexOptions,type ReindexResult,type ReleaseResult,type ReleaseMutationOptions,type ReopenCommandOptions,type ReopenResult,type RestoreResult,type RunHealthOptions,type SchemaAddFieldCommandOptions,type SchemaAddFieldResult,type SchemaAddStatusCommandOptions,type SchemaAddStatusResult,type SchemaAddTypeCommandOptions,type SchemaAddTypeInferCommandOptions,type SchemaAddTypeInferResult,type SchemaAddTypeResult,type SchemaApplyPresetCommandOptions,type SchemaApplyPresetResult,type SchemaInspectResult,type SchemaListFieldsResult,type SchemaListResult,type SchemaRemoveFieldCommandOptions,type SchemaRemoveFieldResult,type SchemaRemoveStatusCommandOptions,type SchemaRemoveStatusResult,type SchemaRemoveTypeCommandOptions,type SchemaRemoveTypeResult,type SchemaShowFieldResult,type SchemaShowResult,type SchemaShowStatusResult,type SchemaResult,type RunSchemaEvolutionMigrationOptions,type SchemaEvolutionMigrationRequest,type SchemaEvolutionMigrationResult,type SchemaSubcommand,type SearchCompactResult,type SearchHit,type SearchHitHighlight,type SearchMatchMode,type SearchOptions,type ClaimNextOptions,type SearchResult,type SearchResultItem,type SearchVerboseResult,type StartTaskResult,type StatsCommandOptions,type StatsResult,type TemplatesListResult,type TemplatesSaveResult,type TemplatesSaveOptions,type TemplatesShowResult,type TestRunsListCommandOptions,type TestRunsLogsCommandOptions,type TestRunsResumeCommandOptions,type TestRunsStopCommandOptions,type ToImportLinkedArtifactsOptions,type ToImportLinkedTestsOptions,type ToImportLogEntriesOptions,type UpdateResult,type UpgradeCommandOptions,type UpgradeResult,type ValidateCommandOptions,type ValidateResult,type WorkspaceContracts,type WorkspaceContractsOptions,type WorkspaceExtensionCommandContract,type WorkspaceFieldContract,}from "./runtime.js";export{extensionMigrate,packageMigrate}from "./package-migrations.js";export{CONTEXT_OUTPUT_VALUES,NEXT_OUTPUT_VALUES,PM_GITIGNORE_END,PM_GITIGNORE_START,analyzeSdkActionCoverage,ensurePmGitignore,getPmGitignoreBlock,closeItem,runAggregate,runClose,runCopy,runContext,runDelete,runFocus,runGet,runNext,runRestore,runUpdate,type CloseCommandOptions,type CopyOptions,type DeleteCommandOptions,type EnsurePmGitignoreResult,type HierarchyChild,type HierarchyNode,type HotFile,type LockLease,type FocusOptions,type ImportPriorityValue,type ProgressEntry,type RecentContextItem,type RestoreCommandOptions,type SdkActionCoverageRow,type StaleEntry,type TestHealthSummary,type UpdateCommandOptions,type WorkloadEntry,}from "./runtime.js";export{runStats}from "./stats.js";export{readImprovementLedger,recordImprovementObservation,type ImprovementDirection,type ImprovementLedgerDocument,type ImprovementLedgerResult,type ImprovementObservation,type ImprovementTrend,type ReadImprovementLedgerOptions,type RecordImprovementObservationOptions,type RecordImprovementObservationResult,}from "./improvement-ledger.js";export{evaluateProvenanceCoverage,projectFleetAttributionAnalytics,projectProvenanceCoverageAnalytics,readHistoryAnalyticsWindow,runFleetAttributionAnalytics,runProvenanceCoverageAnalytics,type FleetAttributionAnalytics,type FleetAttributionDimension,type FleetAttributionRow,type HistoryAnalyticsWindowOptions,type HistoryAnalyticsWindowReceipt,type HistoryAnalyticsEvent,type HistoryAnalyticsWindow,type ProvenanceCoverageAnalytics,}from "./history-analytics.js";export{DEFAULT_EVAL_QUERIES_RELATIVE_PATH,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,parseEvalQuerySet,runEval,type EvalOptions,type EvalQueryReport,type EvalResult,}from "./eval.js";export{runTelemetry,TELEMETRY_SUBCOMMANDS,type TelemetryCommandOptions,type TelemetryFlushResult,type TelemetryStatusSummary,type TelemetrySubcommand,}from "./telemetry.js";export{classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight,type LinkedTestFailureCategory,type LinkedTestCommandSafetyClassification,type TestCommandOptions,type TestResult,type TestRunResult,}from "./test/execution.js";export{assertTestMeasurementRun}from "./test/prerequisites.js";export{TEST_RUN_MEASUREMENT_LIMIT,diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow,type TestRunMeasurementDiff,}from "./test/measurements.js";export{runTestAll,type TestAllCommandOptions,type TestAllItemResult,type TestAllResult,}from "./test/batch.js";export{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode,type LinkedTestPmContextMode,type LinkedTestWorkspaceContextMode,}from "./test/parsers.js";export{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,linkedTestTrustFingerprint,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch,type LinkedTestTrustDecision,}from "./test/trust.js";export{updateLinkedTest,type LinkedTestUpdateSelector,type LinkedTestMetadataPatch,type UpdateLinkedTestOptions,type UpdateLinkedTestResult,}from "./test/update.js";export{runStartBackgroundRun,runTestRunsWorker,type StartBackgroundRunCommandOptions,type StartBackgroundRunResult,}from "./test/runs.js";export{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile,type ProfileConfigEntry,type ProfileName,type ProfilePackageRecommendation,type ProfileTemplateEntry,type ProfileTemplateOptions,type ProjectProfileDefinition,type ProjectProfileRegistrationInput,}from "../core/profile/profile-presets.js";export{planProfileApplication,type ProfileApplicationPlan,type ProfileChangeStatus,type ProfileComponentChange,type ProfileConfigChange,type ProfileConfigPlan,type ProfileCurrentState,type ProfilePackagePlan,type ProfileSchemaPlan,type ProfileTemplateChange,type ProfileTemplatePlan,type ProfileWorkflowChange,type ProfileWorkflowPlan,}from "../core/profile/profile-plan.js";export{describeProfileComposition,describeProjectProfile,type ProjectProfileComposition,type ProjectProfileDescription,type ProjectProfilePackageSummary,}from "../core/profile/profile-describe.js";export{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,type ProfileLintCode,type ProfileLintDimension,type ProfileLintSeverity,type ProjectProfileLintFinding,type ProjectProfileLintReport,}from "../core/profile/profile-lint.js";export * from "./authoring.js";export * from "./governance.js";export * from "./mcp/discovery.js";export * from "./query.js";export * from "./testing.js";export type{GlobalOptions}from "../core/shared/command-types.js";export type{ItemDocument,ItemDeferredField,ItemMetadata,ItemStatus,ItemType,PmSettings,StructuredJsonValue,}from "../types/index.js";export{normalizeDirectExtensionCommandOptions,resolveExtensionFlagOptionKey,type DirectExtensionOptionPolicy,type LooseCommandFlagDefinition,}from "./extension/command-options.js";export type{CheckpointRestoreFn,CheckpointRollbackResult,LoadedMutationCheckpoint}from "../core/checkpoint/mutation-checkpoint.js";export type{CommandOverrideResult,DiscoverExtensionsOptions,ExtensionLayer,LoadedExtension,ParserOverrideResult,PreflightOverrideResult,RegisteredExtensionCommandOverride,RegisteredExtensionParserOverride,RegisteredExtensionPreflightOverride,RegisteredExtensionRendererOverride,RendererOverrideResult,ScopedPreflightOverrideDefinition,ScopedRendererOverrideDefinition,ServiceOverrideResult}from "../core/extensions/extension-types.js";export type{FlagValueKind}from "../core/extensions/flag-value-types.js";export type{HistoryCompactScope}from "../core/history/history-compact-bulk.js";export type{HistoryStreamPolicyManyParams,HistoryStreamPolicyParams,HistoryStreamPolicyResult}from "../core/history/history-stream-policy.js";export type{PatchFailureContext,ResolveHistoryTargetOptions,ResolvedHistoryTarget}from "../core/history/projection.js";export type{ReanchorHistoryOptions,ReanchorResult,ReplayDocument}from "../core/history/replay.js";export type{BodyFileReader}from "../core/io/body-file.js";export type{ItemDocumentFormatOptions}from "../core/item/item-format.js";export type{StdinTokenResolver}from "../core/item/parse.js";export type{Priority}from "../core/item/priority.js";export type{ParseStatusFilterOptions}from "../core/item/status-filter.js";export type{CommandOptionPolicyCommand,CommandOptionPolicyState}from "../core/item/type-registry.js";export type{AcquireLockOptions}from "../core/lock/lock.js";export type{OutputOptions}from "../core/output/output.js";export type{TabularRow}from "../core/output/tabular.js";export type{LoadedRuntimeSchemaSections,RuntimeFieldDefinitionResolved}from "../core/schema/runtime-schema.js";export type{EvaluateTransitionInput,EvaluateTransitionResult}from "../core/schema/type-workflows.js";export type{RefreshSearchArtifactsForMutationOptions,SearchMutationArtifactRefreshResult,VectorizationStatusLedgerReadResult}from "../core/search/cache.js";export type{SearchCorpusOptions,SemanticCorpusCharacterLimitResolution,SemanticCorpusInputOptions}from "../core/search/corpus.js";export type{EvalQuerySet}from "../core/search/eval.js";export type{EmbeddingProviderResolution,ProviderSettingsInput}from "../core/search/providers.js";export type{SemanticRuntimeDefaultsResolution}from "../core/search/semantic-defaults.js";export type{ExecuteVectorRequestOptions,VectorRecord,VectorSettingsInput,VectorStoreConfig,VectorStoreResolution,VectorUpsertResult}from "../core/search/vector-stores.js";export type{SentryLike}from "../core/sentry/instrument.js";export type{AgentSemanticAttribution}from "../core/session/session-state.js";export type{SerialQueue}from "../core/shared/serial-queue.js";export type{SplitCommaListOptions}from "../core/shared/split-comma-list.js";export type{ItemFormatMigrationResult}from "../core/store/item-format-migration.js";export type{ListCacheOptions}from "../core/store/item-metadata-cache.js";export type{SettingsReadResult}from "../core/store/settings.js";export type{TelemetryCommandContext,TelemetryErrorEventContext}from "../core/telemetry/runtime.js";export type{BackgroundLogStream,BackgroundTestRunStatus}from "../core/test/background-runs.js";export type{ValidateFixRecord}from "../core/validate/fix-planning.js";export type{OwnerItemMetadata,StaleLinkOwnerInput}from "../core/validate/missing-link-owners.js";export type{ClassifiedStaleLinkedPath}from "../core/validate/stale-file-classification.js";export type{BuiltinItemType,ConfidenceTextLevel,ContextDepth,ContextSectionName,ContextSettings,GovernanceStartBlockerEnforcement,HistoryEntry,HistoryPatchOp,ItemFormat,ItemTestRunSummary,LinkScope,ParentReferencePolicy,PlanMode,RuntimeSchemaSettings,SprintReleaseFormatPolicy,TestRunMeasurement}from "../types.js";export type{ContentFieldFilters}from "../core/governance/content-fields.js";export type{MissingMetadataFilters}from "../core/governance/metadata-coverage.js";export type{UpdateManyCommandOptions,UpdateManyResult}from "./lifecycle/update-many.js";export type{CommandScope}from "./command-line.js";export type{ContextIntentCursorEnvelope}from "./context-intent-contracts.js";export type{ExactCorpusShape}from "./corpus-shape.js";export type{ExactDefinition,FlagAuthoringDefinition,ItemFieldAuthoringDefinition,ItemTypeAuthoringDefinition,MigrationAuthoringDefinition,SearchProviderAuthoringDefinition,VectorStoreAdapterAuthoringDefinition}from "./define.js";export type{ManagedExtensionRecord}from "./extension/managed-state.js";export type{ValidateItem}from "./governance/validate-item-reader.js";export type{ProjectedGraphResult}from "./graph/run.js";export type{ClaimMutationOptions,ClaimNextResult}from "./lifecycle/claim.js";export type{CloseManyCommandOptions,CloseManyResult}from "./lifecycle/close-many.js";export type{RenamedLinkedArtifactResult}from "./linked-artifacts.js";export type{FilterValueEchoEntry}from "./query/list.js";export type{SearchRenderingQueryExpansion,SearchRenderingRerank}from "./query/search-rendering.js";export type{ImplicitSemanticFallbackReason,VectorIndexRecovery,VectorIndexRecoveryRegistrations}from "./query/search/semantic.js";export type{ReadOutputResultForSession}from "./read-output-contracts.js";export type{InitialReadOptions,ReadOptions,ReadPromise}from "./runtime.js";export type{LinkedTestExecutionResult,RunLinkedTestsOptions}from "./test/execution.js";export type{RegisteredHookEntry}from "./testing.js";export type{TraceabilityCandidate}from "./traceability/source-traceability.js";export type{ExactWorkspaceRecipe}from "./workspace-recipe.js";
|
|
6
|
+
export type{CompletionRuntimeConfig}from "./completion.js";export{isItemAlreadyExistsError,type PmItemAlreadyExistsError,isPmTokenBudgetRecovery,type PmTokenBudgetRecovery,PM_CLI_ERROR_DETAILS_LIMITS,isPmCliErrorDetails,projectPmCliErrorDetails,projectPmCliErrorContextDetails,snapshotPmCliErrorContext,type PmCliErrorDetails,type PmCliErrorDetailValue,type PmCliErrorDetailsOmission,type PmCliErrorDetailsRejection}from "./errors.js";export{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,renderPmCommandVisibilityMarkdown,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier,}from "./agent-capability-contracts.js";export * from "./mcp/protocol.js";export * from "./mcp/executable.js";export * from "./mcp/interactions.js";export * from "./mcp/tasks.js";export * from "./mcp/subscriptions.js";export * from "./mcp/transport.js";export * from "./mcp/authorization.js";export * from "./mcp/apps.js";export * from "./mcp/skills.js";export * from "./cli-contracts/grammar-contracts.js";export * from "./agent-session-context.js";export * from "./environment/agent-environment.js";export type{PmCommandCapabilityContract,PmCommandCapabilityFamily,PmCommandVisibilityContract,PmCommandVisibilityTier,PmMcpPromptArgumentContract,PmMcpPromptContract,PmMcpResourceContract,PmMcpToolProfile,}from "./agent-capability-contracts.js";export{isErrnoError,limitAnnotationEntries,parseAnnotationTextInput,readAnnotationEntries,normalizeAnnotationTransportOptions,resolveAnnotationInput,resolveAnnotationIndex,runAnnotationCommand,wrapOwnershipConflict,type AnnotationCommandConfig,type AnnotationCommandOptions,type AnnotationCommandResult,type AnnotationEntry,type AnnotationInput,type AnnotationHistoryRestoration,type AnnotationMutationReceipt,type AnnotationOmissionReceipt,type AnnotationSourceOptions,type IndexedAnnotationEntry,type OwnershipConflictGuidance,}from "./annotations.js";export{acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,inspectHistoryAuthorStream,parseUnknownAuthorHistoryEventCoordinates,planUnknownAuthorHistoryAcknowledgment,resolveUnknownAuthorAcknowledgmentSelector,scanHistoryAuthorAttribution,type AcknowledgeUnknownAuthorEventsOptions,type HistoryAuthorAttributionScan,type UnknownAuthorAcknowledgmentPlan,type UnknownAuthorAcknowledgmentPlanCoordinate,type UnknownAuthorAcknowledgmentResult,type UnknownAuthorHistoryEvent,}from "./author-attribution.js";export{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape,type BuiltinCorpusShapeName,type CorpusShape,type CorpusShapeEdgeWeight,type CorpusShapeItemPlan,type CorpusShapeMeasurement,type CorpusShapeProfile,}from "./corpus-shape.js";export * from "./core-governance.js";export{createPmCliProgram}from "./cli-program.js";export{runSearchRefreshWorkerEntrypoint}from "./search-refresh-worker.js";export{PM_REPRODUCIBLE_PROCESS_ENV,createReproducibleProcessRunner,resolveReproducibleProcessEnvironment,runWithReproducibleProcessEnvironment,type ReproducibleExecutionSettings,type ReproducibleProcessEnvironment,type ReproducibleProcessRunner,}from "./reproducibility/process.js";export{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe,type WorkspaceRecipe,type WorkspaceRecipeJsonValue,type WorkspaceRecipeOperation,}from "./workspace-recipe.js";export{SNAPSHOT_SCHEMA,WORKSPACE_SNAPSHOT_ACTIONS,createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery,type CreateWorkspaceSnapshotResult,type RestoreWorkspaceSnapshotOptions,type RestoreWorkspaceSnapshotResult,type WorkspaceSnapshotHistoryImpact,type WorkspaceSnapshotManifest,type WorkspaceSnapshotReference,type WorkspaceSnapshotRestorePlan,}from "./workspace-snapshot.js";export{flushTelemetryQueue}from "./telemetry-flush.js";export{PM_HISTORY_COMMAND_ALIASES,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,findPmNamespacedCommand,resolvePmCommandOperation,resolvePmHistoryOperation}from "./cli-contracts.js";export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,type PmCommandAliasContract,type PmCommandAliasLifecycle,type PmCommandAliasRegistration,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,stripGlobalBootstrapTokens,type BootstrapGlobalOptions,type BootstrapHelpRequest,type BootstrapInvocationNormalizationResult,type BootstrapNormalizationEvent,}from "./cli-bootstrap.js";export{quoteCommandArg,quoteWindowsCommandArg,redactUrlCredentialsInText,redactUrlCredentialsInToken,renderPmCommand,resolvePmCommandScopeArgs,URL_CREDENTIAL_PLACEHOLDER,}from "./command-line.js";export * from "./agent/command-recovery.js";export * from "./agent/linked-resource-recovery.js";export * from "./agent/command-suggestions.js";export * from "./agent/item-addressing.js";export * from "./agent/create-option-policy.js";export{runGc,type GcCheckpointsSummary,type GcLocksSummary,}from "./governance/gc.js";export{PM_EXACT_COVERAGE_METRICS,findCoverageDeficits,type PmCoverageDeficit,type PmExactCoverageMetric,}from "./governance/coverage-assurance.js";export{_testOnlyHealthCommand,runHealth,type HealthCheck,}from "./governance/health.js";export{_testOnlyValidateCommand,projectValidateCounts,runValidate,type ValidateCheck,type ValidateCountsFixesSummary,type ValidateCountsResult,type ValidateFixesSummary,type ValidateMutationServices,}from "./governance/validate.js";export{runExtension,type ExtensionCommandAction}from "./extension.js";export{inspectStaticExtensionInventory,type StaticExtensionInventoryEntry,type StaticExtensionInventoryError,type StaticExtensionInventoryResult}from "./extension/static-inventory.js";export{buildExtensionInstallPlan,planExtensionDirectoryCopy,type ExtensionCopyPlan,type ExtensionCopyPlanOptions,type ExtensionInstallPlan,}from "./extension/install-plan.js";export{resolveExtensionInstallSourceIdentity,type ExtensionInstallSourceCandidate,type ExtensionInstallSourceResolution,type ExtensionInstallSourceSelection,type ResolvedExtensionInstallSource,}from "./extension/source-resolution.js";export{applyStoredExtensionMigrationState,readExtensionMigrationState,resolveExtensionMigrationStatePath,runExtensionMigrateAction,runExtensionMigrations,type ExtensionMigrationActionContext,type ExtensionMigrationOutcomeStatus,type ExtensionMigrationReceipt,type ExtensionMigrationRunResult,type ExtensionMigrationState,type ExtensionMigrationStateEntry,type RunExtensionMigrationsOptions,}from "./extension/migrations.js";export{findInstalledNpmPackageCandidate,type GithubInstallSource,type InstalledNpmPackageCandidate,type InstallSource,type LocalInstallSource,type NpmInstallSource,type ResolvedInstallSource,}from "./extension/install-sources.js";export{buildExtensionDescribeResult,renderExtensionDescribeMarkdown,type ExtensionCommandClaimant,type ExtensionCommandOwnership,type ExtensionDescribeActivationStatus,type ExtensionDescribeResult,type ExtensionSurfaceDescription,}from "./extension/describe.js";export{runEvent,runMeet,runRemind,type MeetingEventShortcutOptions,type ReminderShortcutOptions,type SchedulingShortcutCommonOptions,}from "./scheduling-shortcuts.js";export{createExtensionCommandSdk}from "./extension-command-context.js";export{isRuntimeRecord}from "./runtime-input.js";export{resolveStartTaskInProgressStatus}from "./start-task-status.js";export{auditMergeAttributeFence,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall,type MergeFenceAuditOptions,type MergeFenceAuditResult,type MergeFenceRefreshOutcome,type MergeInstallOptions,type MergeInstallContextResolution,type MergeInstallResult,}from "./merge/install.js";export{deriveSchemaEvolutionMigrationId,formatSchemaEvolutionMigrationHuman,planSchemaEvolutionMigration,runSchemaEvolutionMigration,type PlanSchemaEvolutionMigrationOptions,type SchemaEvolutionFieldChange,type SchemaEvolutionItemPlan,type SchemaEvolutionMigrationPlan,}from "./schema-migration.js";export type{RuntimeFieldDefinition,RuntimeFieldValueSchema,}from "./schema.js";export{runInActiveExtensionScope,runWithActiveExtensions,type ActiveExtensionScopeOptions,}from "./runtime.js";export{applyInvocationAuthorOverride}from "./invocation-author.js";export{describeItemRevisionChanges,isItemRevisionConflict,ITEM_REVISION_CONFLICT_CHANGE_LIMIT,ITEM_REVISION_CONFLICT_CODE,normalizeExpectedItemHash,parseExpectHashSpecs,readItemRevision,withExpectedItemRevisions,type ExpectedItemRevision,type ExpectedItemRevisionsOutcome,type ExpectHashSpec,type ItemRevision,type ItemRevisionChange,type ItemRevisionConflictRowFields,type ItemRevisionContext,}from "./lifecycle/item-revision.js";export type{CreateNullClearableOptionKey,NullClearableOptionKey,UpdateNullClearableOptionKey,WithNullClears,}from "./lifecycle/shared-unset-fields.js";export type{MutationInputAudience}from "../core/item/literal-mutation-input.js";export{admitStartWithOpenBlockers,isStartTransition,START_BLOCKED_REFUSAL_CODE,START_BLOCKER_ENFORCEMENT_DEFAULT,}from "./lifecycle/start-blockers.js";export{resolveDeclaredBlockers}from "./query/declared-blockers.js";export{evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,PM_MUTATION_ACTION_CONTRACTS,scanMutationSecrets,decideSecretGuardFinding,SECRET_GUARD_RULE_CATEGORIES,secretGuardRuleCategory,type EvaluateMutationGuardOptions,type MutationActionContract,type MutationGuardResult,type MutationGuardSettings,type MutationHistoryScope,type SecretGuardFinding,type SecretGuardMode,type SecretGuardPolicy,type SecretGuardPolicyDecision,type SecretGuardRule,type SecretGuardRuleCategory,type SecretNormalizationKind,}from "./mutation-guard.js";export{findSimilarItems,findDuplicateClusters,evaluateSimilarityGovernance,similarityAdvisoryWarnings,jaccardSimilarity,normalizeSimilarityText,prepareSimilarityText,scoreItemSimilarity,scorePreparedItemSimilarity,tokenizeSimilarityText,type FindSimilarItemsOptions,type FindDuplicateClustersOptions,type DuplicateCluster,type DuplicateClusterMatch,type DuplicateClustersResult,type SimilarItemCandidate,type SimilarItemMatch,type SimilarItemsResult,type SimilarityAdvisory,type SimilarityRecovery,type PreparedSimilarityText,}from "./similarity.js";export{STALE_WORK_THRESHOLD_SETTING,inspectInProgressWork,inspectStaleInProgressItems,resolveLastActivityAt,scanInProgressWork,scanStaleInProgressItems,type InProgressWorkGroup,type InProgressWorkItem,type InProgressWorkScan,type InspectStaleInProgressOptions,type StaleInProgressItem,type StaleInProgressScan,}from "./governance/stale-work.js";export{buildInProgressSweepCommands,type InProgressSweepCommands,}from "./governance/in-progress-work-health.js";export{describeItemOwnershipConflict,evaluateClaimActivity,resolveItemOwnershipActivity,resolveItemOwnershipConflict,type ClaimActivityEvidence,type ClaimActivityOptions,type ItemOwnershipActivity,type ItemOwnershipConflict,}from "./ownership-source.js";export{discoverNearbyPmRoot}from "./tracker-root-discovery.js";export{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery,}from "./environment/tracker-preflight.js";export{_testOnly as _testOnlyTemplates,type TemplateSource,}from "./templates.js";export{runConfig,_testOnlyConfigCommand,type NestedSettingResultValue,}from "./config.js";export * from "./agent/identity-config.js";export{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance,_testOnly as _testOnlyInitAgentGuidance,type InitAgentGuidanceMode,type InitAgentGuidanceSummary,type RunInitAgentGuidanceOptions,type RunInitAgentGuidanceResult,}from "./init-agent-guidance.js";export{runInit,summarizeInitResult,_testOnly as _testOnlyInit,type InitAgentGuidanceResult,type InitConciseResult,type InitDisplayResult,type InitInstalledPackagesSummary,type InitRegisteredTypePresetSummary,type InitTargetResolution,type InitTypePresetName,}from "./init.js";export{PROFILE_SUBCOMMANDS,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,runProfileApply,runProfileLint,runProfileList,runProfileShow,type ProfileApplyDimension,type ProfileComposition,type ProfileListEntry,}from "./profile.js";export * from "./extension-contracts.js";export{RESERVED_ITEM_FIELD_NAMES}from "../core/extensions/item-fields.js";export type{LocatedItem}from "../core/store/item-store.js";export{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest,type PmPackageCatalogLinkMap,type PmPackageCatalogMediaMap,type PmPackageCatalogMetadata,type PmPackageManifest,type PmPackageResourceKind,type PmPackageResourceMap,}from "../core/packages/manifest.js";export type{CommanderOptionAliasContract,CommanderOptionRegistrationContract,}from "./cli-contracts.js";export{ACTIVITY_FLAG_CONTRACTS,ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_CORE_COMMAND_NAMES,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_ITEM_ACTION_SUBCOMMANDS,PM_DEPRECATED_TOOL_ACTIONS,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTIONS,analyzePmToolActionParity,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PROFILE_FLAG_CONTRACTS,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,verifyToolOptionCliParity,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,buildPmActionToolInputSchema,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,compactFlagAliasContracts,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,projectPmDiagnosticOutput,projectPmDiagnosticText,PM_GENERIC_REFUSAL_GUIDANCE,PM_RECOVERY_ECHO_FIELDS,isGenericRefusalRequired,isGenericRefusalWhy,projectLeanRecoveryPayload,withoutGenericRefusalExamples,analyzeSdkCliParameterCompleteness,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,hasSubcommandFlagContractsForCommand,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions,resolvePmPositionalActionFlagContracts,resolveSubcommandFlagContractsForCommand,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget,resolvePmToolCustomFieldCollision,toCompletionFlagString,withFlagAliasMetadata,}from "./cli-contracts.js";export type{CliFlagContract,OptionsFromContracts,PmActionSchemaContract,PmActionToolInputSchemaOptions,PmToolCustomFieldCollision,PmBulkMutationControlOptions,PmBulkMutationFilterOptions,PmCloseActionOptions,PmCloseManyActionOptions,PmCreateActionOptions,PmMutationAttributionOptions,PmOptionScalar,PmCommandOutputBudgetContract,PmDiagnosticDegradationStep,PmDiagnosticOutputBudgetContract,PmDiagnosticOutputClass,PmDiagnosticOutputReceipt,PmOutputBudgetClass,PmOutputDegradationStep,PmProjectedDiagnostic,PmProjectedTextDiagnostic,PmUpdateActionFields,PmUpdateActionOptions,PmUpdateManyActionOptions,PmExtensionCapabilityContract,PmExtensionPolicyModeContract,PmExtensionPolicySurfaceContract,PmExtensionSandboxProfileContract,PmExtensionServiceNameContract,PmExtensionTrustModeContract,MergeSubcommand,PmToolAction,SdkCliActionParameterCoverage,SdkCliCompletenessContractSource,SdkCliParameterCoverageEntry,SdkCliParameterDisposition,ToolOptionFlagContract,ToolOptionCliParityFinding,ToolOptionCliParityReport,}from "./cli-contracts.js";export * from "./compose.js";export * from "./governance/assurance.js";export * from "./governance/assurance-action.js";export * from "./governance/assurance-runtime.js";export * from "./governance/assurance-presets.js";export * from "./governance/boundary-fixtures.js";export * from "./governance/defect-recurrence.js";export * from "./governance/merge-receipt-history.js";export * from "./compile-cache.js";export * from "./environment/project-runtime-compatibility.js";export * from "./environment/source-context.js";export * from "./environment/host-environment-errors.js";export * from "./cli-contracts/command-exit-contracts.js";export * from "./context-relevance.js";export * from "./context/recency.js";export * from "./context-intent-contracts.js";export * from "./context-intent-runtime.js";export * from "./context-signal-store.js";export * from "./workspace-memory.js";export * from "./lifecycle-completion.js";export * from "./lifecycle-policy.js";export * from "./output-projection.js";export * from "./read-output-contracts.js";export * from "./read-output-rows.js";export * from "./read-output-session.js";export * from "./output-token-accounting.js";export * from "./output/fit-envelope.js";export * from "./context-packing.js";export * from "./context-usage.js";export{classifyHistoryEvent,HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS,type HistoryEventClass,}from "../core/history/event-classification.js";export * from "./dependency-provenance.js";export * from "./duplicates.js";export * from "./lifecycle/reopen.js";export * from "./history-compact.js";export * from "./history-read.js";export * from "../core/history/operation-contract.js";export * from "./history/maintenance.js";export{readHistorySnapshot,type HistoryStreamSnapshot}from "../core/history/read.js";export * from "./history-provenance.js";export * from "./mutation-events.js";export * from "./history-redact.js";export{_testOnly}from "./history-redact.js";export * from "./history-repair.js";export * from "./item-children.js";export * from "./item-schedule.js";export * from "./merge/index.js";export{runDeps,type DepsCollapseMode,type DepsFormat,type DepsGraphEdge,type DepsGraphNode,type DepsGraphResult,type DepsTreeNode,}from "./dependencies.js";export * from "./graph/index.js";export{runDocs}from "./docs.js";export{runFiles,runFilesDiscover,runFilesLookup,type FilesDiscoveryCandidate,type FilesLookupItem,type FilesLookupMatch,}from "./files.js";export{applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,type AddGlobEntry,type LinkedArtifact,type LinkedArtifactCommandOptions,type LinkedArtifactKindConfig,type LinkedArtifactResult,type LinkedCollectionMutationProjection,type LinkedCollectionMutationReceipt,type LinkedPathValidation,type PathMigration,projectLinkedCollectionMutation,writtenLinkedEntries,}from "./linked-artifacts.js";export{LINKED_ARTIFACT_NOTE_CONFLICT_MODES,reviseLinkedNote,type LinkedArtifactLinkOutcome,type LinkedArtifactLinkOutcomeEntry,type LinkedArtifactNoteConflict,type LinkedArtifactNoteConflictMode,}from "./linked-artifacts.js";export * from "./pagination.js";export * from "./query/item-filter-options.js";export * from "./query/parsers.js";export * from "./output.js";export * from "./output-contracts.js";export * from "./agent/task-transcript-contracts.js";export * from "./relationship-analytics.js";export * from "./relationship-context.js";export * from "./relationship-history.js";export * from "./relationship-migration.js";export * from "./workspace-transaction.js";export * from "./workspace-transaction-gc.js";export * from "./item-transaction.js";export * from "./item-metadata-index.js";export * from "./structured-mutations.js";export * from "./lifecycle/structured-mutation-plan.js";export * from "./runtime-primitives.js";export * from "./error-runtime.js";export * from "./error-code-catalog.js";export * from "./generated-error-code-catalog.js";export * from "./agent/refusal-reachability.js";export * from "./agent/refusal-closure-census.js";export * from "./agent/refusal-closure.js";export * from "./agent/closed-domain-contracts.js";export * from "./agent/refusal-corpus-contracts.js";export{MERGE_SUBCOMMAND_VALUES}from "./cli-contracts.js";export * from "./agent/tracker-preflight-contracts.js";export * from "./agent/subcommand-recovery.js";export * from "./flag-invocation-contracts.js";export * from "./cli-contracts/flag-lexicon-contracts.js";export * from "./relationships.js";export * from "./actionability.js";export type{PlanCommandOptions,PlanOperationOptions,PlanCommandResult,PlanDispatchInput,PlanResultPlan,PlanShowDepth,PlanStepSummary,PlanSubcommand,PlanTemplateName,}from "./lifecycle/plan.js";export type{CreateOperationOptions}from "./lifecycle/create.js";export type{PlanMutationReceipt}from "./lifecycle/plan-mutation-receipt.js";export type{UpdateOperationOptions}from "./lifecycle/update.js";export type{AppendOperationOptions}from "./lifecycle/append.js";export type{CloseManyOperationOptions}from "./lifecycle/close-many.js";export type{UpdateManyOperationOptions}from "./lifecycle/update-many.js";export{runCreate}from "./lifecycle/create.js";export{runPlan}from "./lifecycle/plan.js";export{runAppend}from "./lifecycle/append.js";export{STALE_CLAIM_TAKEOVER_REFUSED_CODE,isAlreadyClaimedError,runClaim,runClaimNext,runRelease,type StaleClaimTakeoverReceipt,}from "./lifecycle/claim.js";export{runStartTask,runPauseTask,runCloseTask,type TaskCompositionOptions}from "./lifecycle/task-composition.js";export{runCloseMany}from "./lifecycle/close-many.js";export{runUpdateMany}from "./lifecycle/update-many.js";export{runComments}from "./comments.js";export{runNotes}from "./notes.js";export{runLearnings}from "./learnings.js";export{runUpgrade}from "./governance/upgrade.js";export{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,}from "./lifecycle/plan.js";export * from "./define.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,acquireLock,acquireLockLease,appendHistoryEntry,canonicalDocument,classifyItemFormatVersion,clearWorkspaceContractsCache,commitImportedItem,createHistoryEntry,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,ensureTrackerInitialized,generateItemId,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getSettingsPath,getWorkspaceContracts,isPmCliExpectedError,isTimestampLiteral,listAllItemMetadata,loadCreateTemplateOptions,locateItem,normalizeItemMetadata,normalizeItemFormatVersion,normalizeItemId,normalizeRawItemId,normalizeStatusInput,nowIso,parseTags,pathExists,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString,readSettings,readStringOption,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveItemTypeRegistry,resolveImplicitPmRoot,resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runCalendar,runCompletion,runGuide,runList,runReindex,runSearch,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,scanItemFormatVersions,selectImportAuthor,serializeItemDocument,splitFrontMatter,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportDeferredFields,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,writeFileAtomic,aggregate,append,claim,claimNext,close,reopen,closeTask,comments,config,context,copy,create,deleteItem,deps,docs,duplicates,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,get,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,learnings,list,listAllComplete,next,notes,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,pauseTask,profile,profileApply,profileLint,profileList,profileShow,release,restore,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaShow,schemaShowField,schemaShowStatus,schemaRenameField,schemaRenameType,search,startTask,stats,update,upgrade,validate,type AggregateOptions,type AggregateResult,type AggregateRow,type AppendCommandOptions,type AppendResult,type BlockerEntry,type CalendarOptions,type CalendarResult,type ClaimResult,type ClaimStartReceipt,type CloseResult,type CloseTaskResult,type CommitImportedItemParams,type CommitImportedItemResult,type CommentsCommandOptions,type CommentsResult,type ConfigCommandOptions,type ConfigResult,type CompletionResult,type CompletionShell,type ContractsCommandOptions,type ContractsResult,type ContextFocusItem,type ContextOptions,type ContextOutputFormat,type ContextResult,type CopyResult,type CreatePmCliExpectedErrorOptions,type CreateResult,type CreateTemplateOptions,type Dependency,type DeleteResult,type DepsCommandOptions,type DepsResult,type DocsCommandOptions,type DocsResult,type ExtensionCommandOptions,type ExtensionCommandResult,type FilesCommandOptions,type FilesDiscoverOptions,type FilesDiscoverResult,type FilesLookupOptions,type FilesLookupResult,type FilesResult,type FocusResult,type GcCommandOptions,type GcResult,type GetContractsOptions,type GetOptions,type GetResult,type GuideDepth,type GuideOptions,type GuideOutputFormat,type GuideResult,type HealthResult,type ImportLinkedScope,type InitCommandOptions,type InitResult,type ItemFormatVersionScanEntry,type ItemFormatVersionScanResult,type ItemFormatVersionStatus,type LearningsCommandOptions,type LearningsResult,type LinkedDoc,type LinkedFile,type LinkedTest,type ListedItem,type ListCompactResult,type ListFullResult,type ListOptions,type ListProjectedItem,type ListProjectedItemCore,type ListResult,type ListResultItem,type ListSortField,type ListSortOrder,type ListTreeItem,type ListTreeMetadata,type ListVerboseResult,type PmCompleteListCertificate,type PmCompleteListFailureReceipt,type PmCompleteListFinding,type PmCompleteListFindingCode,type PmCompleteListInspection,type PmCompleteListOptions,type PmCompleteListResult,type LogNote,type NextActionableItem,type NextBlockerRef,type NextOptions,type NextOutputFormat,type NextRecommendation,type NextResult,type NotesCommandOptions,type NotesResult,type PackageCommandOptions,type PackageCommandResult,type PauseTaskResult,type PmActionInput,type PmActionName,type PmActionOptions,type PmClientCloseActionOptions,type PmClientFullMutationOptions,type PmClientMutationOptions,type PmClientOptions,type PmClientRunArgs,type PmCliExpectedError,type ProfileApplyCommandOptions,type ProfileApplyResult,type ProfileLintResult,type ProfileListResult,type ProfileResult,type ProfileShowResult,type ProfileSubcommand,type ReindexOptions,type ReindexResult,type ReleaseResult,type ReleaseMutationOptions,type ReopenCommandOptions,type ReopenResult,type RestoreResult,type RunHealthOptions,type SchemaAddFieldCommandOptions,type SchemaAddFieldResult,type SchemaAddStatusCommandOptions,type SchemaAddStatusResult,type SchemaAddTypeCommandOptions,type SchemaAddTypeInferCommandOptions,type SchemaAddTypeInferResult,type SchemaAddTypeResult,type SchemaApplyPresetCommandOptions,type SchemaApplyPresetResult,type SchemaInspectResult,type SchemaListFieldsResult,type SchemaListResult,type SchemaRemoveFieldCommandOptions,type SchemaRemoveFieldResult,type SchemaRemoveStatusCommandOptions,type SchemaRemoveStatusResult,type SchemaRemoveTypeCommandOptions,type SchemaRemoveTypeResult,type SchemaShowFieldResult,type SchemaShowResult,type SchemaShowStatusResult,type SchemaResult,type RunSchemaEvolutionMigrationOptions,type SchemaEvolutionMigrationRequest,type SchemaEvolutionMigrationResult,type SchemaSubcommand,type SearchCompactResult,type SearchHit,type SearchHitHighlight,type SearchMatchMode,type SearchOptions,type ClaimNextOptions,type SearchResult,type SearchResultItem,type SearchVerboseResult,type StartTaskResult,type StatsCommandOptions,type StatsResult,type TemplatesListResult,type TemplatesSaveResult,type TemplatesSaveOptions,type TemplatesShowResult,type TestRunsListCommandOptions,type TestRunsLogsCommandOptions,type TestRunsResumeCommandOptions,type TestRunsStopCommandOptions,type ToImportLinkedArtifactsOptions,type ToImportLinkedTestsOptions,type ToImportLogEntriesOptions,type UpdateResult,type UpgradeCommandOptions,type UpgradeResult,type ValidateCommandOptions,type ValidateResult,type WorkspaceContracts,type WorkspaceContractsOptions,type WorkspaceExtensionCommandContract,type WorkspaceFieldContract,}from "./runtime.js";export{extensionMigrate,packageMigrate}from "./package-migrations.js";export{CONTEXT_OUTPUT_VALUES,NEXT_OUTPUT_VALUES,PM_GITIGNORE_END,PM_GITIGNORE_START,analyzeSdkActionCoverage,ensurePmGitignore,getPmGitignoreBlock,closeItem,runAggregate,runClose,runCopy,runContext,runDelete,runFocus,runGet,runNext,runRestore,runUpdate,type CloseCommandOptions,type CopyOptions,type DeleteCommandOptions,type EnsurePmGitignoreResult,type HierarchyChild,type HierarchyNode,type HotFile,type LockLease,type FocusOptions,type ImportPriorityValue,type ProgressEntry,type RecentContextItem,type RestoreCommandOptions,type SdkActionCoverageRow,type StaleEntry,type TestHealthSummary,type UpdateCommandOptions,type WorkloadEntry,}from "./runtime.js";export{runStats}from "./stats.js";export{readImprovementLedger,recordImprovementObservation,type ImprovementDirection,type ImprovementLedgerDocument,type ImprovementLedgerResult,type ImprovementObservation,type ImprovementTrend,type ReadImprovementLedgerOptions,type RecordImprovementObservationOptions,type RecordImprovementObservationResult,}from "./improvement-ledger.js";export{evaluateProvenanceCoverage,projectFleetAttributionAnalytics,projectProvenanceCoverageAnalytics,readHistoryAnalyticsWindow,runFleetAttributionAnalytics,runProvenanceCoverageAnalytics,type FleetAttributionAnalytics,type FleetAttributionDimension,type FleetAttributionRow,type HistoryAnalyticsWindowOptions,type HistoryAnalyticsWindowReceipt,type HistoryAnalyticsEvent,type HistoryAnalyticsWindow,type ProvenanceCoverageAnalytics,}from "./history-analytics.js";export{DEFAULT_EVAL_QUERIES_RELATIVE_PATH,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,parseEvalQuerySet,runEval,type EvalOptions,type EvalQueryReport,type EvalResult,}from "./eval.js";export{runTelemetry,TELEMETRY_SUBCOMMANDS,type TelemetryCommandOptions,type TelemetryFlushResult,type TelemetryStatusSummary,type TelemetrySubcommand,}from "./telemetry.js";export{classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight,type LinkedTestFailureCategory,type LinkedTestCommandSafetyClassification,type TestCommandOptions,type TestResult,type TestRunResult,}from "./test/execution.js";export{assertTestMeasurementRun}from "./test/prerequisites.js";export{TEST_RUN_MEASUREMENT_LIMIT,diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow,type TestRunMeasurementDiff,}from "./test/measurements.js";export{runTestAll,type TestAllCommandOptions,type TestAllItemResult,type TestAllResult,}from "./test/batch.js";export{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode,type LinkedTestPmContextMode,type LinkedTestWorkspaceContextMode,}from "./test/parsers.js";export{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,linkedTestTrustFingerprint,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch,type LinkedTestTrustDecision,}from "./test/trust.js";export{updateLinkedTest,type LinkedTestUpdateSelector,type LinkedTestMetadataPatch,type UpdateLinkedTestOptions,type UpdateLinkedTestResult,}from "./test/update.js";export{runStartBackgroundRun,runTestRunsWorker,type StartBackgroundRunCommandOptions,type StartBackgroundRunResult,}from "./test/runs.js";export{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile,type ProfileConfigEntry,type ProfileName,type ProfilePackageRecommendation,type ProfileTemplateEntry,type ProfileTemplateOptions,type ProjectProfileDefinition,type ProjectProfileRegistrationInput,}from "../core/profile/profile-presets.js";export{planProfileApplication,type ProfileApplicationPlan,type ProfileChangeStatus,type ProfileComponentChange,type ProfileConfigChange,type ProfileConfigPlan,type ProfileCurrentState,type ProfilePackagePlan,type ProfileSchemaPlan,type ProfileTemplateChange,type ProfileTemplatePlan,type ProfileWorkflowChange,type ProfileWorkflowPlan,}from "../core/profile/profile-plan.js";export{describeProfileComposition,describeProjectProfile,type ProjectProfileComposition,type ProjectProfileDescription,type ProjectProfilePackageSummary,}from "../core/profile/profile-describe.js";export{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,type ProfileLintCode,type ProfileLintDimension,type ProfileLintSeverity,type ProjectProfileLintFinding,type ProjectProfileLintReport,}from "../core/profile/profile-lint.js";export * from "./authoring.js";export * from "./governance.js";export * from "./mcp/discovery.js";export * from "./query.js";export * from "./testing.js";export type{GlobalOptions}from "../core/shared/command-types.js";export type{ItemDocument,ItemDeferredField,ItemMetadata,ItemStatus,ItemType,PmSettings,StructuredJsonValue,}from "../types/index.js";export{normalizeDirectExtensionCommandOptions,resolveExtensionFlagOptionKey,type DirectExtensionOptionPolicy,type LooseCommandFlagDefinition,}from "./extension/command-options.js";export type{CheckpointRestoreFn,CheckpointRollbackResult,LoadedMutationCheckpoint}from "../core/checkpoint/mutation-checkpoint.js";export type{CommandOverrideResult,DiscoverExtensionsOptions,ExtensionLayer,LoadedExtension,ParserOverrideResult,PreflightOverrideResult,RegisteredExtensionCommandOverride,RegisteredExtensionParserOverride,RegisteredExtensionPreflightOverride,RegisteredExtensionRendererOverride,RendererOverrideResult,ScopedPreflightOverrideDefinition,ScopedRendererOverrideDefinition,ServiceOverrideResult}from "../core/extensions/extension-types.js";export type{FlagValueKind}from "../core/extensions/flag-value-types.js";export type{HistoryCompactScope}from "../core/history/history-compact-bulk.js";export type{HistoryStreamPolicyManyParams,HistoryStreamPolicyParams,HistoryStreamPolicyResult}from "../core/history/history-stream-policy.js";export type{PatchFailureContext,ResolveHistoryTargetOptions,ResolvedHistoryTarget}from "../core/history/projection.js";export type{ReanchorHistoryOptions,ReanchorResult,ReplayDocument}from "../core/history/replay.js";export type{BodyFileReader}from "../core/io/body-file.js";export type{ItemDocumentFormatOptions}from "../core/item/item-format.js";export type{StdinTokenResolver}from "../core/item/parse.js";export type{Priority}from "../core/item/priority.js";export type{ParseStatusFilterOptions}from "../core/item/status-filter.js";export type{CommandOptionPolicyCommand,CommandOptionPolicyState}from "../core/item/type-registry.js";export type{AcquireLockOptions}from "../core/lock/lock.js";export type{OutputOptions}from "../core/output/output.js";export type{TabularRow}from "../core/output/tabular.js";export type{LoadedRuntimeSchemaSections,RuntimeFieldDefinitionResolved}from "../core/schema/runtime-schema.js";export type{EvaluateTransitionInput,EvaluateTransitionResult}from "../core/schema/type-workflows.js";export type{RefreshSearchArtifactsForMutationOptions,SearchMutationArtifactRefreshResult,VectorizationStatusLedgerReadResult}from "../core/search/cache.js";export type{SearchCorpusOptions,SemanticCorpusCharacterLimitResolution,SemanticCorpusInputOptions}from "../core/search/corpus.js";export type{EvalQuerySet}from "../core/search/eval.js";export type{EmbeddingProviderResolution,ProviderSettingsInput}from "../core/search/providers.js";export type{SemanticRuntimeDefaultsResolution}from "../core/search/semantic-defaults.js";export type{ExecuteVectorRequestOptions,VectorRecord,VectorSettingsInput,VectorStoreConfig,VectorStoreResolution,VectorUpsertResult}from "../core/search/vector-stores.js";export type{SentryLike}from "../core/sentry/instrument.js";export type{AgentSemanticAttribution}from "../core/session/session-state.js";export type{SerialQueue}from "../core/shared/serial-queue.js";export type{SplitCommaListOptions}from "../core/shared/split-comma-list.js";export type{ItemFormatMigrationResult}from "../core/store/item-format-migration.js";export type{ListCacheOptions}from "../core/store/item-metadata-cache.js";export type{SettingsReadResult}from "../core/store/settings.js";export type{TelemetryCommandContext,TelemetryErrorEventContext}from "../core/telemetry/runtime.js";export type{BackgroundLogStream,BackgroundTestRunStatus}from "../core/test/background-runs.js";export type{ValidateFixRecord}from "../core/validate/fix-planning.js";export type{OwnerItemMetadata,StaleLinkOwnerInput}from "../core/validate/missing-link-owners.js";export type{ClassifiedStaleLinkedPath}from "../core/validate/stale-file-classification.js";export type{BuiltinItemType,ConfidenceTextLevel,ContextDepth,ContextSectionName,ContextSettings,GovernanceStartBlockerEnforcement,HistoryEntry,HistoryPatchOp,ItemFormat,ItemTestRunSummary,LinkScope,ParentReferencePolicy,PlanMode,RuntimeSchemaSettings,SprintReleaseFormatPolicy,TestRunMeasurement}from "../types.js";export type{ContentFieldFilters}from "../core/governance/content-fields.js";export type{MissingMetadataFilters}from "../core/governance/metadata-coverage.js";export type{UpdateManyCommandOptions,UpdateManyResult}from "./lifecycle/update-many.js";export type{CommandScope}from "./command-line.js";export type{ContextIntentCursorEnvelope}from "./context-intent-contracts.js";export type{ExactCorpusShape}from "./corpus-shape.js";export type{ExactDefinition,FlagAuthoringDefinition,ItemFieldAuthoringDefinition,ItemTypeAuthoringDefinition,MigrationAuthoringDefinition,SearchProviderAuthoringDefinition,VectorStoreAdapterAuthoringDefinition}from "./define.js";export type{ManagedExtensionRecord}from "./extension/managed-state.js";export type{ValidateItem}from "./governance/validate-item-reader.js";export type{ProjectedGraphResult}from "./graph/run.js";export type{ClaimMutationOptions,ClaimNextResult}from "./lifecycle/claim.js";export type{CloseManyCommandOptions,CloseManyResult}from "./lifecycle/close-many.js";export type{RenamedLinkedArtifactResult}from "./linked-artifacts.js";export type{FilterValueEchoEntry}from "./query/list.js";export type{SearchRenderingQueryExpansion,SearchRenderingRerank}from "./query/search-rendering.js";export type{ImplicitSemanticFallbackReason,VectorIndexRecovery,VectorIndexRecoveryRegistrations}from "./query/search/semantic.js";export type{ReadOutputResultForSession}from "./read-output-contracts.js";export type{InitialReadOptions,ReadOptions,ReadPromise}from "./runtime.js";export type{LinkedTestExecutionResult,RunLinkedTestsOptions}from "./test/execution.js";export type{RegisteredHookEntry}from "./testing.js";export type{TraceabilityCandidate}from "./traceability/source-traceability.js";export type{ExactWorkspaceRecipe}from "./workspace-recipe.js";
|
|
@@ -85,8 +85,40 @@ op:"release";
|
|
|
85
85
|
id:string;
|
|
86
86
|
/** Release options forwarded to the public `release` runtime primitive. */
|
|
87
87
|
options?:PmClientFullMutationOptions;}
|
|
88
|
+
/**
|
|
89
|
+
* One exact front-matter finalization inside a bulk mutation batch (GH-1656).
|
|
90
|
+
* It writes the declared fields as given, including native lifecycle clocks
|
|
91
|
+
* (`closed_at`, `completed_at`, `created_at`) and extension fields an `update`
|
|
92
|
+
* row cannot address. The transaction journals the row, attributes its history
|
|
93
|
+
* event to the step, and compensates it by restoring the captured version, so
|
|
94
|
+
* an importer keeps rollback for its source finalization.
|
|
95
|
+
*/
|
|
96
|
+
export interface BulkItemFinalizeMutation{
|
|
97
|
+
/** Discriminates the finalization operation. */
|
|
98
|
+
op:"finalize";
|
|
99
|
+
/** Target item id. */
|
|
100
|
+
id:string;
|
|
101
|
+
/**
|
|
102
|
+
* Front-matter fields written exactly, after the store's canonicalization.
|
|
103
|
+
* Values are retained in the journal, so they must be JSON and must not be
|
|
104
|
+
* secrets. `id`, `updated_at`, `pm_format_version` and `type` are refused,
|
|
105
|
+
* and so is `null` (remove a field with `unset`).
|
|
106
|
+
*/
|
|
107
|
+
set?:Readonly<Record<string,WorkspaceTransactionJsonValue>>;
|
|
108
|
+
/** Front-matter fields removed from the item. */
|
|
109
|
+
unset?:readonly string[];
|
|
110
|
+
/**
|
|
111
|
+
* Optional guard re-checked under the item lock: the step refuses with
|
|
112
|
+
* `upsert_match_changed` unless the locked item still carries this field
|
|
113
|
+
* value, so a finalization never lands on an item another source now owns.
|
|
114
|
+
*/
|
|
115
|
+
match?:BulkItemUniqueKey;
|
|
116
|
+
/** Override the assignee-ownership check, as `force` does for an update. */
|
|
117
|
+
force?:boolean;}
|
|
118
|
+
/** Item mutations expressed through lifecycle commands; the structured document planner emits only these. */
|
|
119
|
+
export type BulkItemLifecycleMutation=BulkItemCreateMutation|BulkItemUpdateMutation|BulkItemCloseMutation|BulkItemReleaseMutation;
|
|
88
120
|
/** Union of the item mutations a bulk transaction batch can carry. */
|
|
89
|
-
export type BulkItemMutation=
|
|
121
|
+
export type BulkItemMutation=BulkItemLifecycleMutation|BulkItemFinalizeMutation;
|
|
90
122
|
/** Options accepted by the bulk item-mutation transaction helper. */
|
|
91
123
|
export interface CommitItemMutationsOptions{
|
|
92
124
|
/** Tracker root that owns the journal and workspace-wide writer lock. */
|
|
@@ -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]="359a47e6-c7e8-5713-bd07-1e19fb81674a")}catch{}})();import crypto from"node:crypto";import{runGet}from"./query/get.js";import{constants,readFileSync}from"node:fs";import{isFileMissingError,readRegularFile,transactionPreviewNonRegularFileError}from"../core/fs/fs-utils.js";import{cp,lstat,mkdir,mkdtemp,open,readdir,realpath,rm,stat,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{getActiveExtensionHooks,getActiveExtensionRegistrations,runWithPreviewMutationGuards,setActiveExtensionRegistrations}from"../core/extensions/index.js";import path from"node:path";import{transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{EXIT_CODE,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS,SETTINGS_FILENAME}from"../core/shared/constants.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{runWithItemMutationPrecondition}from"../core/store/item-mutation-precondition.js";import{activeCoordinatorStep}from"../core/store/transaction-coordinator-scope.js";import{hashDocument,hashHistoryStream}from"../core/history/history.js";import{historyVersionOffset}from"../core/history/version-address.js";import{isConfigurationOnlySettingsRead,readSettings}from"../core/store/settings.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,loadRuntimeSchemaFromOptionalFiles,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{validateSettings}from"../core/store/settings-validator.js";import{resolveWorkspaceRoot}from"../core/store/paths.js";import{getSessionStatePath}from"../core/session/session-state.js";import{PmCliError}from"../core/shared/errors.js";import{stableUpsertValue}from"./structured-mutations.js";import{stableStringify}from"../core/shared/serialization.js";import{assertMutationOptionValueTypes}from"./lifecycle/mutation-option-validation.js";import{readHistoryEntries}from"./history-read.js";import{readHistorySnapshot}from"../core/history/read.js";import{PM_CONTEXT_INTENTS_FILE}from"./context-intent-runtime.js";import{close,create,deleteItem,get,release,restore,update,runWithActiveExtensions}from"./runtime.js";import{commitWorkspaceTransaction,abandonWorkspaceTransaction,readWorkspaceTransaction,workspaceTransactionPlanDigest,validateWorkspaceTransactionIdentity}from"./workspace-transaction.js";async function resolveTransactionSchema(pmRoot,settings){if(!isConfigurationOnlySettingsRead(pmRoot))return{schema:normalizeRuntimeSchemaSettings(settings.schema),typeDefinitionsFromFile:[]};const loaded=await loadGuardedRuntimeSchema(pmRoot,settings.schema);return{schema:loaded.schema,typeDefinitionsFromFile:loaded.type_definitions_from_file??[]}}async function listUpsertKeyCandidates(pmRoot,settings,schemaContext,key){const typeRegistry=resolveItemTypeRegistry({...settings,item_types:{...settings.item_types,definitions:[...settings.item_types?.definitions??[],...schemaContext.typeDefinitionsFromFile]}},getActiveExtensionRegistrations());return(await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,schemaContext.schema)).flatMap(item=>{const value=item[key];return value==null?[]:[{id:item.id,value}]})}function createUniqueKeyIndex(pmRoot){const scans=new Map,scan=async key=>{const settings=await readSettings(pmRoot),schemaContext=await resolveTransactionSchema(pmRoot,settings),byValue=new Map;for(const candidate of await listUpsertKeyCandidates(pmRoot,settings,schemaContext,key)){const stable=stableUpsertValue(candidate.value);byValue.set(stable,[...byValue.get(stable)??[],candidate.id])}return byValue};return{lookup(key){const pending=scans.get(key)??scan(key);return scans.set(key,pending),pending},async recordCreate(item){for(const[key,pending]of scans){const value=item[key];if(value==null)continue;const byValue=await pending,stable=stableUpsertValue(value);byValue.set(stable,[...byValue.get(stable)??[],String(item.id)])}},invalidate(){scans.clear()}}}async function assertUniqueKeyFree(index,unique){const stable=stableUpsertValue(unique.value),existing=(await index.lookup(unique.key)).get(stable)??[];if(existing.length!==0)throw new PmCliError(`Upsert key "${unique.key}" value ${JSON.stringify(stable)} now matches existing item ${existing.join(", ")}; the plan was resolved before it existed.`,EXIT_CODE.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function assertUpsertMatchCurrent(document,id,match){const current=document.metadata[match.key],expected=stableUpsertValue(match.value);if(stableUpsertValue(current)!==expected)throw new PmCliError(`Item ${id} no longer carries upsert key "${match.key}" value ${JSON.stringify(expected)}; the plan selected it before the key changed.`,EXIT_CODE.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function isValidUniqueKey(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const candidate=value;return typeof candidate.key=="string"&&candidate.key.trim().length>0&&candidate.value!==void 0&&candidate.value!==null}function mergeTransactionMutationOptions(source,additions){const merged={...source,...additions};return source===void 0?merged:transferMutationStdinTokenPolicy(source,merged)}async function readItemSnapshot(pmRoot,id){try{const item=(await get(id,{},{pmRoot})).item;return{id:item.id,closedAt:item.closed_at,updatedAt:item.updated_at,assignee:item.assignee,claimPrincipal:item.claim_principal}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.NOT_FOUND)return;throw error}}function deriveStepId(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),fingerprint=crypto.createHash("sha256").update(stableStringify(mutation)).digest("hex").slice(0,12);return`${index+1}-${mutation.op}-${sanitizedTarget}-${fingerprint}`}function deriveOutcomeKey(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${index+1}-${mutation.op}-${sanitizedTarget}`}function bulkHistoryMarker(transactionId,stepId,phase){return`bulk-item-transaction ${transactionId} ${stepId} ${phase}`}function isStepMarkerMessage(message,marker){return message===marker||(message?.startsWith(`${marker} | `)??!1)}async function isUpdateMarkerApplied(pmRoot,canonicalId,transactionId,stepId){const entries=await readHistoryEntries(path.join(pmRoot,"history",`${canonicalId}.jsonl`),canonicalId),applyMarker=bulkHistoryMarker(transactionId,stepId,"apply"),compensateMarker=bulkHistoryMarker(transactionId,stepId,"compensate");for(let index=entries.length-1;index>=0;index-=1){const message=entries[index].message;if(isStepMarkerMessage(message,applyMarker))return!0;if(message===compensateMarker)return!1}return!1}async function prepareRestoreCompensation(pmRoot,mutation){const snapshot=await readItemSnapshot(pmRoot,mutation.id);if(snapshot?.updatedAt===void 0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} does not exist or has no restorable version`,EXIT_CODE.NOT_FOUND);const history=await readHistoryEntries(path.join(pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id);if(history.length===0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} has no restorable history`,EXIT_CODE.NOT_FOUND);return{target_updated_at:snapshot.updatedAt,target_version:String(historyVersionOffset(history)+history.length),target_history_hash:hashHistoryStream(history),target_history_length:history.length}}function partialMutationError(config,itemId,stepId){return new PmCliError(`Transaction ${config.transactionId} cannot safely compensate incomplete step ${stepId}; review item ${itemId} history before recovery.`,EXIT_CODE.CONFLICT,{code:"transaction_partial_mutation",item_id:itemId,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${itemId} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function isTransactionHistoryEntry(entry,transactionId){const prefix=`bulk-item-transaction ${transactionId} `;return[entry.message,entry.context?.item_transaction_step].some(value=>typeof value=="string"&&value.startsWith(prefix))}function hasOwnedCompensationEffects(history,proof,identity){const{expectedHistory,length,version}=proof;if(hashHistoryStream(history)===expectedHistory)return!1;if(typeof length!="number"||!Number.isSafeInteger(length)||length<1||hashHistoryStream(history.slice(0,length))!==expectedHistory||version!==String(historyVersionOffset(history)+length))throw partialMutationError(identity,identity.itemId,identity.stepId);const marker=bulkHistoryMarker(identity.transactionId,identity.stepId,"apply"),changes=history.slice(length),isOwned=entry=>isStepMarkerMessage(entry.message,marker)||entry.context?.item_transaction_step===marker,compensationMarker=bulkHistoryMarker(identity.transactionId,identity.stepId,"compensate");if(changes.filter(entry=>isOwned(entry)||entry.message===compensationMarker).at(-1)?.message===compensationMarker)return!1;const owned=changes.filter(isOwned);if(owned.length===0)return!1;const siblingsRestored=history.at(-1).after_hash===owned.at(-1).after_hash&&changes.every(entry=>isTransactionHistoryEntry(entry,identity.transactionId));if(owned.length!==changes.length&&!siblingsRestored)throw partialMutationError(identity,identity.itemId,identity.stepId);return!0}async function readOwnershipHistory(pmRoot,id){const historyPath=path.join(pmRoot,"history",`${id}.jsonl`),snapshot=await readHistorySnapshot(historyPath,id);return{history:snapshot.entries,assertOwnedUnderLock:(document,refusal)=>{let owned;try{owned=readFileSync(historyPath).equals(snapshot.raw_bytes)&&hashDocument(document)===snapshot.entries.at(-1).after_hash}catch(cause){throw Object.assign(refusal(),{cause})}if(!owned)throw refusal()}}}async function compensateByRestore(config,itemId,stepId,data){const receipt=data!==null&&typeof data=="object"&&!Array.isArray(data)?data:void 0;if(receipt===void 0||typeof receipt.target_updated_at!="string")return;const target=receipt.target_updated_at,current=await readItemSnapshot(config.pmRoot,itemId);if(current===void 0)return;const{history,assertOwnedUnderLock}=await readOwnershipHistory(config.pmRoot,current.id),expectedHistory=receipt.target_history_hash,journalBound=typeof expectedHistory=="string";if(typeof expectedHistory=="string"){if(!hasOwnedCompensationEffects(history,{expectedHistory,length:receipt.target_history_length,version:receipt.target_version},{...config,itemId:current.id,stepId}))return}else{if(current.updatedAt===target)return;if(!await isUpdateMarkerApplied(config.pmRoot,current.id,config.transactionId,stepId))throw partialMutationError(config,current.id,stepId)}const applyRestore=()=>restore(itemId,typeof receipt.target_version=="string"?receipt.target_version:target,{force:!0,author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"compensate")},{pmRoot:config.pmRoot});await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:current.id,validate:document=>{assertOwnedUnderLock(document,()=>partialMutationError(config,current.id,stepId))},compensation:ownedCompensation(config,itemId,stepId,"restore",journalBound)},applyRestore)}const coordinatorOwnedSteps=new WeakMap;function ownedCompensation(config,itemId,stepId,operation,historyBound){const step=historyBound?activeCoordinatorStep(config.pmRoot,config.transactionId):void 0,owner=step===void 0?void 0:coordinatorOwnedSteps.get(step);if(!(owner?.stepId!==stepId||owner.itemId!==itemId||owner.operation!==operation))return{transaction_id:config.transactionId,step_id:stepId,operations:[operation],overrides:[]}}function buildCreateStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);if(snapshot===void 0)return{state:"pending"};if(snapshot.closedAt!==void 0){const history=await readHistoryEntries(path.join(config.pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id),reason=`Compensated: interrupted bulk transaction ${config.transactionId}`;if(history.filter(entry=>entry.op==="close").at(-1)?.patch.some(change=>change.op==="add"||change.op==="replace"?change.path==="/metadata/close_reason"&&change.value===reason:!1)??!1)throw new PmCliError(`Created item ${snapshot.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,EXIT_CODE.CONFLICT,{code:"transaction_create_compensated",item_id:snapshot.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${snapshot.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:snapshot.id,op:"create"}}},async apply(){mutation.unique!==void 0&&await assertUniqueKeyFree(config.uniqueIndex,mutation.unique);const created=await create(mergeTransactionMutationOptions(mutation.options,{author:config.author,id:mutation.id,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),createdItem=created.item;return config.onCreateWarnings?.(String(createdItem.id),created.warnings),await config.uniqueIndex.recordCreate(createdItem),{id:String(createdItem.id),op:"create"}},async compensate(){await compensateCreatedItem(config,mutation.id,stepId)}}}async function compensateCreatedItem(config,id,stepId){const snapshot=await readItemSnapshot(config.pmRoot,id);if(snapshot===void 0||config.createCompensation==="close"&&snapshot.closedAt!==void 0)return;const{history,assertOwnedUnderLock}=await readOwnershipHistory(config.pmRoot,snapshot.id),applyMarker=bulkHistoryMarker(config.transactionId,stepId,"apply"),compensationMarker=bulkHistoryMarker(config.transactionId,stepId,"compensate"),latestMarker=history.filter(entry=>isStepMarkerMessage(entry.message,applyMarker)||entry.message===compensationMarker).at(-1);if(latestMarker?.message!==compensationMarker){if(latestMarker===void 0||!history.every(entry=>isTransactionHistoryEntry(entry,config.transactionId)))throw partialMutationError(config,snapshot.id,stepId);await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:snapshot.id,validate:document=>{assertOwnedUnderLock(document,()=>partialMutationError(config,snapshot.id,stepId))},compensation:ownedCompensation(config,id,stepId,config.createCompensation==="delete"?"delete":"close",!0)},async()=>{const options={force:!0,author:config.author,message:compensationMarker};config.createCompensation==="delete"?await deleteItem(id,options,{pmRoot:config.pmRoot}):await close(id,`Compensated: interrupted bulk transaction ${config.transactionId}`,{...options,validateClose:"off"},{pmRoot:config.pmRoot})})}}function buildUpdateStep(config,mutation,stepId){return{id:stepId,compensatePending:!0,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const applyUpdate=()=>update(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),match=mutation.match;let currentMatch=match;const updatedItem=(await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:String((await get(mutation.id,{},{pmRoot:config.pmRoot})).item.id),validate:document=>{currentMatch!==void 0&&assertUpsertMatchCurrent(document,mutation.id,currentMatch)},committed:document=>{match!==void 0&&(currentMatch={key:match.key,value:structuredClone(document.metadata[match.key])})},historyContext:{item_transaction_step:bulkHistoryMarker(config.transactionId,stepId,"apply")}},applyUpdate)).item;return config.uniqueIndex.invalidate(),{id:String(updatedItem.id),op:"update"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildCloseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"close"}}:snapshot.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"close"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const closedItem=(await close(mutation.id,mutation.reason,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(closedItem.id),op:"close"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildReleaseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"release"}}:snapshot.assignee!==void 0||snapshot.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"release"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const releasedItem=(await release(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(releasedItem.id),op:"release"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildStepForMutation(config,mutation,index){const stepId=deriveStepId(mutation,index),step=buildPlannedStep(config,mutation,stepId);return coordinatorOwnedSteps.set(step,{transactionId:config.transactionId,stepId,itemId:mutation.id,operation:mutation.op!=="create"?"restore":config.createCompensation==="delete"?"delete":"close"}),step}function buildPlannedStep(config,mutation,stepId){switch(mutation.op){case"create":return buildCreateStep(config,mutation,stepId);case"update":return buildUpdateStep(config,mutation,stepId);case"close":return buildCloseStep(config,mutation,stepId);case"release":return buildReleaseStep(config,mutation,stepId)}}function assertValidBulkMutation(mutation,index){if(mutation===null||typeof mutation!="object"||Array.isArray(mutation))throw new TypeError(`Bulk mutation ${index+1} must be an object`);if(!["create","update","close","release"].includes(mutation.op))throw new TypeError(`Bulk mutation ${index+1} op must be create, update, close, or release`);if(typeof mutation.id!="string"||mutation.id.trim().length===0)throw new TypeError(`Bulk mutation ${index+1} requires a non-empty id`);if(mutation.op==="close"&&(typeof mutation.reason!="string"||mutation.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${index+1} requires a non-empty reason`);if(mutation.op==="create"&&mutation.unique!==void 0&&!isValidUniqueKey(mutation.unique))throw new TypeError(`Bulk create mutation ${index+1} unique must be an object with a non-empty key and a value`);if(mutation.op==="update"&&mutation.match!==void 0&&!isValidUniqueKey(mutation.match))throw new TypeError(`Bulk update mutation ${index+1} match must be an object with a non-empty key and a value`);assertMutationOptionValueTypes(mutation.options,mutation.op,index)}function assertValidBulkMutations(mutations){if(mutations.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");const keys=new Map;for(const[index,mutation]of mutations.entries()){if(assertValidBulkMutation(mutation,index),mutation.op!=="create"||mutation.unique===void 0)continue;const{key,value}=mutation.unique,values=keys.get(key)??new Map,stable=stableUpsertValue(value),previous=values.get(stable);if(previous!==void 0)throw new PmCliError(`Bulk create mutations ${previous+1} and ${index+1} share the upsert key value ${JSON.stringify(stable)} for "${key}".`,EXIT_CODE.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});values.set(stable,index),keys.set(key,values)}}function snapshotBulkMutations(input){const mutations=[...input];return assertValidBulkMutations(mutations),mutations.map(mutation=>{const snapshot=structuredClone(mutation);return mutation.options!==void 0&&snapshot.options!==void 0&&transferMutationStdinTokenPolicy(mutation.options,snapshot.options),snapshot})}function previewClockFields(value,pointer=""){return value===null||typeof value!="object"?[]:Object.entries(value).flatMap(([key,nested])=>{const current=`${pointer}/${key.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(key)?[current]:previewClockFields(nested,current)})}async function validateMutationOperation(mutation,index,run){try{return await run()}catch(error){throw error instanceof PmCliError?new PmCliError(error.message,error.exitCode,{...error.context,transaction_operation:{index,op:mutation.op,id:mutation.id}}):error}}function includePreviewPath(root,file,ownedPaths,retainedPaths){const relative=path.relative(root,file),segments=relative.split(path.sep);return segments[0]==="extensions"&&segments[2]==="node_modules"&&!retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`))?!1:["locks","runtime","search"].includes(relative.split(path.sep)[0])?retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`)):relative===""||ownedPaths===void 0||ownedPaths.some(owned=>relative===owned||relative.startsWith(`${owned}${path.sep}`)||owned.startsWith(`${relative}${path.sep}`))}async function previewEntryStat(root,file){const entry=await lstat(file);if(entry.isSymbolicLink())await stat(file);else if(entry.isDirectory()||entry.isFile())return entry;throw transactionPreviewNonRegularFileError(path.relative(root,file))}async function previewFileDigest(root,file){const handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const entry=await handle.stat();if(!entry.isFile())throw transactionPreviewNonRegularFileError(path.relative(root,file));const contents=crypto.createHash("sha256");if(entry.size>0)for await(const chunk of handle.createReadStream({highWaterMark:64*1024,end:entry.size-1,autoClose:!1}))contents.update(chunk);return contents.digest()}finally{await handle.close()}}async function previewTrackerFingerprint(root,ownedPaths,retainedPaths){const fingerprint=crypto.createHash("sha256");async function visit(directory){for(const name of(await readdir(directory)).sort()){const file=path.join(directory,name);includePreviewPath(root,file,ownedPaths,retainedPaths)&&((await previewEntryStat(root,file)).isDirectory()?await visit(file):(fingerprint.update(JSON.stringify(path.relative(root,file))),fingerprint.update(await previewFileDigest(root,file))))}}return await visit(root),fingerprint.digest("hex")}function previewSnapshotChangedError(){return new PmCliError("Tracker changed while preparing the transaction preview; retry against stable state.",EXIT_CODE.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function isDisappearingPreviewPath(error){if(!isFileMissingError(error))return!1;const file=error.path;if(typeof file!="string")return!1;const original=path.resolve(file);let candidate=original;for(;;)try{const entry=await lstat(candidate);return candidate!==original&&entry.isDirectory()}catch(lookupError){if(!isFileMissingError(lookupError))return!1;const parent=path.dirname(candidate);if(parent===candidate)return!1;candidate=parent}}async function readPreviewConfiguration(root,relative){const file=path.join(root,relative);try{let current=root;for(const component of relative.split(path.sep).slice(0,-1))current=path.join(current,component),await previewEntryStat(root,current);if(!(await previewEntryStat(root,file)).isFile())throw transactionPreviewNonRegularFileError(relative);return await readRegularFile(file,transactionPreviewNonRegularFileError(relative))}catch(error){if(await isDisappearingPreviewPath(error))return;throw error}}async function stageGuardedSchemaSections(root,configurationRoot,schemaSettings,configuration){const schema=normalizeRuntimeSchemaSettings(schemaSettings);for(const[section,configuredPath]of Object.entries(schema.files)){const relative=path.relative(root,filePathForSchemaSection(root,configuredPath,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS[section]));if(relative===""||!path.resolve(root,relative).startsWith(path.join(root,path.sep)))throw new PmCliError("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",EXIT_CODE.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${section}`});schema.files[section]=relative;const contents=await readPreviewConfiguration(root,relative);if(configuration?.set(relative,contents),contents!==void 0){const target=path.join(configurationRoot,relative);await mkdir(path.dirname(target),{recursive:!0}),await writeFile(target,contents)}}return loadRuntimeSchemaFromOptionalFiles(configurationRoot,schema)}async function loadGuardedRuntimeSchema(pmRoot,schemaSettings){await stat(pmRoot);const root=await mkdtemp(path.join(tmpdir(),"pm-schema-plan-"));try{const resolvedRoot=await realpath(pmRoot);return await stageGuardedSchemaSections(resolvedRoot,path.join(root,"configuration"),schemaSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}finally{await rm(root,{recursive:!0,force:!0})}}async function resolvePreviewStorage(root,configurationRoot,registrations){const configuration=new Map,rawSettings=await readPreviewConfiguration(root,SETTINGS_FILENAME);configuration.set(SETTINGS_FILENAME,rawSettings);let parsed;try{parsed=JSON.parse(rawSettings??"null")}catch{parsed=null}const validated=validateSettings(parsed),settings=validated.success?validated.data:void 0,loaded=await stageGuardedSchemaSections(root,configurationRoot,settings?.schema,configuration),schema=loaded.schema,sessionPath=path.relative(root,getSessionStatePath(root));configuration.set(sessionPath,await readPreviewConfiguration(root,sessionPath));const registry=resolveItemTypeRegistry({...SETTINGS_DEFAULTS,item_types:{definitions:[...settings?.item_types?.definitions??[],...loaded.type_definitions_from_file??[]]}},registrations),ownedPaths=resolveWorkspaceRoot(root)===root?[...PM_REQUIRED_SUBDIRS.filter(Boolean),SETTINGS_FILENAME,PM_CONTEXT_INTENTS_FILE,"transactions",...registry.folders,...configuration.keys()].map(entry=>path.normalize(entry)):void 0,stagedSettings=settings===void 0?void 0:JSON.stringify({...parsed,schema:{...settings.schema,files:schema.files}});return{configuration,ownedPaths,stagedSettings,registryFolders:registry.folders}}async function stagePreviewTracker(sourceRoot,stagedRoot,registrations){await stat(sourceRoot);try{const resolvedRoot=await realpath(sourceRoot),storage=await resolvePreviewStorage(resolvedRoot,path.join(path.dirname(stagedRoot),"configuration"),registrations),retainedPaths=[...storage.configuration.keys(),...storage.registryFolders].map(entry=>path.normalize(entry)),sourceFingerprint=await previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths);await cp(resolvedRoot,stagedRoot,{recursive:!0,dereference:!1,filter:async source=>includePreviewPath(resolvedRoot,source,storage.ownedPaths,retainedPaths)?(await previewEntryStat(resolvedRoot,source),!0):!1});const[currentFingerprint,stagedFingerprint]=await Promise.all([previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths),previewTrackerFingerprint(stagedRoot,storage.ownedPaths,retainedPaths)]);if(sourceFingerprint!==currentFingerprint||sourceFingerprint!==stagedFingerprint)throw previewSnapshotChangedError();for(const[relative,contents]of storage.configuration)if(await readPreviewConfiguration(stagedRoot,relative)!==contents)throw previewSnapshotChangedError();storage.stagedSettings!==void 0&&await writeFile(path.join(stagedRoot,SETTINGS_FILENAME),storage.stagedSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}}async function previewItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=snapshotBulkMutations(options.mutations),registrations=getActiveExtensionRegistrations(),guards=getActiveExtensionHooks(),root=await mkdtemp(path.join(tmpdir(),"pm-transaction-preview-")),stagedRoot=path.join(root,"tracker");try{await stagePreviewTracker(identity.pmRoot,stagedRoot,registrations);let validated=!1;const warnings=[],records=[],applied=new Set;return await runWithPreviewMutationGuards(guards,()=>runWithActiveExtensions({path:stagedRoot,noExtensions:!0},async()=>{setActiveExtensionRegistrations(registrations);const config={...identity,pmRoot:stagedRoot,createCompensation:"close",uniqueIndex:createUniqueKeyIndex(stagedRoot)},steps=mutations.map((mutation,index)=>{const step=buildStepForMutation({...config,onCreateWarnings:(id,messages)=>{messages.length>0&&warnings.push({index,id,op:"create",warnings:messages})}},mutation,index);return{...step,inspect:()=>validateMutationOperation(mutation,index,()=>step.inspect()),prepareCompensation:()=>validateMutationOperation(mutation,index,async()=>step.prepareCompensation?.()),apply:()=>validateMutationOperation(mutation,index,async()=>{const outcome=await step.apply();return applied.add(index),outcome})}});if(await commitWorkspaceTransaction({...identity,pmRoot:stagedRoot,steps,onTransition:({transition})=>{transition==="committed"&&(validated=!0)}}),validated)for(const[index,mutation]of mutations.entries()){const item=(await runGet(mutation.id,{path:stagedRoot},{full:!0})).item;records.push({index,id:String(item.id),op:mutation.op,execution:applied.has(index)?"applied":"adopted",item,commit_time_fields:previewClockFields(item)})}})),{records,validated,state:validated?"staged_snapshot":"replayed_committed_plan",warnings,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await rm(root,{recursive:!0,force:!0})}}async function commitItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=snapshotBulkMutations(options.mutations),createCompensation=options.createCompensation??"close";if(!["close","delete"].includes(createCompensation))throw new TypeError("Bulk item transaction createCompensation must be close or delete");const stepConfig={...identity,createCompensation,uniqueIndex:createUniqueKeyIndex(identity.pmRoot)},committed=await commitWorkspaceTransaction({...identity,steps:mutations.map((mutation,index)=>buildStepForMutation(stepConfig,mutation,index)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations,createCompensation})),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}}),results={};for(const[index,mutation]of mutations.entries()){const stepId=deriveStepId(mutation,index),value=committed.results[stepId];results[deriveOutcomeKey(mutation,index)]=value}return{transactionId:committed.transactionId,status:"committed",recovered:committed.recovered,results}}function buildItemCompletionMutations(options){const mutations=[];return options.evidence!==void 0&&Object.keys(options.evidence).length>0&&mutations.push({op:"update",id:options.id,options:options.evidence}),mutations.push({op:"close",id:options.id,reason:options.reason,...options.closeOptions===void 0?{}:{options:options.closeOptions}},{op:"release",id:options.id,...options.releaseOptions===void 0?{}:{options:options.releaseOptions}}),mutations}function commitItemCompletion(options){return commitItemMutations({pmRoot:options.pmRoot,transactionId:options.transactionId,author:options.author,mutations:buildItemCompletionMutations(options),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}})}const _testOnlyItemTransaction={buildCreateStep,bulkHistoryMarker,compensateByRestore,deriveStepId,isUpdateMarkerApplied,readItemSnapshot};async function readItemTransaction(pmRoot,transactionId){const journal=await readWorkspaceTransaction(pmRoot,transactionId);return journal===void 0?void 0:{journal,planDigest:workspaceTransactionPlanDigest(journal)}}function recoveryItemSteps(options,journal){const data=journal.recoveryData;if(data===null||typeof data!="object"||Array.isArray(data)||data.kind!=="item-mutations-v1"||!Array.isArray(data.mutations)||!["close","delete"].includes(String(data.createCompensation)))throw new PmCliError("Transaction has no supported item recovery plan",EXIT_CODE.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});const mutations=data.mutations;assertValidBulkMutations(mutations);const config={...options,createCompensation:data.createCompensation,uniqueIndex:createUniqueKeyIndex(options.pmRoot)};return mutations.map((mutation,index)=>buildStepForMutation(config,mutation,index))}async function abandonItemTransaction(options){const identity=validateWorkspaceTransactionIdentity(options),journal=await abandonWorkspaceTransaction({...options,...identity,resolveSteps:receipt=>recoveryItemSteps({...options,...identity},receipt)});return{journal,planDigest:workspaceTransactionPlanDigest(journal)}}export{_testOnlyItemTransaction,abandonItemTransaction,buildItemCompletionMutations,commitItemCompletion,commitItemMutations,listUpsertKeyCandidates,loadGuardedRuntimeSchema,previewItemMutations,readItemTransaction,resolveTransactionSchema};
|
|
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]="737c7105-2837-5a61-bb89-263c84ef1259")}catch{}})();import crypto from"node:crypto";import{runGet}from"./query/get.js";import{constants,readFileSync}from"node:fs";import{isFileMissingError,readRegularFile,transactionPreviewNonRegularFileError}from"../core/fs/fs-utils.js";import{cp,lstat,mkdir,mkdtemp,open,readdir,realpath,rm,stat,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{getActiveExtensionHooks,getActiveExtensionRegistrations,runWithPreviewMutationGuards,setActiveExtensionRegistrations}from"../core/extensions/index.js";import path from"node:path";import{transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{EXIT_CODE,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS,SETTINGS_FILENAME}from"../core/shared/constants.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{runWithItemMutationPrecondition}from"../core/store/item-mutation-precondition.js";import{activeCoordinatorStep}from"../core/store/transaction-coordinator-scope.js";import{hashDocument,hashHistoryStream}from"../core/history/history.js";import{historyVersionOffset}from"../core/history/version-address.js";import{isConfigurationOnlySettingsRead,readSettings}from"../core/store/settings.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,loadRuntimeSchemaFromOptionalFiles,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{validateSettings}from"../core/store/settings-validator.js";import{resolveWorkspaceRoot}from"../core/store/paths.js";import{getSessionStatePath}from"../core/session/session-state.js";import{PmCliError}from"../core/shared/errors.js";import{stableUpsertValue}from"./structured-mutations.js";import{stableStringify}from"../core/shared/serialization.js";import{assertMutationOptionValueTypes}from"./lifecycle/mutation-option-validation.js";import{readHistoryEntries}from"./history-read.js";import{readHistorySnapshot}from"../core/history/read.js";import{applyItemFinalization,assertValidItemFinalization,isJournalValue}from"./transactions/item-finalization.js";import{PM_CONTEXT_INTENTS_FILE}from"./context-intent-runtime.js";import{close,create,deleteItem,get,release,restore,update,runInActiveExtensionScope,runWithActiveExtensions}from"./runtime.js";import{commitWorkspaceTransaction,abandonWorkspaceTransaction,readWorkspaceTransaction,workspaceTransactionPlanDigest,validateWorkspaceTransactionIdentity}from"./workspace-transaction.js";async function resolveTransactionSchema(pmRoot,settings){if(!isConfigurationOnlySettingsRead(pmRoot))return{schema:normalizeRuntimeSchemaSettings(settings.schema),typeDefinitionsFromFile:[]};const loaded=await loadGuardedRuntimeSchema(pmRoot,settings.schema);return{schema:loaded.schema,typeDefinitionsFromFile:loaded.type_definitions_from_file??[]}}async function listUpsertKeyCandidates(pmRoot,settings,schemaContext,key){const typeRegistry=resolveItemTypeRegistry({...settings,item_types:{...settings.item_types,definitions:[...settings.item_types?.definitions??[],...schemaContext.typeDefinitionsFromFile]}},getActiveExtensionRegistrations());return(await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,schemaContext.schema)).flatMap(item=>{const value=item[key];return value==null?[]:[{id:item.id,value}]})}function createUniqueKeyIndex(pmRoot){const scans=new Map,scan=async key=>{const settings=await readSettings(pmRoot),schemaContext=await resolveTransactionSchema(pmRoot,settings),byValue=new Map;for(const candidate of await listUpsertKeyCandidates(pmRoot,settings,schemaContext,key)){const stable=stableUpsertValue(candidate.value);byValue.set(stable,[...byValue.get(stable)??[],candidate.id])}return byValue};return{lookup(key){const pending=scans.get(key)??scan(key);return scans.set(key,pending),pending},async recordCreate(item){for(const[key,pending]of scans){const value=item[key];if(value==null)continue;const byValue=await pending,stable=stableUpsertValue(value);byValue.set(stable,[...byValue.get(stable)??[],String(item.id)])}},invalidate(){scans.clear()}}}async function assertUniqueKeyFree(index,unique){const stable=stableUpsertValue(unique.value),existing=(await index.lookup(unique.key)).get(stable)??[];if(existing.length!==0)throw new PmCliError(`Upsert key "${unique.key}" value ${JSON.stringify(stable)} now matches existing item ${existing.join(", ")}; the plan was resolved before it existed.`,EXIT_CODE.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function assertUpsertMatchCurrent(document,id,match){const current=document.metadata[match.key],expected=stableUpsertValue(match.value);if(stableUpsertValue(current)!==expected)throw new PmCliError(`Item ${id} no longer carries upsert key "${match.key}" value ${JSON.stringify(expected)}; the plan selected it before the key changed.`,EXIT_CODE.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function isValidUniqueKey(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const candidate=value;return typeof candidate.key=="string"&&candidate.key.trim().length>0&&candidate.value!==void 0&&candidate.value!==null}function mergeTransactionMutationOptions(source,additions){const merged={...source,...additions};return source===void 0?merged:transferMutationStdinTokenPolicy(source,merged)}async function readItemSnapshot(pmRoot,id){try{const item=(await get(id,{},{pmRoot})).item;return{id:item.id,closedAt:item.closed_at,updatedAt:item.updated_at,assignee:item.assignee,claimPrincipal:item.claim_principal}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.NOT_FOUND)return;throw error}}function deriveStepId(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),fingerprint=crypto.createHash("sha256").update(stableStringify(mutation)).digest("hex").slice(0,12);return`${index+1}-${mutation.op}-${sanitizedTarget}-${fingerprint}`}function deriveOutcomeKey(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${index+1}-${mutation.op}-${sanitizedTarget}`}function bulkHistoryMarker(transactionId,stepId,phase){return`bulk-item-transaction ${transactionId} ${stepId} ${phase}`}function isStepMarkerMessage(message,marker){return message===marker||(message?.startsWith(`${marker} | `)??!1)}async function isUpdateMarkerApplied(pmRoot,canonicalId,transactionId,stepId){const entries=await readHistoryEntries(path.join(pmRoot,"history",`${canonicalId}.jsonl`),canonicalId),applyMarker=bulkHistoryMarker(transactionId,stepId,"apply"),compensateMarker=bulkHistoryMarker(transactionId,stepId,"compensate");for(let index=entries.length-1;index>=0;index-=1){const message=entries[index].message;if(isStepMarkerMessage(message,applyMarker))return!0;if(message===compensateMarker)return!1}return!1}async function prepareRestoreCompensation(pmRoot,mutation){const snapshot=await readItemSnapshot(pmRoot,mutation.id);if(snapshot?.updatedAt===void 0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} does not exist or has no restorable version`,EXIT_CODE.NOT_FOUND);const history=await readHistoryEntries(path.join(pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id);if(history.length===0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} has no restorable history`,EXIT_CODE.NOT_FOUND);return{target_updated_at:snapshot.updatedAt,target_version:String(historyVersionOffset(history)+history.length),target_history_hash:hashHistoryStream(history),target_history_length:history.length}}function partialMutationError(config,itemId,stepId){return new PmCliError(`Transaction ${config.transactionId} cannot safely compensate incomplete step ${stepId}; review item ${itemId} history before recovery.`,EXIT_CODE.CONFLICT,{code:"transaction_partial_mutation",item_id:itemId,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${itemId} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function isTransactionHistoryEntry(entry,transactionId){const prefix=`bulk-item-transaction ${transactionId} `;return[entry.message,entry.context?.item_transaction_step].some(value=>typeof value=="string"&&value.startsWith(prefix))}function hasOwnedCompensationEffects(history,proof,identity){const{expectedHistory,length,version}=proof;if(hashHistoryStream(history)===expectedHistory)return!1;if(typeof length!="number"||!Number.isSafeInteger(length)||length<1||hashHistoryStream(history.slice(0,length))!==expectedHistory||version!==String(historyVersionOffset(history)+length))throw partialMutationError(identity,identity.itemId,identity.stepId);const marker=bulkHistoryMarker(identity.transactionId,identity.stepId,"apply"),changes=history.slice(length),isOwned=entry=>isStepMarkerMessage(entry.message,marker)||entry.context?.item_transaction_step===marker,compensationMarker=bulkHistoryMarker(identity.transactionId,identity.stepId,"compensate");if(changes.filter(entry=>isOwned(entry)||entry.message===compensationMarker).at(-1)?.message===compensationMarker)return!1;const owned=changes.filter(isOwned);if(owned.length===0)return!1;const siblingsRestored=history.at(-1).after_hash===owned.at(-1).after_hash&&changes.every(entry=>isTransactionHistoryEntry(entry,identity.transactionId));if(owned.length!==changes.length&&!siblingsRestored)throw partialMutationError(identity,identity.itemId,identity.stepId);return!0}async function readOwnershipHistory(pmRoot,id){const historyPath=path.join(pmRoot,"history",`${id}.jsonl`),snapshot=await readHistorySnapshot(historyPath,id);return{history:snapshot.entries,assertOwnedUnderLock:(document,refusal)=>{let owned;try{owned=readFileSync(historyPath).equals(snapshot.raw_bytes)&&hashDocument(document)===snapshot.entries.at(-1).after_hash}catch(cause){throw Object.assign(refusal(),{cause})}if(!owned)throw refusal()}}}async function compensateByRestore(config,itemId,stepId,data){const receipt=data!==null&&typeof data=="object"&&!Array.isArray(data)?data:void 0;if(receipt===void 0||typeof receipt.target_updated_at!="string")return;const target=receipt.target_updated_at,current=await readItemSnapshot(config.pmRoot,itemId);if(current===void 0)return;const{history,assertOwnedUnderLock}=await readOwnershipHistory(config.pmRoot,current.id),expectedHistory=receipt.target_history_hash,journalBound=typeof expectedHistory=="string";if(typeof expectedHistory=="string"){if(!hasOwnedCompensationEffects(history,{expectedHistory,length:receipt.target_history_length,version:receipt.target_version},{...config,itemId:current.id,stepId}))return}else{if(current.updatedAt===target)return;if(!await isUpdateMarkerApplied(config.pmRoot,current.id,config.transactionId,stepId))throw partialMutationError(config,current.id,stepId)}const applyRestore=()=>restore(itemId,typeof receipt.target_version=="string"?receipt.target_version:target,{force:!0,author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"compensate")},{pmRoot:config.pmRoot});await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:current.id,validate:document=>{assertOwnedUnderLock(document,()=>partialMutationError(config,current.id,stepId))},compensation:ownedCompensation(config,itemId,stepId,"restore",journalBound)},applyRestore)}const coordinatorOwnedSteps=new WeakMap;function ownedCompensation(config,itemId,stepId,operation,historyBound){const step=historyBound?activeCoordinatorStep(config.pmRoot,config.transactionId):void 0,owner=step===void 0?void 0:coordinatorOwnedSteps.get(step);if(!(owner?.stepId!==stepId||owner.itemId!==itemId||owner.operation!==operation))return{transaction_id:config.transactionId,step_id:stepId,operations:[operation],overrides:[]}}function buildCreateStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);if(snapshot===void 0)return{state:"pending"};if(snapshot.closedAt!==void 0){const history=await readHistoryEntries(path.join(config.pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id),reason=`Compensated: interrupted bulk transaction ${config.transactionId}`;if(history.filter(entry=>entry.op==="close").at(-1)?.patch.some(change=>change.op==="add"||change.op==="replace"?change.path==="/metadata/close_reason"&&change.value===reason:!1)??!1)throw new PmCliError(`Created item ${snapshot.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,EXIT_CODE.CONFLICT,{code:"transaction_create_compensated",item_id:snapshot.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${snapshot.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:snapshot.id,op:"create"}}},async apply(){mutation.unique!==void 0&&await assertUniqueKeyFree(config.uniqueIndex,mutation.unique);const created=await create(mergeTransactionMutationOptions(mutation.options,{author:config.author,id:mutation.id,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),createdItem=created.item;return config.onCreateWarnings?.(String(createdItem.id),created.warnings),await config.uniqueIndex.recordCreate(createdItem),{id:String(createdItem.id),op:"create"}},async compensate(){await compensateCreatedItem(config,mutation.id,stepId)}}}async function compensateCreatedItem(config,id,stepId){const snapshot=await readItemSnapshot(config.pmRoot,id);if(snapshot===void 0||config.createCompensation==="close"&&snapshot.closedAt!==void 0)return;const{history,assertOwnedUnderLock}=await readOwnershipHistory(config.pmRoot,snapshot.id),applyMarker=bulkHistoryMarker(config.transactionId,stepId,"apply"),compensationMarker=bulkHistoryMarker(config.transactionId,stepId,"compensate"),latestMarker=history.filter(entry=>isStepMarkerMessage(entry.message,applyMarker)||entry.message===compensationMarker).at(-1);if(latestMarker?.message!==compensationMarker){if(latestMarker===void 0||!history.every(entry=>isTransactionHistoryEntry(entry,config.transactionId)))throw partialMutationError(config,snapshot.id,stepId);await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:snapshot.id,validate:document=>{assertOwnedUnderLock(document,()=>partialMutationError(config,snapshot.id,stepId))},compensation:ownedCompensation(config,id,stepId,config.createCompensation==="delete"?"delete":"close",!0)},async()=>{const options={force:!0,author:config.author,message:compensationMarker};config.createCompensation==="delete"?await deleteItem(id,options,{pmRoot:config.pmRoot}):await close(id,`Compensated: interrupted bulk transaction ${config.transactionId}`,{...options,validateClose:"off"},{pmRoot:config.pmRoot})})}}function buildUpdateStep(config,mutation,stepId){return{id:stepId,compensatePending:!0,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const applyUpdate=()=>update(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),match=mutation.match;let currentMatch=match;const updatedItem=(await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:await canonicalItemId(config.pmRoot,mutation.id),validate:document=>{currentMatch!==void 0&&assertUpsertMatchCurrent(document,mutation.id,currentMatch)},committed:document=>{match!==void 0&&(currentMatch={key:match.key,value:structuredClone(document.metadata[match.key])})},historyContext:{item_transaction_step:bulkHistoryMarker(config.transactionId,stepId,"apply")}},applyUpdate)).item;return config.uniqueIndex.invalidate(),{id:String(updatedItem.id),op:"update"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}async function canonicalItemId(pmRoot,id){return String((await get(id,{},{pmRoot})).item.id)}function buildFinalizeStep(config,mutation,stepId){const marker=bulkHistoryMarker(config.transactionId,stepId,"apply");return{id:stepId,compensatePending:!0,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0||!await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:mutation.op}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const id=await canonicalItemId(config.pmRoot,mutation.id),{match}=mutation;return await runInActiveExtensionScope(config.pmRoot,()=>runWithItemMutationPrecondition({pmRoot:config.pmRoot,id,validate:document=>{match!==void 0&&assertUpsertMatchCurrent(document,mutation.id,match)},historyContext:{item_transaction_step:marker}},()=>applyItemFinalization({pmRoot:config.pmRoot,id,author:config.author,message:marker,force:mutation.force,...mutation.set===void 0?{}:{set:mutation.set},...mutation.unset===void 0?{}:{unset:mutation.unset}}))),config.uniqueIndex.invalidate(),{id,op:mutation.op}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildCloseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"close"}}:snapshot.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"close"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const closedItem=(await close(mutation.id,mutation.reason,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(closedItem.id),op:"close"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildReleaseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"release"}}:snapshot.assignee!==void 0||snapshot.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"release"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const releasedItem=(await release(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(releasedItem.id),op:"release"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildStepForMutation(config,mutation,index){const stepId=deriveStepId(mutation,index),step=buildPlannedStep(config,mutation,stepId);return coordinatorOwnedSteps.set(step,{transactionId:config.transactionId,stepId,itemId:mutation.id,operation:mutation.op!=="create"?"restore":config.createCompensation==="delete"?"delete":"close"}),step}function buildPlannedStep(config,mutation,stepId){switch(mutation.op){case"create":return buildCreateStep(config,mutation,stepId);case"update":return buildUpdateStep(config,mutation,stepId);case"close":return buildCloseStep(config,mutation,stepId);case"release":return buildReleaseStep(config,mutation,stepId);case"finalize":return buildFinalizeStep(config,mutation,stepId)}}function assertValidBulkMutation(mutation,index){if(mutation===null||typeof mutation!="object"||Array.isArray(mutation))throw new TypeError(`Bulk mutation ${index+1} must be an object`);if(!["create","update","close","release","finalize"].includes(mutation.op))throw new TypeError(`Bulk mutation ${index+1} op must be create, update, close, release, or finalize`);if(typeof mutation.id!="string"||mutation.id.trim().length===0)throw new TypeError(`Bulk mutation ${index+1} requires a non-empty id`);if(mutation.op==="close"&&(typeof mutation.reason!="string"||mutation.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${index+1} requires a non-empty reason`);if(assertValidBulkKeyGuard(mutation,index),mutation.op==="finalize"){assertValidBulkFinalization(mutation,index);return}assertMutationOptionValueTypes(mutation.options,mutation.op,index)}function assertValidBulkKeyGuard(mutation,index){if(mutation.op==="create"&&mutation.unique!==void 0&&!isValidUniqueKey(mutation.unique))throw new TypeError(`Bulk create mutation ${index+1} unique must be an object with a non-empty key and a value`);if((mutation.op==="update"||mutation.op==="finalize")&&mutation.match!==void 0&&!isValidUniqueKey(mutation.match))throw new TypeError(`Bulk ${mutation.op} mutation ${index+1} match must be an object with a non-empty key and a value`)}const FINALIZE_ROW_KEYS=["op","id","set","unset","match","force"];function assertValidBulkFinalization(mutation,index){const label=`Bulk finalize mutation ${index+1}`,unknown=Object.keys(mutation).filter(key=>!FINALIZE_ROW_KEYS.includes(key));if(unknown.length>0)throw new TypeError(`${label} has unsupported keys: ${unknown.join(", ")}; a finalization carries only ${FINALIZE_ROW_KEYS.join(", ")}`);if(mutation.force!==void 0&&typeof mutation.force!="boolean")throw new TypeError(`${label} force must be a boolean`);if(mutation.match!==void 0&&!isJournalValue(mutation.match))throw new TypeError(`${label} match must be a plain object with a JSON value`);assertValidItemFinalization(mutation,label)}function assertValidBulkMutations(mutations){if(mutations.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");const keys=new Map;for(const[index,mutation]of mutations.entries()){if(assertValidBulkMutation(mutation,index),mutation.op!=="create"||mutation.unique===void 0)continue;const{key,value}=mutation.unique,values=keys.get(key)??new Map,stable=stableUpsertValue(value),previous=values.get(stable);if(previous!==void 0)throw new PmCliError(`Bulk create mutations ${previous+1} and ${index+1} share the upsert key value ${JSON.stringify(stable)} for "${key}".`,EXIT_CODE.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});values.set(stable,index),keys.set(key,values)}}function snapshotBulkMutations(input){const mutations=[...input];assertValidBulkMutations(mutations);const snapshots=mutations.map(mutation=>{const snapshot=structuredClone(mutation);return mutation.op!=="finalize"&&snapshot.op!=="finalize"&&mutation.options!==void 0&&snapshot.options!==void 0&&transferMutationStdinTokenPolicy(mutation.options,snapshot.options),snapshot});return assertValidBulkMutations(snapshots),snapshots}function previewClockFields(value,pointer=""){return value===null||typeof value!="object"?[]:Object.entries(value).flatMap(([key,nested])=>{const current=`${pointer}/${key.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(key)?[current]:previewClockFields(nested,current)})}async function validateMutationOperation(mutation,index,run){try{return await run()}catch(error){throw error instanceof PmCliError?new PmCliError(error.message,error.exitCode,{...error.context,transaction_operation:{index,op:mutation.op,id:mutation.id}}):error}}function includePreviewPath(root,file,ownedPaths,retainedPaths){const relative=path.relative(root,file),segments=relative.split(path.sep);return segments[0]==="extensions"&&segments[2]==="node_modules"&&!retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`))?!1:["locks","runtime","search"].includes(relative.split(path.sep)[0])?retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`)):relative===""||ownedPaths===void 0||ownedPaths.some(owned=>relative===owned||relative.startsWith(`${owned}${path.sep}`)||owned.startsWith(`${relative}${path.sep}`))}async function previewEntryStat(root,file){const entry=await lstat(file);if(entry.isSymbolicLink())await stat(file);else if(entry.isDirectory()||entry.isFile())return entry;throw transactionPreviewNonRegularFileError(path.relative(root,file))}async function previewFileDigest(root,file){const handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const entry=await handle.stat();if(!entry.isFile())throw transactionPreviewNonRegularFileError(path.relative(root,file));const contents=crypto.createHash("sha256");if(entry.size>0)for await(const chunk of handle.createReadStream({highWaterMark:64*1024,end:entry.size-1,autoClose:!1}))contents.update(chunk);return contents.digest()}finally{await handle.close()}}async function previewTrackerFingerprint(root,ownedPaths,retainedPaths){const fingerprint=crypto.createHash("sha256");async function visit(directory){for(const name of(await readdir(directory)).sort()){const file=path.join(directory,name);includePreviewPath(root,file,ownedPaths,retainedPaths)&&((await previewEntryStat(root,file)).isDirectory()?await visit(file):(fingerprint.update(JSON.stringify(path.relative(root,file))),fingerprint.update(await previewFileDigest(root,file))))}}return await visit(root),fingerprint.digest("hex")}function previewSnapshotChangedError(){return new PmCliError("Tracker changed while preparing the transaction preview; retry against stable state.",EXIT_CODE.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function isDisappearingPreviewPath(error){if(!isFileMissingError(error))return!1;const file=error.path;if(typeof file!="string")return!1;const original=path.resolve(file);let candidate=original;for(;;)try{const entry=await lstat(candidate);return candidate!==original&&entry.isDirectory()}catch(lookupError){if(!isFileMissingError(lookupError))return!1;const parent=path.dirname(candidate);if(parent===candidate)return!1;candidate=parent}}async function readPreviewConfiguration(root,relative){const file=path.join(root,relative);try{let current=root;for(const component of relative.split(path.sep).slice(0,-1))current=path.join(current,component),await previewEntryStat(root,current);if(!(await previewEntryStat(root,file)).isFile())throw transactionPreviewNonRegularFileError(relative);return await readRegularFile(file,transactionPreviewNonRegularFileError(relative))}catch(error){if(await isDisappearingPreviewPath(error))return;throw error}}async function stageGuardedSchemaSections(root,configurationRoot,schemaSettings,configuration){const schema=normalizeRuntimeSchemaSettings(schemaSettings);for(const[section,configuredPath]of Object.entries(schema.files)){const relative=path.relative(root,filePathForSchemaSection(root,configuredPath,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS[section]));if(relative===""||!path.resolve(root,relative).startsWith(path.join(root,path.sep)))throw new PmCliError("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",EXIT_CODE.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${section}`});schema.files[section]=relative;const contents=await readPreviewConfiguration(root,relative);if(configuration?.set(relative,contents),contents!==void 0){const target=path.join(configurationRoot,relative);await mkdir(path.dirname(target),{recursive:!0}),await writeFile(target,contents)}}return loadRuntimeSchemaFromOptionalFiles(configurationRoot,schema)}async function loadGuardedRuntimeSchema(pmRoot,schemaSettings){await stat(pmRoot);const root=await mkdtemp(path.join(tmpdir(),"pm-schema-plan-"));try{const resolvedRoot=await realpath(pmRoot);return await stageGuardedSchemaSections(resolvedRoot,path.join(root,"configuration"),schemaSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}finally{await rm(root,{recursive:!0,force:!0})}}async function resolvePreviewStorage(root,configurationRoot,registrations){const configuration=new Map,rawSettings=await readPreviewConfiguration(root,SETTINGS_FILENAME);configuration.set(SETTINGS_FILENAME,rawSettings);let parsed;try{parsed=JSON.parse(rawSettings??"null")}catch{parsed=null}const validated=validateSettings(parsed),settings=validated.success?validated.data:void 0,loaded=await stageGuardedSchemaSections(root,configurationRoot,settings?.schema,configuration),schema=loaded.schema,sessionPath=path.relative(root,getSessionStatePath(root));configuration.set(sessionPath,await readPreviewConfiguration(root,sessionPath));const registry=resolveItemTypeRegistry({...SETTINGS_DEFAULTS,item_types:{definitions:[...settings?.item_types?.definitions??[],...loaded.type_definitions_from_file??[]]}},registrations),ownedPaths=resolveWorkspaceRoot(root)===root?[...PM_REQUIRED_SUBDIRS.filter(Boolean),SETTINGS_FILENAME,PM_CONTEXT_INTENTS_FILE,"transactions",...registry.folders,...configuration.keys()].map(entry=>path.normalize(entry)):void 0,stagedSettings=settings===void 0?void 0:JSON.stringify({...parsed,schema:{...settings.schema,files:schema.files}});return{configuration,ownedPaths,stagedSettings,registryFolders:registry.folders}}async function stagePreviewTracker(sourceRoot,stagedRoot,registrations){await stat(sourceRoot);try{const resolvedRoot=await realpath(sourceRoot),storage=await resolvePreviewStorage(resolvedRoot,path.join(path.dirname(stagedRoot),"configuration"),registrations),retainedPaths=[...storage.configuration.keys(),...storage.registryFolders].map(entry=>path.normalize(entry)),sourceFingerprint=await previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths);await cp(resolvedRoot,stagedRoot,{recursive:!0,dereference:!1,filter:async source=>includePreviewPath(resolvedRoot,source,storage.ownedPaths,retainedPaths)?(await previewEntryStat(resolvedRoot,source),!0):!1});const[currentFingerprint,stagedFingerprint]=await Promise.all([previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths),previewTrackerFingerprint(stagedRoot,storage.ownedPaths,retainedPaths)]);if(sourceFingerprint!==currentFingerprint||sourceFingerprint!==stagedFingerprint)throw previewSnapshotChangedError();for(const[relative,contents]of storage.configuration)if(await readPreviewConfiguration(stagedRoot,relative)!==contents)throw previewSnapshotChangedError();storage.stagedSettings!==void 0&&await writeFile(path.join(stagedRoot,SETTINGS_FILENAME),storage.stagedSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}}async function previewItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=snapshotBulkMutations(options.mutations),registrations=getActiveExtensionRegistrations(),guards=getActiveExtensionHooks(),root=await mkdtemp(path.join(tmpdir(),"pm-transaction-preview-")),stagedRoot=path.join(root,"tracker");try{await stagePreviewTracker(identity.pmRoot,stagedRoot,registrations);let validated=!1;const warnings=[],records=[],applied=new Set;return await runWithPreviewMutationGuards(guards,()=>runWithActiveExtensions({path:stagedRoot,noExtensions:!0},async()=>{setActiveExtensionRegistrations(registrations);const config={...identity,pmRoot:stagedRoot,createCompensation:"close",uniqueIndex:createUniqueKeyIndex(stagedRoot)},steps=mutations.map((mutation,index)=>{const step=buildStepForMutation({...config,onCreateWarnings:(id,messages)=>{messages.length>0&&warnings.push({index,id,op:"create",warnings:messages})}},mutation,index);return{...step,inspect:()=>validateMutationOperation(mutation,index,()=>step.inspect()),prepareCompensation:()=>validateMutationOperation(mutation,index,async()=>step.prepareCompensation?.()),apply:()=>validateMutationOperation(mutation,index,async()=>{const outcome=await step.apply();return applied.add(index),outcome})}});if(await commitWorkspaceTransaction({...identity,pmRoot:stagedRoot,steps,onTransition:({transition})=>{transition==="committed"&&(validated=!0)}}),validated)for(const[index,mutation]of mutations.entries()){const item=(await runGet(mutation.id,{path:stagedRoot},{full:!0})).item;records.push({index,id:String(item.id),op:mutation.op,execution:applied.has(index)?"applied":"adopted",item,commit_time_fields:previewClockFields(item)})}})),{records,validated,state:validated?"staged_snapshot":"replayed_committed_plan",warnings,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await rm(root,{recursive:!0,force:!0})}}async function commitItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=snapshotBulkMutations(options.mutations),createCompensation=options.createCompensation??"close";if(!["close","delete"].includes(createCompensation))throw new TypeError("Bulk item transaction createCompensation must be close or delete");const stepConfig={...identity,createCompensation,uniqueIndex:createUniqueKeyIndex(identity.pmRoot)},committed=await commitWorkspaceTransaction({...identity,steps:mutations.map((mutation,index)=>buildStepForMutation(stepConfig,mutation,index)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations,createCompensation})),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}}),results={};for(const[index,mutation]of mutations.entries()){const stepId=deriveStepId(mutation,index),value=committed.results[stepId];results[deriveOutcomeKey(mutation,index)]=value}return{transactionId:committed.transactionId,status:"committed",recovered:committed.recovered,results}}function buildItemCompletionMutations(options){const mutations=[];return options.evidence!==void 0&&Object.keys(options.evidence).length>0&&mutations.push({op:"update",id:options.id,options:options.evidence}),mutations.push({op:"close",id:options.id,reason:options.reason,...options.closeOptions===void 0?{}:{options:options.closeOptions}},{op:"release",id:options.id,...options.releaseOptions===void 0?{}:{options:options.releaseOptions}}),mutations}function commitItemCompletion(options){return commitItemMutations({pmRoot:options.pmRoot,transactionId:options.transactionId,author:options.author,mutations:buildItemCompletionMutations(options),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}})}const _testOnlyItemTransaction={buildCreateStep,bulkHistoryMarker,compensateByRestore,deriveStepId,isUpdateMarkerApplied,readItemSnapshot};async function readItemTransaction(pmRoot,transactionId){const journal=await readWorkspaceTransaction(pmRoot,transactionId);return journal===void 0?void 0:{journal,planDigest:workspaceTransactionPlanDigest(journal)}}function recoveryItemSteps(options,journal){const data=journal.recoveryData;if(data===null||typeof data!="object"||Array.isArray(data)||data.kind!=="item-mutations-v1"||!Array.isArray(data.mutations)||!["close","delete"].includes(String(data.createCompensation)))throw new PmCliError("Transaction has no supported item recovery plan",EXIT_CODE.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});const mutations=data.mutations;assertValidBulkMutations(mutations);const config={...options,createCompensation:data.createCompensation,uniqueIndex:createUniqueKeyIndex(options.pmRoot)};return mutations.map((mutation,index)=>buildStepForMutation(config,mutation,index))}async function abandonItemTransaction(options){const identity=validateWorkspaceTransactionIdentity(options),journal=await abandonWorkspaceTransaction({...options,...identity,resolveSteps:receipt=>recoveryItemSteps({...options,...identity},receipt)});return{journal,planDigest:workspaceTransactionPlanDigest(journal)}}export{_testOnlyItemTransaction,abandonItemTransaction,buildItemCompletionMutations,commitItemCompletion,commitItemMutations,listUpsertKeyCandidates,loadGuardedRuntimeSchema,previewItemMutations,readItemTransaction,resolveTransactionSchema};
|
|
2
2
|
//# sourceMappingURL=item-transaction.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]="6d26f43a-2279-5f83-98ed-dca98f105c8c")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../environment/project-runtime-compatibility.js";import{enforceWorkflowMutation}from"../../core/policy/workflow-policy-store.js";import jsonPatch from"fast-json-patch";import fs from"node:fs/promises";import{readLocatedItemSnapshot}from"../../core/store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable,transactionCompensationHistoryContext}from"../../core/store/item-mutation-precondition.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{readHistorySnapshot}from"../../core/history/read.js";import{verifyHistoryRewriteNoDrift}from"../../core/history/history-rewrite.js";import{resolveHistorySubject}from"../history/subject.js";import{historyVersionOffset}from"../../core/history/version-address.js";import{writeFileAtomic,appendHistoryEntry,createHistoryEntry,replayToCanonicalItemDocument,replayToItemDocument,toReplayDocument,enforceHistoryStreamPolicyForItem,canonicalDocument,serializeItemDocument,resolveItemTypeRegistry,acquireLockLease,EXIT_CODE,PmCliError,nowIso,getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnWriteHooks,runActiveBeforeMutationHooks,createMutationGuardSdk,getItemPath,resolvePmRoot,resolveWorkspaceRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{applyHistoryPatch,ensureMaterializedHistoryTarget as ensureMaterializedRestoreTarget,extractPatchFailureContext,replayHistoryToTarget as replayToTarget,resolveHistoryTarget}from"../history-read.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../item-metadata-index.js";import{redactOptionalIdentityCredentials}from"../../core/shared/url-credentials.js";async function readRestoreItem(located,settings,history){const snapshot=await readLocatedItemSnapshot(located,{schema:settings.schema});return snapshot.error===null?{raw:snapshot.raw,document:snapshot.document}:{raw:snapshot.raw,document:replayCurrentDocument(history),recovered:!0}}function ensureReplayTarget(target,history){return resolveHistoryTarget(target,history,{errorSubject:"restore",allowFutureTimestamp:!0})}function replayCurrentDocument(history){const currentReplay=replayToTarget(history,history.length-1);return Object.keys(currentReplay.metadata).length===0?{metadata:{},body:currentReplay.body}:canonicalDocument(replayToItemDocument(currentReplay))}async function resolveRestoreSubject(pmRoot,id,settings,typeToFolder){const subject=await resolveHistorySubject(pmRoot,id,settings,typeToFolder),historyPolicy=subject.located?await enforceHistoryStreamPolicyForItem({pmRoot,settings,itemId:subject.id,commandLabel:"restore"}):{warnings:[]};return{...subject,historyPolicyWarnings:historyPolicy.warnings}}function changedFields(beforeDocument,afterDocument){const beforeReplay=toReplayDocument(beforeDocument),afterReplay=toReplayDocument(afterDocument),patch=jsonPatch.compare(beforeReplay,afterReplay),fields=new Set;for(const op of patch){if(op.path==="/body"||op.path.startsWith("/body/")){fields.add("body");continue}const segment=op.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];fields.add(segment.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(fields).sort((a,b)=>a.localeCompare(b))}async function loadRestoreStateUnderLock(params){const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:"restore",readItem:located=>readRestoreItem(located,params.settings,params.history)});return{loadedItemUnderLock:verified.loadedItemUnderLock,existingItemPath:verified.locatedUnderLock?.itemPath??null}}function resolveRestoreCurrentState(loadedItemUnderLock,history){return loadedItemUnderLock?{document:loadedItemUnderLock.document,originalRaw:loadedItemUnderLock.raw}:{document:replayCurrentDocument(history),originalRaw:null}}function collectRestoreOwnershipWarnings(params){const stored=params.document.metadata.assignee?.trim(),hasOwnershipConflict=stored&&stored!==params.author&&!params.force,assigned=redactOptionalIdentityCredentials(stored);if(!hasOwnershipConflict)return[];if(params.enforcement==="strict")throw new PmCliError(`Item ${params.resolvedId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return params.enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.resolvedId}:${assigned}`]:[]}function restoreHistoryContext(context){return Object.keys(context).length===0?void 0:context}async function restorePreviousItemAfterHistoryFailure(params){if(params.existingItemPath&¶ms.resolvedOriginalRaw!==null&¶ms.restoredItemPath!==params.existingItemPath){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw),await fs.rm(params.restoredItemPath,{force:!0});return}if(params.existingItemPath&¶ms.resolvedOriginalRaw!==null){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw);return}await fs.rm(params.restoredItemPath,{force:!0})}async function runRestoreWriteHooks(params){return[...await runActiveOnWriteHooks({path:params.restoredItemPath,scope:"project",op:"restore",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]}),...await runActiveOnWriteHooks({path:params.historyPath,scope:"project",op:"restore:history",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]})]}async function runRestore(id,target,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),subject=await resolveRestoreSubject(pmRoot,id,settings,typeRegistry.type_to_folder),resolvedId=subject.id,{raw:historyRawBeforeLock,entries:history}=await readHistorySnapshot(subject.historyPath,resolvedId);if(history.length===0)throw new PmCliError(`No history exists for ${resolvedId}; restore is unavailable.`,EXIT_CODE.NOT_FOUND);const resolvedTarget=ensureReplayTarget(target,history),replayDocument=ensureMaterializedRestoreTarget(replayToTarget(history,resolvedTarget.historyIndex),resolvedTarget),restoredDocument=replayToCanonicalItemDocument(replayDocument,{schema:settings.schema});if(restoredDocument.metadata.id!==resolvedId)throw new PmCliError(`Restore target resolved to item ${restoredDocument.metadata.id}, expected ${resolvedId}.`,EXIT_CODE.GENERIC_FAILURE);const currentItemRawBeforeLock=(subject.located?await readRestoreItem(subject.located,settings,history):null)?.raw??null,author=resolveAuthor(options.author,settings.author_default),lease=await acquireLockLease(pmRoot,resolvedId,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const{loadedItemUnderLock,existingItemPath}=await loadRestoreStateUnderLock({pmRoot,subject,settings,typeRegistry,historyRawBeforeLock,currentItemRawBeforeLock,history}),itemFormat="toon",currentState=resolveRestoreCurrentState(loadedItemUnderLock,history);loadedItemUnderLock?.recovered===!0&&assertItemRevisionExpectationsOnUnreadable(pmRoot,resolvedId,loadedItemUnderLock.raw),assertItemMutationPreconditions(pmRoot,loadedItemUnderLock?.document??EMPTY_CANONICAL_DOCUMENT,resolvedId),restoredDocument.metadata.pm_format_version=normalizeItemFormatVersion(Math.max(requiredItemFormatVersion(restoredDocument.metadata),requiredItemFormatVersion(currentState.document.metadata))),assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(pmRoot),requiredItemFormatVersion(restoredDocument.metadata));const ownershipWarnings=collectRestoreOwnershipWarnings({document:currentState.document,author,force:options.force,enforcement:settings.governance.ownership_enforcement,resolvedId}),restoreChangedFields=changedFields(currentState.document,restoredDocument),workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"restore",author,before:currentState.document,after:restoredDocument});await runActiveBeforeMutationHooks({pm_root:pmRoot,operation:"restore",before:currentState.document,after:restoredDocument,changed_fields:restoreChangedFields,author,sdk:createMutationGuardSdk({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder})});const serializedRestore=serializeItemDocument(restoredDocument,{format:itemFormat,schema:settings.schema}),restoredItemPath=getItemPath(pmRoot,restoredDocument.metadata.type,resolvedId,itemFormat,typeRegistry.type_to_folder),derivedIndexWarnings=await lease.fence(async()=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(pmRoot,author);let derivedIndexWarnings2;try{await writeFileAtomic(restoredItemPath,serializedRestore),existingItemPath&&restoredItemPath!==existingItemPath&&await fs.rm(existingItemPath);const historyEntry=createHistoryEntry({nowIso:nowIso(),author,op:"restore",before:currentState.document,after:restoredDocument,message:options.message,context:restoreHistoryContext({...workflowPolicy.decisions.length===0?{}:{workflow_policies:workflowPolicy.decisions},...transactionCompensationHistoryContext(pmRoot,[resolvedId,currentState.document.metadata.id,restoredDocument.metadata.id],"restore")})});try{await appendHistoryEntry(subject.historyPath,historyEntry)}catch(error){throw await restorePreviousItemAfterHistoryFailure({existingItemPath,resolvedOriginalRaw:currentState.originalRaw,restoredItemPath}),error}derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot,preferredFormat:settings.item_format,typeToFolder:typeRegistry.type_to_folder,schema:settings.schema,itemPath:restoredItemPath,previousItemPath:existingItemPath??void 0,document:restoredDocument})}finally{await releaseDerivedIndexLock()}return derivedIndexWarnings2});advanceItemMutationPreconditions(pmRoot,restoredDocument,resolvedId);const hookWarnings=await runRestoreWriteHooks({restoredItemPath,historyPath:subject.historyPath,before:currentState.document,after:restoredDocument});recordAfterCommandAffectedItem({id:restoredDocument.metadata.id,op:"restore",item_type:restoredDocument.metadata.type,previous_status:currentState.document.metadata.status,status:restoredDocument.metadata.status,previous:projectAfterCommandItemSnapshot(currentState.document.metadata,restoreChangedFields),current:projectAfterCommandItemSnapshot(restoredDocument.metadata,restoreChangedFields),changed_fields:restoreChangedFields});const targetEntry=history[resolvedTarget.historyIndex],offset=historyVersionOffset(history,!0);return{item:restoredDocument.metadata,restored_from:{kind:resolvedTarget.kind,target:resolvedTarget.raw,history_index:resolvedTarget.historyIndex+1,version:offset===null?null:offset+resolvedTarget.historyIndex+1,entry_ts:targetEntry.ts,entry_op:targetEntry.op},changed_fields:restoreChangedFields,warnings:[...workflowPolicy.warnings,...loadedItemUnderLock?.recovered?["restore_unreadable_item_recovered"]:[],...subject.historyPolicyWarnings,...ownershipWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}const _testOnlyRestoreCommand={applyHistoryPatch,changedFields,ensureMaterializedRestoreTarget,ensureReplayTarget,extractPatchFailureContext,replayCurrentDocument,replayToTarget,resolveRestoreSubject};export{_testOnlyRestoreCommand,runRestore};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0e7afa33-b86c-5a57-8da7-15251271f25e")}catch{}})();import{collectRegisteredItemFieldNames}from"../../core/extensions/item-fields.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{normalizeItemFormatVersion,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../environment/project-runtime-compatibility.js";import{enforceWorkflowMutation}from"../../core/policy/workflow-policy-store.js";import jsonPatch from"fast-json-patch";import fs from"node:fs/promises";import{readLocatedItemSnapshot}from"../../core/store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable,transactionCompensationHistoryContext}from"../../core/store/item-mutation-precondition.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{readHistorySnapshot}from"../../core/history/read.js";import{verifyHistoryRewriteNoDrift}from"../../core/history/history-rewrite.js";import{resolveHistorySubject}from"../history/subject.js";import{historyVersionOffset}from"../../core/history/version-address.js";import{writeFileAtomic,appendHistoryEntry,createHistoryEntry,replayToCanonicalItemDocument,replayToItemDocument,toReplayDocument,enforceHistoryStreamPolicyForItem,canonicalDocument,serializeItemDocument,resolveItemTypeRegistry,acquireLockLease,EXIT_CODE,PmCliError,nowIso,getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnWriteHooks,runActiveBeforeMutationHooks,createMutationGuardSdk,getItemPath,resolvePmRoot,resolveWorkspaceRoot,readSettings,resolveAuthor}from"../runtime-primitives.js";import{applyHistoryPatch,ensureMaterializedHistoryTarget as ensureMaterializedRestoreTarget,extractPatchFailureContext,replayHistoryToTarget as replayToTarget,resolveHistoryTarget}from"../history-read.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../item-metadata-index.js";import{redactOptionalIdentityCredentials}from"../../core/shared/url-credentials.js";function restoreFormat(settings){return{schema:settings.schema,extensionFieldNames:collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}}async function readRestoreItem(located,settings,history){const snapshot=await readLocatedItemSnapshot(located,restoreFormat(settings));return snapshot.error===null?{raw:snapshot.raw,document:snapshot.document}:{raw:snapshot.raw,document:replayCurrentDocument(history),recovered:!0}}function ensureReplayTarget(target,history){return resolveHistoryTarget(target,history,{errorSubject:"restore",allowFutureTimestamp:!0})}function replayCurrentDocument(history){const currentReplay=replayToTarget(history,history.length-1);return Object.keys(currentReplay.metadata).length===0?{metadata:{},body:currentReplay.body}:canonicalDocument(replayToItemDocument(currentReplay))}async function resolveRestoreSubject(pmRoot,id,settings,typeToFolder){const subject=await resolveHistorySubject(pmRoot,id,settings,typeToFolder),historyPolicy=subject.located?await enforceHistoryStreamPolicyForItem({pmRoot,settings,itemId:subject.id,commandLabel:"restore"}):{warnings:[]};return{...subject,historyPolicyWarnings:historyPolicy.warnings}}function changedFields(beforeDocument,afterDocument){const beforeReplay=toReplayDocument(beforeDocument),afterReplay=toReplayDocument(afterDocument),patch=jsonPatch.compare(beforeReplay,afterReplay),fields=new Set;for(const op of patch){if(op.path==="/body"||op.path.startsWith("/body/")){fields.add("body");continue}const segment=op.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];fields.add(segment.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(fields).sort((a,b)=>a.localeCompare(b))}async function loadRestoreStateUnderLock(params){const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:"restore",readItem:located=>readRestoreItem(located,params.settings,params.history)});return{loadedItemUnderLock:verified.loadedItemUnderLock,existingItemPath:verified.locatedUnderLock?.itemPath??null}}function resolveRestoreCurrentState(loadedItemUnderLock,history){return loadedItemUnderLock?{document:loadedItemUnderLock.document,originalRaw:loadedItemUnderLock.raw}:{document:replayCurrentDocument(history),originalRaw:null}}function collectRestoreOwnershipWarnings(params){const stored=params.document.metadata.assignee?.trim(),hasOwnershipConflict=stored&&stored!==params.author&&!params.force,assigned=redactOptionalIdentityCredentials(stored);if(!hasOwnershipConflict)return[];if(params.enforcement==="strict")throw new PmCliError(`Item ${params.resolvedId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return params.enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.resolvedId}:${assigned}`]:[]}function restoreHistoryContext(context){return Object.keys(context).length===0?void 0:context}async function restorePreviousItemAfterHistoryFailure(params){if(params.existingItemPath&¶ms.resolvedOriginalRaw!==null&¶ms.restoredItemPath!==params.existingItemPath){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw),await fs.rm(params.restoredItemPath,{force:!0});return}if(params.existingItemPath&¶ms.resolvedOriginalRaw!==null){await writeFileAtomic(params.existingItemPath,params.resolvedOriginalRaw);return}await fs.rm(params.restoredItemPath,{force:!0})}async function runRestoreWriteHooks(params){return[...await runActiveOnWriteHooks({path:params.restoredItemPath,scope:"project",op:"restore",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]}),...await runActiveOnWriteHooks({path:params.historyPath,scope:"project",op:"restore:history",item_id:params.after.metadata.id,item_type:params.after.metadata.type,before:params.before,after:params.after,changed_fields:["restored"]})]}async function runRestore(id,target,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),subject=await resolveRestoreSubject(pmRoot,id,settings,typeRegistry.type_to_folder),resolvedId=subject.id,{raw:historyRawBeforeLock,entries:history}=await readHistorySnapshot(subject.historyPath,resolvedId);if(history.length===0)throw new PmCliError(`No history exists for ${resolvedId}; restore is unavailable.`,EXIT_CODE.NOT_FOUND);const resolvedTarget=ensureReplayTarget(target,history),replayDocument=ensureMaterializedRestoreTarget(replayToTarget(history,resolvedTarget.historyIndex),resolvedTarget),restoredDocument=replayToCanonicalItemDocument(replayDocument,restoreFormat(settings));if(restoredDocument.metadata.id!==resolvedId)throw new PmCliError(`Restore target resolved to item ${restoredDocument.metadata.id}, expected ${resolvedId}.`,EXIT_CODE.GENERIC_FAILURE);const currentItemRawBeforeLock=(subject.located?await readRestoreItem(subject.located,settings,history):null)?.raw??null,author=resolveAuthor(options.author,settings.author_default),lease=await acquireLockLease(pmRoot,resolvedId,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const{loadedItemUnderLock,existingItemPath}=await loadRestoreStateUnderLock({pmRoot,subject,settings,typeRegistry,historyRawBeforeLock,currentItemRawBeforeLock,history}),itemFormat="toon",currentState=resolveRestoreCurrentState(loadedItemUnderLock,history);loadedItemUnderLock?.recovered===!0&&assertItemRevisionExpectationsOnUnreadable(pmRoot,resolvedId,loadedItemUnderLock.raw),assertItemMutationPreconditions(pmRoot,loadedItemUnderLock?.document??EMPTY_CANONICAL_DOCUMENT,resolvedId),restoredDocument.metadata.pm_format_version=normalizeItemFormatVersion(Math.max(requiredItemFormatVersion(restoredDocument.metadata),requiredItemFormatVersion(currentState.document.metadata))),assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(pmRoot),requiredItemFormatVersion(restoredDocument.metadata));const ownershipWarnings=collectRestoreOwnershipWarnings({document:currentState.document,author,force:options.force,enforcement:settings.governance.ownership_enforcement,resolvedId}),restoreChangedFields=changedFields(currentState.document,restoredDocument),workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"restore",author,before:currentState.document,after:restoredDocument});await runActiveBeforeMutationHooks({pm_root:pmRoot,operation:"restore",before:currentState.document,after:restoredDocument,changed_fields:restoreChangedFields,author,sdk:createMutationGuardSdk({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder})});const serializedRestore=serializeItemDocument(restoredDocument,{format:itemFormat,...restoreFormat(settings)}),restoredItemPath=getItemPath(pmRoot,restoredDocument.metadata.type,resolvedId,itemFormat,typeRegistry.type_to_folder),derivedIndexWarnings=await lease.fence(async()=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(pmRoot,author);let derivedIndexWarnings2;try{await writeFileAtomic(restoredItemPath,serializedRestore),existingItemPath&&restoredItemPath!==existingItemPath&&await fs.rm(existingItemPath);const historyEntry=createHistoryEntry({nowIso:nowIso(),author,op:"restore",before:currentState.document,after:restoredDocument,message:options.message,context:restoreHistoryContext({...workflowPolicy.decisions.length===0?{}:{workflow_policies:workflowPolicy.decisions},...transactionCompensationHistoryContext(pmRoot,[resolvedId,currentState.document.metadata.id,restoredDocument.metadata.id],"restore")})});try{await appendHistoryEntry(subject.historyPath,historyEntry)}catch(error){throw await restorePreviousItemAfterHistoryFailure({existingItemPath,resolvedOriginalRaw:currentState.originalRaw,restoredItemPath}),error}derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot,preferredFormat:settings.item_format,typeToFolder:typeRegistry.type_to_folder,schema:settings.schema,itemPath:restoredItemPath,previousItemPath:existingItemPath??void 0,document:restoredDocument})}finally{await releaseDerivedIndexLock()}return derivedIndexWarnings2});advanceItemMutationPreconditions(pmRoot,restoredDocument,resolvedId);const hookWarnings=await runRestoreWriteHooks({restoredItemPath,historyPath:subject.historyPath,before:currentState.document,after:restoredDocument});recordAfterCommandAffectedItem({id:restoredDocument.metadata.id,op:"restore",item_type:restoredDocument.metadata.type,previous_status:currentState.document.metadata.status,status:restoredDocument.metadata.status,previous:projectAfterCommandItemSnapshot(currentState.document.metadata,restoreChangedFields),current:projectAfterCommandItemSnapshot(restoredDocument.metadata,restoreChangedFields),changed_fields:restoreChangedFields});const targetEntry=history[resolvedTarget.historyIndex],offset=historyVersionOffset(history,!0);return{item:restoredDocument.metadata,restored_from:{kind:resolvedTarget.kind,target:resolvedTarget.raw,history_index:resolvedTarget.historyIndex+1,version:offset===null?null:offset+resolvedTarget.historyIndex+1,entry_ts:targetEntry.ts,entry_op:targetEntry.op},changed_fields:restoreChangedFields,warnings:[...workflowPolicy.warnings,...loadedItemUnderLock?.recovered?["restore_unreadable_item_recovered"]:[],...subject.historyPolicyWarnings,...ownershipWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}const _testOnlyRestoreCommand={applyHistoryPatch,changedFields,ensureMaterializedRestoreTarget,ensureReplayTarget,extractPatchFailureContext,replayCurrentDocument,replayToTarget,resolveRestoreSubject};export{_testOnlyRestoreCommand,runRestore};
|
|
2
2
|
//# sourceMappingURL=restore.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{type ItemDocumentFormatOptions}from "../../core/item/item-format.js";
|
|
1
|
+
import{type ItemDocumentFormatOptions}from "../../core/item/item-format.js";import type{HistoryEntry}from "../../types/index.js";
|
|
2
2
|
/** Restricts which side of a three-way merge wins an unresolvable conflict. */
|
|
3
3
|
export type MergePreferredSide="ours"|"theirs";
|
|
4
4
|
/** Declares how competing item scalar writes select their retained value. */
|
|
@@ -14,7 +14,7 @@ export declare function encodeItemScalarDecisionValue(value:unknown):unknown;
|
|
|
14
14
|
/** Hash scalars in disjoint present/missing domains for collision-free evidence. */
|
|
15
15
|
export declare function hashItemScalarDecisionValue(value:unknown):string;
|
|
16
16
|
/** Restricts the strategy labels reported by the history stream merge. */
|
|
17
|
-
export type HistoryMergeStrategy="identical"|"fast_forward_ours"|"fast_forward_theirs"|"union_reanchor";
|
|
17
|
+
export type HistoryMergeStrategy="identical"|"fast_forward_ours"|"fast_forward_theirs"|"equivalent_bridges"|"union_reanchor";
|
|
18
18
|
/** Documents the history stream merge result payload exchanged by command, SDK, and package integrations. */
|
|
19
19
|
export interface HistoryMergeResult{
|
|
20
20
|
/** Merged JSONL content ready to be written as the resolved history stream. */
|
|
@@ -31,6 +31,23 @@ entries_from_theirs:number;
|
|
|
31
31
|
entries_total:number;
|
|
32
32
|
/** Whether the merged chain required hash re-anchoring (true for every union merge). */
|
|
33
33
|
reanchored:boolean;}
|
|
34
|
+
/**
|
|
35
|
+
* Indexes of `merged` records that cannot be presented as historical states
|
|
36
|
+
* (GH-1715): copies of records either branch already marked replay_inexact
|
|
37
|
+
* and, when the merge dissolves bridges, every record a branch's bridge
|
|
38
|
+
* covers plus every record the merged order places between that segment's
|
|
39
|
+
* first covered record and its bridge. An event interleaved there replays
|
|
40
|
+
* without the unrecorded change too. Records a retained live bridge covers
|
|
41
|
+
* are never marked, since marking would void the digest that keeps them.
|
|
42
|
+
*/
|
|
43
|
+
declare function collectUnionInexactIndexes(merged:HistoryEntry[],sides:HistoryEntry[][],bridgesDissolve:boolean,markerOnlySides?:HistoryEntry[][]):Set<number>;
|
|
44
|
+
/**
|
|
45
|
+
* Whether a repair of the runs recurs among the later records, live or as a
|
|
46
|
+
* neutral copy. Moving it into the shared run would then record it twice.
|
|
47
|
+
*/
|
|
48
|
+
declare function repairRecursAfterRuns(runs:HistoryEntry[],rests:HistoryEntry[]):boolean;
|
|
49
|
+
/** Whether normalized runs may replace the recorded ones: no repair recurs later and every side verifies. */
|
|
50
|
+
declare function normalizationApplies(runs:HistoryEntry[],rests:HistoryEntry[],sides:HistoryEntry[][]):boolean;
|
|
34
51
|
/**
|
|
35
52
|
* Deterministically merge two diverged versions of one append-only history
|
|
36
53
|
* JSONL stream. Identical streams and one-sided fast-forwards keep the winning
|
|
@@ -157,4 +174,6 @@ preferred:MergePreferredSide;}
|
|
|
157
174
|
*/
|
|
158
175
|
export declare function mergeJsonDocuments(baseRaw:string,oursRaw:string,theirsRaw:string,options?:{
|
|
159
176
|
/** Side that wins unresolvable conflicts (default "ours"). */
|
|
160
|
-
preferred?:MergePreferredSide;}):JsonDocumentMergeResult;
|
|
177
|
+
preferred?:MergePreferredSide;}):JsonDocumentMergeResult;
|
|
178
|
+
/** Internal helpers exported only for focused tests. */
|
|
179
|
+
export declare const _testOnly:{collectUnionInexactIndexes:typeof collectUnionInexactIndexes;normalizationApplies:typeof normalizationApplies;repairRecursAfterRuns:typeof repairRecursAfterRuns;};export{};
|