@unbrained/pm-cli 2026.10.20 → 2026.10.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/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +142 -77
- package/dist/cli/error-guidance.d.ts +8 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-QMZ73FCW.js → chunk-2B5HAZFK.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-35ISFIPC.js +113 -0
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5LSN7K4N.js +2 -0
- package/dist/cli-bundle/chunks/chunk-7OTYULIJ.js +30 -0
- package/dist/cli-bundle/chunks/{chunk-GHJOMRSF.js → chunk-AOAQDCXX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZA3XXHEE.js → chunk-BAIVTLJM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LS55VKRK.js → chunk-C37RDYZI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YT2Z3JPC.js → chunk-E3JC3WQL.js} +47 -47
- package/dist/cli-bundle/chunks/{chunk-YECCKB4E.js → chunk-GWIGZDRS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YTHI5DTH.js → chunk-HC2DCGFA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +2 -0
- package/dist/cli-bundle/chunks/chunk-J444ZX23.js +126 -0
- package/dist/cli-bundle/chunks/{chunk-VLJLWZBO.js → chunk-LIC5EUQS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KU4Q3MSI.js → chunk-MV3KYY2A.js} +6 -6
- package/dist/cli-bundle/chunks/chunk-O67N62DT.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TZU6U5ZE.js → chunk-PCPOTFJP.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-TNU3XVPC.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-7ZOIZ2AZ.js → chunk-URV4VHQ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YW6SIKYP.js → chunk-UYYTV2TX.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +9 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-U7VGKIYC.js → indexed-receipt-blobs-L3BOTMZN.js} +2 -2
- package/dist/cli-bundle/chunks/mutation-admission-TATOFEXF.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-NNDV6F6I.js → register-list-query-GULR2IYO.js} +5 -5
- package/dist/cli-bundle/chunks/{register-mutation-3GCBSNQS.js → register-mutation-HLSQ4WVW.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-FE3GGA7O.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-XUIKAIZA.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-CLRGA6O7.js → settlement-hook-UVFYSBMU.js} +2 -2
- package/dist/cli-bundle/chunks/stage-QCPZBZRC.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-25L3L2PF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-25NQRZ7J.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-2GFTVXKZ.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HUZAXSIJ.js → chunk-3LWH2RJC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-46HBJC6J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-A52W6GLA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-CB7TSZ7P.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VLSER3XW.js → chunk-CX5FNEFC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LJPUJ2KK.js → chunk-EHPRSWJE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GC4VMLXL.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KKRFSI2N.js → chunk-GVKYTDOH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NI6NS44Q.js → chunk-KM77WU5U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QGDKWULS.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QWKCQ5PW.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SXVJRLLP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E4II2D2B.js → chunk-TMN3RAXZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-F7FD25TG.js → chunk-UQ5JPBY2.js} +11 -11
- package/dist/cli-bundle/focused-chunks/chunk-UUPJ6OZL.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-VYAZND5Q.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-W2CND3BD.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZGEK57KD.js → chunk-XX5JQCLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-H2G6CCGO.js → indexed-receipt-blobs-AAQOKO5B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-TBKR4KRM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-5SNBBT7C.js → settlement-hook-MNCHFCAX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-RM6MJIMT.js +2 -0
- package/dist/cli-bundle/main.js +21 -21
- 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 +23 -23
- 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 +58 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +7 -7
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/lock/lock-gc.d.ts +12 -5
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.d.ts +33 -0
- package/dist/core/lock/lock-owner.js +2 -0
- package/dist/core/lock/lock.d.ts +11 -22
- package/dist/core/lock/lock.js +4 -3
- package/dist/core/output/output.js +3 -3
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/mcp/server.d.ts +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/agent/command-recovery.d.ts +2 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/context-intent-contracts.d.ts +13 -0
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/contracts.d.ts +1 -1
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core.d.ts +2 -2
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/define.d.ts +15 -16
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/pagination.d.ts +3 -3
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +5 -0
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/session-result.d.ts +39 -0
- package/dist/sdk/read-output/session-result.js +2 -0
- package/dist/sdk/read-output-contracts.d.ts +18 -5
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-session.d.ts +2 -0
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.d.ts +2 -0
- package/dist/sdk/runtime/mutation-admission.js +2 -0
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +6 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +10 -8
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution.d.ts +1 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/workspace.d.ts +3 -1
- package/dist/sdk/workspace.js +8 -5
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +9 -0
- package/docs/ASSURANCE.md +17 -2
- package/docs/COMMANDS.md +17 -3
- package/docs/CONFIGURATION.md +38 -0
- package/docs/CONTEXT_RELEVANCE.md +15 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +56 -3
- package/docs/MCP_OPTION_CONFORMANCE.md +27 -1
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +79 -0
- package/docs/RELATIONSHIP_GRAPH.md +15 -0
- package/docs/RELEASING.md +8 -0
- package/docs/SDK.md +104 -7
- package/docs/TESTING.md +23 -0
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/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-2GGGOD7P.js +0 -30
- package/dist/cli-bundle/chunks/chunk-7NHA5K77.js +0 -126
- package/dist/cli-bundle/chunks/chunk-PNPE2OVJ.js +0 -112
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QETMESEB.js +0 -6
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +0 -2
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-37SU7BZI.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-6IU7BESB.js +0 -65
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +0 -25
- package/dist/cli-bundle/focused-chunks/chunk-AW35RDKA.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-GYHZ7W6O.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-H5Q2HUU6.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-J6EYUGAR.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-KDGUIIRU.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VAYS754X.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VS6VTWTZ.js +0 -8
- package/dist/cli-bundle/focused-chunks/stage-EMTISXR7.js +0 -2
|
@@ -1,6 +1,6 @@
|
|
|
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]="da37bda1-1520-5db0-9dad-bb1acc556de8")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError,readFileIfExists,writeFileAtomic}from"../../core/fs/fs-utils.js";import{access,readFile,realpath}from"node:fs/promises";import{constants}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{pathExists}from"../../core/fs/fs-utils.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{acquireLock}from"../../core/lock/lock.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{resolveAuthor}from"../../core/shared/author.js";import{nowIso}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings,resolveGovernanceKnobs}from"../../core/store/settings.js";import{isPathOutsideRoot}from"../workspace.js";import{resolveSourceContextWritePolicy}from"../environment/source-context.js";import{gitWorkspaceEnvironment,resolveMergeDriverConfigScope,writeMergeDriverGitConfig}from"./worktree-config.js";import{discoverProjectRuntimeVersionPins}from"../environment/project-runtime-compatibility.js";const execFileAsync=promisify(execFile),PM_GITATTRIBUTES_START="# pm-cli:merge-drivers:start",PM_GITATTRIBUTES_END="# pm-cli:merge-drivers:end",PM_GITATTRIBUTES_V2_START="# pm-cli:merge-drivers:v2:start",PM_GITATTRIBUTES_V2_END="# pm-cli:merge-drivers:v2:end",MERGE_FENCE_LOCK_ID="merge-fence",MERGE_ATTRIBUTES_LOCK_ID="merge-attributes";function quoteMergeDriverArgument(value){return`'${value.replaceAll("'",`'"'"'`)}'`}async function resolveMatchingBunLauncher(candidate,version){const resolvedCandidate=await realpath(candidate);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(resolvedCandidate))return;const{stdout}=await execFileAsync(candidate,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return stdout.trim()===version?resolvedCandidate:void 0}async function resolveMergeDriverCliCommand(){const packageRoot=resolvePmPackageRootFromModule(import.meta.url,["../../.."]);let executable=process.execPath,bunLauncherFound=!1;const runtimeIdentity=await realpath(process.execPath),bunVersion=process.versions.bun,pathCandidates=(process.env.PATH??"").split(path.delimiter).filter(directory=>path.isAbsolute(directory)).map(directory=>path.join(directory,bunVersion===void 0?path.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),candidates=bunVersion===void 0?pathCandidates:[process.env.npm_execpath??"",...pathCandidates,runtimeIdentity].filter(candidate=>path.isAbsolute(candidate)&&/^(?:bun|bun\.exe)$/iu.test(path.basename(candidate)));for(const candidate of candidates)try{if(await access(candidate,constants.X_OK),bunVersion!==void 0){const launcher=await resolveMatchingBunLauncher(candidate,bunVersion);if(launcher!==void 0){executable=launcher,bunLauncherFound=!0;break}continue}if(candidate!==runtimeIdentity&&await realpath(candidate)===runtimeIdentity){executable=candidate;break}}catch{}if(bunVersion!==void 0&&!bunLauncherFound)throw new PmCliError("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",EXIT_CODE.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${quoteMergeDriverArgument(executable)} ${quoteMergeDriverArgument(path.join(packageRoot,"dist","cli.js"))}`}const MERGE_DRIVER_DEFINITIONS=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function resolveMergeInstallContext(options){const explicitPath=options.explicitPath?.trim(),sourceWorkspaceRoot=options.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),sourcePmRoot=options.environment.PM_SOURCE_PM_PATH?.trim(),sourcePolicy=resolveSourceContextWritePolicy(options.environment),sourceCoordinatesAvailable=!!(sourceWorkspaceRoot&&sourcePmRoot),sourceContextSelected=explicitPath===void 0&&sourceCoordinatesAvailable&&(options.dryRun||sourcePolicy.source_writes_allowed);if(explicitPath!==void 0){const pmRoot=resolvePmRoot(options.cwd,explicitPath);return{pm_root:pmRoot,workspace_start:pmRoot,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:!1,source_policy:sourcePolicy}}return sourceContextSelected?{pm_root:path.resolve(sourcePmRoot),workspace_start:path.resolve(sourceWorkspaceRoot),source_coordinates_available:!0,source_context_selected:!0,source_policy:sourcePolicy}:{pm_root:sourceCoordinatesAvailable?resolvePmRoot(options.cwd,".agents/pm"):resolvePmRoot(options.cwd),workspace_start:options.cwd,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:!1,source_policy:sourcePolicy}}async function findGitWorkspaceRoot(cwd){try{const{stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await realpath(stdout.trim())}catch{return null}}async function resolveGitWorkspaceRoot(cwd){const workspaceRoot=await findGitWorkspaceRoot(cwd);if(workspaceRoot===null)throw new PmCliError("pm merge install requires a git repository (merge drivers are git configuration).",EXIT_CODE.USAGE);return workspaceRoot}function toPosixRelative(fromPath,toPath){return path.relative(fromPath,toPath).replaceAll("\\","/")}function quoteGitAttributePattern(value){return`"${value.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function readSingleQuotedArgument(command,offset){if(command[offset]!=="'")return null;let value="";for(let index=offset+1;index<command.length;index+=1){if(command.startsWith(`'"'"'`,index)){value+="'",index+=4;continue}if(command[index]==="'")return{value,nextOffset:index+1};value+=command[index]}return null}async function isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,version){if(discoverProjectRuntimeVersionPins(workspaceRoot).filter(pin=>pin.constraint==="exact").some(pin=>pin.version!==version))return!1;const driverWorkspace=await findGitWorkspaceRoot(packageRoot);if(driverWorkspace!==null&&driverWorkspace!==await realpath(workspaceRoot)){const commonDirectories=await Promise.all([driverWorkspace,workspaceRoot].map(async cwd=>{const result=await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,env:gitWorkspaceEnvironment(),timeout:1e4});return realpath(result.stdout.trim())}));if(commonDirectories[0]===commonDirectories[1])return!1}return!0}async function isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot){const nodeArgument=readSingleQuotedArgument(configured,0);if(nodeArgument===null||configured[nodeArgument.nextOffset]!==" ")return!1;const cliArgument=readSingleQuotedArgument(configured,nodeArgument.nextOffset+1);if(cliArgument===null||configured.slice(cliArgument.nextOffset)!==expectedSuffix||!/^(?:node|bun)(?:\.exe)?$/iu.test(path.basename(nodeArgument.value))||path.basename(cliArgument.value)!=="cli.js"||path.basename(path.dirname(cliArgument.value))!=="dist"||!await pathExists(nodeArgument.value)||!await pathExists(cliArgument.value))return!1;try{const packageRoot=path.dirname(path.dirname(cliArgument.value)),manifest=JSON.parse(await readFile(path.join(packageRoot,"package.json"),"utf8")),pmBin=typeof manifest.bin=="string"?manifest.bin:manifest.bin?.pm;return await isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,manifest.version)?manifest.name==="@unbrained/pm-cli"&&pmBin==="dist/cli.js":!1}catch{return!1}}function buildMergeAttributePatterns(trackerRelativeRoot,typeFolders){const prefix=trackerRelativeRoot.length>0?`${trackerRelativeRoot}/`:"",patterns=[`${quoteGitAttributePattern(`${prefix}**/*.toon`)} merge=pm-item-toon`,`${quoteGitAttributePattern(`${prefix}**/*.md`)} merge=pm-item-markdown`];for(const folder of typeFolders)patterns.push(`${quoteGitAttributePattern(`${prefix}${folder}/*.toon`)} merge=pm-item-toon`),patterns.push(`${quoteGitAttributePattern(`${prefix}${folder}/*.md`)} merge=pm-item-markdown`);return patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.jsonl`)} merge=pm-relationship`),patterns.push(`${quoteGitAttributePattern(`${prefix}history/*.jsonl`)} merge=pm-history`),patterns.push(`${quoteGitAttributePattern(`${prefix}settings.json`)} merge=pm-json`),patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.json`)} merge=pm-json`),patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/**`)} merge=text`),patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/.managed-extensions.json`)} merge=pm-json`),patterns}function managedMergeBlocks(content){const blocks=[];let cursor=0;for(;cursor<content.length;){const legacyStart=content.indexOf(PM_GITATTRIBUTES_START,cursor),versionedStart=content.indexOf(PM_GITATTRIBUTES_V2_START,cursor),start=legacyStart===-1?versionedStart:versionedStart===-1?legacyStart:Math.min(legacyStart,versionedStart);if(start===-1)break;const versioned=start===versionedStart,startMarker=versioned?PM_GITATTRIBUTES_V2_START:PM_GITATTRIBUTES_START,endMarker=versioned?PM_GITATTRIBUTES_V2_END:PM_GITATTRIBUTES_END,closing=content.indexOf(endMarker,start+startMarker.length),end=closing===-1?content.length:closing+endMarker.length;blocks.push({start,end,closed:closing!==-1,lines:content.slice(start+startMarker.length,closing===-1?end:closing).split(`
|
|
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]="b1828465-0619-514c-8956-2a81dea9efbc")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError,readFileIfExists,writeFileAtomic}from"../../core/fs/fs-utils.js";import{access,readFile,realpath}from"node:fs/promises";import{constants}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{pathExists}from"../../core/fs/fs-utils.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{acquireLock}from"../../core/lock/lock.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{resolveAuthor}from"../../core/shared/author.js";import{nowIso}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings,resolveGovernanceKnobs}from"../../core/store/settings.js";import{isPathOutsideRoot}from"../workspace.js";import{resolveSourceContextWritePolicy}from"../environment/source-context.js";import{gitWorkspaceEnvironment,resolveMergeDriverConfigScope,writeMergeDriverGitConfig}from"./worktree-config.js";import{discoverProjectRuntimeVersionPins}from"../environment/project-runtime-compatibility.js";const execFileAsync=promisify(execFile),PM_GITATTRIBUTES_START="# pm-cli:merge-drivers:start",PM_GITATTRIBUTES_END="# pm-cli:merge-drivers:end",PM_GITATTRIBUTES_V2_START="# pm-cli:merge-drivers:v2:start",PM_GITATTRIBUTES_V2_END="# pm-cli:merge-drivers:v2:end",MERGE_FENCE_LOCK_ID="merge-fence",MERGE_ATTRIBUTES_LOCK_ID="merge-attributes";function quoteMergeDriverArgument(value){return`'${value.replaceAll("'",`'"'"'`)}'`}async function resolveMatchingBunLauncher(candidate,version){const resolvedCandidate=await realpath(candidate);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(resolvedCandidate))return;const{stdout}=await execFileAsync(candidate,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return stdout.trim()===version?resolvedCandidate:void 0}async function resolveMergeDriverCliCommand(){const packageRoot=resolvePmPackageRootFromModule(import.meta.url,["../../.."]);let executable=process.execPath,bunLauncherFound=!1;const runtimeIdentity=await realpath(process.execPath),bunVersion=process.versions.bun,pathCandidates=(process.env.PATH??"").split(path.delimiter).filter(directory=>path.isAbsolute(directory)).map(directory=>path.join(directory,bunVersion===void 0?path.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),candidates=bunVersion===void 0?pathCandidates:[process.env.npm_execpath??"",...pathCandidates,runtimeIdentity].filter(candidate=>path.isAbsolute(candidate)&&/^(?:bun|bun\.exe)$/iu.test(path.basename(candidate)));for(const candidate of candidates)try{if(await access(candidate,constants.X_OK),bunVersion!==void 0){const launcher=await resolveMatchingBunLauncher(candidate,bunVersion);if(launcher!==void 0){executable=launcher,bunLauncherFound=!0;break}continue}if(candidate!==runtimeIdentity&&await realpath(candidate)===runtimeIdentity){executable=candidate;break}}catch{}if(bunVersion!==void 0&&!bunLauncherFound)throw new PmCliError("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",EXIT_CODE.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${quoteMergeDriverArgument(executable)} ${quoteMergeDriverArgument(path.join(packageRoot,"dist","cli.js"))}`}const MERGE_DRIVER_DEFINITIONS=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function resolveMergeInstallContext(options){const explicitPath=options.explicitPath?.trim(),sourceWorkspaceRoot=options.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),sourcePmRoot=options.environment.PM_SOURCE_PM_PATH?.trim(),sourcePolicy=resolveSourceContextWritePolicy(options.environment),sourceCoordinatesAvailable=!!(sourceWorkspaceRoot&&sourcePmRoot),sourceContextSelected=explicitPath===void 0&&sourceCoordinatesAvailable&&(options.dryRun||sourcePolicy.source_writes_allowed);if(explicitPath!==void 0){const pmRoot=resolvePmRoot(options.cwd,explicitPath);return{pm_root:pmRoot,workspace_start:pmRoot,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:!1,source_policy:sourcePolicy}}return sourceContextSelected?{pm_root:path.resolve(sourcePmRoot),workspace_start:path.resolve(sourceWorkspaceRoot),source_coordinates_available:!0,source_context_selected:!0,source_policy:sourcePolicy}:{pm_root:sourceCoordinatesAvailable?resolvePmRoot(options.cwd,".agents/pm"):resolvePmRoot(options.cwd),workspace_start:options.cwd,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:!1,source_policy:sourcePolicy}}async function findGitWorkspaceRoot(cwd){try{const{stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await realpath(stdout.trim())}catch{return null}}async function resolveGitWorkspaceRoot(cwd){const workspaceRoot=await findGitWorkspaceRoot(cwd);if(workspaceRoot===null)throw new PmCliError("pm merge install requires a git repository (merge drivers are git configuration).",EXIT_CODE.USAGE);return workspaceRoot}function toPosixRelative(fromPath,toPath){return path.relative(fromPath,toPath).split(path.sep).join("/")}function literalGitAttributePath(value){return value.replace(/[\\*?[\]!]/gu,"\\$&")}function quoteGitAttributePattern(value){return`"${value.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function readSingleQuotedArgument(command,offset){if(command[offset]!=="'")return null;let value="";for(let index=offset+1;index<command.length;index+=1){if(command.startsWith(`'"'"'`,index)){value+="'",index+=4;continue}if(command[index]==="'")return{value,nextOffset:index+1};value+=command[index]}return null}async function isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,version){if(discoverProjectRuntimeVersionPins(workspaceRoot).filter(pin=>pin.constraint==="exact").some(pin=>pin.version!==version))return!1;const driverWorkspace=await findGitWorkspaceRoot(packageRoot);if(driverWorkspace!==null&&driverWorkspace!==await realpath(workspaceRoot)){const commonDirectories=await Promise.all([driverWorkspace,workspaceRoot].map(async cwd=>{const result=await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,env:gitWorkspaceEnvironment(),timeout:1e4});return realpath(result.stdout.trim())}));if(commonDirectories[0]===commonDirectories[1])return!1}return!0}async function isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot){const nodeArgument=readSingleQuotedArgument(configured,0);if(nodeArgument===null||configured[nodeArgument.nextOffset]!==" ")return!1;const cliArgument=readSingleQuotedArgument(configured,nodeArgument.nextOffset+1);if(cliArgument===null||configured.slice(cliArgument.nextOffset)!==expectedSuffix||!/^(?:node|bun)(?:\.exe)?$/iu.test(path.basename(nodeArgument.value))||path.basename(cliArgument.value)!=="cli.js"||path.basename(path.dirname(cliArgument.value))!=="dist"||!await pathExists(nodeArgument.value)||!await pathExists(cliArgument.value))return!1;try{const packageRoot=path.dirname(path.dirname(cliArgument.value)),manifest=JSON.parse(await readFile(path.join(packageRoot,"package.json"),"utf8")),pmBin=typeof manifest.bin=="string"?manifest.bin:manifest.bin?.pm;return await isMergeDriverWorkspaceCompatible(packageRoot,workspaceRoot,manifest.version)?manifest.name==="@unbrained/pm-cli"&&pmBin==="dist/cli.js":!1}catch{return!1}}function buildMergeAttributePatterns(trackerRelativeRoot,typeFolders){const prefix=trackerRelativeRoot.length>0?`${literalGitAttributePath(trackerRelativeRoot)}/`:"",patterns=[`${quoteGitAttributePattern(`${prefix}**/*.toon`)} merge=pm-item-toon`,`${quoteGitAttributePattern(`${prefix}**/*.md`)} merge=pm-item-markdown`];for(const folder of typeFolders){const literalFolder=literalGitAttributePath(folder);patterns.push(`${quoteGitAttributePattern(`${prefix}${literalFolder}/*.toon`)} merge=pm-item-toon`),patterns.push(`${quoteGitAttributePattern(`${prefix}${literalFolder}/*.md`)} merge=pm-item-markdown`)}return patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.jsonl`)} merge=pm-relationship`),patterns.push(`${quoteGitAttributePattern(`${prefix}history/*.jsonl`)} merge=pm-history`),patterns.push(`${quoteGitAttributePattern(`${prefix}settings.json`)} merge=pm-json`),patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.json`)} merge=pm-json`),patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/**`)} merge=text`),patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/.managed-extensions.json`)} merge=pm-json`),patterns}function managedMergeBlocks(content){const blocks=[];let cursor=0;for(;cursor<content.length;){const legacyStart=content.indexOf(PM_GITATTRIBUTES_START,cursor),versionedStart=content.indexOf(PM_GITATTRIBUTES_V2_START,cursor),start=legacyStart===-1?versionedStart:versionedStart===-1?legacyStart:Math.min(legacyStart,versionedStart);if(start===-1)break;const versioned=start===versionedStart,startMarker=versioned?PM_GITATTRIBUTES_V2_START:PM_GITATTRIBUTES_START,endMarker=versioned?PM_GITATTRIBUTES_V2_END:PM_GITATTRIBUTES_END,closing=content.indexOf(endMarker,start+startMarker.length),end=closing===-1?content.length:closing+endMarker.length;blocks.push({start,end,closed:closing!==-1,lines:content.slice(start+startMarker.length,closing===-1?end:closing).split(`
|
|
2
2
|
`).map(line=>line.trim()).filter(Boolean)}),cursor=end}return blocks}function blockBelongsToTracker(lines,patterns,trackerRelativeRoot){const ownedPatterns=new Set(patterns),prefix=quoteGitAttributePattern(trackerRelativeRoot.length>0?`${trackerRelativeRoot}/`:"").slice(0,-1);return lines.some(line=>ownedPatterns.has(line)||line.startsWith(prefix)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(line.slice(prefix.length)))}async function reconcileGitattributesBlock(workspaceRoot,trackerRelativeRoot,patterns,dryRun){const gitattributesPath=path.join(workspaceRoot,".gitattributes"),gitDirectory=dryRun?null:(await execFileAsync("git",["rev-parse","--absolute-git-dir"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),releaseLock=gitDirectory===null?null:await acquireLock(gitDirectory,MERGE_ATTRIBUTES_LOCK_ID,120,"merge-fence",!1,!0,5e3);try{const current=await readFileIfExists(gitattributesPath)??"",block=[PM_GITATTRIBUTES_V2_START,...patterns,PM_GITATTRIBUTES_V2_END].join(`
|
|
3
|
-
`),blocks=managedMergeBlocks(current),owned=blocks.filter(candidate=>blockBelongsToTracker(candidate.lines,patterns,trackerRelativeRoot));owned.length===0&&trackerRelativeRoot===".agents/pm"&&blocks.length===1&&blocks[0].lines.every(line=>!line.includes("
|
|
3
|
+
`),blocks=managedMergeBlocks(current),owned=blocks.filter(candidate=>blockBelongsToTracker(candidate.lines,patterns,trackerRelativeRoot));owned.length===0&&trackerRelativeRoot===".agents/pm"&&blocks.length===1&&blocks[0].lines.every(line=>!line.includes("/"))&&owned.push(blocks[0]);let next;if(owned.length>0){const first=owned[0];next=current;for(const duplicate of owned.slice(1).reverse())next=`${next.slice(0,duplicate.start)}${next.slice(duplicate.end)}`;next=`${next.slice(0,first.start)}${block}${next.slice(first.end)}`}else{const prefix=current.trimEnd();next=`${prefix.length>0?`${prefix}
|
|
4
4
|
|
|
5
5
|
`:""}${block}
|
|
6
6
|
`}return next===current?{path:gitattributesPath,changed:!1}:(dryRun||await writeFileAtomic(gitattributesPath,next),{path:gitattributesPath,changed:!0})}finally{await releaseLock?.()}}function resolveProjectMergeTypeFolders(settings){const registry=resolveItemTypeRegistry(settings,null);return[...new Set(Object.values(registry.type_to_folder))].sort((left,right)=>left.localeCompare(right))}async function auditMergeAttributeFence(pmRoot,typeFolders){const resolvedRoot=path.resolve(pmRoot);let fenceDirectory=null,fenceContent="",directory=resolvedRoot;for(let depth=0;depth<8;depth+=1){const candidate=path.join(directory,".gitattributes");try{const raw=await readFile(candidate,"utf8");if(raw.includes(PM_GITATTRIBUTES_V2_START)||raw.includes(PM_GITATTRIBUTES_START)){fenceDirectory=directory,fenceContent=raw;break}}catch{}const parent=path.dirname(directory);if(parent===directory)break;directory=parent}if(fenceDirectory===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};const fencePath=path.join(fenceDirectory,".gitattributes"),relativeRoot=toPosixRelative(fenceDirectory,resolvedRoot),blocks=managedMergeBlocks(fenceContent),expected=buildMergeAttributePatterns(relativeRoot,typeFolders),owned=blocks.filter(block=>blockBelongsToTracker(block.lines,expected,relativeRoot)),committed=owned.flatMap(block=>block.closed?block.lines:[]),committedSet=new Set(committed),expectedSet=new Set(expected),missing=expected.filter(line=>!committedSet.has(line)),stale=committed.filter(line=>!expectedSet.has(line));return{status:owned.length!==1||!owned[0].closed||missing.length>0||stale.length>0?"drift":"ok",path:fencePath,missing_patterns:missing,stale_patterns:stale,schema_scope:"project"}}async function auditMergeDriverConfiguration(workspaceRoot){const missingKeys=[],driftedKeys=[];for(const definition of MERGE_DRIVER_DEFINITIONS){const key=`merge.${definition.key}.driver`,expectedSuffix=` merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`;try{const{stdout}=await execFileAsync("git",["config","--get",key],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),encoding:"utf8",windowsHide:!0,timeout:1e4}),configured=stdout.trim();await isPortableMergeDriverCommand(configured,expectedSuffix,workspaceRoot)||driftedKeys.push(key)}catch{missingKeys.push(key)}}return{status:missingKeys.length>0?"missing":driftedKeys.length>0?"drift":"ok",missing_keys:missingKeys,drifted_keys:driftedKeys}}async function refreshMergeAttributeFenceIfInstalled(pmRoot){let workspaceRoot;try{workspaceRoot=await resolveGitWorkspaceRoot(path.resolve(pmRoot))}catch{return{status:"no_git"}}const trackerRelativeRoot=toPosixRelative(workspaceRoot,path.resolve(pmRoot)),lockSettings=await readSettings(pmRoot),owner=resolveAuthor(void 0,lockSettings.author_default),releaseLock=await acquireLock(pmRoot,MERGE_FENCE_LOCK_ID,lockSettings.locks.ttl_seconds,owner,!1,resolveGovernanceKnobs(lockSettings).force_required_for_stale_lock,lockSettings.locks.wait_ms);try{const gitattributesPath=path.join(workspaceRoot,".gitattributes");let current;try{current=await readFile(gitattributesPath,"utf8")}catch(error){if(error instanceof Error&&"code"in error&&isFileMissingError(error))return{status:"not_installed",path:gitattributesPath};throw error}if(!current.includes(PM_GITATTRIBUTES_V2_START)&&!current.includes(PM_GITATTRIBUTES_START))return{status:"not_installed",path:gitattributesPath};const settings=await readSettings(pmRoot),typeFolders=resolveProjectMergeTypeFolders(settings),outcome=await reconcileGitattributesBlock(workspaceRoot,trackerRelativeRoot,buildMergeAttributePatterns(trackerRelativeRoot,typeFolders),!1);return{status:outcome.changed?"refreshed":"unchanged",path:outcome.path}}finally{await releaseLock()}}async function runMergeInstall(options,global2){const context=resolveMergeInstallContext({cwd:process.cwd(),explicitPath:global2.path,dryRun:options.dryRun===!0,environment:process.env}),pmRoot=context.pm_root;await assertInitializedTracker(pmRoot);const workspaceRoot=await resolveGitWorkspaceRoot(context.workspace_start);return installMergeFence({pmRoot,workspaceRoot,dryRun:options.dryRun===!0,preCommitHook:options.preCommitHook===!0})}async function installMergeDriverConfiguration(workspaceRoot,entries){const commonDirectory=(await execFileAsync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout.trim(),release=await acquireLock(commonDirectory,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{const scope=await resolveMergeDriverConfigScope(workspaceRoot);let stdout;try{stdout=(await execFileAsync("git",["config",scope,"--null","--get-regexp","."],{cwd:workspaceRoot,env:gitWorkspaceEnvironment(),timeout:1e4})).stdout}catch(error){if(typeof error!="object"||error===null||!("code"in error)||error.code!==1)throw error;stdout=""}const current=new Map(stdout.split("\0").filter(Boolean).map(entry=>{const separator=entry.indexOf(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="95103919-d686-5c3b-bd51-928f5b2314ef")}catch{}})();import{BRIEF_LIST_FIELDS}from"../query/projection-contracts.js";function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function hasStandardBriefProjection(value){if(!isRecord(value))return!1;const fields=value.fields;return value.mode==="brief"&&Object.keys(value).length===2&&Array.isArray(fields)&&(fields.length===BRIEF_LIST_FIELDS.length||fields.length===BRIEF_LIST_FIELDS.length+1&&fields.at(-1)==="priority")&&BRIEF_LIST_FIELDS.every((field,index)=>fields[index]===field)}function hasStandardPagination(value,count){return typeof value.has_more=="boolean"&&value.truncated===value.has_more&&value.count===count&&typeof value.total=="number"&&Number.isSafeInteger(value.total)&&(value.has_more?value.total>count&&typeof value.next_cursor=="string"&&value.next_cursor.length>0:value.total===count&&value.next_cursor==null)}function hasCompactibleSource(value){return isRecord(value)&&(value.status==="complete"||value.status==="unchecked")&&value.unreadable_item_count===0&&value.unreadable_directory_count===0}function hasDefaultOmissions(value){if(!isRecord(value)||!Array.isArray(value.omitted_field_groups))return!1;const groups=value.omitted_field_groups,group=groups[0];return value.has_omissions===!0&&value.omitted_field_group_count===1&&Object.keys(value).length===3&&groups.length===1&&isRecord(group)&&Object.keys(group).length===2&&group.name==="full_item_fields"&&group.restore_with==="--full"}function projectPmBriefListEnvelope(value){if(!isRecord(value)||!Array.isArray(value.items)||Object.hasOwn(value,"details")||!hasStandardBriefProjection(value.projection)||!hasCompactibleSource(value.completeness)||!hasStandardPagination(value,value.items.length)||!hasDefaultOmissions(value.omission_receipt))return value;const{total,has_more:hasMore,truncated:_truncated,next_cursor:nextCursor,completeness,projection:_projection,now:_now,omission_receipt:_omissions,sorting,...rest}=value,completed=completeness.status==="complete"&&!hasMore&&Object.keys(completeness).length===3,{unreadable_item_count:_items,unreadable_directory_count:_directories,...source}=completeness;return{...rest,...completed?{}:{total,has_more:hasMore,completeness:source},...hasMore?{next_cursor:nextCursor}:{},...isRecord(sorting)&&sorting.sort==="default"&&sorting.order==="asc"&&Object.keys(sorting).length===2?{}:{sorting},details:"--full"}}export{projectPmBriefListEnvelope};
|
|
2
2
|
//# sourceMappingURL=list-envelope.js.map
|
package/dist/sdk/pagination.d.ts
CHANGED
|
@@ -41,13 +41,13 @@ export declare function createQueryFingerprint(command:string,contract:unknown):
|
|
|
41
41
|
/** Encode the last emitted item id into a versioned opaque base64url cursor. */
|
|
42
42
|
export declare function encodeQueryCursor(fingerprint:string,afterId:string,afterIndex?:number,snapshot?:string):string;
|
|
43
43
|
/** Decode and validate an opaque cursor without imposing caller query identity. */
|
|
44
|
-
export declare function decodeQueryCursorEnvelope(cursor:unknown):QueryCursorEnvelope;
|
|
44
|
+
export declare function decodeQueryCursorEnvelope(cursor:unknown,cursorFlag?:"--after" | "--cursor"):QueryCursorEnvelope;
|
|
45
45
|
/** Decode and validate complete cursor state against a query fingerprint. */
|
|
46
|
-
export declare function decodeQueryCursorState(cursor:unknown,expectedFingerprint:string):QueryCursorState;
|
|
46
|
+
export declare function decodeQueryCursorState(cursor:unknown,expectedFingerprint:string,cursorFlag?:"--after" | "--cursor"):QueryCursorState;
|
|
47
47
|
/** Decode and validate a cursor against the normalized query fingerprint. */
|
|
48
48
|
export declare function decodeQueryCursor(cursor:unknown,expectedFingerprint:string):string;
|
|
49
49
|
/** Resolve the first row after a validated cursor's stable id tiebreaker. */
|
|
50
|
-
export declare function resolveQueryCursorStart<T>(rows:readonly T[],cursor:string | undefined,fingerprint:string,readId:(row:T) => string):number;
|
|
50
|
+
export declare function resolveQueryCursorStart<T>(rows:readonly T[],cursor:string | undefined,fingerprint:string,readId:(row:T) => string,cursorFlag?:"--after" | "--cursor"):number;
|
|
51
51
|
/** Page an ordered result through the shared stable cursor contract. */
|
|
52
52
|
export declare function paginateQueryRows<T>(rows:readonly T[],options:{
|
|
53
53
|
cursor?:string;
|
package/dist/sdk/pagination.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b6a81cf4-3095-5197-8e73-f017d98b1ccf")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"./read-output/options.js";import{createHash}from"node:crypto";import{PmCliError}from"../core/shared/errors.js";import{EXIT_CODE}from"../core/shared/constants.js";import{stableStringify}from"../core/shared/serialization.js";import{decodeReadOutputContinuationCursor}from"./read-output/continuation.js";const QUERY_CURSOR_VERSION=1,MAX_CURSOR_LENGTH=4096,BASE64URL_PATTERN=/^[A-Za-z0-9_-]+$/;function optionKeyForFlag(flag){return flag.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(_,character)=>character.toUpperCase())}function selectCursorSemanticOptions(options,contracts){const universalFlags=[...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS],presentationKeys=new Set(universalFlags.flatMap(flag=>[optionKeyForFlag(flag),flag.slice(2).replaceAll("-","_")]));for(const contract of contracts)if(contract.cursor_semantics==="presentation"){presentationKeys.add(optionKeyForFlag(contract.flag));for(const alias of contract.aliases??[])presentationKeys.add(optionKeyForFlag(alias))}return Object.fromEntries(Object.entries(options).filter(([key])=>!presentationKeys.has(key)))}function createQueryFingerprint(command,contract){return createHash("sha256").update(command).update("\0").update(stableStringify(contract)).digest("hex").slice(0,24)}function encodeQueryCursor(fingerprint,afterId,afterIndex,snapshot){return Buffer.from(JSON.stringify({version:QUERY_CURSOR_VERSION,fingerprint,after_id:afterId,...afterIndex===void 0?{}:{after_index:afterIndex},...snapshot===void 0?{}:{snapshot}})).toString("base64url")}function invalidCursor(message,cursorFlag){return new PmCliError(message,EXIT_CODE.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the original query without ${cursorFlag} to obtain a fresh cursor.`]})}function isQueryCursorEnvelope(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const envelope=value;return envelope.version===QUERY_CURSOR_VERSION&&typeof envelope.fingerprint=="string"&&typeof envelope.after_id=="string"&&envelope.after_id.length>0&&(envelope.after_index===void 0||Number.isSafeInteger(envelope.after_index)&&envelope.after_index>=0)&&(envelope.snapshot===void 0||typeof envelope.snapshot=="string"&&envelope.snapshot.length>0)}function decodeQueryCursorEnvelope(cursor,cursorFlag="--after"){if(typeof cursor!="string")throw invalidCursor("Query cursor is malformed.",cursorFlag);const normalized=cursor.trim();if(normalized.length===0||normalized.length>MAX_CURSOR_LENGTH||!BASE64URL_PATTERN.test(normalized))throw invalidCursor("Query cursor is malformed.",cursorFlag);let parsed;try{parsed=JSON.parse(Buffer.from(normalized,"base64url").toString("utf8"))}catch{throw invalidCursor("Query cursor is malformed.",cursorFlag)}if(!isQueryCursorEnvelope(parsed)){let outputCursor=!1;try{decodeReadOutputContinuationCursor(normalized),outputCursor=!0}catch{}throw outputCursor?new PmCliError(`An output cursor must be continued with --output-cursor, not ${cursorFlag}.`,EXIT_CODE.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the same query, replacing ${cursorFlag} with --output-cursor ${normalized}; retain any producer ${cursorFlag} cursor from the original page.`]}):invalidCursor("Query cursor version or payload is unsupported.",cursorFlag)}return parsed}function decodeQueryCursorState(cursor,expectedFingerprint,cursorFlag="--after"){const envelope=decodeQueryCursorEnvelope(cursor,cursorFlag);if(envelope.fingerprint!==expectedFingerprint)throw invalidCursor(`Query cursor does not match the current filters, sort, or query (${envelope.fingerprint} != ${expectedFingerprint}).`,cursorFlag);return{after_id:envelope.after_id,...envelope.after_index===void 0?{}:{after_index:envelope.after_index},...envelope.snapshot===void 0?{}:{snapshot:envelope.snapshot}}}function decodeQueryCursor(cursor,expectedFingerprint){return decodeQueryCursorState(cursor,expectedFingerprint).after_id}function resolveQueryCursorStart(rows,cursor,fingerprint,readId,cursorFlag="--after"){if(cursor===void 0)return 0;const state=decodeQueryCursorState(cursor,fingerprint,cursorFlag),index=rows.findIndex(row=>readId(row)===state.after_id);if(index<0){if(state.after_index!==void 0)return Math.min(state.after_index,rows.length);throw invalidCursor(`Query cursor item ${state.after_id} is no longer present in this result set.`,cursorFlag)}return index+1}function paginateQueryRows(rows,options){if(options.cursor!==void 0&&decodeQueryCursorState(options.cursor,options.fingerprint).snapshot!==options.snapshot)throw invalidCursor("Query cursor does not match the requested snapshot.","--after");const pageStart=resolveQueryCursorStart(rows,options.cursor,options.fingerprint,options.readId),pageRows=rows.slice(pageStart,pageStart+options.limit),hasMore=pageRows.length>0&&pageStart+pageRows.length<rows.length,lastRow=pageRows.at(-1);return{rows:pageRows,has_more:hasMore,...hasMore&&lastRow!==void 0?{next_cursor:encodeQueryCursor(options.fingerprint,options.readId(lastRow),pageStart+pageRows.length-1,options.snapshot)}:{}}}const QUERY_CURSOR_CONTRACT=Object.freeze({version:QUERY_CURSOR_VERSION,max_length:MAX_CURSOR_LENGTH});export{QUERY_CURSOR_CONTRACT,createQueryFingerprint,decodeQueryCursor,decodeQueryCursorEnvelope,decodeQueryCursorState,encodeQueryCursor,paginateQueryRows,resolveQueryCursorStart,selectCursorSemanticOptions};
|
|
2
2
|
//# sourceMappingURL=pagination.js.map
|