@unbrained/pm-cli 2026.10.8 → 2026.10.9

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.
Files changed (90) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +17 -0
  3. package/dist/cli/register-list-query.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +151 -151
  5. package/dist/cli-bundle/chunks/{chunk-ZHIMZ65M.js → chunk-55MK3QQM.js} +30 -30
  6. package/dist/cli-bundle/chunks/{chunk-34L2BS2Z.js → chunk-5MOFELIF.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-ZBVAZ7XX.js → chunk-5NR6TDYB.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-OG66KEOF.js → chunk-5TCQ5J3V.js} +74 -78
  9. package/dist/cli-bundle/chunks/{chunk-K6E2FFUT.js → chunk-CPZOW6L2.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-TNU56MZI.js → chunk-E4XR5LKU.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-RCFZ6H2Y.js → chunk-KOGF6O6W.js} +3 -3
  12. package/dist/cli-bundle/chunks/{chunk-JDTBPW4Y.js → chunk-N7GKWO4G.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-L7U5FSZ5.js → chunk-NIF7JOPW.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-MJVRF67I.js → chunk-P5NS7EFC.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-HFCIAXLP.js → chunk-QQHNXCO3.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-FOLSEOJ2.js → chunk-XW3BLWFF.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-UGFN5NJ2.js → chunk-ZNXRGATT.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-list-query-PYVSPGPV.js → register-list-query-2YOWMNWY.js} +7 -7
  19. package/dist/cli-bundle/chunks/{register-mutation-WXP3YLIN.js → register-mutation-ILOWFMTV.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-operations-WL25C3NP.js → register-operations-BMK65YM3.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-setup-PFKYNEQI.js → register-setup-24TFFK6N.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/{chunk-PEBOVLEG.js → chunk-2ATAD56F.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-6TKAFFEB.js → chunk-2CJWTLQG.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-EOUORVJA.js → chunk-362645PL.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-V3EPBB6V.js → chunk-AU6VJGTY.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-L3CZNKZE.js → chunk-B3YW6H2I.js} +16 -20
  27. package/dist/cli-bundle/focused-chunks/{chunk-XT7JAVHI.js → chunk-DMSADMEU.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-2KSPGWLH.js → chunk-DSLNUL2Q.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-A3W6HFFO.js → chunk-EZ4367G4.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-MW2TQHZ3.js → chunk-IARAEFMA.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-OSKXYRYZ.js → chunk-MCVWZUGK.js} +27 -27
  32. package/dist/cli-bundle/focused-chunks/{chunk-F2ME5MJY.js → chunk-PBCYGO7X.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-PBPPIGUL.js → chunk-PLTTMQAW.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-OLCJ2PJS.js → chunk-SAN3KPX4.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-DRHJOG5X.js → chunk-W5AE7GKZ.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-LZQGEVKT.js → chunk-WAOXID5J.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-BDT5EALU.js → chunk-WOEZJUA2.js} +2 -2
  38. package/dist/cli-bundle/main.js +2 -2
  39. package/dist/cli-bundle/sdk-authoring.js +1 -1
  40. package/dist/cli-bundle/sdk-contracts.js +1 -1
  41. package/dist/cli-bundle/sdk-core.js +22 -22
  42. package/dist/cli-bundle/sdk-governance.js +1 -1
  43. package/dist/cli-bundle/sdk-graph.js +1 -1
  44. package/dist/cli-bundle/sdk-merge.js +50 -50
  45. package/dist/cli-bundle/sdk-query.js +1 -1
  46. package/dist/cli-bundle/sdk-runtime.js +1 -1
  47. package/dist/cli-bundle/sdk-testing.js +1 -1
  48. package/dist/cli-bundle/sdk.js +7 -7
  49. package/dist/core/history/event-index.d.ts +1 -2
  50. package/dist/core/history/event-index.js +2 -2
  51. package/dist/core/output/output.d.ts +16 -14
  52. package/dist/core/output/output.js +6 -10
  53. package/dist/core/store/item-metadata-query-index.d.ts +1 -2
  54. package/dist/core/store/item-metadata-query-index.js +1 -1
  55. package/dist/core/store/sqlite-runtime.d.ts +15 -0
  56. package/dist/core/store/sqlite-runtime.js +2 -0
  57. package/dist/sdk/output/table-rows.d.ts +37 -0
  58. package/dist/sdk/output/table-rows.js +2 -0
  59. package/dist/sdk/output.d.ts +1 -0
  60. package/dist/sdk/output.js +2 -2
  61. package/dist/sdk/public-surface.json +1 -1
  62. package/dist/sdk/read-output-contracts.d.ts +3 -3
  63. package/dist/sdk/read-output-contracts.js +1 -1
  64. package/dist/sdk/test/workspace-snapshot.d.ts +1 -1
  65. package/dist/sdk/test/workspace-snapshot.js +1 -1
  66. package/docs/AGENT_OUTPUT_ENCODINGS.md +119 -0
  67. package/docs/PACKAGE_GATE_ACCEPTANCE.md +56 -0
  68. package/docs/README.md +2 -0
  69. package/docs/TESTING.md +11 -3
  70. package/marketplace.json +2 -2
  71. package/package.json +1 -1
  72. package/packages/pm-beads/package.json +1 -1
  73. package/packages/pm-calendar/package.json +1 -1
  74. package/packages/pm-command-kit/package.json +1 -1
  75. package/packages/pm-digital-twin/package.json +1 -1
  76. package/packages/pm-governance-audit/package.json +1 -1
  77. package/packages/pm-guide-shell/package.json +1 -1
  78. package/packages/pm-kanban/package.json +1 -1
  79. package/packages/pm-lifecycle-hooks/package.json +1 -1
  80. package/packages/pm-linked-test-adapters/package.json +1 -1
  81. package/packages/pm-search-advanced/package.json +1 -1
  82. package/packages/pm-templates/package.json +1 -1
  83. package/packages/pm-todos/package.json +1 -1
  84. package/packages/pm-vcs/package.json +1 -1
  85. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  86. package/plugins/pm-claude/package.json +2 -2
  87. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  88. package/plugins/pm-codex/package.json +2 -2
  89. package/plugins/pm-codex/plugin.json +1 -1
  90. package/runtime-dependencies.json +2 -2
@@ -1,5 +1,6 @@
1
1
  import type { DatabaseSync } from "node:sqlite";
2
2
  import type { HistoryEntry } from "../../types/index.js";
3
+ import { loadDatabaseSync, loadStableDatabaseSync } from "../store/sqlite-runtime.js";
3
4
  type DatabaseSyncConstructor = typeof DatabaseSync;
4
5
  /** Stable location of one history entry inside its authoritative stream. */
5
6
  export interface IndexedHistoryEvent {
@@ -49,8 +50,6 @@ export interface HistoryEventIndexQueryResult {
49
50
  }
50
51
  /** Latest substantive immutable event for each requested history stream. */
51
52
  export type LatestSubstantiveHistoryEvents = Readonly<Record<string, IndexedHistoryEvent>>;
52
- declare function loadDatabaseSync(loadModule: (specifier: string) => unknown): DatabaseSyncConstructor | null;
53
- declare function loadStableDatabaseSync(nodeVersion: string, loadModule: (specifier: string) => unknown): DatabaseSyncConstructor | null;
54
53
  /** Rebuild the complete optional event projection from authoritative streams. */
55
54
  export declare function rebuildHistoryEventIndex(pmRoot: string): Promise<boolean>;
56
55
  /**
@@ -1,5 +1,5 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a70d2ff9-9664-5cad-9657-ab9c54422bc2")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";import{isFileMissingError}from"../fs/fs-utils.js";import{acquireLock,captureProcessIdentity,isProcessIdentityAlive}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";const EVENT_INDEX_FILENAME="history-event-index.sqlite",EVENT_INDEX_VERSION="5",AUTHORITATIVE_HISTORY_CACHE_LIMIT=8,HISTORY_EVENT_INDEX_LOCK_ID="history-event-index",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_LOCK_CONTENDED=Symbol("history-index-lock-contended"),authoritativeHistoryCaches=new Map;function eventIndexPath(pmRoot){return path.join(pmRoot,"runtime",EVENT_INDEX_FILENAME)}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){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,HISTORY_EVENT_INDEX_LOCK_WAIT_MS);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
2
- `,{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 withHistoryEventIndexLock(pmRoot,operation){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index:${process.pid}`,!1,!1,HISTORY_EVENT_INDEX_LOCK_WAIT_MS);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}function loadDatabaseSync(loadModule){try{return loadModule(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function loadStableDatabaseSync(nodeVersion,loadModule){const nodeMajor=Number.parseInt(nodeVersion,10);return Number.isFinite(nodeMajor)&&nodeMajor>=22?loadDatabaseSync(loadModule):null}let RuntimeDatabaseSync;function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function createSchema(database){database.exec(`
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]="59e8ff0e-d2af-5f7a-a64b-1b86e075acdc")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";import{isFileMissingError}from"../fs/fs-utils.js";import{acquireLock,captureProcessIdentity,isProcessIdentityAlive}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="5",AUTHORITATIVE_HISTORY_CACHE_LIMIT=8,HISTORY_EVENT_INDEX_LOCK_ID="history-event-index",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_LOCK_CONTENDED=Symbol("history-index-lock-contended"),authoritativeHistoryCaches=new Map;function eventIndexPath(pmRoot){return path.join(pmRoot,"runtime",EVENT_INDEX_FILENAME)}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){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,HISTORY_EVENT_INDEX_LOCK_WAIT_MS);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
2
+ `,{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 withHistoryEventIndexLock(pmRoot,operation){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index:${process.pid}`,!1,!1,HISTORY_EVENT_INDEX_LOCK_WAIT_MS);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(`
3
3
  PRAGMA journal_mode = OFF;
4
4
  PRAGMA synchronous = OFF;
5
5
  CREATE TABLE metadata (
@@ -1,8 +1,8 @@
1
- /** Documents the output options payload exchanged by command, SDK, and package integrations. */
1
+ /** Host output controls shared by command execution and extension rendering. */
2
2
  export interface OutputOptions {
3
- /** Value that configures or reports json for this contract. */
3
+ /** Select JSON explicitly; otherwise use the host default format. */
4
4
  json?: boolean;
5
- /** Value that configures or reports quiet for this contract. */
5
+ /** Suppress process output while retaining the active command result. */
6
6
  quiet?: boolean;
7
7
  /** When true, mutation results drop the verbose changed_fields array (keeps changed_field_count). */
8
8
  noChangedFields?: boolean;
@@ -30,20 +30,22 @@ export interface OutputOptions {
30
30
  outputRowContract?: boolean;
31
31
  /** Fallback output format used when callers do not provide an override. */
32
32
  defaultOutputFormat?: "toon" | "json";
33
- /** Value that configures or reports command for this contract. */
33
+ /** Command identity used to resolve read contracts and extension overrides. */
34
34
  command?: string;
35
- /** Value that configures or reports command args for this contract. */
35
+ /** Positional arguments passed to the output service override. */
36
36
  commandArgs?: string[];
37
- /** Inputs that customize the command operation. */
37
+ /** Command options merged with active invocation options for output contracts. */
38
38
  commandOptions?: Record<string, unknown>;
39
- /** Value that configures or reports pm root for this contract. */
39
+ /** Tracker root supplied to the output service override. */
40
40
  pmRoot?: string;
41
41
  }
42
- /** Implements write stdout for the public runtime surface of this module. */
42
+ /** Write stdout and return false when its consumer has closed the pipe. */
43
43
  export declare function writeStdout(text: string): boolean;
44
- /** Implements write stderr for the public runtime surface of this module. */
44
+ /** Write stderr and preserve diagnostic delivery failures in the process exit code. */
45
45
  export declare function writeStderr(text: string): boolean;
46
- declare function compactToonValue(value: unknown): unknown | undefined;
46
+ /** Keep sparse presentation rules shared while allowing lean JSON to retain count aliases. */
47
+ declare function compactToonValue(value: unknown, omitDuplicateCountAliases?: boolean): unknown | undefined;
48
+ /** Render objects recursively and arrays through the standard TOON encoder. */
47
49
  declare function renderToonValue(value: unknown, depth: number): string;
48
50
  /**
49
51
  * Render a result with pm's built-in JSON or TOON formatter without invoking
@@ -51,13 +53,13 @@ declare function renderToonValue(value: unknown, depth: number): string;
51
53
  * so reported token cost describes the bytes the host emits by default.
52
54
  */
53
55
  export declare function formatBuiltInOutput(result: unknown, format: "json" | "toon"): string;
54
- /** Implements format output for the public runtime surface of this module. */
56
+ /** Resolve command ownership and suppression before projecting and rendering the result. */
55
57
  export declare function formatOutput(result: unknown, options: OutputOptions): string;
56
- /** Implements print result for the public runtime surface of this module. */
58
+ /** Apply declared exit codes and mutation projection before writing a nonquiet result. */
57
59
  export declare function printResult(result: unknown, options: OutputOptions): void;
58
- /** Implements print error for the public runtime surface of this module. */
60
+ /** Apply the error service override and emit one newline-terminated diagnostic. */
59
61
  export declare function printError(message: string): void;
60
- /** Public contract for output test only, shared by SDK and presentation-layer consumers. */
62
+ /** Internal rendering seams retained for deterministic presentation regression tests. */
61
63
  export declare const outputTestOnly: {
62
64
  compactToonValue: typeof compactToonValue;
63
65
  renderToonValue: typeof renderToonValue;
@@ -1,24 +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]="226eaad9-e87a-5ee9-a35b-e1a6f05b8965")}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";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),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 shouldUseNativeOutput(result){return isPlainObject(result)&&result[NATIVE_OUTPUT_MARKER]===!0}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 isToonPrimitive(value){return value===null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"}function tabularObjectArray(value){if(value.length===0||!value.every(isPlainObject))return!1;const keys=Object.keys(value[0]);return keys.length>0&&value.every(entry=>Object.keys(entry).length===keys.length&&keys.every(key=>Object.hasOwn(entry,key)&&isToonPrimitive(entry[key])))}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="391a4170-d29a-5c61-a0db-05181ebb0239")}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";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
- `)}function renderToonObjectEntry(key,entry,depth){const indent=" ".repeat(depth);return!isPlainObject(entry)&&!Array.isArray(entry)?`${indent}${key}: ${renderScalar(entry)}`:Array.isArray(entry)&&entry.length===0?`${indent}${key}: []`:Array.isArray(entry)&&tabularObjectArray(entry)?indentToon(encodeToon({[key]:entry}),depth):isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
4
- ${renderToonValue(entry,depth+1)}`}function compactToonValue(value){if(value!=null){if(Array.isArray(value)){const compactedEntries=value.map(entry=>compactToonValue(entry)).filter(entry=>entry!==void 0);return compactedEntries.length>0?compactedEntries:void 0}if(isPlainObject(value)){const compacted={};for(const[key,entry]of Object.entries(value)){if(key==="omitted_field_groups"&&Array.isArray(entry)&&entry.length===0){compacted[key]=[];continue}const compactedEntry=compactToonValue(entry);compactedEntry!==void 0&&(compacted[key]=compactedEntry)}return Object.keys(compacted).length>0?compacted:void 0}return value}}function renderToonValue(value,depth){const indent=" ".repeat(depth);if(Array.isArray(value))return value.length===0?"[]":tabularObjectArray(value)?indentToon(encodeToon(value),depth):value.map(entry=>{if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}- ${renderScalar(entry)}`;const lines=renderToonValue(entry,depth+1).split(`
5
- `),[firstLine,...rest]=lines;return rest.length===0?`${indent}- ${firstLine.trimStart()}`:`${indent}- ${firstLine.trimStart()}
6
- ${rest.join(`
7
- `)}`}).join(`
8
- `);if(isPlainObject(value)){const entries=Object.entries(value);return entries.length===0?"{}":entries.map(([key,entry])=>renderToonObjectEntry(key,entry,depth)).join(`
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 compactToonValue(value,omitDuplicateCountAliases=!0){if(value!=null){if(Array.isArray(value)){const compactedEntries=value.map(entry=>compactToonValue(entry,omitDuplicateCountAliases)).filter(entry=>entry!==void 0);return compactedEntries.length>0?compactedEntries:void 0}if(isPlainObject(value)){const compacted={},entries=Object.entries(value).filter(([key,entry])=>{const canonicalCount=COLLECTION_COUNT_ALIASES.get(key);return!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[key]=[];continue}const compactedEntry=compactToonValue(entry,omitDuplicateCountAliases);compactedEntry!==void 0&&(compacted[key]=compactedEntry)}return Object.keys(compacted).length>0?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`))).join(`
9
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(`
10
6
  `)}
11
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(`
12
8
  `)}
13
- `}function resolveOutputFormat(options){return options.json===!0||options.json===void 0&&options.defaultOutputFormat==="json"?"json":"toon"}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value);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 projectCompleteBriefList(value){if(!isPlainObject(value)||!Array.isArray(value.items)||Object.hasOwn(value,"details")||!isPlainObject(value.projection)||value.projection.mode!=="brief"||!isPlainObject(value.completeness)||value.completeness.status!=="complete"||[value.completeness.unreadable_item_count,value.completeness.unreadable_directory_count].some(count=>count!==0)||[value.has_more,value.truncated].some(flag=>flag!==!1)||value.count!==value.items.length||value.total!==value.count||!isPlainObject(value.omission_receipt)||JSON.stringify(value.omission_receipt.omitted_field_groups)!==JSON.stringify([{name:"full_item_fields",restore_with:"--full"}]))return value;const{total:_total,has_more:_hasMore,truncated:_truncated,next_cursor:_nextCursor,completeness:_completeness,projection:_projection,now:_now,omission_receipt:_omissions,sorting,...rest}=value;return{...rest,...isPlainObject(sorting)&&sorting.sort==="default"?{}:{sorting},details:"--full"}}function formatBuiltInOutput(result,format){if(format==="json")return`${JSON.stringify(result,null,2)}
9
+ `}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,!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 projectCompleteBriefList(value){if(!isPlainObject(value)||!Array.isArray(value.items)||Object.hasOwn(value,"details")||!isPlainObject(value.projection)||value.projection.mode!=="brief"||!isPlainObject(value.completeness)||value.completeness.status!=="complete"||[value.completeness.unreadable_item_count,value.completeness.unreadable_directory_count].some(count=>count!==0)||[value.has_more,value.truncated].some(flag=>flag!==!1)||value.count!==value.items.length||value.total!==value.count||!isPlainObject(value.omission_receipt)||JSON.stringify(value.omission_receipt.omitted_field_groups)!==JSON.stringify([{name:"full_item_fields",restore_with:"--full"}]))return value;const{total:_total,has_more:_hasMore,truncated:_truncated,next_cursor:_nextCursor,completeness:_completeness,projection:_projection,now:_now,omission_receipt:_omissions,sorting,...rest}=value;return{...rest,...isPlainObject(sorting)&&sorting.sort==="default"?{}:{sorting},details:"--full"}}function formatBuiltInOutput(result,format){if(format==="json")return`${JSON.stringify(result,null,2)}
14
10
  `;const compactedToon=compactToonValue(projectCompleteBriefList(result));return compactedToon===void 0?`{}
15
11
  `:`${renderToonValue(compactedToon,0)}
16
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 }.
17
13
  `),serviceOverride.handled&&typeof serviceOverride.result=="string"?{result:serviceOverride.result,rendered:serviceOverride.result.endsWith(`
18
14
  `)?serviceOverride.result:`${serviceOverride.result}
19
- `,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options){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)??resolveOutputFormat(options),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(`
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(`
20
16
  `)?rendererOverride.rendered:`${rendererOverride.rendered}
21
- `):format==="json"?formatBuiltInOutput(options.lean===!0?projectLeanJsonValue(value):value,"json"):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,nativeOutput=shouldUseNativeOutput(commandOverride.result),effectiveResult=suppressedOutput?suppressedOutput.result:stripNativeOutputMarker(commandOverride.result);return setActiveCommandResult(effectiveResult),suppressedOutput?(setActiveCommandResultOmitted(effectiveResult),""):formatEffectiveOutput(effectiveResult,nativeOutput,options)}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(`
17
+ `):format==="json"?formatBuiltInOutput(options.lean===!0?projectLeanJsonValue(value):value,"json"):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(`
22
18
  `)?rendered:`${rendered}
23
19
  `)}const outputTestOnly={compactToonValue,renderToonValue};export{formatBuiltInOutput,formatOutput,outputTestOnly,printError,printResult,writeStderr,writeStdout};
