@unbrained/pm-cli 2026.10.19 → 2026.10.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +58 -0
- package/dist/cli/error-guidance.d.ts +15 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-4MJ6WBMA.js → chunk-2B5HAZFK.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-LBEMB3BW.js → chunk-4OYU5OXQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4XFVAXA4.js → chunk-5PZ7JNMI.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-C6SAXKBO.js +3 -0
- package/dist/cli-bundle/chunks/chunk-DIKQ2AL5.js +2 -0
- package/dist/cli-bundle/chunks/chunk-DIR3YEFD.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-O2ZRRLAP.js → chunk-DJQVNDXO.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-DR6DUBTU.js +30 -0
- package/dist/cli-bundle/chunks/{chunk-5GZSX5HU.js → chunk-EMGMLKRV.js} +47 -47
- package/dist/cli-bundle/chunks/chunk-GWIGZDRS.js +3 -0
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-QG4LMU7A.js → chunk-KBSVPUFD.js} +46 -45
- package/dist/cli-bundle/chunks/{chunk-NX7Q4LGN.js → chunk-MOC5BJHW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-MZZIAC6S.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-DMFM5R4G.js → chunk-NNB65OOO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D3EDNAN7.js → chunk-QPV6UD55.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6DS5CAN2.js → chunk-TMXWWOPJ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-H3XYP24A.js → chunk-V3XONSVC.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-V5GJTXYW.js +126 -0
- package/dist/cli-bundle/chunks/chunk-XAWE4EAK.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-XH7C3A5N.js → chunk-ZNKFMIVA.js} +6 -6
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +2 -0
- package/dist/cli-bundle/{focused-chunks/indexed-receipt-blobs-QW2VWWJE.js → chunks/indexed-receipt-blobs-65XXSPPR.js} +2 -2
- package/dist/cli-bundle/chunks/mutation-admission-FNWOVJLN.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-WQUVDJIH.js → register-list-query-6PT5Y2EZ.js} +5 -5
- package/dist/cli-bundle/chunks/{register-mutation-IWIBQIO3.js → register-mutation-TAIQV46L.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-ONIRO22G.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-OQMUZBJV.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-UNFMCKKQ.js → settlement-hook-UVFYSBMU.js} +2 -2
- package/dist/cli-bundle/chunks/stage-FCPVFO3B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-32ZKLRWM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3TEIACFU.js → chunk-3LWH2RJC.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-OV2WVLUR.js → chunk-44353U27.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4HJVAUFX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SKYLOPU2.js → chunk-5IMM7GOF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JBJJW2WL.js → chunk-6QSZHRM7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-7UD7XTOE.js +12 -0
- package/dist/cli-bundle/focused-chunks/{chunk-H6BVQ63U.js → chunk-CUWNNU4N.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-E2S42XCT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GRSQGMRR.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HYMYAGSY.js → chunk-HNCMYF2W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WZTEFFQI.js → chunk-IAGFXKMZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JI3RXXRN.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-JMZPZQHR.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RLRMNFLF.js → chunk-KVYUQS6Y.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-O3M6YWVL.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-P5D7MHDS.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-PDOWLRHC.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-T27TLSEU.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GWTV45SB.js → chunk-VD64TPXI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JDBO7SMR.js → chunk-VE6MTRH5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XE7P7N5X.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YIWDX6KO.js +91 -0
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +2 -0
- package/dist/cli-bundle/{chunks/indexed-receipt-blobs-BVSHK4WQ.js → focused-chunks/indexed-receipt-blobs-CRP6HAZY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-KM57KDDF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-X4FNHTOD.js → settlement-hook-MNCHFCAX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-UJYGWNZ7.js +2 -0
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +23 -23
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +58 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +8 -8
- package/dist/core/fs/fs-utils.d.ts +2 -2
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/event-index.js +2 -2
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/lock/lock-gc.d.ts +12 -5
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.d.ts +33 -0
- package/dist/core/lock/lock-owner.js +2 -0
- package/dist/core/lock/lock.d.ts +11 -22
- package/dist/core/lock/lock.js +4 -3
- package/dist/core/output/output.d.ts +7 -2
- package/dist/core/output/output.js +5 -5
- package/dist/core/shared/errors.d.ts +50 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/settings.js +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/dependencies/context-budget-recovery.d.ts +21 -0
- package/dist/sdk/dependencies/context-budget-recovery.js +2 -0
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/errors.d.ts +4 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.d.ts +13 -0
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.d.ts +14 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
- package/dist/sdk/output/list-envelope.d.ts +7 -0
- package/dist/sdk/output/list-envelope.js +2 -0
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/pagination.d.ts +3 -3
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/relationship-context.d.ts +2 -0
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.d.ts +2 -0
- package/dist/sdk/runtime/mutation-admission.js +2 -0
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +2 -0
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/test/execution.d.ts +1 -0
- package/dist/sdk/test/execution.js +2 -2
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +9 -0
- package/docs/ASSURANCE.md +17 -2
- package/docs/COMMANDS.md +31 -3
- package/docs/CONFIGURATION.md +29 -0
- package/docs/CONTEXT_RELEVANCE.md +15 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -3
- package/docs/PR_REVIEW_LOOP.md +32 -12
- package/docs/SCRIPTING.md +10 -0
- package/docs/SDK.md +144 -0
- package/docs/TESTING.md +43 -1
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4CXQSRSP.js +0 -126
- package/dist/cli-bundle/chunks/chunk-4ICKT4GH.js +0 -3
- package/dist/cli-bundle/chunks/chunk-OEJ3G7XT.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QBNEZII5.js +0 -30
- package/dist/cli-bundle/chunks/chunk-QKAAZWGC.js +0 -3
- package/dist/cli-bundle/chunks/chunk-TK3G3GAP.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-SUWOZNDU.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-QGM5YJW7.js +0 -2
- package/dist/cli-bundle/chunks/stage-7DELI4Z5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2IEWB6MB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5YTOYBTZ.js +0 -65
- package/dist/cli-bundle/focused-chunks/chunk-BJMPRB7A.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-ENZMATOY.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-EOQ6W25I.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-FEN7WOOP.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-JCLC6HKT.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-KLJN44VY.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-L4PL3GZR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PXDR77TO.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-Y54ONBEX.js +0 -25
- package/dist/cli-bundle/focused-chunks/stage-MZSVQYO4.js +0 -2
|
@@ -29,12 +29,12 @@ export declare function readFileIfExists(targetPath:string):Promise<string | nul
|
|
|
29
29
|
*/
|
|
30
30
|
export declare function readRegularFile(targetPath:string,rejectionError:Error):Promise<string>;
|
|
31
31
|
/**
|
|
32
|
-
* Refuse unsafe preview storage
|
|
32
|
+
* Refuse unsafe preview storage with bounded tracker-relative diagnostics. Entry and
|
|
33
33
|
* opened-descriptor checks share this usage error so SDK callers can repair
|
|
34
34
|
* tracker configuration rather than treating a preserved safety boundary as
|
|
35
35
|
* an unexpected runtime fault. Native filesystem failures retain their codes.
|
|
36
36
|
*/
|
|
37
|
-
export declare function transactionPreviewNonRegularFileError():PmCliError;
|
|
37
|
+
export declare function transactionPreviewNonRegularFileError(relativePath?:string):PmCliError;
|
|
38
38
|
/**
|
|
39
39
|
* Replace a UTF-8 file through a sibling temporary file and atomic rename.
|
|
40
40
|
* Parent directories are created by default. Background consumers can disable
|
package/dist/core/fs/fs-utils.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3792f1fd-ed9d-5252-887d-e4517a55fb9c")}catch{}})();import*as fs from"node:fs/promises";import{constants}from"node:fs";import path from"node:path";import crypto from"node:crypto";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const WINDOWS_RENAME_RETRY_DELAYS_MS=[10,25,50,100];async function ensureDir(dirPath){await fs.mkdir(dirPath,{recursive:!0})}async function pathExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isFileAbsentError(error){return isFileMissingError(error)||isErrno(error,"ENOTDIR")}function isFileMissingError(error){return isErrno(error,"ENOENT")}async function readFileIfExists(targetPath){try{return await fs.readFile(targetPath,"utf8")}catch(error){if(isFileAbsentError(error))return null;throw error}}async function readRegularFile(targetPath,rejectionError){const handle=await fs.open(targetPath,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{if(!(await handle.stat()).isFile())throw rejectionError;return await handle.readFile("utf8")}finally{await handle.close()}}function transactionPreviewNonRegularFileError(relativePath){const relative=relativePath?.replaceAll(path.sep,"/"),contained=relative!==void 0&&!path.posix.isAbsolute(relative)&&!path.win32.isAbsolute(relative)&&!relative.split("/").includes(".."),first=contained?relative.split("/")[0]:void 0,areas={"settings.json":"settings",runtime:"runtime",schema:"schema",history:"history",transactions:"transactions"},area=first===void 0?"tracker_storage":Object.hasOwn(areas,first)?areas[first]:"tracker_storage",safe=contained&&relative.length>0&&relative.length<=160&&relative.split("/").every(part=>part!=="."&&/^[a-zA-Z0-9_.-]+$/u.test(part)),location=safe?relative:`${area} (entry name redacted)`;return new PmCliError(`Transaction preview requires regular files and directories. Inspect ${location} relative to the selected tracker root.`,EXIT_CODE.USAGE,{code:"transaction_preview_non_regular_file",preview_storage:{storage_area:area,...safe?{relative_entry:relative}:{},entry_redacted:!safe},required:"regular files and directories within the configured tracker storage",why:"Preview does not follow linked entries or read special files.",nextSteps:[`Inspect ${location} within the selected tracker for links, directories used as files, or special files; do not follow link targets.`,"Restore the intended regular files and directories, then retry the original dry-run command."]})}async function writeFileAtomic(targetPath,contents,options={}){const dirPath=path.dirname(targetPath);options.createParentDirectories!==!1&&await ensureDir(dirPath);const tempPath=path.join(dirPath,`.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.tmp`);await fs.writeFile(tempPath,contents,"utf8");try{await fs.rename(tempPath,targetPath)}catch(error){if(process.platform==="win32"&&(isErrno(error,"EPERM")||isErrno(error,"EBUSY"))){let lastError=error;for(const delayMs of WINDOWS_RENAME_RETRY_DELAYS_MS){await new Promise(resolve=>setTimeout(resolve,delayMs));try{await fs.rename(tempPath,targetPath);return}catch(retryError){if(lastError=retryError,!isErrno(retryError,"EPERM")&&!isErrno(retryError,"EBUSY"))break}}try{await fs.unlink(tempPath)}catch{}throw lastError}if(isErrno(error,"EXDEV")){try{await fs.copyFile(tempPath,targetPath)}finally{try{await fs.unlink(tempPath)}catch{}}return}try{await fs.unlink(tempPath)}catch{}throw error}}async function appendLineAtomic(targetPath,line){const dirPath=path.dirname(targetPath);await ensureDir(dirPath);const handle=await fs.open(targetPath,"a");try{await handle.writeFile(`${line}
|
|
2
2
|
`,"utf8")}finally{await handle.close()}}async function removeFileIfExists(targetPath){try{await fs.unlink(targetPath)}catch(error){if(!isFileAbsentError(error))throw error}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}export{appendLineAtomic,ensureDir,isFileAbsentError,isFileMissingError,pathExists,readFileIfExists,readRegularFile,removeFileIfExists,transactionPreviewNonRegularFileError,writeFileAtomic};
|
|
3
3
|
//# sourceMappingURL=fs-utils.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f0373f8f-7396-57df-9c8d-9a3315168b5a")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";import{setImmediate as yieldToEventLoop}from"node:timers/promises";import{isFileMissingError}from"../fs/fs-utils.js";import{acquireLock,captureProcessIdentity,isProcessIdentityAlive,hasUnexpiredLockOwner}from"../lock/lock.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{isMillisecondPrecisionRfc3339DateTime}from"../shared/time.js";import{readHistoryEntries}from"./read.js";import{classifyHistoryEvent}from"./event-classification.js";import{loadDatabaseSync,loadStableDatabaseSync}from"../store/sqlite-runtime.js";const EVENT_INDEX_FILENAME="history-event-index.sqlite",EVENT_INDEX_VERSION="6",AUTHORITATIVE_HISTORY_CACHE_LIMIT=8,HISTORY_EVENT_INDEX_LOCK_ID="history-event-index",HISTORY_EVENT_INDEX_APPEND_OWNER_PREFIX="history-event-index:append:",HISTORY_EVENT_INDEX_REPAIR_COOLDOWN_MS=5e3,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS=300,HISTORY_EVENT_INDEX_LOCK_WAIT_MS=3e4,HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID="history-event-index-invalidation",HISTORY_EVENT_INDEX_INVALIDATION_DIRECTORY="history-event-index-invalidations",HISTORY_EVENT_INDEX_INVALIDATION_MAX_UNVERIFIED_AGE_MS=HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS*2*1e3,HISTORY_INDEX_CHANGED=Symbol("history-index-changed"),authoritativeHistoryCaches=new Map;function eventIndexPath(pmRoot){return path.join(pmRoot,"runtime",EVENT_INDEX_FILENAME)}function refusedHistoryRepairPath(pmRoot){return path.join(pmRoot,"runtime","history-event-index-repair-deferred")}async function hasRecentRefusedHistoryRepair(pmRoot){try{const deferredAt=Number(await fs.readFile(refusedHistoryRepairPath(pmRoot),"utf8")),age=Date.now()-deferredAt;return age>=0&&age<HISTORY_EVENT_INDEX_REPAIR_COOLDOWN_MS}catch{return!1}}async function deferAutomaticHistoryRepair(pmRoot){try{await fs.writeFile(refusedHistoryRepairPath(pmRoot),`${Date.now()}
|
|
2
2
|
`)}catch{}}function historyEventIndexInvalidationDirectory(pmRoot){return path.join(pmRoot,"runtime",HISTORY_EVENT_INDEX_INVALIDATION_DIRECTORY)}async function listHistoryEventIndexInvalidations(pmRoot){const entries=await fs.readdir(historyEventIndexInvalidationDirectory(pmRoot)).catch(error=>{if(isFileMissingError(error))return[];throw error});return{pending:entries.filter(name=>name.endsWith(".pending")).sort(),committed:entries.filter(name=>name.endsWith(".committed")).sort()}}async function recoverAbandonedHistoryEventIndexInvalidations(pmRoot){const invalidations=await listHistoryEventIndexInvalidations(pmRoot);return{pending:(await Promise.all(invalidations.pending.map(async name=>{const owner=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(name);if(owner!==null){const processStartIdentity=owner[2];if(await isProcessIdentityAlive({pid:Number(owner[1]),...processStartIdentity==="unknown"?{}:{process_start_identity:processStartIdentity}},Math.max(0,Date.now()-Number(owner[3])),HISTORY_EVENT_INDEX_INVALIDATION_MAX_UNVERIFIED_AGE_MS))return name}return await fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}),null}))).filter(name=>name!==null),committed:invalidations.committed}}async function withHistoryEventIndexInvalidationLock(pmRoot,operation,waitMs=HISTORY_EVENT_INDEX_LOCK_WAIT_MS){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index-invalidation:${process.pid}`,!1,!1,waitMs,waitMs===0?{maxWaitMs:0}:void 0);try{return await operation()}finally{await release()}}async function beginHistoryEventIndexInvalidation(pmRoot){const directory=historyEventIndexInvalidationDirectory(pmRoot);await fs.mkdir(directory,{recursive:!0});const token=randomUUID(),processIdentity=await captureProcessIdentity(),pendingPath=path.join(directory,`${processIdentity.pid}-${processIdentity.process_start_identity??"unknown"}-${Date.now()}-${token}.pending`);return await fs.writeFile(pendingPath,`pending
|
|
3
3
|
`,{flag:"wx"}),{pendingPath,committedPath:path.join(directory,`${token}.committed`)}}function sameInvalidationNames(left,right){return left.length===right.length&&left.every((name,index)=>name===right[index])}async function invalidateHistoryEventIndex(pmRoot){try{await fs.rm(eventIndexPath(pmRoot),{force:!0})}catch{}}async function recordHistoryEventIndexInvalidation(pmRoot,retainCache){const directory=historyEventIndexInvalidationDirectory(pmRoot);await fs.mkdir(directory,{recursive:!0}),await fs.writeFile(path.join(directory,`${randomUUID()}${retainCache?".contended":""}.committed`),`committed
|
|
4
4
|
`,{flag:"wx"}),retainCache||await invalidateHistoryEventIndex(pmRoot)}function hasContendedHistoryEventIndexInvalidation(invalidations){return invalidations.committed.some(name=>name.endsWith(".contended.committed"))}function hasNativeHistoryEventIndexContention(pmRoot,Database){let database;try{return database=new Database(eventIndexPath(pmRoot)),database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN EXCLUSIVE"),!1}catch(error){return isHistoryIndexSqliteContention(error)}finally{database?.close()}}async function historyEventIndexAppendIsActive(pmRoot,invalidations){return invalidations.pending.length>0||await hasUnexpiredLockOwner(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_APPEND_OWNER_PREFIX)}async function withHistoryEventIndexLock(pmRoot,operation,waitMs=HISTORY_EVENT_INDEX_LOCK_WAIT_MS,purpose="rebuild"){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index:${purpose}:${process.pid}`,!1,!1,waitMs,waitMs===0?{maxWaitMs:0}:void 0);try{return await operation()}finally{await release()}}async function readAuthoritativeHistorySnapshot(pmRoot){const historyRoot=path.join(pmRoot,"history"),entries=await fs.readdir(historyRoot,{withFileTypes:!0}).catch(error=>{if(typeof error=="object"&&error!==null&&"code"in error&&error.code==="ENOENT")return[];throw error}),cached=authoritativeHistoryCaches.get(pmRoot)??{streams:new Map,ordered_events:[]},presentStreams=new Set;let changed=!authoritativeHistoryCaches.has(pmRoot);for(const historyFile of entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).sort((left,right)=>left.name.localeCompare(right.name))){const streamId=historyFile.name.slice(0,-6);presentStreams.add(streamId);const historyPath=path.join(historyRoot,historyFile.name),stats=await fs.stat(historyPath,{bigint:!0}),signature=[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":");if(cached.streams.get(streamId)?.signature===signature)continue;const history=await readIndexableHistoryEntries(historyPath,streamId);cached.streams.set(streamId,{signature,byte_size:Number(stats.size),events:history.map((entry,streamOffset)=>({stream_id:streamId,stream_offset:streamOffset,entry}))}),changed=!0}for(const streamId of cached.streams.keys())presentStreams.has(streamId)||(cached.streams.delete(streamId),changed=!0);if(changed&&(cached.ordered_events=[...cached.streams.values()].flatMap(stream=>stream.events).sort(compareHistoryEventPosition)),authoritativeHistoryCaches.delete(pmRoot),authoritativeHistoryCaches.set(pmRoot,cached),authoritativeHistoryCaches.size>AUTHORITATIVE_HISTORY_CACHE_LIMIT){const oldestRoot=authoritativeHistoryCaches.keys().next().value;authoritativeHistoryCaches.delete(oldestRoot)}return{events:cached.ordered_events,stream_byte_sizes:new Map([...cached.streams].map(([streamId,stream])=>[streamId,stream.byte_size]))}}async function readIndexableHistoryEntries(historyPath,streamId){const entries=await readHistoryEntries(historyPath,streamId);for(const[index,entry]of entries.entries())if(typeof entry.ts!="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim()))throw new PmCliError(`History for ${streamId} contains an invalid or sub-millisecond timestamp at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return entries.map(entry=>({...entry,ts:new Date(entry.ts.trim()).toISOString()}))}async function readAuthoritativeHistoryEvents(pmRoot){return(await readAuthoritativeHistorySnapshot(pmRoot)).events}let RuntimeDatabaseSync;function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function createSchema(database){database.exec(`
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
stream_id, stream_offset, ts, author, agent_harness,
|
|
41
41
|
agent_instance, op, event_class, entry_json
|
|
42
42
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(event.stream_id,event.stream_offset,entry.ts,entry.author,entry.agent_harness??null,entry.agent_instance??null,entry.op,classifyHistoryEvent(entry),JSON.stringify(entry))}function parseIndexedHistoryEvent(row){const entry=JSON.parse(String(row.entry_json));return typeof entry.ts!="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim())?null:{stream_id:String(row.stream_id),stream_offset:Number(row.stream_offset),entry:{...entry,ts:new Date(entry.ts.trim()).toISOString()}}}function upsertStreamByteSize(database,streamId,byteSize){database.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
|
|
43
|
-
ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(streamId,byteSize)}async function rebuildHistoryEventIndex(pmRoot,options={}){const Database=resolveDatabaseSync();return Database?withHistoryEventIndexLock(pmRoot,async()=>{let invalidations;try{invalidations=await withHistoryEventIndexInvalidationLock(pmRoot,()=>recoverAbandonedHistoryEventIndexInvalidations(pmRoot),options.lockWaitMs)}catch(error){if(error instanceof PmCliError&&error.code==="lock_conflict")return!1;throw error}if(invalidations.pending.length>0||hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database))return!1;const targetPath=eventIndexPath(pmRoot);await fs.mkdir(path.dirname(targetPath),{recursive:!0});const temporaryPath=`${targetPath}.${randomUUID()}.tmp`;let database;try{database=new Database(temporaryPath),createSchema(database),database.exec("BEGIN IMMEDIATE");const authoritative=await readAuthoritativeHistorySnapshot(pmRoot);await populateHistoryEventIndex(database,authoritative),database.exec("COMMIT"),database.close(),database=void 0;const published=await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const current=await recoverAbandonedHistoryEventIndexInvalidations(pmRoot);return current.pending.length>0||!sameInvalidationNames(invalidations.committed,current.committed)||hasContendedHistoryEventIndexInvalidation(current)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?!1:(await fs.rm(targetPath,{force:!0}),await fs.rename(temporaryPath,targetPath),!0)},options.lockWaitMs);return published&&await Promise.all(invalidations.committed.map(name=>fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}))),published||(await deferAutomaticHistoryRepair(pmRoot),await fs.rm(temporaryPath,{force:!0})),published}catch(error){throw await deferAutomaticHistoryRepair(pmRoot),database?.close(),await fs.rm(temporaryPath,{force:!0}),error}},options.lockWaitMs):!1}async function populateHistoryEventIndex(database,snapshot){let inserted=0;for(const event of snapshot.events)insertEvent(database,event),++inserted%500===0&&await yieldToEventLoop();for(const[streamId,byteSize]of snapshot.stream_byte_sizes)upsertStreamByteSize(database,streamId,byteSize),++inserted%500===0&&await yieldToEventLoop()}function matchesSet(value,accepted){return!accepted||accepted.length===0||accepted.includes(value)}function compareHistoryEventPosition(left,right){return left.entry.ts.localeCompare(right.entry.ts)||left.stream_id.localeCompare(right.stream_id)||left.stream_offset-right.stream_offset}function canonicalHistoryQueryTimestamp(value){const milliseconds=Date.parse(value);return Number.isFinite(milliseconds)?new Date(milliseconds).toISOString():value}function isInsideHistoryEventWindow(event,query){if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){if(compareHistoryEventPosition(event,{stream_id:query.after_stream_id,stream_offset:query.after_stream_offset,entry:{...event.entry,ts:canonicalHistoryQueryTimestamp(query.after_ts)}})<=0)return!1}else if(query.since_ts!==void 0&&event.entry.ts<canonicalHistoryQueryTimestamp(query.since_ts))return!1;return!0}function matchesHistoryEventHarness(event,query){return!query.harnesses||query.harnesses.length===0||query.harnesses.includes(event.entry.agent_harness??"")?!0:event.entry.agent_harness===void 0&&(query.harness_alias_authors??[]).includes(event.entry.author)}function matchesHistoryEventQuery(event,query){return!isInsideHistoryEventWindow(event,query)||!matchesSet(event.entry.op,query.ops)||!matchesSet(event.entry.author,query.authors)||!matchesSet(event.entry.agent_instance??"",query.agent_instances)||!matchesSet(event.stream_id,query.stream_ids)||!matchesHistoryEventHarness(event,query)?!1:(query.provenance??[]).every(predicate=>{const value=event.entry.agent_provenance?.[predicate.dimension]?.value;return value!==void 0&&predicate.values.includes(value)})}async function queryHistoryEventStreams(pmRoot,query){const limit=Math.max(0,Math.floor(query.limit)),rows=(await readAuthoritativeHistoryEvents(pmRoot)).filter(event=>matchesHistoryEventQuery(event,query)).slice(0,limit+1);return{events:rows.slice(0,query.limit),has_more:rows.length>query.limit}}async function historyEventIndexHasAppendBase(database,historyPath){const stored=database.prepare("SELECT byte_size FROM streams WHERE stream_id = ?").get(path.basename(historyPath,".jsonl"));let actualSize=0;try{actualSize=(await fs.stat(historyPath)).size}catch(error){if(!isFileMissingError(error))throw error}return Number(stored?.byte_size??0)===actualSize}async function appendHistoryEntryWithEventIndex(historyPath,entry,append){const pmRoot=path.dirname(path.dirname(historyPath)),Database=resolveDatabaseSync();let authoritativeAppendCommitted=!1;const appendAuthoritative=async()=>{await append(),authoritativeAppendCommitted=!0};if(!Database){await appendUnindexedHistory(pmRoot,appendAuthoritative);return}try{await withHistoryEventIndexLock(pmRoot,async()=>{const targetPath=eventIndexPath(pmRoot);try{await fs.access(targetPath)}catch{await appendAuthoritative();return}let database;try{if(database=new Database(targetPath),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)throw new TypeError("Unsupported history event index version");if(!await historyEventIndexHasAppendBase(database,historyPath))throw new TypeError("Stale history event index append base")}catch(error){if(database?.close(),isHistoryIndexSqliteContention(error))throw error;await recordHistoryEventIndexInvalidation(pmRoot,!0),await appendAuthoritative();return}try{database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN IMMEDIATE")}catch(error){throw database.close(),error}let appended=!1;try{await appendAuthoritative(),appended=!0;const streamId=path.basename(historyPath,".jsonl"),offset=database.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(streamId);insertEvent(database,{stream_id:streamId,stream_offset:Number(offset.value),entry}),upsertStreamByteSize(database,streamId,(await fs.stat(historyPath)).size),database.exec("COMMIT"),database.close()}catch(error){if(database?.close(),!appended)throw error;await recordHistoryEventIndexInvalidation(pmRoot,isHistoryIndexSqliteContention(error))}},0,"append")}catch(error){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);return}if(!isHistoryIndexWriteContention(error))throw error;await appendUnindexedHistory(pmRoot,appendAuthoritative,isHistoryIndexSqliteContention(error))}}async function appendUnindexedHistory(pmRoot,append,nativeContention=!1){let authoritativeAppendCommitted=!1,pendingMarkerPath;try{await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const contended=nativeContention||hasContendedHistoryEventIndexInvalidation(await listHistoryEventIndexInvalidations(pmRoot)),marker=await beginHistoryEventIndexInvalidation(pmRoot);pendingMarkerPath=marker.pendingPath;try{await append(),authoritativeAppendCommitted=!0}catch(appendError){throw await fs.rm(marker.pendingPath,{force:!0}),appendError}await fs.rename(marker.pendingPath,contended?marker.committedPath.replace(/\.committed$/u,".contended.committed"):marker.committedPath),contended||await invalidateHistoryEventIndex(pmRoot)})}catch(fallbackError){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);try{await fs.rm(pendingMarkerPath,{force:!0})}catch{}return}throw fallbackError}}async function removeHistoryEventIndexForHistoryPath(historyPath){await fs.rm(eventIndexPath(path.dirname(path.dirname(historyPath))),{force:!0})}function appendSetPredicate(clauses,parameters,column,values){!values||values.length===0||(clauses.push(`${column} IN (${values.map(()=>"?").join(", ")})`),parameters.push(...values))}function appendHarnessPredicate(clauses,parameters,harnesses,aliasAuthors){if(!harnesses||harnesses.length===0)return;const harnessPlaceholders=harnesses.map(()=>"?").join(", "),aliases=aliasAuthors??[];if(aliases.length>0){clauses.push(`(agent_harness IN (${harnessPlaceholders}) OR (agent_harness IS NULL AND author IN (${aliases.map(()=>"?").join(", ")})))`),parameters.push(...harnesses,...aliases);return}clauses.push(`agent_harness IN (${harnessPlaceholders})`),parameters.push(...harnesses)}async function readHistoryEventIndexSnapshot(pmRoot,Database,requestedStreamIds,read){let database;try{const invalidations=await listHistoryEventIndexInvalidations(pmRoot);if(await historyEventIndexAppendIsActive(pmRoot,invalidations))return HISTORY_INDEX_CHANGED;const before=await historyEventIndexSignature(pmRoot);if(invalidations.committed.length>0)return hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?HISTORY_INDEX_CHANGED:null;if(database=new Database(eventIndexPath(pmRoot),{readOnly:!0}),database.exec("BEGIN"),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)return null;const result=read(database);if(result===null)return null;const storedSizes=readHistoryEventIndexStreamSizes(database,requestedStreamIds),completed=database;database=void 0,completed.close();const streamIds=await historyIndexValidationStreamIds([...storedSizes.keys()],pmRoot,requestedStreamIds),sizesMatch=await historyIndexMatchesStreamSizes(storedSizes,pmRoot,streamIds),current=await listHistoryEventIndexInvalidations(pmRoot);return current.committed.length>0||await historyEventIndexAppendIsActive(pmRoot,current)||before!==await historyEventIndexSignature(pmRoot)?HISTORY_INDEX_CHANGED:sizesMatch?result:null}catch(error){return isHistoryIndexSqliteContention(error)?HISTORY_INDEX_CHANGED:null}finally{database?.close()}}function isHistoryIndexSqliteContention(error){return typeof error=="object"&&error!==null&&"errcode"in error&&[5,6].includes(error.errcode)}function isHistoryIndexWriteContention(error){return isHistoryIndexSqliteContention(error)||error instanceof PmCliError&&error.code==="lock_conflict"}function readHistoryEventIndexStreamSizes(database,requestedStreamIds){const storedSizes=new Map,ids=requestedStreamIds&&requestedStreamIds.length>0?[...new Set(requestedStreamIds)]:void 0;if(ids===void 0)for(const row of database.prepare("SELECT stream_id, byte_size FROM streams").all())storedSizes.set(String(row.stream_id),Number(row.byte_size));else for(let start=0;start<ids.length;start+=500){const chunk=ids.slice(start,start+500);for(const row of database.prepare(`SELECT stream_id, byte_size FROM streams WHERE stream_id IN (${chunk.map(()=>"?").join(", ")})`).all(...chunk))storedSizes.set(String(row.stream_id),Number(row.byte_size))}return storedSizes}async function historyEventIndexSignature(pmRoot){const stats=await fs.stat(eventIndexPath(pmRoot),{bigint:!0});return[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":")}async function readHistoryEventIndexPage(pmRoot,query){const Database=resolveDatabaseSync();if(!Database)return{result:null,repair_needed:!1};const clauses=[],parameters=[];if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){clauses.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");const afterTimestamp=canonicalHistoryQueryTimestamp(query.after_ts);parameters.push(afterTimestamp,afterTimestamp,query.after_stream_id,afterTimestamp,query.after_stream_id,query.after_stream_offset)}else query.since_ts!==void 0&&(clauses.push("ts >= ?"),parameters.push(canonicalHistoryQueryTimestamp(query.since_ts)));appendSetPredicate(clauses,parameters,"op",query.ops),appendSetPredicate(clauses,parameters,"author",query.authors),appendHarnessPredicate(clauses,parameters,query.harnesses,query.harness_alias_authors),appendSetPredicate(clauses,parameters,"agent_instance",query.agent_instances);for(const predicate of query.provenance??[])clauses.push(`json_extract(entry_json, '$.agent_provenance.${predicate.dimension}.value') IN (${predicate.values.map(()=>"?").join(", ")})`),parameters.push(...predicate.values);appendSetPredicate(clauses,parameters,"stream_id",query.stream_ids);const where=clauses.length===0?"":` WHERE ${clauses.join(" AND ")}`,attempt=await readHistoryEventIndexSnapshot(pmRoot,Database,query.stream_ids,database=>{const rows=database.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
43
|
+
ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(streamId,byteSize)}async function rebuildHistoryEventIndex(pmRoot,options={}){const Database=resolveDatabaseSync();return Database?withHistoryEventIndexLock(pmRoot,async()=>{let invalidations;try{invalidations=await withHistoryEventIndexInvalidationLock(pmRoot,()=>recoverAbandonedHistoryEventIndexInvalidations(pmRoot),options.lockWaitMs)}catch(error){if(error instanceof PmCliError&&error.code==="lock_conflict")return!1;throw error}if(invalidations.pending.length>0||hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database))return!1;const targetPath=eventIndexPath(pmRoot);await fs.mkdir(path.dirname(targetPath),{recursive:!0});const temporaryPath=`${targetPath}.${randomUUID()}.tmp`;let database;try{database=new Database(temporaryPath),createSchema(database),database.exec("BEGIN IMMEDIATE");const authoritative=await readAuthoritativeHistorySnapshot(pmRoot);await populateHistoryEventIndex(database,authoritative),database.exec("COMMIT"),database.close(),database=void 0;const published=await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const current=await recoverAbandonedHistoryEventIndexInvalidations(pmRoot);return current.pending.length>0||!sameInvalidationNames(invalidations.committed,current.committed)||hasContendedHistoryEventIndexInvalidation(current)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?!1:(await fs.rm(targetPath,{force:!0}),await fs.rename(temporaryPath,targetPath),!0)},options.lockWaitMs);return published&&await Promise.all(invalidations.committed.map(name=>fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}))),published||(await deferAutomaticHistoryRepair(pmRoot),await fs.rm(temporaryPath,{force:!0})),published}catch(error){throw await deferAutomaticHistoryRepair(pmRoot),database?.close(),await fs.rm(temporaryPath,{force:!0}),error}},options.lockWaitMs):!1}async function populateHistoryEventIndex(database,snapshot){let inserted=0;for(const event of snapshot.events)insertEvent(database,event),++inserted%500===0&&await yieldToEventLoop();for(const[streamId,byteSize]of snapshot.stream_byte_sizes)upsertStreamByteSize(database,streamId,byteSize),++inserted%500===0&&await yieldToEventLoop()}function matchesSet(value,accepted){return!accepted||accepted.length===0||accepted.includes(value)}function compareHistoryEventPosition(left,right){return left.entry.ts.localeCompare(right.entry.ts)||left.stream_id.localeCompare(right.stream_id)||left.stream_offset-right.stream_offset}function canonicalHistoryQueryTimestamp(value){const milliseconds=Date.parse(value);return Number.isFinite(milliseconds)?new Date(milliseconds).toISOString():value}function isInsideHistoryEventWindow(event,query){if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){if(compareHistoryEventPosition(event,{stream_id:query.after_stream_id,stream_offset:query.after_stream_offset,entry:{...event.entry,ts:canonicalHistoryQueryTimestamp(query.after_ts)}})<=0)return!1}else if(query.since_ts!==void 0&&event.entry.ts<canonicalHistoryQueryTimestamp(query.since_ts))return!1;return!0}function matchesHistoryEventHarness(event,query){return!query.harnesses||query.harnesses.length===0||query.harnesses.includes(event.entry.agent_harness??"")?!0:event.entry.agent_harness===void 0&&(query.harness_alias_authors??[]).includes(event.entry.author)}function matchesHistoryEventQuery(event,query){return!isInsideHistoryEventWindow(event,query)||!matchesSet(event.entry.op,query.ops)||!matchesSet(event.entry.author,query.authors)||!matchesSet(event.entry.agent_instance??"",query.agent_instances)||!matchesSet(event.stream_id,query.stream_ids)||!matchesHistoryEventHarness(event,query)?!1:(query.provenance??[]).every(predicate=>{const value=event.entry.agent_provenance?.[predicate.dimension]?.value;return value!==void 0&&predicate.values.includes(value)})}async function queryHistoryEventStreams(pmRoot,query){const limit=Math.max(0,Math.floor(query.limit)),rows=(await readAuthoritativeHistoryEvents(pmRoot)).filter(event=>matchesHistoryEventQuery(event,query)).slice(0,limit+1);return{events:rows.slice(0,query.limit),has_more:rows.length>query.limit}}async function historyEventIndexHasAppendBase(database,historyPath){const stored=database.prepare("SELECT byte_size FROM streams WHERE stream_id = ?").get(path.basename(historyPath,".jsonl"));let actualSize=0;try{actualSize=(await fs.stat(historyPath)).size}catch(error){if(!isFileMissingError(error))throw error}return Number(stored?.byte_size??0)===actualSize}async function appendHistoryEntryWithEventIndex(historyPath,entry,append){const pmRoot=path.dirname(path.dirname(historyPath)),Database=resolveDatabaseSync();let authoritativeAppendCommitted=!1;const appendAuthoritative=async()=>{await append(),authoritativeAppendCommitted=!0};if(!Database){await appendUnindexedHistory(pmRoot,appendAuthoritative);return}try{await withHistoryEventIndexLock(pmRoot,async()=>{const targetPath=eventIndexPath(pmRoot);try{await fs.access(targetPath)}catch{await appendAuthoritative();return}let database;try{if(database=new Database(targetPath),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)throw new TypeError("Unsupported history event index version");if(!await historyEventIndexHasAppendBase(database,historyPath))throw new TypeError("Stale history event index append base")}catch(error){if(database?.close(),isHistoryIndexSqliteContention(error))throw error;await recordHistoryEventIndexInvalidation(pmRoot,!0),await appendAuthoritative();return}try{database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN IMMEDIATE")}catch(error){if(database.close(),isHistoryIndexSqliteContention(error)||!(error instanceof Error)||error.code!=="ERR_SQLITE_ERROR")throw error;await recordHistoryEventIndexInvalidation(pmRoot,!1),await appendAuthoritative();return}let appended=!1;try{await appendAuthoritative(),appended=!0;const streamId=path.basename(historyPath,".jsonl"),offset=database.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(streamId);insertEvent(database,{stream_id:streamId,stream_offset:Number(offset.value),entry}),upsertStreamByteSize(database,streamId,(await fs.stat(historyPath)).size),database.exec("COMMIT"),database.close()}catch(error){if(database?.close(),!appended)throw error;await recordHistoryEventIndexInvalidation(pmRoot,isHistoryIndexSqliteContention(error))}},0,"append")}catch(error){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);return}if(!isHistoryIndexWriteContention(error))throw error;await appendUnindexedHistory(pmRoot,appendAuthoritative,isHistoryIndexSqliteContention(error))}}async function appendUnindexedHistory(pmRoot,append,nativeContention=!1){let authoritativeAppendCommitted=!1,pendingMarkerPath;try{await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const contended=nativeContention||hasContendedHistoryEventIndexInvalidation(await listHistoryEventIndexInvalidations(pmRoot)),marker=await beginHistoryEventIndexInvalidation(pmRoot);pendingMarkerPath=marker.pendingPath;try{await append(),authoritativeAppendCommitted=!0}catch(appendError){throw await fs.rm(marker.pendingPath,{force:!0}),appendError}await fs.rename(marker.pendingPath,contended?marker.committedPath.replace(/\.committed$/u,".contended.committed"):marker.committedPath),contended||await invalidateHistoryEventIndex(pmRoot)})}catch(fallbackError){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);try{await fs.rm(pendingMarkerPath,{force:!0})}catch{}return}throw fallbackError}}async function removeHistoryEventIndexForHistoryPath(historyPath){await fs.rm(eventIndexPath(path.dirname(path.dirname(historyPath))),{force:!0})}function appendSetPredicate(clauses,parameters,column,values){!values||values.length===0||(clauses.push(`${column} IN (${values.map(()=>"?").join(", ")})`),parameters.push(...values))}function appendHarnessPredicate(clauses,parameters,harnesses,aliasAuthors){if(!harnesses||harnesses.length===0)return;const harnessPlaceholders=harnesses.map(()=>"?").join(", "),aliases=aliasAuthors??[];if(aliases.length>0){clauses.push(`(agent_harness IN (${harnessPlaceholders}) OR (agent_harness IS NULL AND author IN (${aliases.map(()=>"?").join(", ")})))`),parameters.push(...harnesses,...aliases);return}clauses.push(`agent_harness IN (${harnessPlaceholders})`),parameters.push(...harnesses)}async function readHistoryEventIndexSnapshot(pmRoot,Database,requestedStreamIds,read){let database;try{const invalidations=await listHistoryEventIndexInvalidations(pmRoot);if(await historyEventIndexAppendIsActive(pmRoot,invalidations))return HISTORY_INDEX_CHANGED;const before=await historyEventIndexSignature(pmRoot);if(invalidations.committed.length>0)return hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?HISTORY_INDEX_CHANGED:null;if(database=new Database(eventIndexPath(pmRoot),{readOnly:!0}),database.exec("BEGIN"),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)return null;const result=read(database);if(result===null)return null;const storedSizes=readHistoryEventIndexStreamSizes(database,requestedStreamIds),completed=database;database=void 0,completed.close();const streamIds=await historyIndexValidationStreamIds([...storedSizes.keys()],pmRoot,requestedStreamIds),sizesMatch=await historyIndexMatchesStreamSizes(storedSizes,pmRoot,streamIds),current=await listHistoryEventIndexInvalidations(pmRoot);return current.committed.length>0||await historyEventIndexAppendIsActive(pmRoot,current)||before!==await historyEventIndexSignature(pmRoot)?HISTORY_INDEX_CHANGED:sizesMatch?result:null}catch(error){return isHistoryIndexSqliteContention(error)?HISTORY_INDEX_CHANGED:null}finally{database?.close()}}function isHistoryIndexSqliteContention(error){return typeof error=="object"&&error!==null&&"errcode"in error&&[5,6].includes(error.errcode)}function isHistoryIndexWriteContention(error){return isHistoryIndexSqliteContention(error)||error instanceof PmCliError&&error.code==="lock_conflict"}function readHistoryEventIndexStreamSizes(database,requestedStreamIds){const storedSizes=new Map,ids=requestedStreamIds&&requestedStreamIds.length>0?[...new Set(requestedStreamIds)]:void 0;if(ids===void 0)for(const row of database.prepare("SELECT stream_id, byte_size FROM streams").all())storedSizes.set(String(row.stream_id),Number(row.byte_size));else for(let start=0;start<ids.length;start+=500){const chunk=ids.slice(start,start+500);for(const row of database.prepare(`SELECT stream_id, byte_size FROM streams WHERE stream_id IN (${chunk.map(()=>"?").join(", ")})`).all(...chunk))storedSizes.set(String(row.stream_id),Number(row.byte_size))}return storedSizes}async function historyEventIndexSignature(pmRoot){const stats=await fs.stat(eventIndexPath(pmRoot),{bigint:!0});return[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":")}async function readHistoryEventIndexPage(pmRoot,query){const Database=resolveDatabaseSync();if(!Database)return{result:null,repair_needed:!1};const clauses=[],parameters=[];if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){clauses.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");const afterTimestamp=canonicalHistoryQueryTimestamp(query.after_ts);parameters.push(afterTimestamp,afterTimestamp,query.after_stream_id,afterTimestamp,query.after_stream_id,query.after_stream_offset)}else query.since_ts!==void 0&&(clauses.push("ts >= ?"),parameters.push(canonicalHistoryQueryTimestamp(query.since_ts)));appendSetPredicate(clauses,parameters,"op",query.ops),appendSetPredicate(clauses,parameters,"author",query.authors),appendHarnessPredicate(clauses,parameters,query.harnesses,query.harness_alias_authors),appendSetPredicate(clauses,parameters,"agent_instance",query.agent_instances);for(const predicate of query.provenance??[])clauses.push(`json_extract(entry_json, '$.agent_provenance.${predicate.dimension}.value') IN (${predicate.values.map(()=>"?").join(", ")})`),parameters.push(...predicate.values);appendSetPredicate(clauses,parameters,"stream_id",query.stream_ids);const where=clauses.length===0?"":` WHERE ${clauses.join(" AND ")}`,attempt=await readHistoryEventIndexSnapshot(pmRoot,Database,query.stream_ids,database=>{const rows=database.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
44
44
|
FROM events${where}
|
|
45
45
|
ORDER BY ts, stream_id, stream_offset
|
|
46
46
|
LIMIT ?`).all(...parameters,Math.max(0,Math.floor(query.limit))+1),events=rows.slice(0,query.limit).map(parseIndexedHistoryEvent);return events.includes(null)?null:{events,has_more:rows.length>query.limit}});return{result:attempt===HISTORY_INDEX_CHANGED?null:attempt,repair_needed:attempt===null&&!await hasRecentRefusedHistoryRepair(pmRoot)}}async function queryHistoryEventIndex(pmRoot,query){return(await readHistoryEventIndexPage(pmRoot,query)).result}function collectLatestSubstantiveEvents(events,requested){const latest=Object.create(null);for(const event of events){if(!requested.has(event.stream_id)||classifyHistoryEvent(event.entry)!=="substantive")continue;const current=latest[event.stream_id];(current===void 0||compareHistoryEventPosition(current,event)<0)&&(latest[event.stream_id]=event)}return latest}async function readHistoryStreamByteSize(pmRoot,streamId){if(path.basename(streamId)!==streamId)return null;try{return(await fs.stat(path.join(pmRoot,"history",`${streamId}.jsonl`))).size}catch(error){if(isFileMissingError(error))return 0;throw error}}async function historyIndexMatchesStreamSizes(storedSizes,pmRoot,streamIds){for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500),currentSizes=await Promise.all(chunk.map(streamId=>readHistoryStreamByteSize(pmRoot,streamId)));for(const[index,currentSize]of currentSizes.entries()){if(currentSize===null)return!1;const streamId=chunk[index],storedSize=storedSizes.get(streamId);if(!(currentSize===0&&storedSize===void 0)&¤tSize!==storedSize)return!1}}return!0}async function historyIndexValidationStreamIds(indexed,pmRoot,requestedStreamIds){if(requestedStreamIds&&requestedStreamIds.length>0)return[...new Set(requestedStreamIds.filter(streamId=>streamId.trim().length>0))];const authoritative=await fs.readdir(path.join(pmRoot,"history"),{withFileTypes:!0}).then(entries=>entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).map(entry=>entry.name.slice(0,-6))).catch(error=>{if(isFileMissingError(error))return[];throw error});return[...new Set([...indexed,...authoritative])]}async function readIndexedLatestSubstantiveEvents(Database,pmRoot,streamIds,requested){return Database?readHistoryEventIndexSnapshot(pmRoot,Database,streamIds,database=>{const indexed=[];for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500),parsed=database.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a319e7d9-e248-573b-bf1f-35217ce49fd0")}catch{}})();import{isTerminalStatus,normalizeStatusForRegistry}from"./status.js";import{BUILTIN_ITEM_EXECUTION_ROLES,resolveTypeDefinition}from"./type-registry.js";import{resolveCanonicalRelationshipKind}from"../../sdk/relationships.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"./dependency-reference.js";function resolveItemExecutionRole(type,registry){return(registry===void 0?void 0:resolveTypeDefinition(type,registry))?.execution_role??BUILTIN_ITEM_EXECUTION_ROLES[type.trim().toLowerCase()]??"agent"}const BLOCKED_BY_DEPENDENCY_KIND="blocked_by",BLOCKS_DEPENDENCY_KIND="blocks",ACTIONABILITY_ORDERING_KINDS=Object.freeze([BLOCKED_BY_DEPENDENCY_KIND,BLOCKS_DEPENDENCY_KIND]),NO_ACTIVE_BLOCKER_SENTINEL="no-active-blocker";function normalizeItemId(id){return id.trim().toLowerCase()}function blockerReferenceKey(id,external){return external?`external:${id}`:`local:${normalizeItemId(id)}`}function collectBlockedByIds(item){const ids=new Map,scalar=typeof item.blocked_by=="string"?item.blocked_by.trim():"";if(scalar.length>0&&normalizeItemId(scalar)!==NO_ACTIVE_BLOCKER_SENTINEL){const external=isExternalDependencyReference(scalar);ids.set(blockerReferenceKey(scalar,external),external?scalar:normalizeItemId(scalar))}for(const dependency of item.dependencies??[]){const dependencyId=typeof dependency.id=="string"?dependency.id.trim():"";if(resolveCanonicalRelationshipKind(dependency.kind)===BLOCKED_BY_DEPENDENCY_KIND&&dependencyId.length>0&&normalizeItemId(dependencyId)!==NO_ACTIVE_BLOCKER_SENTINEL){const external=isExternalDependencyReference(dependencyId)||isExternalDependencySourceKind(dependency.source_kind);ids.set(blockerReferenceKey(dependencyId,external),external?dependencyId:normalizeItemId(dependencyId))}}return[...ids.values()].sort((left,right)=>left.localeCompare(right))}function indexBlockedByIds(corpus){const idsByItem=new Map;for(const item of corpus){const itemId=normalizeItemId(item.id);itemId.length!==0&&idsByItem.set(itemId,new Set(collectBlockedByIds(item)))}for(const candidate of corpus){const candidateId=normalizeItemId(candidate.id);if(candidateId.length!==0)for(const dependency of candidate.dependencies??[]){const targetId=resolveCanonicalRelationshipKind(dependency.kind)===BLOCKS_DEPENDENCY_KIND&&typeof dependency.id=="string"?normalizeItemId(dependency.id):"";if(targetId.length===0||targetId===NO_ACTIVE_BLOCKER_SENTINEL)continue;const blockerIds=idsByItem.get(targetId)??new Set;blockerIds.add(candidateId),idsByItem.set(targetId,blockerIds)}}return new Map([...idsByItem].map(([itemId,blockerIds])=>[itemId,[...blockerIds].sort((left,right)=>left.localeCompare(right))]))}function collectBlockedByIdsFromCorpus(item,corpus){const itemId=normalizeItemId(item.id);return itemId.length>0?indexBlockedByIds(corpus).get(itemId)??collectBlockedByIds(item):collectBlockedByIds(item)}function resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem){const itemWithId=item,blockerIds=typeof itemWithId.id=="string"?blockerIdsByItem?.get(normalizeItemId(itemWithId.id))??collectBlockedByIdsFromCorpus(itemWithId,[...itemsById.values()]):collectBlockedByIds(item),structuredExternalBlockerIds=new Set((item.dependencies??[]).filter(dependency=>resolveCanonicalRelationshipKind(dependency.kind)===BLOCKED_BY_DEPENDENCY_KIND&&isExternalDependencySourceKind(dependency.source_kind)&&typeof dependency.id=="string"&&dependency.id.trim().length>0).map(dependency=>blockerReferenceKey(dependency.id.trim(),!0)));return blockerIds.map(id=>{if(isExternalDependencyReference(id)||structuredExternalBlockerIds.has(blockerReferenceKey(id,!0)))return{id,title:null,status:null,resolved:!1,external:!0,...typeof item.updated_at=="string"?{blocked_since:item.updated_at}:{},resolver:null};const blocker=itemsById.get(normalizeItemId(id));return blocker?{id,title:blocker.title,status:blocker.status,resolved:isTerminalStatus(blocker.status,statusRegistry)}:{id,title:null,status:null,resolved:!1}})}function resolveItemBlockers(item,itemsById,statusRegistry){return resolveItemBlockersWithIndex(item,itemsById,statusRegistry)}function collectDependencyBlockedIds(corpus,statusRegistry){const itemsById=new Map(corpus.map(item=>[normalizeItemId(item.id),item])),blockerIdsByItem=indexBlockedByIds(corpus),candidateStatuses=new Set([...resolveActiveStatusSet(statusRegistry),...statusRegistry.blocked_statuses]),blocked=new Set;for(const item of corpus){const normalizedStatus=normalizeStatusForRegistry(item.status,statusRegistry);candidateStatuses.has(normalizedStatus)&&(statusRegistry.blocked_statuses.has(normalizedStatus)||resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem).some(blocker=>!blocker.resolved))&&blocked.add(normalizeItemId(item.id))}return blocked}function selectActionableEntries(report,statusRegistry,options={},typeRegistry){const candidates=[...report.ready,...report.decisions,...report.gates];options.includeContainers===!0&&candidates.push(...report.containers.filter(entry=>entry.open_blockers.length===0&&!statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(entry.item.status,statusRegistry))));const selected={ready:[],decisions:[],gates:[]};for(const entry of candidates){const role=resolveItemExecutionRole(entry.item.type,typeRegistry);role==="human"&&options.includeDecisions!==!0?selected.decisions.push(entry):role==="gate"&&options.includeGates!==!0?selected.gates.push(entry):selected.ready.push(entry)}return selected}function resolveActiveStatusSet(statusRegistry){return statusRegistry.active_statuses.size>0?statusRegistry.active_statuses:new Set([statusRegistry.open_status])}function hasOpenDescendant(rootId,childrenByParent,statusRegistry){const stack=[normalizeItemId(rootId)],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(!visited.has(current)){visited.add(current);for(const child of childrenByParent.get(current)??[]){if(!isTerminalStatus(child.status,statusRegistry))return!0;stack.push(normalizeItemId(child.id))}}}return!1}function indexCorpus(corpus){const itemsById=new Map,childrenByParent=new Map,blockedByReverse=new Map,blockerIdsByItem=indexBlockedByIds(corpus);for(const item of corpus){itemsById.set(normalizeItemId(item.id),item);const parent=typeof item.parent=="string"?item.parent.trim():"";if(parent.length>0){const parentKey=normalizeItemId(parent),siblings=childrenByParent.get(parentKey)??[];siblings.push(item),childrenByParent.set(parentKey,siblings)}for(const blockerId of blockerIdsByItem.get(normalizeItemId(item.id))){const blockerKey=normalizeItemId(blockerId),dependents=blockedByReverse.get(blockerKey)??[];dependents.push(item.id),blockedByReverse.set(blockerKey,dependents)}}return{itemsById,childrenByParent,blockedByReverse,blockerIdsByItem}}function computeActionabilityReport(candidates,corpus,statusRegistry,typeRegistry){const{itemsById,childrenByParent,blockedByReverse,blockerIdsByItem}=indexCorpus(corpus),activeStatuses=new Set([...resolveActiveStatusSet(statusRegistry),...statusRegistry.blocked_statuses]),nonTerminalIds=new Set(corpus.filter(entry=>!isTerminalStatus(entry.status,statusRegistry)).map(entry=>normalizeItemId(entry.id))),ready=[],blocked=[],containers=[],decisions=[],gates=[];let activeCount=0;for(const item of candidates){if(!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry)))continue;activeCount+=1;const openBlockers=resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem).filter(blocker=>!blocker.resolved),unblocks=(blockedByReverse.get(normalizeItemId(item.id))??[]).filter(dependentId=>nonTerminalIds.has(normalizeItemId(dependentId))).sort((left,right)=>left.localeCompare(right)),entry={item,open_blockers:openBlockers,unblocks};if(hasOpenDescendant(item.id,childrenByParent,statusRegistry)){containers.push(entry);continue}const lifecycleBlocked=statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry));if(openBlockers.length===0&&!lifecycleBlocked){const role=resolveItemExecutionRole(item.type,typeRegistry);role==="human"?decisions.push(entry):role==="gate"?gates.push(entry):ready.push(entry)}else blocked.push(entry)}return{ready,blocked,containers,decisions,gates,active_count:activeCount,container_count:containers.length}}export{ACTIONABILITY_ORDERING_KINDS,collectBlockedByIds,collectBlockedByIdsFromCorpus,collectDependencyBlockedIds,computeActionabilityReport,indexBlockedByIds,resolveItemBlockers,resolveItemExecutionRole,selectActionableEntries};
|
|
2
2
|
//# sourceMappingURL=actionability.js.map
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Safety-first policy: if a lock file cannot be read or parsed, it is RETAINED
|
|
5
5
|
* rather than deleted. We only remove locks whose staleness can be conclusively
|
|
6
|
-
* determined from the
|
|
6
|
+
* determined from the embedded lease or positive same-host owner-death evidence.
|
|
7
|
+
* Deletion is revalidated under the writer cleanup gate.
|
|
7
8
|
*
|
|
8
9
|
* Staleness formula: (now_ms - Date.parse(created_at)) > ttl_seconds * 1000
|
|
9
10
|
* Zero ttl means any lock older than 0 ms is stale. Negative ttl means always stale.
|
|
@@ -22,10 +23,14 @@ created_at:string | null;
|
|
|
22
23
|
ttl_seconds:number | null;
|
|
23
24
|
/** floor((now - created_at)/1000), null if unparseable */
|
|
24
25
|
age_seconds:number | null;
|
|
25
|
-
/**
|
|
26
|
+
/** True only when lease expiry or positive original-owner death is established. */
|
|
26
27
|
stale:boolean;
|
|
27
28
|
/** Value that configures or reports reason for this contract. */
|
|
28
|
-
reason:"expired" | "active" | "unparseable";
|
|
29
|
+
reason:"expired" | "owner_dead" | "active" | "unparseable";
|
|
30
|
+
/** Verified original-process liveness, when the receipt supports same-host observation. */
|
|
31
|
+
owner_state?:"alive" | "dead" | "unknown";
|
|
32
|
+
/** Valid recorded PID, available for diagnosis without revealing host coordinates. */
|
|
33
|
+
pid?:number;
|
|
29
34
|
}
|
|
30
35
|
/** Documents the lock gc hooks payload exchanged by command, SDK, and package integrations. */
|
|
31
36
|
export interface LockGcHooks {
|
|
@@ -57,7 +62,7 @@ warnings:string[];
|
|
|
57
62
|
entries:StaleLockScanEntry[];
|
|
58
63
|
}
|
|
59
64
|
/** Fine-grained classification outcome for one readable lock file's content. `unparseable_json` and `invalid_timestamp` both surface as the coarse `reason: "unparseable"` on the scan entry (gc retains both), but stay distinct here so callers can emit precise warnings. */
|
|
60
|
-
export type LockClassificationDetail = "active" | "expired" | "unparseable_json" | "invalid_timestamp";
|
|
65
|
+
export type LockClassificationDetail = "active" | "expired" | "owner_dead" | "unparseable_json" | "invalid_timestamp";
|
|
61
66
|
/** Documents the lock content classification payload exchanged by command, SDK, and package integrations. */
|
|
62
67
|
export interface LockContentClassification {
|
|
63
68
|
/** Value that configures or reports detail for this contract. */
|
|
@@ -65,7 +70,7 @@ detail:LockClassificationDetail;
|
|
|
65
70
|
/** Value that configures or reports entry for this contract. */
|
|
66
71
|
entry:StaleLockScanEntry;
|
|
67
72
|
}
|
|
68
|
-
/** Pure classification
|
|
73
|
+
/** Pure TTL classification retained for callers that cannot observe the owner process. Health and GC additionally share conservative same-host liveness observation. */
|
|
69
74
|
export declare function classifyLockContent(file:string,raw:string,nowMs:number):LockContentClassification;
|
|
70
75
|
/** Documents the lock health scan payload exchanged by command, SDK, and package integrations. */
|
|
71
76
|
export interface LockHealthScan {
|
|
@@ -79,6 +84,8 @@ stale_lock_count:number;
|
|
|
79
84
|
unreadable_lock_count:number;
|
|
80
85
|
/** invalid JSON, wrong shape, or an unparseable created_at timestamp */
|
|
81
86
|
unparseable_lock_count:number;
|
|
87
|
+
/** At most twenty verified dead-owner receipts for actionable full health diagnosis. */
|
|
88
|
+
owner_dead_lock_samples?:StaleLockScanEntry[];
|
|
82
89
|
}
|
|
83
90
|
/** Read-only locks scan for `pm health`: classifies every lock file with the same policy `pm gc --scope locks` uses but never removes anything. */
|
|
84
91
|
export declare function scanLockHealth(pmRoot:string,now?:number):Promise<LockHealthScan>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6b4ef85f-d844-53e3-ba32-08b95377584a")}catch{}})();import{inspectLockOwner}from"./lock-owner.js";import{acquireStaleCleanupGate,recordDeadLockRecovery}from"./lock.js";import{isFileMissingError}from"../fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";function parseLock(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return null;const candidate=parsed,{id,owner,created_at,ttl_seconds}=candidate;return typeof id!="string"||typeof owner!="string"||typeof created_at!="string"||typeof ttl_seconds!="number"||!Number.isFinite(ttl_seconds)?null:{id,owner,created_at,ttl_seconds,pid:candidate.pid,host_identity:candidate.host_identity,process_start_identity:candidate.process_start_identity}}function classifyLockContent(file,raw,nowMs){const lock=parseLock(raw);if(lock===null)return{detail:"unparseable_json",entry:{file,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};const createdAtMs=Date.parse(lock.created_at);if(!Number.isFinite(createdAtMs))return{detail:"invalid_timestamp",entry:{file,id:lock.id,owner:lock.owner,created_at:lock.created_at,ttl_seconds:lock.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};const ageMs=nowMs-createdAtMs,age_seconds=Math.floor(ageMs/1e3),stale=ageMs>lock.ttl_seconds*1e3;return{detail:stale?"expired":"active",entry:{file,id:lock.id,owner:lock.owner,created_at:lock.created_at,ttl_seconds:lock.ttl_seconds,age_seconds,stale,reason:stale?"expired":"active"}}}async function classifyObservedLock(file,raw,nowMs){const classified=classifyLockContent(file,raw,nowMs);if(classified.detail!=="active")return classified;const lock=parseLock(raw),state=await inspectLockOwner(lock);return state==="unknown"?classified:{detail:state==="dead"?"owner_dead":"active",entry:{...classified.entry,owner_state:state,pid:lock.pid,...state==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function removeObservedLock(lockPath,raw,ownerDead){const release=await acquireStaleCleanupGate(lockPath,"gc");if(release===null)return!1;try{let current;try{current=await fs.readFile(lockPath,"utf8")}catch(error){if(isFileMissingError(error))return!0;throw error}if(current!==raw)return!1;ownerDead&&await recordDeadLockRecovery(lockPath,raw);try{await fs.unlink(lockPath)}catch(error){if(!isFileMissingError(error))throw error}return!0}finally{await release()}}function addHealthObservation(scan,detail,entry){detail==="owner_dead"&&(scan.owner_dead_lock_samples??=[],scan.owner_dead_lock_samples.length<20&&scan.owner_dead_lock_samples.push(entry)),detail==="active"?scan.active_lock_count+=1:detail==="expired"||detail==="owner_dead"?scan.stale_lock_count+=1:scan.unparseable_lock_count+=1}async function scanLockHealth(pmRoot,now){const nowMs=now??Date.now(),locksDir=path.join(pmRoot,"locks"),scan={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0};let dirEntries;try{dirEntries=(await fs.readdir(locksDir)).filter(f=>f.endsWith(".lock")).sort()}catch(error){if(isFileMissingError(error))return scan;throw error}for(const file of dirEntries){let raw;try{raw=await fs.readFile(path.join(locksDir,file),"utf8")}catch(readError){if(isFileMissingError(readError))continue;scan.scanned+=1,scan.unreadable_lock_count+=1;continue}scan.scanned+=1;const{detail,entry}=await classifyObservedLock(file,raw,nowMs);addHealthObservation(scan,detail,entry)}return scan}async function removeOrPreviewLock(result,options,absPath,relPath,file,raw,entry){if(!options.dryRun){try{if(!await removeObservedLock(absPath,raw,entry.reason==="owner_dead")){result.warnings.push(`lock_changed_or_busy:${file}`),result.retained.push(relPath),result.entries.push(entry);return}}catch{result.warnings.push(`lock_remove_failed:${file}`),result.retained.push(relPath),result.entries.push(entry);return}if(options.hooks?.onWrite){const hookWarnings=await options.hooks.onWrite(absPath);result.warnings.push(...hookWarnings)}}result.removed.push(relPath),result.entries.push(entry)}async function runLockGc(pmRoot,options){const{hooks}=options,nowMs=options.now??Date.now(),locksDir=path.join(pmRoot,"locks"),result={scanned:0,removed:[],retained:[],warnings:[],entries:[]};let dirEntries;try{dirEntries=(await fs.readdir(locksDir)).filter(f=>f.endsWith(".lock")).sort()}catch(error){if(isFileMissingError(error))return result;throw error}for(const file of dirEntries){result.scanned+=1;const absPath=path.join(locksDir,file),relPath=`locks/${file}`;if(hooks?.onRead){const hookWarnings=await hooks.onRead(absPath);result.warnings.push(...hookWarnings)}let raw;try{raw=await fs.readFile(absPath,"utf8")}catch(readError){if(isFileMissingError(readError)){result.scanned-=1;continue}result.warnings.push(`lock_unreadable:${file}`),result.retained.push(relPath),result.entries.push({file,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}const classified=await classifyObservedLock(file,raw,nowMs);if(classified.detail==="unparseable_json"){result.warnings.push(`lock_unparseable:${file}`),result.retained.push(relPath),result.entries.push(classified.entry);continue}if(classified.detail==="invalid_timestamp"){result.warnings.push(`lock_invalid_timestamp:${file}`),result.retained.push(relPath),result.entries.push(classified.entry);continue}if(classified.detail==="active"){result.retained.push(relPath),result.entries.push(classified.entry);continue}await removeOrPreviewLock(result,options,absPath,relPath,file,raw,classified.entry)}return result}export{classifyLockContent,runLockGc,scanLockHealth};
|
|
2
2
|
//# sourceMappingURL=lock-gc.js.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Stable operating-system identity for a process when the host exposes one. */
|
|
2
|
+
export interface ProcessIdentity {
|
|
3
|
+
/** Operating-system process identifier captured with the owner record. */
|
|
4
|
+
pid:number;
|
|
5
|
+
/** Host process-start coordinate that distinguishes reuse of the same PID. */
|
|
6
|
+
process_start_identity?:string;
|
|
7
|
+
}
|
|
8
|
+
/** Untrusted optional receipt coordinates; validate before observing host processes. */
|
|
9
|
+
export interface LockOwnerIdentity {
|
|
10
|
+
/** PID recorded by the writer; legacy GC receipts may omit it. */
|
|
11
|
+
pid?:unknown;
|
|
12
|
+
/** Opaque boot and PID-namespace identity, absent on unsupported hosts. */
|
|
13
|
+
host_identity?:unknown;
|
|
14
|
+
/** Original process start tick, absent on legacy receipts. */
|
|
15
|
+
process_start_identity?:unknown;
|
|
16
|
+
}
|
|
17
|
+
/** Parse the kernel start tick without treating spaces in a process name as fields. */
|
|
18
|
+
export declare function parseLinuxProcessStartIdentity(raw:string):string | null;
|
|
19
|
+
/** Read the host process-start coordinate used to distinguish PID reuse. */
|
|
20
|
+
export declare function readProcessStartIdentity(pid:number):Promise<string | null>;
|
|
21
|
+
/** Capture the current PID plus a host process-start coordinate when available. */
|
|
22
|
+
export declare function captureProcessIdentity(pid?:number):Promise<ProcessIdentity>;
|
|
23
|
+
/**
|
|
24
|
+
* Verify that a captured process owner still exists, with a bounded grace
|
|
25
|
+
* period when the host cannot expose a reusable-PID-safe start coordinate.
|
|
26
|
+
*/
|
|
27
|
+
export declare function isProcessIdentityAlive(identity:ProcessIdentity,unverifiedAgeMs:number,maxUnverifiedAgeMs:number):Promise<boolean>;
|
|
28
|
+
/** Opaque same-boot, same-PID-namespace coordinate; unavailable means no early reclaim. */
|
|
29
|
+
export declare function readLockHostIdentity():Promise<string | null>;
|
|
30
|
+
/** Capture only the coordinates this host can actually verify later. */
|
|
31
|
+
export declare function captureLockOwnerIdentity():Promise<LockOwnerIdentity>;
|
|
32
|
+
/** Positive proof of original-owner death; foreign, legacy, inaccessible and malformed evidence stays unknown. */
|
|
33
|
+
export declare function inspectLockOwner(identity:LockOwnerIdentity | null):Promise<"alive" | "dead" | "unknown">;
|
|
@@ -0,0 +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]="d1f829a5-70d6-5096-86f7-717440dd67d5")}catch{}})();import fs from"node:fs/promises";import{createHash}from"node:crypto";function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function isProcessAlive(pid){if(!Number.isSafeInteger(pid)||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error){return!isErrno(error,"ESRCH")}}function parseLinuxProcessStartIdentity(raw){const closeParenIndex=raw.lastIndexOf(")");if(closeParenIndex<0)return null;const startTime=raw.slice(closeParenIndex+2).trim().split(/\s+/u)[19];return startTime!==void 0&&/^\d+$/u.test(startTime)?startTime:null}async function readProcessStartIdentity(pid){try{return parseLinuxProcessStartIdentity(await fs.readFile(`/proc/${pid}/stat`,"utf8"))}catch{return null}}async function captureProcessIdentity(pid=process.pid){const processStartIdentity=await readProcessStartIdentity(pid);return{pid,...processStartIdentity===null?{}:{process_start_identity:processStartIdentity}}}async function isProcessIdentityAlive(identity,unverifiedAgeMs,maxUnverifiedAgeMs){if(!isProcessAlive(identity.pid))return!1;const currentStartIdentity=await readProcessStartIdentity(identity.pid);return identity.process_start_identity!==void 0&¤tStartIdentity!==null?currentStartIdentity===identity.process_start_identity:unverifiedAgeMs<=maxUnverifiedAgeMs}async function readLockHostIdentity(){try{const[boot,namespace]=await Promise.all([fs.readFile("/proc/sys/kernel/random/boot_id","utf8"),fs.readlink("/proc/self/ns/pid")]);return!/^[a-f0-9-]{36}\s*$/u.test(boot)||!/^pid:\[\d+\]$/u.test(namespace)?null:createHash("sha256").update(`${boot.trim()}:${namespace}`).digest("hex")}catch{return null}}async function captureLockOwnerIdentity(){const[host,start]=await Promise.all([readLockHostIdentity(),readProcessStartIdentity(process.pid)]);return host!==null&&start!==null?{host_identity:host,process_start_identity:start}:{}}async function inspectLockOwner(identity){if(!identity||typeof identity.pid!="number"||!Number.isSafeInteger(identity.pid)||identity.pid<=0||typeof identity.host_identity!="string"||typeof identity.process_start_identity!="string"||!/^\d+$/u.test(identity.process_start_identity))return"unknown";const host=await readLockHostIdentity();if(host===null||host!==identity.host_identity)return"unknown";try{process.kill(identity.pid,0)}catch(error){return isErrno(error,"ESRCH")?"dead":"unknown"}const current=await readProcessStartIdentity(identity.pid);return current===null?"unknown":current===identity.process_start_identity?"alive":"dead"}export{captureLockOwnerIdentity,captureProcessIdentity,inspectLockOwner,isProcessIdentityAlive,parseLinuxProcessStartIdentity,readLockHostIdentity,readProcessStartIdentity};
|
|
2
|
+
//# sourceMappingURL=lock-owner.js.map
|
package/dist/core/lock/lock.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
import { parseLinuxProcessStartIdentity,readProcessStartIdentity,type LockOwnerIdentity } from "./lock-owner.js";
|
|
2
|
+
export { captureProcessIdentity,isProcessIdentityAlive,readProcessStartIdentity,} from "./lock-owner.js";
|
|
3
|
+
interface LockInfo extends LockOwnerIdentity {
|
|
2
4
|
id:string;
|
|
3
5
|
pid:number;
|
|
4
6
|
owner:string;
|
|
@@ -15,13 +17,6 @@ lockInfo:LockReadResult;
|
|
|
15
17
|
shouldRetryCreate:boolean;
|
|
16
18
|
staleRemovalCounted:boolean;
|
|
17
19
|
}
|
|
18
|
-
/** Stable operating-system identity for a process when the host exposes one. */
|
|
19
|
-
export interface ProcessIdentity {
|
|
20
|
-
/** Operating-system process identifier captured with the owner record. */
|
|
21
|
-
pid:number;
|
|
22
|
-
/** Host process-start coordinate that distinguishes reuse of the same PID. */
|
|
23
|
-
process_start_identity?:string;
|
|
24
|
-
}
|
|
25
20
|
declare function parseLockInfo(raw:string):LockReadResult;
|
|
26
21
|
declare function readLockInfo(lockPath:string,emitReadHook?:boolean):Promise<LockReadResult>;
|
|
27
22
|
declare function isErrno(error:unknown,code:string):boolean;
|
|
@@ -34,24 +29,17 @@ declare function isErrno(error:unknown,code:string):boolean;
|
|
|
34
29
|
* when its parent remains writable, preserving genuine permission failures.
|
|
35
30
|
*/
|
|
36
31
|
declare function isLockCreateContention(error:unknown,lockPath:string,platform?:NodeJS.Platform):Promise<boolean>;
|
|
37
|
-
declare function buildLockPayload(id:string,owner:string,ttlSeconds:number,token?:string):LockInfo
|
|
32
|
+
declare function buildLockPayload(id:string,owner:string,ttlSeconds:number,token?:string):Promise<LockInfo>;
|
|
38
33
|
declare function isStaleLock(info:LockInfo | null,ttlSeconds:number):boolean;
|
|
39
34
|
/** Observe a built-in lock's owner lease without acquiring it or changing storage. */
|
|
40
35
|
export declare function hasUnexpiredLockOwner(pmRoot:string,id:string,ownerPrefix:string):Promise<boolean>;
|
|
41
36
|
declare function lockOwnerSuffix(info:LockInfo | null):string;
|
|
42
37
|
/** Resolves the effective bounded wait budget for a contended lock: the PM_LOCK_WAIT_MS environment override wins when it parses as a non-negative integer, then the caller-provided budget (settings `locks.wait_ms`), then 0 (fail-fast, the pre-wait behavior). */
|
|
43
38
|
declare function resolveLockWaitMs(waitMs:number | undefined):number;
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
export declare function captureProcessIdentity(pid?:number):Promise<ProcessIdentity>;
|
|
49
|
-
/**
|
|
50
|
-
* Verify that a captured process owner still exists, with a bounded grace
|
|
51
|
-
* period when the host cannot expose a reusable-PID-safe start coordinate.
|
|
52
|
-
*/
|
|
53
|
-
export declare function isProcessIdentityAlive(identity:ProcessIdentity,unverifiedAgeMs:number,maxUnverifiedAgeMs:number):Promise<boolean>;
|
|
54
|
-
declare function acquireStaleCleanupGate(lockPath:string,_id:string):Promise<(() => Promise<void>) | null>;
|
|
39
|
+
/** Fence lock publication, release and garbage collection under one cleanup owner. */
|
|
40
|
+
export declare function acquireStaleCleanupGate(lockPath:string,_id:string):Promise<(() => Promise<void>) | null>;
|
|
41
|
+
/** Retain an immutable local audit of early-recovery intent before removing the observed owner. */
|
|
42
|
+
export declare function recordDeadLockRecovery(lockPath:string,raw:string):Promise<void>;
|
|
55
43
|
declare function removeConfirmedStaleLock(params:{
|
|
56
44
|
lockPath:string;
|
|
57
45
|
id:string;
|
|
@@ -80,7 +68,9 @@ removeConfirmedStaleLock:typeof removeConfirmedStaleLock;
|
|
|
80
68
|
};
|
|
81
69
|
/**
|
|
82
70
|
* Acquire a token-owned tracker lock with bounded contention waiting and
|
|
83
|
-
* explicit stale-owner policy.
|
|
71
|
+
* explicit stale-owner policy. Proven same-host original-process death permits
|
|
72
|
+
* automatic early recovery; unverifiable owners retain TTL policy.
|
|
73
|
+
* Background consumers may disable creation of
|
|
84
74
|
* parent directories so acquiring or retrying a lock cannot revive removed
|
|
85
75
|
* storage. An explicit maxWaitMs caps contention retries even when the process
|
|
86
76
|
* environment requests a longer wait. Extension overrides receive that ceiling
|
|
@@ -92,4 +82,3 @@ createParentDirectories?:boolean;
|
|
|
92
82
|
/** Ceiling on the effective retry budget, including PM_LOCK_WAIT_MS. */
|
|
93
83
|
maxWaitMs?:number;
|
|
94
84
|
}):Promise<() => Promise<void>>;
|
|
95
|
-
export {};
|
package/dist/core/lock/lock.js
CHANGED
|
@@ -1,4 +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
|
-
`,"utf8")}finally{await handle.close()}}catch(error){throw await unlinkLockWithHook(lockPath,"lock:release"),error}}finally{await releaseCleanupGate()}await emitLockWriteHook(lockPath,"lock:create")}async function unlinkLockWithHook(lockPath,op){try{return await fs.unlink(lockPath),await emitLockWriteHook(lockPath,op),!0}catch{return!1}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=Date.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null){try{const current2=await readLockInfo(lockPath,!1);isOwnedLock(current2.info,id,owner,token)&&await unlinkLockWithHook(lockPath,"lock:release")}finally{await releaseCleanupGate()}return}const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,owner,token))return;const elapsedMs=Date.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}function isOwnedLock(info,id,owner,token){return info?.id===id&&info.pid===process.pid&&info.owner===owner&&info.token===token}function isStaleLock(info,ttlSeconds){const createdAtMs=info?.created_at?Date.parse(info.created_at):Number.NaN;return(Number.isFinite(createdAtMs)?Date.now()-createdAtMs:Number.POSITIVE_INFINITY)>ttlSeconds*1e3}async function hasUnexpiredLockOwner(pmRoot,id,ownerPrefix){const{info}=await readLockInfo(getLockPath(pmRoot,id),!1);return info!==null&&info.owner.startsWith(ownerPrefix)&&!
|
|
3
|
-
`,"utf8")}catch{return await removeStaleCleanupGateDirectory(gatePath),null}return owner}async function removeExpiredStaleCleanupGate(gatePath){let gateAgeMs;try{const stats=await fs.stat(gatePath);if(gateAgeMs=Date.now()-stats.mtimeMs,gateAgeMs<=STALE_CLEANUP_GATE_STALE_MS)return!1}catch(error){return isFileMissingError(error)}const owner=await readStaleCleanupGateOwner(gatePath);return owner!==null&&await isProcessIdentityAlive(owner,gateAgeMs,STALE_CLEANUP_GATE_MAX_UNVERIFIED_MS)?!1:removeStaleCleanupGateDirectory(gatePath)}async function acquireStaleCleanupGate(lockPath,_id){const gatePath=`${lockPath}${STALE_CLEANUP_GATE_SUFFIX}`,owner=await tryCreateStaleCleanupGate(gatePath);if(owner!==null)return async()=>releaseStaleCleanupGate(gatePath,owner.token);if(!await removeExpiredStaleCleanupGate(gatePath))return null;const recoveredOwner=await tryCreateStaleCleanupGate(gatePath);return recoveredOwner===null?null:async()=>releaseStaleCleanupGate(gatePath,recoveredOwner.token)}async function
|
|
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]="8aac3d30-44d1-5876-ab56-6dbc2285d28f")}catch{}})();import{isFileMissingError}from"../fs/fs-utils.js";import{constants as fsConstants}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{runActiveOnReadHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{getLockPath}from"../store/paths.js";import{nowIso}from"../shared/time.js";import{captureProcessIdentity,captureLockOwnerIdentity,inspectLockOwner,isProcessIdentityAlive,parseLinuxProcessStartIdentity,readProcessStartIdentity}from"./lock-owner.js";import{captureProcessIdentity as captureProcessIdentity2,isProcessIdentityAlive as isProcessIdentityAlive2,readProcessStartIdentity as readProcessStartIdentity2}from"./lock-owner.js";function parseLockInfo(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{info:null,warnings:["lock_info_invalid_shape"]};const candidate=parsed,id=candidate.id,pid=candidate.pid,owner=candidate.owner,token=candidate.token,createdAt=candidate.created_at,ttlSeconds=candidate.ttl_seconds;return typeof id!="string"||typeof pid!="number"||!Number.isFinite(pid)||typeof owner!="string"||token!==void 0&&(typeof token!="string"||token.trim().length===0)||typeof createdAt!="string"||typeof ttlSeconds!="number"||!Number.isFinite(ttlSeconds)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id,pid,owner,...typeof token=="string"?{token}:{},created_at:createdAt,ttl_seconds:ttlSeconds,host_identity:candidate.host_identity,process_start_identity:candidate.process_start_identity},warnings:[]}}async function readLockInfo(lockPath,emitReadHook=!0){try{const raw=await fs.readFile(lockPath,"utf8");return emitReadHook&&await runActiveOnReadHooks({path:lockPath,scope:"project"}),parseLockInfo(raw)}catch(error){return isFileMissingError(error)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}async function isLockCreateContention(error,lockPath,platform=process.platform){if(isErrno(error,"EEXIST"))return!0;if(!isErrno(error,"EPERM")&&!isErrno(error,"EACCES")&&!isErrno(error,"EBUSY"))return!1;try{return await fs.lstat(lockPath),!0}catch(probeError){if(platform!=="win32"||!isFileMissingError(probeError)&&!isErrno(probeError,"EPERM")&&!isErrno(probeError,"EACCES")&&!isErrno(probeError,"EBUSY"))return!1}try{return await fs.access(path.dirname(lockPath),fsConstants.W_OK),!0}catch{return!1}}async function emitLockWriteHook(lockPath,op){await runActiveOnWriteHooks({path:lockPath,scope:"project",op})}async function buildLockPayload(id,owner,ttlSeconds,token=randomUUID()){return{...await captureLockOwnerIdentity(),id,pid:process.pid,owner,token,created_at:nowIso(),ttl_seconds:ttlSeconds}}async function createLockFile(lockPath,id,owner,ttlSeconds,token,createParentDirectories){createParentDirectories&&await fs.mkdir(path.dirname(lockPath),{recursive:!0});const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null)throw await fs.access(path.dirname(lockPath)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});try{const handle=await fs.open(lockPath,"wx");try{try{await handle.writeFile(`${JSON.stringify(await buildLockPayload(id,owner,ttlSeconds,token),null,2)}
|
|
2
|
+
`,"utf8")}finally{await handle.close()}}catch(error){throw await unlinkLockWithHook(lockPath,"lock:release"),error}}finally{await releaseCleanupGate()}await emitLockWriteHook(lockPath,"lock:create")}async function unlinkLockWithHook(lockPath,op){try{return await fs.unlink(lockPath),await emitLockWriteHook(lockPath,op),!0}catch{return!1}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=Date.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null){try{const current2=await readLockInfo(lockPath,!1);isOwnedLock(current2.info,id,owner,token)&&await unlinkLockWithHook(lockPath,"lock:release")}finally{await releaseCleanupGate()}return}const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,owner,token))return;const elapsedMs=Date.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}function isOwnedLock(info,id,owner,token){return info?.id===id&&info.pid===process.pid&&info.owner===owner&&info.token===token}function isStaleLock(info,ttlSeconds){const createdAtMs=info?.created_at?Date.parse(info.created_at):Number.NaN;return(Number.isFinite(createdAtMs)?Date.now()-createdAtMs:Number.POSITIVE_INFINITY)>ttlSeconds*1e3}async function isConfirmedDeadLock(info){return info!==null&&Number.isFinite(Date.parse(info.created_at))&&await inspectLockOwner(info)==="dead"}async function isReclaimableLock(info,ttlSeconds){return isStaleLock(info,ttlSeconds)||await isConfirmedDeadLock(info)}async function hasUnexpiredLockOwner(pmRoot,id,ownerPrefix){const{info}=await readLockInfo(getLockPath(pmRoot,id),!1);return info!==null&&info.owner.startsWith(ownerPrefix)&&!await isReclaimableLock(info,info.ttl_seconds)}function lockOwnerSuffix(info){return info?.owner?` (owner ${info.owner})`:""}const LOCK_WAIT_INITIAL_DELAY_MS=25,LOCK_WAIT_MAX_DELAY_MS=200,LOCK_CONFLICT_RETRY_HINT_MS=250,MAX_STALE_LOCK_REMOVALS=3,STALE_CLEANUP_GATE_SUFFIX=".stale-cleanup",STALE_CLEANUP_GATE_OWNER_FILE="owner.json",STALE_CLEANUP_GATE_STALE_MS=1e4,LOCK_RELEASE_GATE_WAIT_MS=STALE_CLEANUP_GATE_STALE_MS+LOCK_WAIT_MAX_DELAY_MS,STALE_CLEANUP_GATE_MAX_UNVERIFIED_MS=60*6e4;function parseNonNegativeIntegerWaitMs(value){if(typeof value=="string"){const trimmed=value.trim();if(!/^\d+$/.test(trimmed))return;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)?parsed:void 0}if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return Math.trunc(value)}function resolveLockWaitMs(waitMs){const envRaw=process.env.PM_LOCK_WAIT_MS,envParsed=parseNonNegativeIntegerWaitMs(envRaw);if(envParsed!==void 0)return envParsed;const callerParsed=parseNonNegativeIntegerWaitMs(waitMs);return callerParsed!==void 0?callerParsed:0}function cappedLockWaitMs(waitMs,maxWaitMs){return Math.min(resolveLockWaitMs(waitMs),maxWaitMs??1/0)}function sleepWithJitter(baseDelayMs){const jitteredMs=Math.max(1,Math.round(baseDelayMs*(.5+Math.random())));return new Promise(resolve=>setTimeout(resolve,jitteredMs))}async function buildLockConflictError(id,info,waitedMs){const ownerState=await inspectLockOwner(info),waitedSuffix=waitedMs>0?` after waiting ${waitedMs}ms`:"";return new PmCliError(`Item ${id} is locked${lockOwnerSuffix(info)} (owner process ${ownerState})${waitedSuffix}`,EXIT_CODE.CONFLICT,{code:"lock_conflict",item_id:id,reason:`lock_owner_${ownerState}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS}})}function resolveLockOverrideRelease(result){if(typeof result=="function")return result;if(typeof result=="object"&&result!==null&&"release"in result){const release=result.release;return typeof release=="function"?release:null}return null}function throwIfStaleLockNeedsForce(id,lockInfo,force,forceRequired){if(!force&&forceRequired){const warningSuffix=lockInfo.warnings.length>0?` (${lockInfo.warnings.join(",")})`:"";throw new PmCliError(`Item ${id} lock is stale${warningSuffix}; rerun with --force when supported for this command`,EXIT_CODE.CONFLICT)}}function parseStaleCleanupGateOwner(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return null;const candidate=parsed,pid=candidate.pid,token=candidate.token,processStartIdentity=candidate.process_start_identity;return typeof pid!="number"||!Number.isInteger(pid)||pid<=0||typeof token!="string"||token.length===0||processStartIdentity!==void 0&&(typeof processStartIdentity!="string"||!/^\d+$/u.test(processStartIdentity))?null:{pid,token,...typeof processStartIdentity=="string"?{process_start_identity:processStartIdentity}:{}}}async function readStaleCleanupGateOwner(gatePath){try{return parseStaleCleanupGateOwner(await fs.readFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),"utf8"))}catch{return null}}async function removeStaleCleanupGateDirectory(gatePath){try{return await fs.rm(gatePath,{recursive:!0,force:!0}),!0}catch{return!1}}async function releaseStaleCleanupGate(gatePath,token){const owner=await readStaleCleanupGateOwner(gatePath);owner===null||owner.token!==token||await removeStaleCleanupGateDirectory(gatePath)}async function tryCreateStaleCleanupGate(gatePath){try{await fs.mkdir(gatePath)}catch(error){return isErrno(error,"EEXIST"),null}const owner={...await captureProcessIdentity(),token:randomUUID()};try{await fs.writeFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),`${JSON.stringify(owner)}
|
|
3
|
+
`,"utf8")}catch{return await removeStaleCleanupGateDirectory(gatePath),null}return owner}async function removeExpiredStaleCleanupGate(gatePath){let gateAgeMs;try{const stats=await fs.stat(gatePath);if(gateAgeMs=Date.now()-stats.mtimeMs,gateAgeMs<=STALE_CLEANUP_GATE_STALE_MS)return!1}catch(error){return isFileMissingError(error)}const owner=await readStaleCleanupGateOwner(gatePath);return owner!==null&&await isProcessIdentityAlive(owner,gateAgeMs,STALE_CLEANUP_GATE_MAX_UNVERIFIED_MS)?!1:removeStaleCleanupGateDirectory(gatePath)}async function acquireStaleCleanupGate(lockPath,_id){const gatePath=`${lockPath}${STALE_CLEANUP_GATE_SUFFIX}`,owner=await tryCreateStaleCleanupGate(gatePath);if(owner!==null)return async()=>releaseStaleCleanupGate(gatePath,owner.token);if(!await removeExpiredStaleCleanupGate(gatePath))return null;const recoveredOwner=await tryCreateStaleCleanupGate(gatePath);return recoveredOwner===null?null:async()=>releaseStaleCleanupGate(gatePath,recoveredOwner.token)}async function recordDeadLockRecovery(lockPath,raw){const directory=path.join(path.dirname(lockPath),"recoveries");await fs.mkdir(directory,{recursive:!0}),await fs.writeFile(path.join(directory,`${randomUUID()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:nowIso(),lock:JSON.parse(raw)})}
|
|
4
|
+
`,{encoding:"utf8",flag:"wx",mode:384})}async function removeConfirmedStaleLock(params){const releaseCleanupGate=await acquireStaleCleanupGate(params.lockPath,params.id);if(releaseCleanupGate===null)return{lockInfo:params.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{const currentLockInfo=await readLockInfo(params.lockPath);if(currentLockInfo.info===null&¤tLockInfo.warnings.length===0)return{lockInfo:currentLockInfo,shouldRetryCreate:!0,staleRemovalCounted:!1};const ownerDead=await isConfirmedDeadLock(currentLockInfo.info);if(!isStaleLock(currentLockInfo.info,params.ttlSeconds)&&!ownerDead)return{lockInfo:currentLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};if(throwIfStaleLockNeedsForce(params.id,currentLockInfo,params.force||ownerDead,params.forceRequiredForStaleLock),params.staleRemovals>=MAX_STALE_LOCK_REMOVALS)throw await buildLockConflictError(params.id,currentLockInfo.info,Date.now()-params.startedAtMs);return ownerDead&&await recordDeadLockRecovery(params.lockPath,JSON.stringify(currentLockInfo.info)),{lockInfo:currentLockInfo,shouldRetryCreate:await unlinkLockWithHook(params.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await releaseCleanupGate()}}const _testOnly={parseLockInfo,readLockInfo,isErrno,isLockCreateContention,buildLockPayload,isStaleLock,lockOwnerSuffix,resolveLockWaitMs,parseLinuxProcessStartIdentity,readProcessStartIdentity,acquireStaleCleanupGate,removeConfirmedStaleLock};async function acquireLock(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){const maxWaitMs=parseNonNegativeIntegerWaitMs(options.maxWaitMs),lockOverride=await runActiveServiceOverride("lock_acquire",{pm_root:pmRoot,id,ttl_seconds:ttlSeconds,owner,force,force_required_for_stale_lock:forceRequiredForStaleLock,...maxWaitMs===void 0?{}:{max_wait_ms:maxWaitMs}});if(lockOverride.handled){const release=resolveLockOverrideRelease(lockOverride.result);if(release)return async()=>{await Promise.resolve(release()),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})}}const lockPath=getLockPath(pmRoot,id),waitBudgetMs=cappedLockWaitMs(waitMs,maxWaitMs),startedAtMs=Date.now();let staleRemovals=0,backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;const token=randomUUID();for(;;)try{return await createLockFile(lockPath,id,owner,ttlSeconds,token,options.createParentDirectories!==!1),async()=>{await releaseOwnedLock(lockPath,id,owner,token),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})}}catch(error){if(!await isLockCreateContention(error,lockPath))throw new PmCliError(`Failed to acquire lock for ${id}: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE);let lockInfo=await readLockInfo(lockPath);if(await isReclaimableLock(lockInfo.info,ttlSeconds)){const staleRemoval=await removeConfirmedStaleLock({lockPath,id,ttlSeconds,force,forceRequiredForStaleLock,staleRemovals,waitBudgetMs,startedAtMs,fallbackLockInfo:lockInfo});if(lockInfo=staleRemoval.lockInfo,staleRemoval.staleRemovalCounted&&(staleRemovals+=1),staleRemoval.shouldRetryCreate)continue}const elapsedMs=Date.now()-startedAtMs;if(waitBudgetMs===0||elapsedMs>=waitBudgetMs)throw await buildLockConflictError(id,lockInfo.info,waitBudgetMs===0?0:elapsedMs);await sleepWithJitter(Math.min(backoffMs,waitBudgetMs-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}export{_testOnly,acquireLock,acquireStaleCleanupGate,captureProcessIdentity2 as captureProcessIdentity,hasUnexpiredLockOwner,isProcessIdentityAlive2 as isProcessIdentityAlive,readProcessStartIdentity2 as readProcessStartIdentity,recordDeadLockRecovery};
|
|
4
5
|
//# sourceMappingURL=lock.js.map
|
|
@@ -43,8 +43,13 @@ pmRoot?:string;
|
|
|
43
43
|
export declare function writeStdout(text:string):boolean;
|
|
44
44
|
/** Write stderr and preserve diagnostic delivery failures in the process exit code. */
|
|
45
45
|
export declare function writeStderr(text:string):boolean;
|
|
46
|
+
/** Independent presentation policies shared by recursive value compaction. */
|
|
47
|
+
interface OutputCompactionPolicy {
|
|
48
|
+
readonly omitDuplicateCountAliases:boolean;
|
|
49
|
+
readonly preserveRowFacts:boolean;
|
|
50
|
+
}
|
|
46
51
|
/** Keep sparse presentation rules shared while allowing lean JSON to retain count aliases. */
|
|
47
|
-
declare function compactToonValue(value:unknown,
|
|
52
|
+
declare function compactToonValue(value:unknown,policy?:OutputCompactionPolicy,preserveEmpty?:boolean):unknown | undefined;
|
|
48
53
|
/** Render objects recursively and arrays through the standard TOON encoder. */
|
|
49
54
|
declare function renderToonValue(value:unknown,depth:number):string;
|
|
50
55
|
/**
|
|
@@ -52,7 +57,7 @@ declare function renderToonValue(value:unknown,depth:number):string;
|
|
|
52
57
|
* extension overrides. SDK budget accounting uses this exact representation
|
|
53
58
|
* so reported token cost describes the bytes the host emits by default.
|
|
54
59
|
*/
|
|
55
|
-
export declare function formatBuiltInOutput(result:unknown,format:"json" | "toon"):string;
|
|
60
|
+
export declare function formatBuiltInOutput(result:unknown,format:"json" | "toon",lean?:boolean):string;
|
|
56
61
|
/** Resolve command ownership and suppression before projecting and rendering the result. */
|
|
57
62
|
export declare function formatOutput(result:unknown,options:OutputOptions):string;
|
|
58
63
|
/** Apply declared exit codes and mutation projection before writing a nonquiet result. */
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="dd3b19cb-eda3-5ee9-a838-f0abaa5cc8ea")}catch{}})();import{getActiveCommandContext,runActiveCommandOverride,runActiveRendererOverride,runActiveServiceOverrideSync,setActiveCommandResult}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{isHostOutputSuppressed}from"./output-control.js";import{projectMutationResult}from"./mutation-projection.js";import{attachReadOutputContracts}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt}from"../../sdk/context-usage.js";import{isReadOutputBudgetExceeded,resolveReadOutputEncoding}from"../../sdk/read-output-contracts.js";import{encode as encodeToon}from"@toon-format/toon";import{encodePmTableRows}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope}from"../../sdk/output/list-envelope.js";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),COLLECTION_COUNT_ALIASES=new Map([["notes_count","notes"],["tests_count","tests"]]),NATIVE_OUTPUT_MARKER="__pm_native_output";let streamErrorHandlersInstalled=!1;function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function setActiveCommandResultOmitted(source){const omitted={read_output:{result_omitted:!0}};propagateContextUsageServingReceipt(source,omitted),setActiveCommandResult(omitted)}function setActiveCommandDeliveryResult(result,receiptSource,structuredDeliveryPreserved){if(structuredDeliveryPreserved){setActiveCommandResult(result);return}setActiveCommandResultOmitted(receiptSource)}function stripNativeOutputMarker(result){if(!isPlainObject(result)||result[NATIVE_OUTPUT_MARKER]!==!0)return result;const{[NATIVE_OUTPUT_MARKER]:_marker,...rest}=result;return rest}function isBrokenPipeError(error){return typeof error=="object"&&error!==null&&error.code==="EPIPE"}function markStdoutBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.SUCCESS)}function markStderrBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function markBrokenPipeExitCode(target){if(target==="stdout"){markStdoutBrokenPipeExitCode();return}markStderrBrokenPipeExitCode()}function handleUnhandledStreamError(error){const unhandled=error instanceof Error?error:new Error(String(error));setImmediate(()=>{throw unhandled})}function installStreamErrorHandlers(){streamErrorHandlersInstalled||(streamErrorHandlersInstalled=!0,process.stdout.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stdout");return}handleUnhandledStreamError(error)}),process.stderr.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stderr");return}handleUnhandledStreamError(error)}))}function writeToStream(target,text){installStreamErrorHandlers();try{return target==="stdout"?process.stdout.write(text):process.stderr.write(text),!0}catch(error){if(isBrokenPipeError(error))return markBrokenPipeExitCode(target),!1;throw error}}function writeStdout(text){return writeToStream("stdout",text)}function writeStderr(text){return writeToStream("stderr",text)}function renderScalar(value){return typeof value=="string"?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":JSON.stringify(value)}function tabularObjectArray(value){const keys=Object.keys(value[0]);return keys.length>0&&value.every(entry=>Object.keys(entry).length===keys.length&&keys.every(key=>{if(!Object.hasOwn(entry,key))return!1;const cell=entry[key];return cell===null||typeof cell=="string"||typeof cell=="number"||typeof cell=="boolean"}))}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
|
|
2
2
|
`).map(line=>`${indent}${line}`).join(`
|
|
3
3
|
`)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);if(allowNestedTable&&entry.length>=2&&entry.every(isPlainObject)&&!tabularObjectArray(entry)&&isNestedTableCandidateBounded(entry)){const table=encodePmTableRows(entry),tabular=indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:table.encoding}),depth);if(Buffer.byteLength(tabular)<Buffer.byteLength(expanded))return tabular}return expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
|
|
4
|
-
${renderToonValue(entry,depth+1)}`}function
|
|
4
|
+
${renderToonValue(entry,depth+1)}`}function compactToonArray(values,policy,preserveEmpty){const compactedEntries=values.map(entry=>compactToonValue(entry,policy,preserveEmpty||policy.preserveRowFacts&&isPlainObject(entry))).filter(entry=>entry!==void 0);return compactedEntries.length>0||preserveEmpty?compactedEntries:void 0}function compactToonValue(value,policy={omitDuplicateCountAliases:!0,preserveRowFacts:!0},preserveEmpty=!1){if(value===null)return preserveEmpty?null:void 0;if(Array.isArray(value))return compactToonArray(value,policy,preserveEmpty);if(isPlainObject(value)){const compacted=[],entries=Object.entries(value).filter(([key,entry])=>{const canonicalCount=COLLECTION_COUNT_ALIASES.get(key);return!policy.omitDuplicateCountAliases||canonicalCount===void 0||!isPlainObject(value.collection_counts)||entry!==value.collection_counts[canonicalCount]});for(const[key,entry]of entries){if(key==="omitted_field_groups"&&Array.isArray(entry)&&entry.length===0){compacted.push([key,[]]);continue}const compactedEntry=compactToonValue(entry,policy,preserveEmpty);compactedEntry!==void 0&&compacted.push([key,compactedEntry])}return compacted.length>0||preserveEmpty?Object.fromEntries(compacted):void 0}return value}function renderToonValue(value,depth){const indent=" ".repeat(depth);if(Array.isArray(value))return value.length===0?"[]":indentToon(encodeToon(value),depth);if(isPlainObject(value)){const entries=Object.entries(value);return entries.length===0?"{}":entries.map(([key,entry])=>renderToonObjectEntry(key,entry,depth,!Object.hasOwn(value,`${key}_encoding`)&&!(key==="checks"&&isPlainObject(value.verdict)&&value.verdict.authority==="ok"))).join(`
|
|
5
5
|
`)}return`${indent}${renderScalar(value)}`}function renderDefaultMarkdownResult(value){if(!isPlainObject(value)||value.output_default!=="markdown"||typeof value.view!="string"||!Array.isArray(value.events)||!Array.isArray(value.days))return null;const lines=[`# pm calendar (${value.view})`,""],summary=isPlainObject(value.summary)?value.summary:{};if(lines.push(`- events: ${String(summary.events??0)}`),lines.push(""),value.events.length===0)return lines.push("No calendar events matched the selected filters."),`${lines.join(`
|
|
6
6
|
`)}
|
|
7
7
|
`;for(const event of value.events){if(!isPlainObject(event))continue;const kind=typeof event.kind=="string"?event.kind:"event",title=typeof event.item_title=="string"?event.item_title:"",itemId=typeof event.item_id=="string"?event.item_id:"",reminderText=typeof event.reminder_text=="string"&&event.reminder_text.length>0?` ${event.reminder_text}`:"";lines.push(`- [${kind}] ${itemId} ${title}${reminderText}`.trim())}return`${lines.join(`
|
|
8
8
|
`)}
|
|
9
|
-
`}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value
|
|
10
|
-
|
|
9
|
+
`}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectLinkedTestEvidence(value,lean){if(!isPlainObject(value)||!Array.isArray(value.run_results)||!value.run_results.every(isPlainObject))return value;const rows=value.run_results,contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0),sharedContext=contexts.length===rows.length&&contexts.length>0&&contexts.every(context=>JSON.stringify(context)===JSON.stringify(contexts[0]))?contexts[0]:void 0,runResults=rows.map(row=>{const{execution_context:_executionContext,stdout,stderr,...rest}=row;return sharedContext===void 0?row:!lean||row.status!=="passed"?{...rest,stdout,stderr}:rest});return{...value,...sharedContext===void 0?{}:{execution_context:sharedContext},run_results:runResults}}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1){if(format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
|
|
10
|
+
`}const compactedToon=compactToonValue(projectEmptyCheckDetails(projectPmBriefListEnvelope(result)),{omitDuplicateCountAliases:!0,preserveRowFacts:!0});return compactedToon===void 0?`{}
|
|
11
11
|
`:`${renderToonValue(compactedToon,0)}
|
|
12
12
|
`}function resolveOutputService(effectiveResult,nativeOutput,options,format){const serviceOverride=nativeOutput?{handled:!1,result:effectiveResult,warnings:[]}:runActiveServiceOverrideSync("output_format",{command:options.command,args:options.commandArgs,command_options:options.commandOptions,global:{...options},pm_root:options.pmRoot,format,options:{...options},result:effectiveResult}),legacyPayloadEchoWarning=serviceOverride.warnings.find(warning=>warning.startsWith("extension_output_format_payload_echo_deprecated:"));return legacyPayloadEchoWarning!==void 0&&writeStderr(`Warning: ${legacyPayloadEchoWarning}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
|
|
13
13
|
`),serviceOverride.handled&&typeof serviceOverride.result=="string"?{result:serviceOverride.result,rendered:serviceOverride.result.endsWith(`
|
|
14
14
|
`)?serviceOverride.result:`${serviceOverride.result}
|
|
15
15
|
`,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat){const activeCommandContext=getActiveCommandContext(),command=options.command??activeCommandContext?.command,commandOptions={...activeCommandContext?.options,...options.commandOptions,...Object.fromEntries([["outputInclude",options.outputInclude],["outputLimit",options.outputLimit],["outputBudget",options.outputBudget],["outputFormat",options.outputFormat],["outputSession",options.outputSession],["outputCursor",options.outputCursor],["outputRowContract",options.outputRowContract]].filter(entry=>entry[1]!==void 0))},format=resolveReadOutputEncoding(command??"",commandOptions)??defaultFormat,resolvedCommandOptions={...commandOptions,resolvedOutputFormat:format},effectiveOptions={...options,command,commandOptions:resolvedCommandOptions},service=resolveOutputService(effectiveResult,nativeOutput,effectiveOptions,format);if(service.rendered!==null)return setActiveCommandResultOmitted(effectiveResult),service.rendered;const outputResult=service.result;propagateContextUsageServingReceipt(effectiveResult,outputResult);const projectedOutputResult=command==="test"?projectLinkedTestEvidence(outputResult,options.lean===!0):outputResult,intentOutputResult=attachReadOutputContracts(command,resolvedCommandOptions,projectedOutputResult);isReadOutputBudgetExceeded(intentOutputResult)&&(process.exitCode||=EXIT_CODE.USAGE);let{structuredDeliveryPreserved}=service;const renderResolvedOutput=value=>{if(format==="toon"){const markdownDefault=renderDefaultMarkdownResult(value);if(markdownDefault!==null)return markdownDefault}const rendererOverride=nativeOutput?{rendered:null}:runActiveRendererOverride(format,value);return rendererOverride.rendered!==null?(structuredDeliveryPreserved=!1,rendererOverride.rendered.endsWith(`
|
|
16
16
|
`)?rendererOverride.rendered:`${rendererOverride.rendered}
|
|
17
|
-
`):format==="json"?formatBuiltInOutput(options.lean===!0
|
|
17
|
+
`):format==="json"?formatBuiltInOutput(value,"json",options.lean===!0):formatBuiltInOutput(value,"toon")},accountedOutputResult=options.tokenAccounting===!0?attachOutputTokenAccounting(intentOutputResult,renderResolvedOutput):intentOutputResult,rendered=renderResolvedOutput(accountedOutputResult);return setActiveCommandDeliveryResult(accountedOutputResult,effectiveResult,options.quiet!==!0&&structuredDeliveryPreserved),rendered}function formatOutput(result,options){const commandOverride=runActiveCommandOverride(result),suppressedOutput=isHostOutputSuppressed(commandOverride.result)?commandOverride.result:null,nativeResult=commandOverride.result,nativeOutput=isPlainObject(nativeResult)&&nativeResult[NATIVE_OUTPUT_MARKER]===!0,effectiveResult=suppressedOutput?suppressedOutput.result:stripNativeOutputMarker(commandOverride.result);if(setActiveCommandResult(effectiveResult),suppressedOutput)return setActiveCommandResultOmitted(effectiveResult),"";const defaultFormat=options.json===!0||options.json===void 0&&options.defaultOutputFormat==="json"?"json":"toon";return formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat)}function printResult(result,options){isPlainObject(result)&&Number.isInteger(result.exit_code)&&DECLARED_PROCESS_EXIT_CODES.has(Number(result.exit_code))&&(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=Number(result.exit_code));const projected=options.idOnly?projectMutationResult(result,{idOnly:!0}):options.fullChangedFields?result:options.noChangedFields?projectMutationResult(result,{changedFields:"compact"}):projectMutationResult(result,{compactEnvelope:!0}),rendered=formatOutput(projected,options);options.quiet||writeStdout(rendered)}function printError(message){const override=runActiveServiceOverrideSync("error_format",{message}),rendered=override.handled&&typeof override.result=="string"?override.result:message;writeStderr(rendered.endsWith(`
|
|
18
18
|
`)?rendered:`${rendered}
|
|
19
19
|
`)}const outputTestOnly={compactToonValue,renderToonValue};export{formatBuiltInOutput,formatOutput,outputTestOnly,printError,printResult,writeStderr,writeStdout};
|
|
20
20
|
//# sourceMappingURL=output.js.map
|