@unbrained/pm-cli 2026.10.31 → 2026.11.2
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-user/references/ECOSYSTEM_PLANNING.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +3 -3
- package/CHANGELOG.md +27 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +1 -1
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/register-operations.d.ts +3 -3
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-GMBDZID5.js → chunk-3A4NVHYS.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-VC7TA67O.js → chunk-3ZQQVJT2.js} +19 -19
- package/dist/cli-bundle/chunks/{chunk-XDDPSWIW.js → chunk-4HW253W2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4OELCF3O.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-6PSDQ7T7.js → chunk-533L6D2N.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-35Q2B2GJ.js → chunk-ABFFRQRO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-BFZUJ5QP.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-SBVX5CMV.js → chunk-D52QQ7LP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-P3LNMWL2.js → chunk-DAZFCSDV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-43R7UTWV.js → chunk-EN27ZQSV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MRUA2Z43.js → chunk-GK2CHAT3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BS2KXT24.js → chunk-HOGKWJU5.js} +42 -42
- package/dist/cli-bundle/chunks/{chunk-WX25MU4N.js → chunk-J3JM36EH.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-V6EWBTNH.js → chunk-JRXD7SIL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-U7JXZMU5.js → chunk-K46GDAKX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PT7TS6E7.js → chunk-KJLGBLR3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2AHSPMKJ.js → chunk-NGRPD3ZO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-OJR2YGXF.js +31 -0
- package/dist/cli-bundle/chunks/chunk-QHHFXNSQ.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-TL3O5GZA.js → chunk-RGHLQGEX.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-24J6TNYE.js → chunk-VEOFWE32.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-ZNWDYDFF.js +129 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-KGMJVFH2.js → indexed-receipt-blobs-IEJ2QOW3.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-JHPBH6N7.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-I4RHIT3Q.js → mutation-admission-QUNQZCZ5.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-MVDL5EXG.js → register-list-query-NZTK3AXA.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-GAF7LXRB.js → register-mutation-2OFAMOVH.js} +2 -2
- package/dist/cli-bundle/chunks/register-operations-RFMM5KZ6.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-MZN6ONB3.js → register-setup-6B6Q7M5L.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-YWSWFOZY.js → settlement-hook-UTCEZBFT.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-2ZORTOF6.js → stage-VLI4OBVX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4QPGJO2G.js → chunk-3UD6F2KQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EA65HVBO.js → chunk-4NVPDZLX.js} +12 -12
- package/dist/cli-bundle/focused-chunks/{chunk-KKRIFBSL.js → chunk-4UUE3YXZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NRBUMDLF.js → chunk-5UDDRPYR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SFQKCA5K.js → chunk-745IDMTD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QFMJGQGO.js → chunk-B6OOKKOX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-5MCGYBOQ.js → chunk-EJJWOFP5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-FUGYXUUL.js +80 -0
- package/dist/cli-bundle/focused-chunks/{chunk-6F6APBCX.js → chunk-HMXVTWIV.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-HSAEEWSI.js → chunk-I4Z2SCV5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JLN5CFYM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-K4FMZB4Y.js +23 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DFUTCKUF.js → chunk-MQVBWFJF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2J7T2UCH.js → chunk-NJFMG3IK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HPWT3RBG.js → chunk-PCCZ72C3.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-PF553UVP.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MW77Q3AQ.js → chunk-Q23K6WLV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Y6UYRMVG.js → chunk-QNXXOFLQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JLXGRDTG.js → chunk-QVFE5LIX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-KH5QJXY7.js → chunk-RUCG6UWN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JNKRUCVZ.js → chunk-SGWYNU7T.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-TGS5RXBY.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PC3R5CJV.js → chunk-WD43E7RU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PFBQOZPK.js → chunk-YM4AMP7H.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-KHWT44EK.js → indexed-receipt-blobs-FT3KF6VJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-LU75EG7D.js → item-transaction-F4SN7TXJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-KDJ7SCPA.js → mutation-admission-7R2FXJ5O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-SJV52ZTV.js → settlement-hook-KMIBD4F2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-R4KEBO37.js → stage-6B3O2GZ6.js} +2 -2
- package/dist/cli-bundle/main.js +24 -24
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +9 -9
- package/dist/core/extensions/extension-types.d.ts +5 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/item/parse.js +2 -2
- package/dist/core/lock/lock-confinement.d.ts +55 -0
- package/dist/core/lock/lock-confinement.js +2 -0
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock.js +2 -2
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output.js +2 -2
- package/dist/core/shared/errors.d.ts +6 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/settings-sections.d.ts +61 -0
- package/dist/core/store/settings-sections.js +3 -0
- package/dist/core/store/settings-validator.d.ts +4 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +29 -2
- package/dist/core/store/settings.js +4 -3
- package/dist/core/telemetry/consent.js +2 -2
- package/dist/core/telemetry/runtime.js +2 -2
- package/dist/core/test/background-runs.js +3 -3
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context-intent-contracts.d.ts +17 -0
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/error-code-catalog-rows.d.ts +39 -0
- package/dist/sdk/generated/error-code-catalog-rows.js +2 -0
- package/dist/sdk/generated/generated-error-code-catalog-part-1.d.ts +3 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.d.ts +3 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/generated-error-code-catalog.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init-agent-guidance.js +2 -2
- package/dist/sdk/lifecycle/claim.d.ts +27 -0
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.d.ts +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/output/list-envelope.d.ts +8 -0
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output.d.ts +1 -1
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +2 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.d.ts +2 -0
- package/dist/sdk/runtime.d.ts +2 -2
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/start-task-status.d.ts +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/docs/AGENT_EVIDENCE_CONSISTENCY.md +10 -0
- package/docs/AGENT_GUIDE.md +3 -3
- package/docs/COMMANDS.md +1 -0
- package/docs/COMMAND_NAMESPACES.md +1 -1
- package/docs/CONFIGURATION.md +9 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +9 -6
- package/docs/LIFECYCLE_COMMANDS.md +19 -4
- package/docs/RELEASING.md +22 -2
- package/docs/SDK.md +37 -2
- package/docs/SDK_ACTION_CONFORMANCE.md +21 -0
- package/docs/SDK_CONFIGURATION_SAFETY.md +55 -0
- package/docs/TESTING.md +2 -1
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/agent-task-transcripts.json +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +12 -3
- package/marketplace.json +1 -1
- package/package.json +9 -3
- 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-HSBTITO4.js +0 -3
- package/dist/cli-bundle/chunks/chunk-WNF6FOL7.js +0 -31
- package/dist/cli-bundle/chunks/chunk-WRXQAW7Q.js +0 -114
- package/dist/cli-bundle/chunks/chunk-YT5D5HNG.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ZTJVOBDU.js +0 -128
- package/dist/cli-bundle/chunks/item-transaction-UWV6UNSV.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-JLFRL36Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-57HPXGOQ.js +0 -79
- package/dist/cli-bundle/focused-chunks/chunk-AFVN2KCP.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-GP2WU43K.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-NOKG4RFN.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-WHIE2C6Q.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
-
`)}async function readBackgroundTestRunRecord(pmRoot,runId){const recordPath=getTestRunRecordPath(pmRoot,runId),raw=await readFileIfExists(recordPath);return raw?parseBackgroundRunRecord(raw,recordPath):null}async function listBackgroundRunRecordPaths(pmRoot){const recordsRoot=getTestRunsRecordsPath(pmRoot);return await pathExists(recordsRoot)?(await fs.readdir(recordsRoot,{withFileTypes:!0})).filter(entry=>entry.isFile()&&entry.name.endsWith(".json")).map(entry=>path.join(recordsRoot,entry.name)).sort((left,right)=>right.localeCompare(left)):[]}function parseLinuxRssStatus(raw){const match=raw.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(match)return Number.parseInt(match[1],10)*1024}async function readLinuxRssBytes(pid){if(process.platform==="linux")try{const raw=await fs.readFile(`/proc/${pid}/status`,"utf8");return parseLinuxRssStatus(raw)}catch{return}}function parseLinuxCpuStat(raw){const closeParenIndex=raw.lastIndexOf(")");if(closeParenIndex<0)return{};const parts=raw.slice(closeParenIndex+2).trim().split(/\s+/),utimeTicks=Number.parseInt(parts[11],10),stimeTicks=Number.parseInt(parts[12],10);return!Number.isFinite(utimeTicks)||!Number.isFinite(stimeTicks)?{}:{cpu_user_seconds:utimeTicks/PROC_STAT_TICKS_PER_SECOND,cpu_system_seconds:stimeTicks/PROC_STAT_TICKS_PER_SECOND}}async function readLinuxCpuSeconds(pid){if(process.platform!=="linux")return{};try{const raw=await fs.readFile(`/proc/${pid}/stat`,"utf8");return parseLinuxCpuStat(raw)}catch{return{}}}async function buildResourceSnapshot(record){const pid=record.child_pid??record.worker_pid;if(!isPidRunning(pid))return;const rssBytes=await readLinuxRssBytes(pid),cpu=await readLinuxCpuSeconds(pid),startedAtMs=record.started_at?Date.parse(record.started_at):Number.NaN,uptimeSeconds=Number.isFinite(startedAtMs)?Math.max(0,(nowMs()-startedAtMs)/1e3):void 0;return{recorded_at:nowIso(),rss_bytes:rssBytes,cpu_user_seconds:cpu.cpu_user_seconds,cpu_system_seconds:cpu.cpu_system_seconds,uptime_seconds:uptimeSeconds}}function readCount(value){return typeof value=="number"&&Number.isFinite(value)?value:0}function evaluateWorkerResult(kind,payload){if(!payload||typeof payload!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};const record=payload;if(kind==="test-all"){const totals=record.totals??{};return{summary:{items:typeof totals.items=="number"?totals.items:void 0,linked_tests:typeof totals.linked_tests=="number"?totals.linked_tests:void 0,passed:readCount(totals.passed),failed:readCount(totals.failed),skipped:readCount(totals.skipped),fail_on_skipped_triggered:record.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:payload}}const runResults=Array.isArray(record.run_results)?record.run_results:[];let passed=0,failed=0,skipped=0;for(const entry of runResults){if(!entry||typeof entry!="object")continue;const status=entry.status;if(status==="passed"){passed+=1;continue}if(status==="failed"||status==="refused"){failed+=1;continue}skipped+=1}return{summary:{passed,failed,skipped,fail_on_skipped_triggered:record.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:payload}}function parseProgressLine(stderrLine){const line=stderrLine.trim();if(line.length===0)return null;const testAllMatch=line.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(testAllMatch){const itemIndex=Number.parseInt(testAllMatch[1],10),itemTotal=Number.parseInt(testAllMatch[2],10);return{item_index:itemIndex,item_total:itemTotal,item_id:testAllMatch[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:nowIso(),phase:testAllMatch[3]?.toLowerCase()==="end"?"finished":"running"}}const linkedTestMatch=line.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!linkedTestMatch)return null;const index=Number.parseInt(linkedTestMatch[1],10),total=Number.parseInt(linkedTestMatch[2],10),elapsed=linkedTestMatch[4]?Number.parseInt(linkedTestMatch[4],10):void 0,commandMatch=line.match(/\scommand="((?:\\.|[^"\\])*)"/),currentCommand=commandMatch?commandMatch[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:index,linked_test_total:total,current_command:currentCommand,elapsed_ms:Number.isFinite(elapsed)?elapsed:void 0,heartbeat_at:nowIso(),phase:linkedTestMatch[3]?.toLowerCase()==="end"?"finished":"running"}}function splitLines(value){return value.split(/\r?\n/).map(entry=>entry.trimEnd()).filter(entry=>entry.length>0)}function tailLines(value,limit){if(limit<=0)return[];const lines=splitLines(value);return lines.length<=limit?lines:lines.slice(lines.length-limit)}async function resolveBackgroundCliEntry(cwd){const configured=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(configured&&configured.length>0){const resolvedConfigured=path.resolve(cwd,configured);if(await pathExists(resolvedConfigured))return resolvedConfigured}const distEntry=path.resolve(cwd,"dist","cli.js");if(await pathExists(distEntry))return distEntry;const argvEntry=process.argv[1]?.trim();if(argvEntry&&argvEntry.length>0){const resolvedArgvEntry=path.resolve(cwd,argvEntry);if(await pathExists(resolvedArgvEntry))return resolvedArgvEntry}throw new PmCliError("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",EXIT_CODE.GENERIC_FAILURE)}async function refreshRunIfStale(pmRoot,record){if(!BACKGROUND_RUN_ACTIVE_STATUSES.has(record.status)||isPidRunning(record.worker_pid)||record.finished_at)return record;const next={...record,status:"failed",finished_at:nowIso(),error:record.error??"Background test run worker exited before writing terminal status."};return await writeBackgroundRunRecord(pmRoot,next),next}async function startBackgroundTestRun(options){await ensureBackgroundRunStorage(options.pmRoot);const normalizedArgs=normalizeCommandArgs(options.commandArgs);if(normalizedArgs.length===0)throw new PmCliError("Background test run requires command arguments.",EXIT_CODE.USAGE);const fingerprint=buildBackgroundTestRunFingerprint(options.kind,normalizedArgs,options.pmRoot),existingRuns=await listBackgroundTestRuns(options.pmRoot,{});for(const existing of existingRuns){const refreshed=await refreshRunIfStale(options.pmRoot,existing);if(refreshed.fingerprint===fingerprint&&!(!BACKGROUND_RUN_ACTIVE_STATUSES.has(refreshed.status)||!isPidRunning(refreshed.worker_pid)))return{started:!1,run:{...refreshed,duplicate_of:refreshed.id},duplicate_of:refreshed.id}}const runId=buildRunId(),createdAt=nowIso(),stdoutPath=getTestRunStdoutPath(options.pmRoot,runId),stderrPath=getTestRunStderrPath(options.pmRoot,runId),resultPath=getTestRunResultPath(options.pmRoot,runId);await fs.writeFile(stdoutPath,"","utf8"),await fs.writeFile(stderrPath,"","utf8");const record={id:runId,kind:options.kind,status:"queued",created_at:createdAt,updated_at:createdAt,requested_by:options.requestedBy,fingerprint,command_args:normalizedArgs,command_label:summarizeCommandLabel(normalizedArgs),pm_root:options.pmRoot,global_pm_root:options.globalPmRoot,target_id:options.targetId,status_filter:options.statusFilter,attempt:typeof options.attempt=="number"&&Number.isFinite(options.attempt)&&options.attempt>=1?Math.floor(options.attempt):1,resumed_from:options.resumedFrom,resumed_by:options.resumedBy,stdout_path:stdoutPath,stderr_path:stderrPath,result_path:resultPath,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:createdAt}};return await writeBackgroundRunRecord(options.pmRoot,record),{started:!0,run:record}}async function spawnBackgroundTestRunWorker(options){const record=await readBackgroundTestRunRecord(options.pmRoot,options.runId);if(!record)throw new PmCliError(`Background test run ${options.runId} not found`,EXIT_CODE.NOT_FOUND);if(BACKGROUND_RUN_TERMINAL_STATUSES.has(record.status))throw new PmCliError(`Background test run ${record.id} is already terminal (${record.status}).`,EXIT_CODE.CONFLICT);const cliEntry=await resolveBackgroundCliEntry(process.cwd()),args=[];options.noExtensions===!0&&args.push("--no-extensions"),args.push("--path",record.pm_root,"test-runs-worker",record.id);const env={...process.env,PM_PATH:record.pm_root,PM_GLOBAL_PATH:record.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:record.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(record.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:record.resumed_from??"",FORCE_COLOR:"0"},child=spawn(process.execPath,[cliEntry,...args],{cwd:process.cwd(),env,detached:!0,stdio:"ignore",windowsHide:!0});child.unref();const next={...record,status:"queued",worker_pid:child.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:nowIso()}};return await writeBackgroundRunRecord(options.pmRoot,next),next}async function appendFileOrdered(queue,filePath,text){await queue,await fs.appendFile(filePath,text,"utf8")}function resolvePositiveEnvInteger(name,fallback){const parsed=Number.parseInt(process.env[name]??"",10);return Number.isFinite(parsed)&&parsed>0?parsed:fallback}function buildBackgroundWorkerEnv(record){return{...process.env,PM_PATH:record.pm_root,PM_GLOBAL_PATH:record.global_pm_root,FORCE_COLOR:"0"}}function buildBackgroundWorkerChildArgs(record,noExtensions){return noExtensions?["--no-extensions",...record.command_args]:[...record.command_args]}function createBackgroundRunRecordWriteScheduler(pmRoot,record){let writeQueue=Promise.resolve();return{schedule(){writeQueue=writeQueue.then(async()=>{try{await writeBackgroundRunRecord(pmRoot,record)}catch{}})},async flush(){await writeQueue}}}function requestChildSignal(child,signal){try{child.kill(signal)}catch{}}async function requestBackgroundWorkerStop(record,child,state,scheduleRecordWrite){state.stopRequested||(state.stopRequested=!0,record.stop_requested_at=nowIso(),record.progress={...record.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:nowIso()},scheduleRecordWrite(),requestChildSignal(child,"SIGTERM"),setTimeout(()=>requestChildSignal(child,"SIGKILL"),resolvePositiveEnvInteger("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",DEFAULT_BACKGROUND_RUN_FORCE_KILL_DELAY_MS)).unref?.())}function buildItemBackgroundProgress(line,progressPatch,phase){return{phase,message:line,heartbeat_at:nowIso(),item_index:progressPatch.item_index,item_total:progressPatch.item_total,item_id:progressPatch.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function buildLinkedTestBackgroundProgress(line,record,progressPatch,phase){return{phase,message:line,heartbeat_at:nowIso(),item_index:progressPatch.item_index??record.progress?.item_index,item_total:progressPatch.item_total??record.progress?.item_total,item_id:progressPatch.item_id??record.progress?.item_id,linked_test_index:progressPatch.linked_test_index,linked_test_total:progressPatch.linked_test_total,current_command:progressPatch.current_command,elapsed_ms:progressPatch.elapsed_ms}}function applyBackgroundWorkerProgressLine(record,line,stopRequested){const progressPatch=parseProgressLine(line);if(!progressPatch)return!1;const phase=record.progress?.phase==="stopping"?"stopping":"running";return record.progress=progressPatch.item_id?buildItemBackgroundProgress(line,progressPatch,phase):buildLinkedTestBackgroundProgress(line,record,progressPatch,phase),progressPatch.phase==="finished"&&!stopRequested&&(record.progress.phase="running"),!0}function parseBackgroundWorkerStdout(stdoutBuffer){if(stdoutBuffer.trim().length===0)return null;try{return JSON.parse(stdoutBuffer)}catch{return null}}function resolveBackgroundWorkerFinalStatus(record,stopRequested){return stopRequested?"stopped":record.exit_code===0&&(record.summary?.failed??0)===0&&record.summary?.fail_on_skipped_triggered!==!0?"passed":"failed"}function buildFinishedBackgroundProgress(record,stopRequested){return{phase:"finished",message:stopRequested?"Background run stopped.":`Background run finished with status=${record.status}.`,heartbeat_at:nowIso(),item_index:record.progress?.item_index,item_total:record.progress?.item_total,item_id:record.progress?.item_id,linked_test_index:record.progress?.linked_test_index,linked_test_total:record.progress?.linked_test_total,current_command:record.progress?.current_command,elapsed_ms:record.progress?.elapsed_ms}}async function writeBackgroundWorkerResult(record,parsedResult,stdoutBuffer){if(parsedResult!==null){await writeFileAtomic(record.result_path,`${JSON.stringify(parsedResult,null,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]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}catch{}})();import fs from"node:fs/promises";import{spawn}from"node:child_process";import{createHash,randomBytes}from"node:crypto";import path from"node:path";import{ensureDir,pathExists,readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{PmCliError}from"../shared/errors.js";import{EXIT_CODE}from"../shared/constants.js";import{nowIso}from"../shared/time.js";import{getTestRunRecordPath,getTestRunResultPath,getTestRunStderrPath,getTestRunStdoutPath,getTestRunsPath,getTestRunsRecordsPath,getTestRunsResultsPath,getTestRunsStderrPath,getTestRunsStdoutPath}from"../store/paths.js";const BACKGROUND_RUN_ACTIVE_STATUSES=new Set(["queued","running"]),BACKGROUND_RUN_TERMINAL_STATUSES=new Set(["passed","failed","stopped","canceled"]),DEFAULT_BACKGROUND_RUN_RESOURCE_SNAPSHOT_INTERVAL_MS=3e3,DEFAULT_BACKGROUND_RUN_FORCE_KILL_DELAY_MS=3e3,DEFAULT_BACKGROUND_RUN_HEARTBEAT_STALE_MS=3e4,DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES=100,PROC_STAT_TICKS_PER_SECOND=100;function nowMs(){return Date.now()}function normalizeCommandArgs(args){return args.map(entry=>entry.trim()).filter(entry=>entry.length>0)}function summarizeCommandLabel(args){const joined=args.join(" ").replaceAll(/\s+/g," ").trim();return joined.length<=180?joined:`${joined.slice(0,177)}...`}function buildRunId(){const timePart=Date.now().toString(36),randomPart=randomBytes(3).toString("hex");return`tr-${timePart}-${randomPart}`}function buildBackgroundTestRunFingerprint(kind,commandArgs,pmRoot){const payload={kind,command:normalizeCommandArgs(commandArgs),pm_root:path.resolve(pmRoot)};return createHash("sha256").update(JSON.stringify(payload)).digest("hex")}function isPidRunning(pid){if(!Number.isInteger(pid)||!pid||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error){return(typeof error=="object"&&error!==null&&"code"in error?error.code:void 0)==="EPERM"}}async function ensureBackgroundRunStorage(pmRoot){await ensureDir(getTestRunsPath(pmRoot)),await ensureDir(getTestRunsRecordsPath(pmRoot)),await ensureDir(getTestRunsStdoutPath(pmRoot)),await ensureDir(getTestRunsStderrPath(pmRoot)),await ensureDir(getTestRunsResultsPath(pmRoot))}async function parseBackgroundRunRecord(raw,recordPath){try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!="object"||typeof parsed.id!="string")throw new Error("invalid run record payload");return parsed}catch(error){throw new PmCliError(`Failed to parse background test run record at ${recordPath}: ${error instanceof Error?error.message:String(error)}`,EXIT_CODE.GENERIC_FAILURE)}}async function writeBackgroundRunRecord(pmRoot,record){const next={...record,updated_at:nowIso()};await writeFileAtomic(getTestRunRecordPath(pmRoot,record.id),`${JSON.stringify(next,null,2)}
|
|
2
|
+
`)}async function readBackgroundTestRunRecord(pmRoot,runId){const recordPath=getTestRunRecordPath(pmRoot,runId),raw=await readFileIfExists(recordPath);return raw?parseBackgroundRunRecord(raw,recordPath):null}async function listBackgroundRunRecordPaths(pmRoot){const recordsRoot=getTestRunsRecordsPath(pmRoot);return await pathExists(recordsRoot)?(await fs.readdir(recordsRoot,{withFileTypes:!0})).filter(entry=>entry.isFile()&&entry.name.endsWith(".json")).map(entry=>path.join(recordsRoot,entry.name)).sort((left,right)=>right.localeCompare(left)):[]}function parseLinuxRssStatus(raw){const match=raw.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(match)return Number.parseInt(match[1],10)*1024}async function readLinuxRssBytes(pid){if(process.platform==="linux")try{const raw=await fs.readFile(`/proc/${pid}/status`,"utf8");return parseLinuxRssStatus(raw)}catch{return}}function parseLinuxCpuStat(raw){const closeParenIndex=raw.lastIndexOf(")");if(closeParenIndex<0)return{};const parts=raw.slice(closeParenIndex+2).trim().split(/\s+/),utimeTicks=Number.parseInt(parts[11],10),stimeTicks=Number.parseInt(parts[12],10);return!Number.isFinite(utimeTicks)||!Number.isFinite(stimeTicks)?{}:{cpu_user_seconds:utimeTicks/PROC_STAT_TICKS_PER_SECOND,cpu_system_seconds:stimeTicks/PROC_STAT_TICKS_PER_SECOND}}async function readLinuxCpuSeconds(pid){if(process.platform!=="linux")return{};try{const raw=await fs.readFile(`/proc/${pid}/stat`,"utf8");return parseLinuxCpuStat(raw)}catch{return{}}}async function buildResourceSnapshot(record){const pid=record.child_pid??record.worker_pid;if(!isPidRunning(pid))return;const rssBytes=await readLinuxRssBytes(pid),cpu=await readLinuxCpuSeconds(pid),startedAtMs=record.started_at?Date.parse(record.started_at):Number.NaN,uptimeSeconds=Number.isFinite(startedAtMs)?Math.max(0,(nowMs()-startedAtMs)/1e3):void 0;return{recorded_at:nowIso(),rss_bytes:rssBytes,cpu_user_seconds:cpu.cpu_user_seconds,cpu_system_seconds:cpu.cpu_system_seconds,uptime_seconds:uptimeSeconds}}function readCount(value){return typeof value=="number"&&Number.isFinite(value)?value:0}function evaluateWorkerResult(kind,payload){if(!payload||typeof payload!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};const record=payload;if(kind==="test-all"){const totals=record.totals??{};return{summary:{items:typeof totals.items=="number"?totals.items:void 0,linked_tests:typeof totals.linked_tests=="number"?totals.linked_tests:void 0,passed:readCount(totals.passed),failed:readCount(totals.failed),skipped:readCount(totals.skipped),fail_on_skipped_triggered:record.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:payload}}const runResults=Array.isArray(record.run_results)?record.run_results:[];let passed=0,failed=0,skipped=0;for(const entry of runResults){if(!entry||typeof entry!="object")continue;const status=entry.status;if(status==="passed"){passed+=1;continue}if(status==="failed"||status==="refused"){failed+=1;continue}skipped+=1}return{summary:{passed,failed,skipped,fail_on_skipped_triggered:record.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:payload}}function parseProgressLine(stderrLine){const line=stderrLine.trim();if(line.length===0)return null;const testAllMatch=line.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(testAllMatch){const itemIndex=Number.parseInt(testAllMatch[1],10),itemTotal=Number.parseInt(testAllMatch[2],10);return{item_index:itemIndex,item_total:itemTotal,item_id:testAllMatch[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:nowIso(),phase:testAllMatch[3]?.toLowerCase()==="end"?"finished":"running"}}const linkedTestMatch=line.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!linkedTestMatch)return null;const index=Number.parseInt(linkedTestMatch[1],10),total=Number.parseInt(linkedTestMatch[2],10),elapsed=linkedTestMatch[4]?Number.parseInt(linkedTestMatch[4],10):void 0,commandMatch=line.match(/\scommand="((?:\\.|[^"\\])*)"/),currentCommand=commandMatch?commandMatch[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:index,linked_test_total:total,current_command:currentCommand,elapsed_ms:Number.isFinite(elapsed)?elapsed:void 0,heartbeat_at:nowIso(),phase:linkedTestMatch[3]?.toLowerCase()==="end"?"finished":"running"}}function splitLines(value){return value.split(/\r?\n/).map(entry=>entry.trimEnd()).filter(entry=>entry.length>0)}function tailLines(value,limit){if(limit<=0)return[];const lines=splitLines(value);return lines.length<=limit?lines:lines.slice(lines.length-limit)}async function resolveBackgroundCliEntry(cwd){const configured=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(configured&&configured.length>0){const resolvedConfigured=path.resolve(cwd,configured);if(await pathExists(resolvedConfigured))return resolvedConfigured}const distEntry=path.resolve(cwd,"dist","cli.js");if(await pathExists(distEntry))return distEntry;const argvEntry=process.argv[1]?.trim();if(argvEntry&&argvEntry.length>0){const resolvedArgvEntry=path.resolve(cwd,argvEntry);if(await pathExists(resolvedArgvEntry))return resolvedArgvEntry}throw new PmCliError("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",EXIT_CODE.GENERIC_FAILURE)}async function refreshRunIfStale(pmRoot,record){if(!BACKGROUND_RUN_ACTIVE_STATUSES.has(record.status)||isPidRunning(record.worker_pid)||record.finished_at)return record;const next={...record,status:"failed",finished_at:nowIso(),error:record.error??"Background test run worker exited before writing terminal status."};return await writeBackgroundRunRecord(pmRoot,next),next}async function startBackgroundTestRun(options){await ensureBackgroundRunStorage(options.pmRoot);const normalizedArgs=normalizeCommandArgs(options.commandArgs);if(normalizedArgs.length===0)throw new PmCliError("Background test run requires command arguments.",EXIT_CODE.USAGE);const fingerprint=buildBackgroundTestRunFingerprint(options.kind,normalizedArgs,options.pmRoot),existingRuns=await listBackgroundTestRuns(options.pmRoot,{});for(const existing of existingRuns){const refreshed=await refreshRunIfStale(options.pmRoot,existing);if(refreshed.fingerprint===fingerprint&&!(!BACKGROUND_RUN_ACTIVE_STATUSES.has(refreshed.status)||!isPidRunning(refreshed.worker_pid)))return{started:!1,run:{...refreshed,duplicate_of:refreshed.id},duplicate_of:refreshed.id}}const runId=buildRunId(),createdAt=nowIso(),stdoutPath=getTestRunStdoutPath(options.pmRoot,runId),stderrPath=getTestRunStderrPath(options.pmRoot,runId),resultPath=getTestRunResultPath(options.pmRoot,runId);await fs.writeFile(stdoutPath,"","utf8"),await fs.writeFile(stderrPath,"","utf8");const record={id:runId,kind:options.kind,status:"queued",created_at:createdAt,updated_at:createdAt,requested_by:options.requestedBy,fingerprint,command_args:normalizedArgs,command_label:summarizeCommandLabel(normalizedArgs),pm_root:options.pmRoot,global_pm_root:options.globalPmRoot,target_id:options.targetId,status_filter:options.statusFilter,attempt:typeof options.attempt=="number"&&Number.isFinite(options.attempt)&&options.attempt>=1?Math.floor(options.attempt):1,resumed_from:options.resumedFrom,resumed_by:options.resumedBy,stdout_path:stdoutPath,stderr_path:stderrPath,result_path:resultPath,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:createdAt}};return await writeBackgroundRunRecord(options.pmRoot,record),{started:!0,run:record}}async function spawnBackgroundTestRunWorker(options){const record=await readBackgroundTestRunRecord(options.pmRoot,options.runId);if(!record)throw new PmCliError(`Background test run ${options.runId} not found`,EXIT_CODE.NOT_FOUND);if(BACKGROUND_RUN_TERMINAL_STATUSES.has(record.status))throw new PmCliError(`Background test run ${record.id} is already terminal (${record.status}).`,EXIT_CODE.CONFLICT);const cliEntry=await resolveBackgroundCliEntry(process.cwd()),args=[];options.noExtensions===!0&&args.push("--no-extensions"),args.push("--path",record.pm_root,"test-runs-worker",record.id);const env={...process.env,PM_PATH:record.pm_root,PM_GLOBAL_PATH:record.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:record.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(record.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:record.resumed_from??"",FORCE_COLOR:"0"},child=spawn(process.execPath,[cliEntry,...args],{cwd:process.cwd(),env,detached:!0,stdio:"ignore",windowsHide:!0});child.unref();const next={...record,status:"queued",worker_pid:child.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:nowIso()}};return await writeBackgroundRunRecord(options.pmRoot,next),next}async function appendFileOrdered(queue,filePath,text){await queue,await fs.appendFile(filePath,text,"utf8")}function resolvePositiveEnvInteger(name,fallback){const parsed=Number.parseInt(process.env[name]??"",10);return Number.isFinite(parsed)&&parsed>0?parsed:fallback}function buildBackgroundWorkerEnv(record){return{...process.env,PM_PATH:record.pm_root,PM_GLOBAL_PATH:record.global_pm_root,FORCE_COLOR:"0"}}function buildBackgroundWorkerChildArgs(record,noExtensions){return noExtensions?["--no-extensions",...record.command_args]:[...record.command_args]}function createBackgroundRunRecordWriteScheduler(pmRoot,record){let writeQueue=Promise.resolve();return{schedule(){writeQueue=writeQueue.then(async()=>{try{await writeBackgroundRunRecord(pmRoot,record)}catch{}})},async flush(){await writeQueue}}}function requestChildSignal(child,signal){try{child.kill(signal)}catch{}}async function requestBackgroundWorkerStop(record,child,state,scheduleRecordWrite){state.stopRequested||(state.stopRequested=!0,record.stop_requested_at=nowIso(),record.progress={...record.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:nowIso()},scheduleRecordWrite(),requestChildSignal(child,"SIGTERM"),setTimeout(()=>requestChildSignal(child,"SIGKILL"),resolvePositiveEnvInteger("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",DEFAULT_BACKGROUND_RUN_FORCE_KILL_DELAY_MS)).unref?.())}function buildItemBackgroundProgress(line,progressPatch,phase){return{phase,message:line,heartbeat_at:nowIso(),item_index:progressPatch.item_index,item_total:progressPatch.item_total,item_id:progressPatch.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function buildLinkedTestBackgroundProgress(line,record,progressPatch,phase){return{phase,message:line,heartbeat_at:nowIso(),item_index:progressPatch.item_index??record.progress?.item_index,item_total:progressPatch.item_total??record.progress?.item_total,item_id:progressPatch.item_id??record.progress?.item_id,linked_test_index:progressPatch.linked_test_index,linked_test_total:progressPatch.linked_test_total,current_command:progressPatch.current_command,elapsed_ms:progressPatch.elapsed_ms}}function applyBackgroundWorkerProgressLine(record,line,stopRequested){const progressPatch=parseProgressLine(line);if(!progressPatch)return!1;const phase=record.progress?.phase==="stopping"?"stopping":"running";return record.progress=progressPatch.item_id?buildItemBackgroundProgress(line,progressPatch,phase):buildLinkedTestBackgroundProgress(line,record,progressPatch,phase),progressPatch.phase==="finished"&&!stopRequested&&(record.progress.phase="running"),!0}function parseBackgroundWorkerStdout(stdoutBuffer){if(stdoutBuffer.trim().length===0)return null;try{return JSON.parse(stdoutBuffer)}catch{return null}}function resolveBackgroundWorkerFinalStatus(exitCode,summary,stopRequested){return stopRequested?"stopped":exitCode===0&&summary.failed===0&&summary.fail_on_skipped_triggered!==!0?"passed":"failed"}function buildFinishedBackgroundProgress(record,stopRequested){return{phase:"finished",message:stopRequested?"Background run stopped.":`Background run finished with status=${record.status}.`,heartbeat_at:nowIso(),item_index:record.progress?.item_index,item_total:record.progress?.item_total,item_id:record.progress?.item_id,linked_test_index:record.progress?.linked_test_index,linked_test_total:record.progress?.linked_test_total,current_command:record.progress?.current_command,elapsed_ms:record.progress?.elapsed_ms}}async function writeBackgroundWorkerResult(record,parsedResult,stdoutBuffer){if(parsedResult!==null){await writeFileAtomic(record.result_path,`${JSON.stringify(parsedResult,null,2)}
|
|
3
3
|
`);return}await writeFileAtomic(record.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:tailLines(stdoutBuffer,DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES)},null,2)}
|
|
4
|
-
`)}async function runBackgroundTestRunWorker(pmRoot,runId,noExtensions=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const record={...loaded,status:"running",started_at:loaded.started_at??nowIso(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:nowIso()}},cliEntry=await resolveBackgroundCliEntry(process.cwd()),env=buildBackgroundWorkerEnv(record);await writeBackgroundRunRecord(pmRoot,record);const childArgs=buildBackgroundWorkerChildArgs(record,noExtensions),child=spawn(process.execPath,[cliEntry,...childArgs],{cwd:process.cwd(),env,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});record.child_pid=child.pid;const recordWriteScheduler=createBackgroundRunRecordWriteScheduler(pmRoot,record),scheduleRecordWrite=recordWriteScheduler.schedule;let stdoutWriteQueue=Promise.resolve(),stderrWriteQueue=Promise.resolve(),stdoutBuffer="",stderrBuffer="";const stopState={stopRequested:!1},onSignal=()=>{requestBackgroundWorkerStop(record,child,stopState,scheduleRecordWrite)};process.on("SIGTERM",onSignal),process.on("SIGINT",onSignal);const resourceTimer=setInterval(()=>{(async()=>(record.resource=await buildResourceSnapshot(record),record.progress.heartbeat_at=nowIso(),scheduleRecordWrite()))()},resolvePositiveEnvInteger("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",DEFAULT_BACKGROUND_RUN_RESOURCE_SNAPSHOT_INTERVAL_MS));resourceTimer.unref?.(),child.stdout?.on("data",chunk=>{const text=chunk.toString("utf8");stdoutBuffer+=text,stdoutWriteQueue=appendFileOrdered(stdoutWriteQueue,record.stdout_path,text)}),child.stderr?.on("data",chunk=>{const text=chunk.toString("utf8");stderrWriteQueue=appendFileOrdered(stderrWriteQueue,record.stderr_path,text),stderrBuffer+=text;const parts=stderrBuffer.split(/\r?\n/);stderrBuffer=parts.pop();let progressChanged=!1;for(const part of parts){const line=part.trimEnd();line.length>0&&applyBackgroundWorkerProgressLine(record,line,stopState.stopRequested)&&(progressChanged=!0)}progressChanged&&scheduleRecordWrite()});let exitCode=null,signal=null;try{({code:exitCode,signal}=await new Promise(resolve=>{child.on("close",(code,closeSignal)=>{resolve({code,signal:closeSignal})})}))}finally{clearInterval(resourceTimer),process.off("SIGTERM",onSignal),process.off("SIGINT",onSignal)}await stdoutWriteQueue,await stderrWriteQueue;const trailingStderrLine=stderrBuffer.trimEnd();trailingStderrLine.length>0&&applyBackgroundWorkerProgressLine(record,trailingStderrLine,stopState.stopRequested)&&scheduleRecordWrite(),stderrBuffer="";const parsedResult=parseBackgroundWorkerStdout(stdoutBuffer),evaluated=evaluateWorkerResult(record.kind,parsedResult);return record.summary=evaluated.summary,record.exit_code=typeof exitCode=="number"?exitCode:void 0,record.signal=signal??void 0,record.finished_at=nowIso(),record.status=resolveBackgroundWorkerFinalStatus(record,stopState.stopRequested),record.progress=buildFinishedBackgroundProgress(record,stopState.stopRequested),record.resource=await buildResourceSnapshot(record),await writeBackgroundWorkerResult(record,parsedResult,stdoutBuffer),await writeBackgroundRunRecord(pmRoot,record),await recordWriteScheduler.flush(),record}async function listBackgroundTestRuns(pmRoot,options){const recordPaths=await listBackgroundRunRecordPaths(pmRoot),runs=[];for(const recordPath of recordPaths){const raw=await readFileIfExists(recordPath);if(!raw)continue;const parsed=await parseBackgroundRunRecord(raw,recordPath);runs.push(parsed)}const refreshed=[];for(const run of runs)refreshed.push(await refreshRunIfStale(pmRoot,run));const sorted=(options.status?refreshed.filter(entry=>entry.status===options.status):refreshed).sort((left,right)=>{const byUpdated=Date.parse(right.updated_at)-Date.parse(left.updated_at);return Number.isFinite(byUpdated)&&byUpdated!==0?byUpdated:right.id.localeCompare(left.id)}),limit=typeof options.limit=="number"&&options.limit>=0?options.limit:void 0;return limit===void 0?sorted:sorted.slice(0,limit)}async function getBackgroundTestRunStatus(pmRoot,runId){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded),workerAlive=isPidRunning(refreshed.worker_pid),childAlive=isPidRunning(refreshed.child_pid);refreshed.status==="running"&&!childAlive&&!refreshed.finished_at&&!workerAlive&&(refreshed.status="failed",refreshed.finished_at=nowIso(),refreshed.error=refreshed.error??"Background run process exited unexpectedly.",await writeBackgroundRunRecord(pmRoot,refreshed)),refreshed.status==="running"&&(refreshed.resource=await buildResourceSnapshot(refreshed),await writeBackgroundRunRecord(pmRoot,refreshed));const heartbeatAt=refreshed.progress?.heartbeat_at,heartbeatAtMs=heartbeatAt?Date.parse(heartbeatAt):Number.NaN,lagMs=Number.isFinite(heartbeatAtMs)?Math.max(0,nowMs()-heartbeatAtMs):void 0,staleMs=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),staleThresholdMs=Number.isFinite(staleMs)&&staleMs>0?staleMs:DEFAULT_BACKGROUND_RUN_HEARTBEAT_STALE_MS,healthState=refreshed.status==="running"?lagMs!==void 0&&lagMs>staleThresholdMs?"stale":"healthy":"inactive";return{run:refreshed,health:{state:healthState,last_heartbeat_at:heartbeatAt,heartbeat_lag_ms:lagMs,worker_alive:workerAlive,child_alive:childAlive}}}function sendBackgroundRunStopSignal(record,force){const signal=force?"SIGKILL":"SIGTERM";if(!isPidRunning(record.worker_pid)||!record.worker_pid)return"none";try{return process.kill(record.worker_pid,signal),signal}catch{return"none"}}function buildStoppingBackgroundProgress(record,signalSent){return{phase:"stopping",message:signalSent==="none"?"Run marked stopped.":`Stop requested via ${signalSent}.`,heartbeat_at:nowIso(),item_index:record.progress?.item_index,item_total:record.progress?.item_total,item_id:record.progress?.item_id,linked_test_index:record.progress?.linked_test_index,linked_test_total:record.progress?.linked_test_total,current_command:record.progress?.current_command,elapsed_ms:record.progress?.elapsed_ms}}async function stopBackgroundTestRun(pmRoot,runId,force=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded);if(BACKGROUND_RUN_TERMINAL_STATUSES.has(refreshed.status))return{run:refreshed,signal_sent:"none"};const signalSent=sendBackgroundRunStopSignal(refreshed,force);return signalSent==="none"&&(refreshed.status="stopped",refreshed.finished_at=refreshed.finished_at??nowIso()),refreshed.stop_requested_at=nowIso(),refreshed.progress=buildStoppingBackgroundProgress(refreshed,signalSent),await writeBackgroundRunRecord(pmRoot,refreshed),{run:refreshed,signal_sent:signalSent}}async function resumeBackgroundTestRun(pmRoot,runId,requestedBy,noExtensions=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded);if(!BACKGROUND_RUN_TERMINAL_STATUSES.has(refreshed.status))throw new PmCliError(`Background test run ${runId} is not terminal and cannot be resumed.`,EXIT_CODE.CONFLICT);const started=await startBackgroundTestRun({pmRoot:refreshed.pm_root,globalPmRoot:refreshed.global_pm_root,kind:refreshed.kind,commandArgs:refreshed.command_args,requestedBy,targetId:refreshed.target_id,statusFilter:refreshed.status_filter,resumedFrom:refreshed.id,resumedBy:requestedBy,attempt:refreshed.attempt+1});if(!started.started)return started.run;const spawned=await spawnBackgroundTestRunWorker({pmRoot,runId:started.run.id,noExtensions}),prior={...refreshed,resumed_by:spawned.id};return await writeBackgroundRunRecord(pmRoot,prior),spawned}async function readBackgroundTestRunLogs(pmRoot,runId,stream,tail){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const resolvedTail=typeof tail=="number"&&Number.isFinite(tail)&&tail>=0?Math.floor(tail):DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES,stdoutRaw=stream==="stdout"||stream==="both"?await readFileIfExists(loaded.stdout_path)??"":"",stderrRaw=stream==="stderr"||stream==="both"?await readFileIfExists(loaded.stderr_path)??"":"";return{run:loaded,stream,tail:resolvedTail,stdout:stream==="stdout"||stream==="both"?tailLines(stdoutRaw,resolvedTail):[],stderr:stream==="stderr"||stream==="both"?tailLines(stderrRaw,resolvedTail):[]}}const _testOnly={buildResourceSnapshot,evaluateWorkerResult,isPidRunning,parseLinuxCpuStat,parseLinuxRssStatus,parseProgressLine,readLinuxCpuSeconds,readLinuxRssBytes,refreshRunIfStale,splitLines,tailLines};export{_testOnly,buildBackgroundTestRunFingerprint,getBackgroundTestRunStatus,listBackgroundTestRuns,readBackgroundTestRunLogs,readBackgroundTestRunRecord,resumeBackgroundTestRun,runBackgroundTestRunWorker,spawnBackgroundTestRunWorker,startBackgroundTestRun,stopBackgroundTestRun};
|
|
4
|
+
`)}async function runBackgroundTestRunWorker(pmRoot,runId,noExtensions=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const record={...loaded,status:"running",started_at:loaded.started_at??nowIso(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:nowIso()}},cliEntry=await resolveBackgroundCliEntry(process.cwd()),env=buildBackgroundWorkerEnv(record);await writeBackgroundRunRecord(pmRoot,record);const childArgs=buildBackgroundWorkerChildArgs(record,noExtensions),child=spawn(process.execPath,[cliEntry,...childArgs],{cwd:process.cwd(),env,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});record.child_pid=child.pid;const recordWriteScheduler=createBackgroundRunRecordWriteScheduler(pmRoot,record),scheduleRecordWrite=recordWriteScheduler.schedule;let stdoutWriteQueue=Promise.resolve(),stderrWriteQueue=Promise.resolve(),stdoutBuffer="",stderrBuffer="";const stopState={stopRequested:!1},onSignal=()=>{requestBackgroundWorkerStop(record,child,stopState,scheduleRecordWrite)};process.on("SIGTERM",onSignal),process.on("SIGINT",onSignal);const resourceTimer=setInterval(()=>{(async()=>(record.resource=await buildResourceSnapshot(record),record.progress.heartbeat_at=nowIso(),scheduleRecordWrite()))()},resolvePositiveEnvInteger("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",DEFAULT_BACKGROUND_RUN_RESOURCE_SNAPSHOT_INTERVAL_MS));resourceTimer.unref?.(),child.stdout?.on("data",chunk=>{const text=chunk.toString("utf8");stdoutBuffer+=text,stdoutWriteQueue=appendFileOrdered(stdoutWriteQueue,record.stdout_path,text)}),child.stderr?.on("data",chunk=>{const text=chunk.toString("utf8");stderrWriteQueue=appendFileOrdered(stderrWriteQueue,record.stderr_path,text),stderrBuffer+=text;const parts=stderrBuffer.split(/\r?\n/);stderrBuffer=parts.pop();let progressChanged=!1;for(const part of parts){const line=part.trimEnd();line.length>0&&applyBackgroundWorkerProgressLine(record,line,stopState.stopRequested)&&(progressChanged=!0)}progressChanged&&scheduleRecordWrite()});let exitCode=null,signal=null;try{({code:exitCode,signal}=await new Promise(resolve=>{child.on("close",(code,closeSignal)=>{resolve({code,signal:closeSignal})})}))}finally{clearInterval(resourceTimer),process.off("SIGTERM",onSignal),process.off("SIGINT",onSignal)}await stdoutWriteQueue,await stderrWriteQueue;const trailingStderrLine=stderrBuffer.trimEnd();trailingStderrLine.length>0&&applyBackgroundWorkerProgressLine(record,trailingStderrLine,stopState.stopRequested)&&scheduleRecordWrite(),stderrBuffer="";const parsedResult=parseBackgroundWorkerStdout(stdoutBuffer),evaluated=evaluateWorkerResult(record.kind,parsedResult);return record.summary=evaluated.summary,record.exit_code=typeof exitCode=="number"?exitCode:void 0,record.signal=signal??void 0,record.finished_at=nowIso(),record.status=resolveBackgroundWorkerFinalStatus(record.exit_code,evaluated.summary,stopState.stopRequested),record.progress=buildFinishedBackgroundProgress(record,stopState.stopRequested),record.resource=await buildResourceSnapshot(record),await writeBackgroundWorkerResult(record,parsedResult,stdoutBuffer),await writeBackgroundRunRecord(pmRoot,record),await recordWriteScheduler.flush(),record}async function listBackgroundTestRuns(pmRoot,options){const recordPaths=await listBackgroundRunRecordPaths(pmRoot),runs=[];for(const recordPath of recordPaths){const raw=await readFileIfExists(recordPath);if(!raw)continue;const parsed=await parseBackgroundRunRecord(raw,recordPath);runs.push(parsed)}const refreshed=[];for(const run of runs)refreshed.push(await refreshRunIfStale(pmRoot,run));const sorted=(options.status?refreshed.filter(entry=>entry.status===options.status):refreshed).sort((left,right)=>{const byUpdated=Date.parse(right.updated_at)-Date.parse(left.updated_at);return Number.isFinite(byUpdated)&&byUpdated!==0?byUpdated:right.id.localeCompare(left.id)}),limit=typeof options.limit=="number"&&options.limit>=0?options.limit:void 0;return limit===void 0?sorted:sorted.slice(0,limit)}async function getBackgroundTestRunStatus(pmRoot,runId){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded),workerAlive=isPidRunning(refreshed.worker_pid),childAlive=isPidRunning(refreshed.child_pid);refreshed.status==="running"&&!childAlive&&!refreshed.finished_at&&!workerAlive&&(refreshed.status="failed",refreshed.finished_at=nowIso(),refreshed.error=refreshed.error??"Background run process exited unexpectedly.",await writeBackgroundRunRecord(pmRoot,refreshed)),refreshed.status==="running"&&(refreshed.resource=await buildResourceSnapshot(refreshed),await writeBackgroundRunRecord(pmRoot,refreshed));const heartbeatAt=refreshed.progress?.heartbeat_at,heartbeatAtMs=heartbeatAt?Date.parse(heartbeatAt):Number.NaN,lagMs=Number.isFinite(heartbeatAtMs)?Math.max(0,nowMs()-heartbeatAtMs):void 0,staleMs=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),staleThresholdMs=Number.isFinite(staleMs)&&staleMs>0?staleMs:DEFAULT_BACKGROUND_RUN_HEARTBEAT_STALE_MS,healthState=refreshed.status==="running"?lagMs!==void 0&&lagMs>staleThresholdMs?"stale":"healthy":"inactive";return{run:refreshed,health:{state:healthState,last_heartbeat_at:heartbeatAt,heartbeat_lag_ms:lagMs,worker_alive:workerAlive,child_alive:childAlive}}}function sendBackgroundRunStopSignal(record,force){const signal=force?"SIGKILL":"SIGTERM";if(!isPidRunning(record.worker_pid)||!record.worker_pid)return"none";try{return process.kill(record.worker_pid,signal),signal}catch{return"none"}}function buildStoppingBackgroundProgress(record,signalSent){return{phase:"stopping",message:signalSent==="none"?"Run marked stopped.":`Stop requested via ${signalSent}.`,heartbeat_at:nowIso(),item_index:record.progress?.item_index,item_total:record.progress?.item_total,item_id:record.progress?.item_id,linked_test_index:record.progress?.linked_test_index,linked_test_total:record.progress?.linked_test_total,current_command:record.progress?.current_command,elapsed_ms:record.progress?.elapsed_ms}}async function stopBackgroundTestRun(pmRoot,runId,force=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded);if(BACKGROUND_RUN_TERMINAL_STATUSES.has(refreshed.status))return{run:refreshed,signal_sent:"none"};const signalSent=sendBackgroundRunStopSignal(refreshed,force);return signalSent==="none"&&(refreshed.status="stopped",refreshed.finished_at=refreshed.finished_at??nowIso()),refreshed.stop_requested_at=nowIso(),refreshed.progress=buildStoppingBackgroundProgress(refreshed,signalSent),await writeBackgroundRunRecord(pmRoot,refreshed),{run:refreshed,signal_sent:signalSent}}async function resumeBackgroundTestRun(pmRoot,runId,requestedBy,noExtensions=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded);if(!BACKGROUND_RUN_TERMINAL_STATUSES.has(refreshed.status))throw new PmCliError(`Background test run ${runId} is not terminal and cannot be resumed.`,EXIT_CODE.CONFLICT);const started=await startBackgroundTestRun({pmRoot:refreshed.pm_root,globalPmRoot:refreshed.global_pm_root,kind:refreshed.kind,commandArgs:refreshed.command_args,requestedBy,targetId:refreshed.target_id,statusFilter:refreshed.status_filter,resumedFrom:refreshed.id,resumedBy:requestedBy,attempt:refreshed.attempt+1});if(!started.started)return started.run;const spawned=await spawnBackgroundTestRunWorker({pmRoot,runId:started.run.id,noExtensions}),prior={...refreshed,resumed_by:spawned.id};return await writeBackgroundRunRecord(pmRoot,prior),spawned}async function readBackgroundTestRunLogs(pmRoot,runId,stream,tail){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const resolvedTail=typeof tail=="number"&&Number.isFinite(tail)&&tail>=0?Math.floor(tail):DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES,stdoutRaw=stream==="stdout"||stream==="both"?await readFileIfExists(loaded.stdout_path)??"":"",stderrRaw=stream==="stderr"||stream==="both"?await readFileIfExists(loaded.stderr_path)??"":"";return{run:loaded,stream,tail:resolvedTail,stdout:stream==="stdout"||stream==="both"?tailLines(stdoutRaw,resolvedTail):[],stderr:stream==="stderr"||stream==="both"?tailLines(stderrRaw,resolvedTail):[]}}const _testOnly={buildResourceSnapshot,evaluateWorkerResult,isPidRunning,parseLinuxCpuStat,parseLinuxRssStatus,parseProgressLine,readLinuxCpuSeconds,readLinuxRssBytes,refreshRunIfStale,splitLines,tailLines};export{_testOnly,buildBackgroundTestRunFingerprint,getBackgroundTestRunStatus,listBackgroundTestRuns,readBackgroundTestRunLogs,readBackgroundTestRunRecord,resumeBackgroundTestRun,runBackgroundTestRunWorker,spawnBackgroundTestRunWorker,startBackgroundTestRun,stopBackgroundTestRun};
|
|
5
5
|
//# sourceMappingURL=background-runs.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]="1cbef336-00a6-5072-aaf1-8262adb112eb")}catch{}})();import{normalizeUniqueStringList}from"./string-lists.js";import{PM_TOOL_ACTIONS}from"./enum-contracts.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS}from"./tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as BASE_TOOL_PARAMETER_PROPERTIES,PM_TOOL_PARAMETER_METADATA as BASE_TOOL_PARAMETER_METADATA,PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES as BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA,PLAN_ACTION_PARAMETER_PROPERTIES,PLAN_ACTION_PARAMETER_METADATA}from"./tool-parameter-tables.js";import{toUniqueFlagContracts,withFlagAliasMetadata}from"./flag-contracts.js";import{resolveReadOutputSurface}from"../read-output-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./commander-mutation-options.js";const PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES={...BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},PM_TOOL_PARAMETER_PROPERTIES={...BASE_TOOL_PARAMETER_PROPERTIES,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},PM_TOOL_PARAMETER_METADATA={...BASE_TOOL_PARAMETER_METADATA,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},PM_TOOL_GLOBAL_PARAMETER_KEYS=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],PM_TOOL_READ_OUTPUT_PARAMETER_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES=new Set(["action","cwd","options",...Object.keys(PM_TOOL_PARAMETER_PROPERTIES).filter(property=>property!=="severity")]);function resolvePmToolCustomFieldCollision(field){const normalized=field.trim().toLowerCase();let property="";for(let index=0;index<normalized.length;index+=1){const character=normalized[index];if(character!=="-"&&character!=="_"){property+=character;continue}let nextIndex=index+1;for(;normalized[nextIndex]==="-"||normalized[nextIndex]==="_";)nextIndex+=1;const nextCharacter=normalized[nextIndex];if(nextCharacter!==void 0&&(nextCharacter>="a"&&nextCharacter<="z"||nextCharacter>="0"&&nextCharacter<="9")){property+=nextCharacter.toUpperCase(),index=nextIndex;continue}property+=normalized.slice(index,nextIndex),index=nextIndex-1}return PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES.has(property)?{field,property,owner:"mcp_tool_input",nested_path:`options.${property}`}:void 0}const PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},PLAN_CREATE_METADATA_PARAMETER_KEYS=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(PM_TOOL_ACTIONS.filter(action=>action==="upgrade"||action==="install"||action==="extension"||action==="package"||action.startsWith("extension-")||action.startsWith("package-")).map(action=>[action,["project","local","global"]]))});function toSchemaKeyList(values){return normalizeUniqueStringList(values)}const CREATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CREATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param)]),UPDATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),"force"]),UPDATE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),...UPDATE_CONTRACT_PARAMETER_KEYS.filter(key=>key!=="allowMissingParent"&&key!=="completedAt"),"dryRun","rollback","noCheckpoint"]),CLOSE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),CONTEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CONTEXT_OPTION_CONTRACTS.map(entry=>entry.param),"past","section"]),ACTIVITY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_ACTIVITY_OPTION_CONTRACTS.map(entry=>entry.param),"stream"]),LIST_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_LIST_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS=LIST_CONTRACT_PARAMETER_KEYS.filter(parameter=>parameter!=="all"&¶meter!=="status"),LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],AGGREGATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_AGGREGATE_OPTION_CONTRACTS.map(entry=>entry.param),"count","completion","includeUnparented"]),SEARCH_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...TOOL_SEARCH_FILTER_OPTION_CONTRACTS.map(entry=>entry.param)]),NEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","message","force"],CLOSE_ACTION_OPTION_KEYS=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","assignee","message","force"],MANAGED_EXTENSION_PACKAGE_OPTION_KEYS=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function managedLifecycleSchemaContracts(prefix){return{[`${prefix}-init`]:{required:["target"],optional:["scope","capability",...prefix==="package"?["declarative"]:[]]},[`${prefix}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${prefix}-uninstall`]:{required:["target"],optional:["scope"]},[`${prefix}-explore`]:{optional:["scope"]},[`${prefix}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline"]},[`${prefix}-describe`]:{optional:["target","scope","markdown","output"]},[`${prefix}-reload`]:{optional:["scope","watch"]},[`${prefix}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${prefix}-catalog`]:{optional:["scope","fields"]},[`${prefix}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${prefix}-adopt-all`]:{optional:["scope"]},[`${prefix}-activate`]:{required:["target"],optional:["scope"]},[`${prefix}-deactivate`]:{required:["target"],optional:["scope"]},[prefix]:{optional:MANAGED_EXTENSION_PACKAGE_OPTION_KEYS,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}const SCHEDULING_ACTION_SCHEMA_CONTRACT={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},UPGRADE_ACTION_SCHEMA_CONTRACT={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},PM_TOOL_ACTION_SCHEMA_CONTRACTS={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...managedLifecycleSchemaContracts("extension"),...managedLifecycleSchemaContracts("package"),"package-upgrade":UPGRADE_ACTION_SCHEMA_CONTRACT,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:UPGRADE_ACTION_SCHEMA_CONTRACT,create:{required:["title","description","type","status","priority","message"],optional:CREATE_CONTRACT_PARAMETER_KEYS},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-all":{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-draft":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-open":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-in-progress":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-blocked":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-closed":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-canceled":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},aggregate:{optional:AGGREGATE_CONTRACT_PARAMETER_KEYS},guide:{optional:["list","format","depth"]},context:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},ctx:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:SEARCH_CONTRACT_PARAMETER_KEYS,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["verify","since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:SCHEDULING_ACTION_SCHEMA_CONTRACT,event:SCHEDULING_ACTION_SCHEMA_CONTRACT,remind:{required:["title"],optional:["at","text","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...NEXT_CONTRACT_PARAMETER_KEYS,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","order","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","inheritFocus","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...PLAN_CREATE_METADATA_PARAMETER_KEYS,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},activity:{optional:ACTIVITY_CONTRACT_PARAMETER_KEYS},restore:{required:["id","target"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},update:{required:["id"],optional:UPDATE_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:UPDATE_MANY_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...CLOSE_ACTION_OPTION_KEYS,...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"close-many":{optional:CLOSE_MANY_CONTRACT_PARAMETER_KEYS},delete:{required:["id"],optional:["dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},append:{required:["id","body"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","maxAttempts","includeDecisions",...NEXT_CONTRACT_PARAMETER_KEYS,...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"next",schema:{const:!0}}],[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"pause-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"close-task":{required:["id"],optional:["text","validateClose",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},PM_TOOL_ACTION_PARAMETER_CONTRACTS=Object.freeze(Object.fromEntries(PM_TOOL_ACTIONS.map(action=>[action,PM_TOOL_ACTION_SCHEMA_CONTRACTS[action]])));function fallbackToolParameterDescription(key){return key.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,value=>value.toUpperCase()).concat(".")}function decorateToolParameterDefinition(key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=PM_TOOL_PARAMETER_METADATA[key];return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterMetadata(action,key){if(action==="history-attest"&&key==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(action==="history-attest"&&key==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(action==="claim"&&key==="start")return{description:"Claim an explicit item and move it to its configured in-progress status."};if((action==="list"||action.startsWith("list-"))&&key==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_METADATA,key))return PLAN_ACTION_PARAMETER_METADATA[key];const actionOverrides=PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA[action];return actionOverrides&&Object.prototype.hasOwnProperty.call(actionOverrides,key)?actionOverrides[key]:PM_TOOL_PARAMETER_METADATA[key]}function decorateActionScopedToolParameterDefinition(action,key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=actionScopedToolParameterMetadata(action,key);return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterDefinition(action,key){if(action==="claim"&&key==="start")return{type:"boolean"};const actionProperties=PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES[action];return actionProperties&&Object.prototype.hasOwnProperty.call(actionProperties,key)?actionProperties[key]:action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_PROPERTIES,key)?PLAN_ACTION_PARAMETER_PROPERTIES[key]:(action==="get"||action==="history"||action==="search")&&key==="format"?{type:"string",enum:["json","toon"]}:key==="pause"||key==="handoff"||key==="releaseAssignment"||key==="hashAlgorithm"?PM_TOOL_PARAMETER_PROPERTIES[key]:BASE_TOOL_PARAMETER_PROPERTIES[key]}function buildActionScopedSchemaProperties(action,allowedKeys){const properties={action:{const:action,description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."}};for(const key of allowedKeys){if(key==="action")continue;const definition=actionScopedToolParameterDefinition(action,key);definition&&(properties[key]=decorateActionScopedToolParameterDefinition(action,key,definition))}return properties}function buildOneOfSchemaEntries(action,oneOfRequiredGroups){const allOneOfFields=oneOfRequiredGroups.flat();return oneOfRequiredGroups.map(requiredFields=>{const otherFields=allOneOfFields.filter(field=>!requiredFields.includes(field));return{required:[...requiredFields],...otherFields.length>0?{not:{anyOf:otherFields.map(field=>({required:[field]}))}}:{},...action==="history-repair"&&requiredFields.includes("all")?{properties:{all:{const:!0}}}:action==="claim"&&requiredFields.includes("next")?{properties:{next:{const:!0}}}:{}}})}function schemaPropertyCondition(property,value){return{...value===void 0?{}:{properties:{[property]:{const:value}}},required:[property]}}function buildActionScopedAllOf(contract){const allOf=[];if(contract.conditionalRequired&&contract.conditionalRequired.length>0)for(const entry of contract.conditionalRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{required:entry.required}});if(contract.dependentAnyOfRequired&&contract.dependentAnyOfRequired.length>0)for(const entry of contract.dependentAnyOfRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{anyOf:entry.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))}});if(contract.mutuallyExclusive&&contract.mutuallyExclusive.length>0)for(const group of contract.mutuallyExclusive)allOf.push({not:{required:toSchemaKeyList(group)}});if(contract.mutuallyExclusiveWhen&&contract.mutuallyExclusiveWhen.length>0)for(const group of contract.mutuallyExclusiveWhen)allOf.push({not:{allOf:group.map(condition=>({properties:{[condition.property]:condition.schema},required:[condition.property]}))}});return allOf}function pmToolActionParameterKeys(action){if(!Object.prototype.hasOwnProperty.call(PM_TOOL_ACTION_SCHEMA_CONTRACTS,action))return;const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],mutationParameterKeys=PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS[action]??[];return toSchemaKeyList(["action",...PM_TOOL_GLOBAL_PARAMETER_KEYS,...resolveReadOutputSurface(action)!==void 0?PM_TOOL_READ_OUTPUT_PARAMETER_KEYS:[],...mutationParameterKeys,...contract.required??[],...contract.optional??[]])}function pmToolActionNestedOptionKeys(action){const parameterKeys=pmToolActionParameterKeys(action);if(parameterKeys===void 0)return;const mutationContracts=action==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:action==="update"?UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:[];return toSchemaKeyList([...parameterKeys,...mutationContracts.flatMap(({keys,target})=>[target,...keys]),...PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS[action]??[]])}function buildActionScopedToolSchema(action){const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],required=toSchemaKeyList(contract.required??[]),allowedKeys=pmToolActionParameterKeys(action),schema={type:"object",additionalProperties:!1,required:["action",...required],title:`pm action "${action}" parameters`,properties:buildActionScopedSchemaProperties(action,allowedKeys)};contract.anyOfRequired&&contract.anyOfRequired.length>0&&(schema.anyOf=contract.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))),contract.oneOfRequired&&contract.oneOfRequired.length>0&&(schema.oneOf=buildOneOfSchemaEntries(action,contract.oneOfRequired));const allOf=buildActionScopedAllOf(contract);return allOf.length>0&&(schema.allOf=allOf),schema}function buildPmActionToolInputSchema(action,options={}){const actionSchema=buildActionScopedToolSchema(action),actionProperties={...actionSchema.properties};delete actionProperties.action;const conditionalBranches=[...actionSchema.anyOf??[],...actionSchema.oneOf??[]],required=(options.required??actionSchema.required.map(String)).filter(key=>key==="action"?!1:options.required===void 0?!0:!conditionalBranches.some(branch=>branch.required?.map(String).includes(key))),schema={type:"object",additionalProperties:options.additionalProperties??!0,properties:{...actionProperties,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...options.properties},required};return actionSchema.anyOf!==void 0&&(schema.anyOf=actionSchema.anyOf),actionSchema.oneOf!==void 0&&(schema.oneOf=actionSchema.oneOf),actionSchema.allOf!==void 0&&(schema.allOf=actionSchema.allOf),schema}function createLazyContractSchema(build){let value;const resolve=()=>value??=build();return new Proxy({},{get:(_target,prop)=>resolve()[prop],has:(_target,prop)=>prop in resolve(),ownKeys:()=>Reflect.ownKeys(resolve()),getOwnPropertyDescriptor:(_target,prop)=>{const descriptor=Reflect.getOwnPropertyDescriptor(resolve(),prop);return descriptor&&(descriptor.configurable=!0),descriptor}})}const PM_TOOL_PARAMETERS_SCHEMA_VERSION="4.23.0",PM_TOOL_PARAMETERS_SCHEMA_MAJOR=PM_TOOL_PARAMETERS_SCHEMA_VERSION.split(".")[0],PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION="1.12.0",PM_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${PM_TOOL_PARAMETERS_SCHEMA_MAJOR}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":PM_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",oneOf:PM_TOOL_ACTIONS.map(action=>buildActionScopedToolSchema(action))}));function toProviderCompatibleParameterDefinition(key,definition){const decorated=decorateToolParameterDefinition(key,definition);if(typeof decorated.type=="string")return decorated;const firstTypedVariant=(Array.isArray(decorated.anyOf)?decorated.anyOf:[]).find(variant=>typeof variant.type=="string");if(firstTypedVariant){const{anyOf:_anyOf2,...rest2}=decorated;return{...firstTypedVariant,...rest2}}const{anyOf:_anyOf,...rest}=decorated;return{...rest,type:"string"}}function buildProviderCompatibleToolSchema(){const properties={action:{type:"string",description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(const key of Object.keys(PM_TOOL_PARAMETER_PROPERTIES).sort())properties[key]=toProviderCompatibleParameterDefinition(key,PM_TOOL_PARAMETER_PROPERTIES[key]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",additionalProperties:!1,required:["action"],properties}}const PM_PROVIDER_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(buildProviderCompatibleToolSchema),_testOnlyCliContracts={buildActionScopedToolSchema,buildProviderCompatibleToolSchema,decorateActionScopedToolParameterDefinition,decorateToolParameterDefinition,toolActionSchemaContracts:PM_TOOL_ACTION_SCHEMA_CONTRACTS,toolParameterMetadata:PM_TOOL_PARAMETER_METADATA,toProviderCompatibleParameterDefinition,toUniqueFlagContracts,withFlagAliasMetadata};export{CLOSE_ACTION_OPTION_KEYS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,_testOnlyCliContracts,buildPmActionToolInputSchema,pmToolActionNestedOptionKeys,pmToolActionParameterKeys,resolvePmToolCustomFieldCollision};
|
|
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]="1119e9ef-dbdd-5e2f-abe8-176699263a97")}catch{}})();import{normalizeUniqueStringList}from"./string-lists.js";import{PM_TOOL_ACTIONS}from"./enum-contracts.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS}from"./tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as BASE_TOOL_PARAMETER_PROPERTIES,PM_TOOL_PARAMETER_METADATA as BASE_TOOL_PARAMETER_METADATA,PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES as BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA,PLAN_ACTION_PARAMETER_PROPERTIES,PLAN_ACTION_PARAMETER_METADATA}from"./tool-parameter-tables.js";import{toUniqueFlagContracts,withFlagAliasMetadata}from"./flag-contracts.js";import{resolveReadOutputSurface}from"../read-output-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./commander-mutation-options.js";const PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES={...BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},PM_TOOL_PARAMETER_PROPERTIES={...BASE_TOOL_PARAMETER_PROPERTIES,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},PM_TOOL_PARAMETER_METADATA={...BASE_TOOL_PARAMETER_METADATA,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},PM_TOOL_GLOBAL_PARAMETER_KEYS=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],PM_TOOL_READ_OUTPUT_PARAMETER_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES=new Set(["action","cwd","options",...Object.keys(PM_TOOL_PARAMETER_PROPERTIES).filter(property=>property!=="severity")]);function resolvePmToolCustomFieldCollision(field){const normalized=field.trim().toLowerCase();let property="";for(let index=0;index<normalized.length;index+=1){const character=normalized[index];if(character!=="-"&&character!=="_"){property+=character;continue}let nextIndex=index+1;for(;normalized[nextIndex]==="-"||normalized[nextIndex]==="_";)nextIndex+=1;const nextCharacter=normalized[nextIndex];if(nextCharacter!==void 0&&(nextCharacter>="a"&&nextCharacter<="z"||nextCharacter>="0"&&nextCharacter<="9")){property+=nextCharacter.toUpperCase(),index=nextIndex;continue}property+=normalized.slice(index,nextIndex),index=nextIndex-1}return PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES.has(property)?{field,property,owner:"mcp_tool_input",nested_path:`options.${property}`}:void 0}const PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},PLAN_CREATE_METADATA_PARAMETER_KEYS=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(PM_TOOL_ACTIONS.filter(action=>action==="upgrade"||action==="install"||action==="extension"||action==="package"||action.startsWith("extension-")||action.startsWith("package-")).map(action=>[action,["project","local","global"]]))});function toSchemaKeyList(values){return normalizeUniqueStringList(values)}const CREATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CREATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param)]),UPDATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),"force"]),UPDATE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),...UPDATE_CONTRACT_PARAMETER_KEYS.filter(key=>key!=="allowMissingParent"&&key!=="completedAt"),"dryRun","rollback","noCheckpoint"]),CLOSE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),CONTEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CONTEXT_OPTION_CONTRACTS.map(entry=>entry.param),"past","section"]),ACTIVITY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_ACTIVITY_OPTION_CONTRACTS.map(entry=>entry.param),"stream"]),LIST_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_LIST_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS=LIST_CONTRACT_PARAMETER_KEYS.filter(parameter=>parameter!=="all"&¶meter!=="status"),LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],AGGREGATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_AGGREGATE_OPTION_CONTRACTS.map(entry=>entry.param),"count","completion","includeUnparented"]),SEARCH_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...TOOL_SEARCH_FILTER_OPTION_CONTRACTS.map(entry=>entry.param)]),NEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","message","force"],CLOSE_ACTION_OPTION_KEYS=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","assignee","message","force"],MANAGED_EXTENSION_PACKAGE_OPTION_KEYS=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function managedLifecycleSchemaContracts(prefix){return{[`${prefix}-init`]:{required:["target"],optional:["scope","capability",...prefix==="package"?["declarative"]:[]]},[`${prefix}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${prefix}-uninstall`]:{required:["target"],optional:["scope"]},[`${prefix}-explore`]:{optional:["scope"]},[`${prefix}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline"]},[`${prefix}-describe`]:{optional:["target","scope","markdown","output"]},[`${prefix}-reload`]:{optional:["scope","watch"]},[`${prefix}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${prefix}-catalog`]:{optional:["scope","fields"]},[`${prefix}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${prefix}-adopt-all`]:{optional:["scope"]},[`${prefix}-activate`]:{required:["target"],optional:["scope"]},[`${prefix}-deactivate`]:{required:["target"],optional:["scope"]},[prefix]:{optional:MANAGED_EXTENSION_PACKAGE_OPTION_KEYS,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}const SCHEDULING_ACTION_SCHEMA_CONTRACT={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},UPGRADE_ACTION_SCHEMA_CONTRACT={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},PM_TOOL_ACTION_SCHEMA_CONTRACTS={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...managedLifecycleSchemaContracts("extension"),...managedLifecycleSchemaContracts("package"),"package-upgrade":UPGRADE_ACTION_SCHEMA_CONTRACT,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:UPGRADE_ACTION_SCHEMA_CONTRACT,create:{required:["title","description","type","status","priority","message"],optional:CREATE_CONTRACT_PARAMETER_KEYS},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-all":{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-draft":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-open":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-in-progress":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-blocked":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-closed":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-canceled":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},aggregate:{optional:AGGREGATE_CONTRACT_PARAMETER_KEYS},guide:{optional:["list","format","depth"]},context:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},ctx:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:SEARCH_CONTRACT_PARAMETER_KEYS,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["verify","since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:SCHEDULING_ACTION_SCHEMA_CONTRACT,event:SCHEDULING_ACTION_SCHEMA_CONTRACT,remind:{required:["title"],optional:["at","text","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...NEXT_CONTRACT_PARAMETER_KEYS,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","order","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","inheritFocus","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...PLAN_CREATE_METADATA_PARAMETER_KEYS,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},activity:{optional:ACTIVITY_CONTRACT_PARAMETER_KEYS},restore:{required:["id","target"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},update:{required:["id"],optional:UPDATE_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:UPDATE_MANY_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...CLOSE_ACTION_OPTION_KEYS,...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"close-many":{optional:CLOSE_MANY_CONTRACT_PARAMETER_KEYS},delete:{required:["id"],optional:["dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},append:{required:["id","body"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","maxAttempts","includeDecisions",...NEXT_CONTRACT_PARAMETER_KEYS,...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}},{property:"id",schema:{type:"string"}}]]},release:{required:["id"],optional:["pause","handoff",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"pause-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"close-task":{required:["id"],optional:["text","validateClose",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},PM_TOOL_ACTION_PARAMETER_CONTRACTS=Object.freeze(Object.fromEntries(PM_TOOL_ACTIONS.map(action=>[action,PM_TOOL_ACTION_SCHEMA_CONTRACTS[action]])));function fallbackToolParameterDescription(key){return key.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,value=>value.toUpperCase()).concat(".")}function decorateToolParameterDefinition(key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=PM_TOOL_PARAMETER_METADATA[key];return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterMetadata(action,key){if(action==="history-attest"&&key==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(action==="history-attest"&&key==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(action==="claim"&&key==="start")return{description:"Move the claimed item to its configured in-progress status; with next, the selected item is claimed and started in one locked write."};if((action==="list"||action.startsWith("list-"))&&key==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_METADATA,key))return PLAN_ACTION_PARAMETER_METADATA[key];const actionOverrides=PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA[action];return actionOverrides&&Object.prototype.hasOwnProperty.call(actionOverrides,key)?actionOverrides[key]:PM_TOOL_PARAMETER_METADATA[key]}function decorateActionScopedToolParameterDefinition(action,key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=actionScopedToolParameterMetadata(action,key);return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterDefinition(action,key){if(action==="claim"&&key==="start")return{type:"boolean"};const actionProperties=PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES[action];return actionProperties&&Object.prototype.hasOwnProperty.call(actionProperties,key)?actionProperties[key]:action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_PROPERTIES,key)?PLAN_ACTION_PARAMETER_PROPERTIES[key]:(action==="get"||action==="history"||action==="search")&&key==="format"?{type:"string",enum:["json","toon"]}:key==="pause"||key==="handoff"||key==="releaseAssignment"||key==="hashAlgorithm"?PM_TOOL_PARAMETER_PROPERTIES[key]:BASE_TOOL_PARAMETER_PROPERTIES[key]}function buildActionScopedSchemaProperties(action,allowedKeys){const properties={action:{const:action,description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."}};for(const key of allowedKeys){if(key==="action")continue;const definition=actionScopedToolParameterDefinition(action,key);definition&&(properties[key]=decorateActionScopedToolParameterDefinition(action,key,definition))}return properties}function buildOneOfSchemaEntries(action,oneOfRequiredGroups){const allOneOfFields=oneOfRequiredGroups.flat();return oneOfRequiredGroups.map(requiredFields=>{const otherFields=allOneOfFields.filter(field=>!requiredFields.includes(field));return{required:[...requiredFields],...otherFields.length>0?{not:{anyOf:otherFields.map(field=>({required:[field]}))}}:{},...action==="history-repair"&&requiredFields.includes("all")?{properties:{all:{const:!0}}}:action==="claim"&&requiredFields.includes("next")?{properties:{next:{const:!0}}}:{}}})}function schemaPropertyCondition(property,value){return{...value===void 0?{}:{properties:{[property]:{const:value}}},required:[property]}}function buildActionScopedAllOf(contract){const allOf=[];if(contract.conditionalRequired&&contract.conditionalRequired.length>0)for(const entry of contract.conditionalRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{required:entry.required}});if(contract.dependentAnyOfRequired&&contract.dependentAnyOfRequired.length>0)for(const entry of contract.dependentAnyOfRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{anyOf:entry.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))}});if(contract.mutuallyExclusive&&contract.mutuallyExclusive.length>0)for(const group of contract.mutuallyExclusive)allOf.push({not:{required:toSchemaKeyList(group)}});if(contract.mutuallyExclusiveWhen&&contract.mutuallyExclusiveWhen.length>0)for(const group of contract.mutuallyExclusiveWhen)allOf.push({not:{allOf:group.map(condition=>({properties:{[condition.property]:condition.schema},required:[condition.property]}))}});return allOf}function pmToolActionParameterKeys(action){if(!Object.prototype.hasOwnProperty.call(PM_TOOL_ACTION_SCHEMA_CONTRACTS,action))return;const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],mutationParameterKeys=PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS[action]??[];return toSchemaKeyList(["action",...PM_TOOL_GLOBAL_PARAMETER_KEYS,...resolveReadOutputSurface(action)!==void 0?PM_TOOL_READ_OUTPUT_PARAMETER_KEYS:[],...mutationParameterKeys,...contract.required??[],...contract.optional??[]])}function pmToolActionNestedOptionKeys(action){const parameterKeys=pmToolActionParameterKeys(action);if(parameterKeys===void 0)return;const mutationContracts=action==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:action==="update"?UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:[];return toSchemaKeyList([...parameterKeys,...mutationContracts.flatMap(({keys,target})=>[target,...keys]),...PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS[action]??[]])}function buildActionScopedToolSchema(action){const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],required=toSchemaKeyList(contract.required??[]),allowedKeys=pmToolActionParameterKeys(action),schema={type:"object",additionalProperties:!1,required:["action",...required],title:`pm action "${action}" parameters`,properties:buildActionScopedSchemaProperties(action,allowedKeys)};contract.anyOfRequired&&contract.anyOfRequired.length>0&&(schema.anyOf=contract.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))),contract.oneOfRequired&&contract.oneOfRequired.length>0&&(schema.oneOf=buildOneOfSchemaEntries(action,contract.oneOfRequired));const allOf=buildActionScopedAllOf(contract);return allOf.length>0&&(schema.allOf=allOf),schema}function buildPmActionToolInputSchema(action,options={}){const actionSchema=buildActionScopedToolSchema(action),actionProperties={...actionSchema.properties};delete actionProperties.action;const conditionalBranches=[...actionSchema.anyOf??[],...actionSchema.oneOf??[]],required=(options.required??actionSchema.required.map(String)).filter(key=>key==="action"?!1:options.required===void 0?!0:!conditionalBranches.some(branch=>branch.required?.map(String).includes(key))),schema={type:"object",additionalProperties:options.additionalProperties??!0,properties:{...actionProperties,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...options.properties},required};return actionSchema.anyOf!==void 0&&(schema.anyOf=actionSchema.anyOf),actionSchema.oneOf!==void 0&&(schema.oneOf=actionSchema.oneOf),actionSchema.allOf!==void 0&&(schema.allOf=actionSchema.allOf),schema}function createLazyContractSchema(build){let value;const resolve=()=>value??=build();return new Proxy({},{get:(_target,prop)=>resolve()[prop],has:(_target,prop)=>prop in resolve(),ownKeys:()=>Reflect.ownKeys(resolve()),getOwnPropertyDescriptor:(_target,prop)=>{const descriptor=Reflect.getOwnPropertyDescriptor(resolve(),prop);return descriptor&&(descriptor.configurable=!0),descriptor}})}const PM_TOOL_PARAMETERS_SCHEMA_VERSION="4.23.0",PM_TOOL_PARAMETERS_SCHEMA_MAJOR=PM_TOOL_PARAMETERS_SCHEMA_VERSION.split(".")[0],PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION="1.12.0",PM_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${PM_TOOL_PARAMETERS_SCHEMA_MAJOR}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":PM_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",oneOf:PM_TOOL_ACTIONS.map(action=>buildActionScopedToolSchema(action))}));function toProviderCompatibleParameterDefinition(key,definition){const decorated=decorateToolParameterDefinition(key,definition);if(typeof decorated.type=="string")return decorated;const firstTypedVariant=(Array.isArray(decorated.anyOf)?decorated.anyOf:[]).find(variant=>typeof variant.type=="string");if(firstTypedVariant){const{anyOf:_anyOf2,...rest2}=decorated;return{...firstTypedVariant,...rest2}}const{anyOf:_anyOf,...rest}=decorated;return{...rest,type:"string"}}function buildProviderCompatibleToolSchema(){const properties={action:{type:"string",description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(const key of Object.keys(PM_TOOL_PARAMETER_PROPERTIES).sort())properties[key]=toProviderCompatibleParameterDefinition(key,PM_TOOL_PARAMETER_PROPERTIES[key]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",additionalProperties:!1,required:["action"],properties}}const PM_PROVIDER_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(buildProviderCompatibleToolSchema),_testOnlyCliContracts={buildActionScopedToolSchema,buildProviderCompatibleToolSchema,decorateActionScopedToolParameterDefinition,decorateToolParameterDefinition,toolActionSchemaContracts:PM_TOOL_ACTION_SCHEMA_CONTRACTS,toolParameterMetadata:PM_TOOL_PARAMETER_METADATA,toProviderCompatibleParameterDefinition,toUniqueFlagContracts,withFlagAliasMetadata};export{CLOSE_ACTION_OPTION_KEYS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,_testOnlyCliContracts,buildPmActionToolInputSchema,pmToolActionNestedOptionKeys,pmToolActionParameterKeys,resolvePmToolCustomFieldCollision};
|
|
2
2
|
//# sourceMappingURL=tool-schema.js.map
|