24
20
  //# sourceMappingURL=output.js.map
@@ -1,8 +1,7 @@
1
1
  import type { DatabaseSync } from "node:sqlite";
2
2
  import type { ItemMetadata, LinkedFile, LinkScope } from "../../types/index.js";
3
+ import { loadDatabaseSync, loadStableDatabaseSync } from "./sqlite-runtime.js";
3
4
  type DatabaseSyncConstructor = typeof DatabaseSync;
4
- declare function loadDatabaseSync(loadModule: (specifier: string) => unknown): DatabaseSyncConstructor | null;
5
- declare function loadStableDatabaseSync(nodeVersion: string, loadModule: (specifier: string) => unknown): DatabaseSyncConstructor | null;
6
5
  /** One light-metadata row projected into the persistent query index. */
7
6
  export interface ItemMetadataQueryIndexRow {
8
7
  /** Tracker-relative authoritative item path. */
@@ -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]="e10ab0c5-e777-5364-b7fb-464e42400ab2")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";const QUERY_INDEX_FILENAME="metadata-query-index.sqlite",QUERY_INDEX_VERSION="5";function loadDatabaseSync(loadModule){try{return loadModule(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}let RuntimeDatabaseSync;function loadStableDatabaseSync(nodeVersion,loadModule){const nodeMajor=Number.parseInt(nodeVersion,10);return Number.isFinite(nodeMajor)&&nodeMajor>=22?loadDatabaseSync(loadModule):null}function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function normalizeIndexWindowValue(value,fallback){return Math.max(0,Math.floor(value===void 0?fallback:value))}function queryIndexPath(pmRoot){return path.join(pmRoot,"runtime",QUERY_INDEX_FILENAME)}function createSchema(database){database.exec(`
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]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";import{loadDatabaseSync,loadStableDatabaseSync}from"./sqlite-runtime.js";const QUERY_INDEX_FILENAME="metadata-query-index.sqlite",QUERY_INDEX_VERSION="5";let RuntimeDatabaseSync;function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function normalizeIndexWindowValue(value,fallback){return Math.max(0,Math.floor(value===void 0?fallback:value))}function queryIndexPath(pmRoot){return path.join(pmRoot,"runtime",QUERY_INDEX_FILENAME)}function createSchema(database){database.exec(`
2
2
  PRAGMA foreign_keys = ON;
3
3
  PRAGMA journal_mode = OFF;
4
4
  PRAGMA synchronous = OFF;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @module core/store/sqlite-runtime
3
+ * Loads the optional native accelerator without its one-time experimental
4
+ * announcement contaminating CLI machine channels. Application warnings retain
5
+ * their original delivery; no environment or asynchronous warning policy changes.
6
+ */
7
+ import type { DatabaseSync } from "node:sqlite";
8
+ /**
9
+ * Load synchronously and filter only Node's exact SQLite announcement during
10
+ * that call. Restore the prior emitter even when the optional module is absent.
11
+ * The caller still receives every other warning with its original arguments.
12
+ */
13
+ export declare function loadDatabaseSync(loadModule: (specifier: string) => unknown): typeof DatabaseSync | null;
14
+ /** Skip native probing on runtimes below the supported SQLite capability floor. */
15
+ export declare function loadStableDatabaseSync(nodeVersion: string, loadModule: (specifier: string) => unknown): typeof DatabaseSync | null;
@@ -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]="812b558d-59f3-58d6-b04e-6a4f8689e866")}catch{}})();function loadDatabaseSync(loadModule){const emitWarning=process.emitWarning;process.emitWarning=(warning,...args)=>{warning==="SQLite is an experimental feature and might change at any time"&&args[0]==="ExperimentalWarning"||Reflect.apply(emitWarning,process,[warning,...args])};try{return loadModule(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=emitWarning}}function loadStableDatabaseSync(nodeVersion,loadModule){const nodeMajor=Number.parseInt(nodeVersion,10);return Number.isFinite(nodeMajor)&&nodeMajor>=22?loadDatabaseSync(loadModule):null}export{loadDatabaseSync,loadStableDatabaseSync};
2
+ //# sourceMappingURL=sqlite-runtime.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @module sdk/output/table-rows
3
+ *
4
+ * Lossless nested-cell projection for key-hoisted agent tables. Scalar columns
5
+ * retain their types; declared JSON columns and absent coordinates restore the
6
+ * original rows without confusing missing fields with explicit null values.
7
+ */
8
+ import type { JsonValue } from "@toon-format/toon";
9
+ /** Metadata required to restore nested cells and sparse object rows. */
10
+ export interface PmTableCellEncoding {
11
+ /** Columns whose every present cell contains a JSON-serialized value. */
12
+ json_columns: string[];
13
+ /** Missing field coordinates, expressed as [zero-based row, column name]. */
14
+ absent: Array<[number, string]>;
15
+ }
16
+ /** Primitive rows accepted by the standard TOON tabular encoder. */
17
+ export interface PmEncodedTableRows {
18
+ /** Key-hoisted rows with primitive cells and null padding for absent keys. */
19
+ rows: Record<string, string | number | boolean | null>[];
20
+ /** Explicit decoding metadata; never inferred from cell content. */
21
+ encoding: PmTableCellEncoding;
22
+ }
23
+ /**
24
+ * Project JSON object rows into a lossless table, preserving key order by first
25
+ * occurrence. A column containing any container serializes all present values
26
+ * as JSON so mixed strings, nulls, arrays, and objects remain unambiguous.
27
+ * Allocation is proportional to rows times distinct columns; callers budget
28
+ * that dense grid before encoding sparse inputs. The host formatter preflights
29
+ * automatic candidates and falls back to expanded TOON for sparse grids.
30
+ */
31
+ export declare function encodePmTableRows(rows: readonly Record<string, JsonValue>[]): PmEncodedTableRows;
32
+ /**
33
+ * Restore rows emitted by {@link encodePmTableRows}. Metadata is explicit, so
34
+ * strings resembling JSON stay strings unless their column declares JSON.
35
+ * Malformed JSON cells throw instead of silently changing their meaning.
36
+ */
37
+ export declare function decodePmTableRows(table: PmEncodedTableRows): Record<string, JsonValue>[];
@@ -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]="8936e93f-25bf-58cc-ba91-37cc2677c5d2")}catch{}})();function encodePmTableRows(rows){const columns=[...new Set(rows.flatMap(row=>Object.keys(row)))],jsonColumns=columns.filter(column=>rows.some(row=>{const cell=row[column];return cell!==null&&typeof cell=="object"})),nested=new Set(jsonColumns),absent=[];return{rows:rows.map((row,index)=>Object.fromEntries(columns.map(column=>{if(!Object.hasOwn(row,column))return absent.push([index,column]),[column,null];const cell=row[column];return[column,nested.has(column)?JSON.stringify(cell):cell]}))),encoding:{json_columns:jsonColumns,absent}}}function decodePmTableRows(table){const nested=new Set(table.encoding.json_columns),absent=new Set(table.encoding.absent.map(([row,column])=>JSON.stringify([row,column])));return table.rows.map((row,index)=>Object.fromEntries(Object.entries(row).flatMap(([column,cell])=>absent.has(JSON.stringify([index,column]))?[]:[[column,nested.has(column)?JSON.parse(String(cell)):cell]])))}export{decodePmTableRows,encodePmTableRows};
2
+ //# sourceMappingURL=table-rows.js.map
@@ -5,6 +5,7 @@
5
5
  * renderers, and custom SDK-built hosts.
6
6
  */
7
7
  export { SUPPRESS_HOST_OUTPUT_MARKER, isHostOutputSuppressed, suppressHostOutput, type SuppressedHostOutput, } from "../core/output/output-control.js";
8
+ export { encodePmTableRows, decodePmTableRows, type PmTableCellEncoding, type PmEncodedTableRows, } from "./output/table-rows.js";
8
9
  /**
9
10
  * Serialize object rows as newline-delimited JSON without adding a trailing
10
11
  * newline. CLI hosts can append their final newline while SDK consumers can
@@ -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]="0b246b9c-4fb8-50ed-9fa9-c7d90f8ba87f")}catch{}})();import{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput}from"../core/output/output-control.js";function serializeNdjsonRows(rows){return rows.map((row,index)=>{if(typeof row!="object"||row===null||Array.isArray(row))throw new TypeError(`NDJSON row ${index} must be a non-null object.`);const serialized=JSON.stringify(row);if(serialized===void 0)throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);const projected=JSON.parse(serialized);if(typeof projected!="object"||projected===null||Array.isArray(projected))throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);return serialized}).join(`
2
- `)}function serializeNdjsonStream(rows,trailer){if(trailer.count!==rows.length)throw new TypeError(`NDJSON trailer count ${trailer.count} does not match ${rows.length} ${rows.length===1?"row":"rows"}.`);for(const[index,row]of rows.entries())if(typeof row=="object"&&row!==null&&!Array.isArray(row)&&Reflect.get(row,"record_type")==="pm.stream.trailer")throw new TypeError(`NDJSON row ${index} uses reserved record_type pm.stream.trailer`);return serializeNdjsonRows([...rows,{...trailer,record_type:"pm.stream.trailer"}])}export{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,serializeNdjsonRows,serializeNdjsonStream,suppressHostOutput};
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]="1a6915d3-31fe-5269-b945-caef21172c86")}catch{}})();import{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput}from"../core/output/output-control.js";import{encodePmTableRows,decodePmTableRows}from"./output/table-rows.js";function serializeNdjsonRows(rows){return rows.map((row,index)=>{if(typeof row!="object"||row===null||Array.isArray(row))throw new TypeError(`NDJSON row ${index} must be a non-null object.`);const serialized=JSON.stringify(row);if(serialized===void 0)throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);const projected=JSON.parse(serialized);if(typeof projected!="object"||projected===null||Array.isArray(projected))throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);return serialized}).join(`
2
+ `)}function serializeNdjsonStream(rows,trailer){if(trailer.count!==rows.length)throw new TypeError(`NDJSON trailer count ${trailer.count} does not match ${rows.length} ${rows.length===1?"row":"rows"}.`);for(const[index,row]of rows.entries())if(typeof row=="object"&&row!==null&&!Array.isArray(row)&&Reflect.get(row,"record_type")==="pm.stream.trailer")throw new TypeError(`NDJSON row ${index} uses reserved record_type pm.stream.trailer`);return serializeNdjsonRows([...rows,{...trailer,record_type:"pm.stream.trailer"}])}export{SUPPRESS_HOST_OUTPUT_MARKER,decodePmTableRows,encodePmTableRows,isHostOutputSuppressed,serializeNdjsonRows,serializeNdjsonStream,suppressHostOutput};
3
3
  //# sourceMappingURL=output.js.map