@unbrained/pm-cli 2026.10.2 → 2026.10.4

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 (104) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +31 -1
  3. package/dist/cli/error-guidance.js +1 -1
  4. package/dist/cli/runtime/invocation-options.js +1 -1
  5. package/dist/cli/runtime/selection.js +1 -1
  6. package/dist/cli/runtime-compatibility-boundary.d.ts +1 -1
  7. package/dist/cli/runtime-compatibility-boundary.js +3 -3
  8. package/dist/cli-bundle/bundle-manifest.json +149 -149
  9. package/dist/cli-bundle/chunks/{chunk-HY6M34B4.js → chunk-7CE2DJMA.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-WP6NRH72.js → chunk-7UVXKI7K.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-7FUEQOYG.js → chunk-D7Z2ZMJL.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-TRYXVQ7W.js → chunk-GZMWISWW.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-ZI7F3FVE.js → chunk-J52QIRRZ.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-R4TUD355.js → chunk-JDKD3WGG.js} +6 -6
  15. package/dist/cli-bundle/chunks/chunk-JQ7DW663.js +2 -0
  16. package/dist/cli-bundle/chunks/{chunk-SV7CZEVV.js → chunk-QXIDOOWT.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-XOUBIF6Z.js → chunk-SMKHR6BM.js} +49 -49
  18. package/dist/cli-bundle/chunks/{chunk-MTJMOI4I.js → chunk-V3U77H3V.js} +31 -31
  19. package/dist/cli-bundle/chunks/{chunk-Z2GYDSAO.js → chunk-XZDWAYJC.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-R7ULWMBG.js → chunk-Y6VRBTP3.js} +71 -71
  21. package/dist/cli-bundle/chunks/{chunk-CZLAWXDR.js → chunk-YAAFYFS4.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-list-query-R4PHNB7W.js → register-list-query-QBGXO5JJ.js} +2 -2
  23. package/dist/cli-bundle/chunks/{register-mutation-PDDAUDYV.js → register-mutation-53ZLT4RX.js} +2 -2
  24. package/dist/cli-bundle/chunks/{register-operations-A5HJT46K.js → register-operations-OBK2FXUU.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-setup-EZ2F25JI.js → register-setup-HM3OCBH2.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-FKK2HI3S.js → chunk-2JFYR56O.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-UTRSM3ZK.js → chunk-32EVUSS4.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-DBD4W4QP.js → chunk-467EW5RL.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-IR4UXLRP.js → chunk-5GUSO2P4.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-GMYUNHST.js → chunk-6XBRADQQ.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-EJN7DY3B.js → chunk-7O4NUJVO.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-E754JDLY.js → chunk-CURTIIQT.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-4FFPGNCJ.js → chunk-IJUWEEEB.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-XRSCIYHR.js → chunk-JCVMOSWQ.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-ZIXFMIUL.js → chunk-JMJK2L4Z.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-WCY6HRZO.js → chunk-KG3H4UZZ.js} +14 -14
  37. package/dist/cli-bundle/focused-chunks/{chunk-VVWYI2X7.js → chunk-MHQ2XICU.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-3BIYG72P.js → chunk-Q6DJ5DFQ.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-BLCTBSGT.js → chunk-RJV6QVJE.js} +26 -26
  40. package/dist/cli-bundle/focused-chunks/{chunk-GBD4EN6S.js → chunk-ZE2JZ7R6.js} +11 -11
  41. package/dist/cli-bundle/focused-chunks/chunk-ZLEN4HZD.js +165 -0
  42. package/dist/cli-bundle/main.js +22 -22
  43. package/dist/cli-bundle/sdk-authoring.js +1 -1
  44. package/dist/cli-bundle/sdk-contracts.js +1 -1
  45. package/dist/cli-bundle/sdk-core.js +31 -31
  46. package/dist/cli-bundle/sdk-governance.js +1 -1
  47. package/dist/cli-bundle/sdk-graph.js +1 -1
  48. package/dist/cli-bundle/sdk-merge.js +23 -23
  49. package/dist/cli-bundle/sdk-query.js +1 -1
  50. package/dist/cli-bundle/sdk-runtime.js +1 -1
  51. package/dist/cli-bundle/sdk-testing.js +1 -1
  52. package/dist/cli-bundle/sdk.js +1 -1
  53. package/dist/core/extensions/extension-types.d.ts +8 -1
  54. package/dist/core/extensions/extension-types.js +1 -1
  55. package/dist/core/shared/secret-rules.js +1 -1
  56. package/dist/core/shared/time.js +1 -1
  57. package/dist/core/store/settings.d.ts +11 -2
  58. package/dist/core/store/settings.js +2 -2
  59. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  60. package/dist/sdk/cli-bootstrap.js +1 -1
  61. package/dist/sdk/context-intent-contracts.js +1 -1
  62. package/dist/sdk/extension-command-context.js +1 -1
  63. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  64. package/dist/sdk/item-transaction.js +1 -1
  65. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  66. package/dist/sdk/lifecycle/task-composition.js +1 -1
  67. package/dist/sdk/linked-artifacts.d.ts +1 -1
  68. package/dist/sdk/linked-artifacts.js +1 -1
  69. package/dist/sdk/output-projection.js +1 -1
  70. package/dist/sdk/public-surface.json +1 -1
  71. package/dist/sdk/query/get.js +1 -1
  72. package/dist/sdk/query/search-pagination.d.ts +1 -1
  73. package/dist/sdk/query/search-pagination.js +1 -1
  74. package/dist/sdk/test/execution.js +2 -2
  75. package/dist/sdk/test/workspace-snapshot.d.ts +11 -0
  76. package/dist/sdk/test/workspace-snapshot.js +2 -0
  77. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +109 -0
  78. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +25 -0
  79. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
  80. package/docs/SDK_AUDITED_MUTATIONS.md +35 -0
  81. package/docs/TESTING.md +40 -5
  82. package/docs/ecosystem-review-2026-09-28.json +2864 -3157
  83. package/marketplace.json +2 -2
  84. package/package.json +5 -4
  85. package/packages/pm-beads/package.json +1 -1
  86. package/packages/pm-calendar/package.json +1 -1
  87. package/packages/pm-command-kit/package.json +1 -1
  88. package/packages/pm-digital-twin/package.json +1 -1
  89. package/packages/pm-governance-audit/package.json +1 -1
  90. package/packages/pm-guide-shell/package.json +1 -1
  91. package/packages/pm-kanban/package.json +1 -1
  92. package/packages/pm-lifecycle-hooks/package.json +1 -1
  93. package/packages/pm-linked-test-adapters/package.json +1 -1
  94. package/packages/pm-search-advanced/package.json +1 -1
  95. package/packages/pm-templates/package.json +1 -1
  96. package/packages/pm-todos/package.json +1 -1
  97. package/packages/pm-vcs/package.json +1 -1
  98. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  99. package/plugins/pm-claude/package.json +2 -2
  100. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  101. package/plugins/pm-codex/package.json +2 -2
  102. package/plugins/pm-codex/plugin.json +1 -1
  103. package/dist/cli-bundle/chunks/chunk-7NL3A2BY.js +0 -2
  104. package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +0 -165
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bb855f72-341c-5dc3-ade5-dd3102275cd8")}catch(e2){}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import fg from"fast-glob";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,createStdinTokenResolver,looksLikeGenericKeyValueEntry,parseCsvKv}from"../core/item/parse.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isRemoteLinkedArtifactReference}from"../core/validate/linked-artifact-reference.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{stableValueEquals}from"../core/shared/serialization.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{SCOPE_VALUES}from"../types/index.js";import{resolveAuthor}from"../core/shared/author.js";const LINKED_ARTIFACT_ADD_KEYS=["path","scope","note"];const LINKED_ARTIFACT_ADD_GLOB_KEYS=["pattern","glob","path","scope","note"];const LINKED_ARTIFACT_REMOVE_KEYS=["path"];const LINKED_ARTIFACT_MIGRATE_KEYS=["from","to"];const LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS=new Set(["note","scope"]);function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value)){throw new PmCliError(`Invalid scope "${raw}". Valid scopes: ${SCOPE_VALUES.join(", ")} (default: project).`,EXIT_CODE.USAGE)}return value}function looksLikeStructuredPathEntry(raw){if(raw.startsWith("```")||raw.includes("\n")){return true}if(/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw)){return true}const firstCommaIndex=raw.indexOf(",");const leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length);const equalsIndex=leadingSegment.indexOf("=");if(equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))){return false}return leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value){if(character==="(")depth+=1;if(character===")")depth-=1;if(depth<0)return false}return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed)){return{path:trimmed,scope:"project",note:void 0}}const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2)){return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return void 0;const label=trimmed.slice(0,delimiterIndex).trim();const destination=trimmed.slice(delimiterIndex+1).trim();if(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)){return void 0}return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){if(!raw)return[];return raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS);if(!kv.path){throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE)}return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]})}function parseAddGlobEntries(raw){if(!raw)return[];return raw.map(entry=>{const trimmed=entry.trim();if(!trimmed){throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE)}if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern){throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE)}return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}})}function parseRemoveEntries(raw){if(!raw)return[];return raw.map(entry=>{const trimmed=entry.trim();if(!trimmed){throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE)}if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove");const unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0){throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE)}assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS);if(!kv.path){throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE)}return kv.path}return trimmed})}function parseMigrateEntries(raw){if(!raw)return[];return raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim();const to=kv.to?.trim();if(!from||!to){throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE)}return{from,to}})}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations){if(next.startsWith(migration.from)){next=`${migration.to}${next.slice(migration.from.length)}`}}return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0){return}const addedPaths=new Set(adds.map(entry=>applyPathMigrations(entry.path,migrations)));const conflicts=[...new Set(removes.map(entry=>applyPathMigrations(entry,migrations)).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length===0){return}throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed)){return trimmed}if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed)){return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep))}const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);if(invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)){return normalizeLinkedPath(path.normalize(trimmed))}return normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){const absolutePattern=path.isAbsolute(entry.pattern);const matches=await fg(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:true,dot:true,unique:true,followSymbolicLinks:true});const sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches){expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0){return adds}if(!hasAddFlags){throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE)}const trimmed=note.trim();if(trimmed.length===0){return adds}return adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);if(byPath!==0)return byPath;return left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right));const existingFiles=[];const missingPaths=[];const nonFilePaths=[];const remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{const stats=await fs.stat(resolvedPath);if(stats.isFile()){existingFiles.push(relativePath)}else{nonFilePaths.push(relativePath)}}catch(error){if(typeof error==="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);if(migratedPath!==current[index].path){current[index]={...current[index],path:migratedPath};count+=1}}const migratedAdds=adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);if(migratedPath!==entry.path)count+=1;return{...entry,path:migratedPath}});return{adds:migratedAdds,removes:removes.map(entry=>applyPathMigrations(entry,migrations)),count}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable){const merged=dedupeLinkedArtifacts(current);for(const add of adds){const index=merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope);if(index<0){merged.push(add)}else if(add.note!==void 0){merged[index]={...merged[index],note:add.note}}}if(removes.length>0){for(let index=merged.length-1;index>=0;index-=1){if(removes.includes(merged[index].path))merged.splice(index,1)}}return appendStable?merged:sortLinkedArtifacts(merged)}async function buildLinkedArtifactResult(params){const paths=params.artifacts.map(entry=>entry.path);return{id:params.id,artifacts:params.artifacts,changed:params.changed,count:params.artifacts.length,migrations_applied:params.migrationsApplied&&params.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed?await validateLinkedPaths(paths,params.workspaceRoot):void 0}}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config;const stdinResolver=createStdinTokenResolver();const pmRoot=resolvePmRoot(process.cwd(),global2.path);const workspaceRoot=resolveWorkspaceRoot(pmRoot);const invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const resolvedAdds=await stdinResolver.resolveList(options.add,"--add");const resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob");const resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove");const resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate");const parsedAdds=parseAddEntries(resolvedAdds,config.bareNoun).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)}));const addGlobs=parseAddGlobEntries(resolvedAddGlobs);const expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot);const adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,parsedAdds.length>0||addGlobs.length>0);const removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot));const migrations=parseMigrateEntries(resolvedMigrations);assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations);const shouldMutate=adds.length>0||removes.length>0||migrations.length>0;if(!shouldMutate){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located){throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND)}const loaded=await readLocatedItem(located,{schema:settings.schema});const artifacts2=loaded.document.metadata[metadataKey]??[];return buildLinkedArtifactResult({id:located.id,artifacts:artifacts2,changed:false,options,workspaceRoot})}const author=resolveAuthor(options.author,settings.author_default);const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:true,mutate(document){const metadata=document.metadata;const current=metadata[metadataKey]??[];const next=[...current];const migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations);const normalized=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===true);if(normalized.length>0){metadata[metadataKey]=normalized}else{delete metadata[metadataKey]}const changed=!stableValueEquals(current,normalized);return{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}});const artifacts=result.item[metadataKey]??[];const migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:"));const migrationCount=migrationWarning?Number(migrationWarning.slice("path_migrations_applied:".length)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result)){out[field==="artifacts"?key:field]=value}return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4adcee44-f1a4-5ac8-b9a9-5981a3197bce")}catch(e2){}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{glob}from"tinyglobby";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,createStdinTokenResolver,looksLikeGenericKeyValueEntry,parseCsvKv}from"../core/item/parse.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isRemoteLinkedArtifactReference}from"../core/validate/linked-artifact-reference.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{stableValueEquals}from"../core/shared/serialization.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{SCOPE_VALUES}from"../types/index.js";import{resolveAuthor}from"../core/shared/author.js";const LINKED_ARTIFACT_ADD_KEYS=["path","scope","note"];const LINKED_ARTIFACT_ADD_GLOB_KEYS=["pattern","glob","path","scope","note"];const LINKED_ARTIFACT_REMOVE_KEYS=["path"];const LINKED_ARTIFACT_MIGRATE_KEYS=["from","to"];const LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS=new Set(["note","scope"]);function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value)){throw new PmCliError(`Invalid scope "${raw}". Valid scopes: ${SCOPE_VALUES.join(", ")} (default: project).`,EXIT_CODE.USAGE)}return value}function looksLikeStructuredPathEntry(raw){if(raw.startsWith("```")||raw.includes("\n")){return true}if(/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw)){return true}const firstCommaIndex=raw.indexOf(",");const leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length);const equalsIndex=leadingSegment.indexOf("=");if(equalsIndex>=0&&!/\s/u.test(raw)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(raw)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(raw)||[raw.indexOf("/"),raw.indexOf("\\")].some(separatorIndex=>separatorIndex>=0&&separatorIndex<equalsIndex))){return false}return leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value){if(character==="(")depth+=1;if(character===")")depth-=1;if(depth<0)return false}return depth===0}function parseDocumentationReference(trimmed){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(trimmed)&&!looksLikeStructuredPathEntry(trimmed)){return{path:trimmed,scope:"project",note:void 0}}const labelEnd=trimmed.indexOf("](");if(trimmed.startsWith("[")&&labelEnd>0&&trimmed.endsWith(")")){const destination2=trimmed.slice(labelEnd+2,-1).trim();if(destination2.length>0&&hasBalancedParentheses(destination2)){return{path:destination2,scope:"project",note:trimmed.slice(1,labelEnd).trim()||void 0}}}const delimiterIndex=trimmed.indexOf(",");if(delimiterIndex<0)return void 0;const label=trimmed.slice(0,delimiterIndex).trim();const destination=trimmed.slice(delimiterIndex+1).trim();if(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)){return void 0}return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){if(!raw)return[];return raw.flatMap(entry=>{const trimmed=entry.trim();if(bareNoun==="doc"){const reference=parseDocumentationReference(trimmed);if(reference!==void 0)return[reference]}assertNoAmbiguousBareCommaEntry(trimmed,"--add",`${bareNoun} path`,looksLikeStructuredPathEntry(trimmed));const kv=looksLikeStructuredPathEntry(trimmed)?parseCsvKv(entry,"--add"):{path:trimmed};assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS);if(!kv.path){throw new PmCliError(`--add requires path=<value> or a bare ${bareNoun} path`,EXIT_CODE.USAGE)}return[{path:kv.path,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}]})}function parseAddGlobEntries(raw){if(!raw)return[];return raw.map(entry=>{const trimmed=entry.trim();if(!trimmed){throw new PmCliError("--add-glob requires a glob pattern value",EXIT_CODE.USAGE)}if(trimmed.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--add-glob");assertNoUnknownCsvKeys(kv,"--add-glob",LINKED_ARTIFACT_ADD_GLOB_KEYS);const pattern=kv.pattern?.trim()||kv.glob?.trim()||kv.path?.trim();if(!pattern){throw new PmCliError("--add-glob key/value form requires pattern=<glob>",EXIT_CODE.USAGE)}return{pattern,scope:ensureScope(kv.scope),note:kv.note?.trim()||void 0}}return{pattern:trimmed,scope:"project"}})}function parseRemoveEntries(raw){if(!raw)return[];return raw.map(entry=>{const trimmed=entry.trim();if(!trimmed){throw new PmCliError("--remove requires a path value",EXIT_CODE.USAGE)}if(trimmed.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove");const unsupportedRemoveKeys=Object.keys(kv).filter(key=>LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS.has(key.toLowerCase()));if(unsupportedRemoveKeys.length>0){throw new PmCliError(`--remove identifies a linked artifact by path only and does not accept ${unsupportedRemoveKeys.map(key=>`"${key}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,EXIT_CODE.USAGE)}assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS);if(!kv.path){throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE)}return kv.path}return trimmed})}function parseMigrateEntries(raw){if(!raw)return[];return raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim();const to=kv.to?.trim();if(!from||!to){throw new PmCliError("--migrate requires from=<value> and to=<value>",EXIT_CODE.USAGE)}return{from,to}})}function applyPathMigrations(artifactPath,migrations){let next=artifactPath;for(const migration of migrations){if(next.startsWith(migration.from)){next=`${migration.to}${next.slice(migration.from.length)}`}}return next}function assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations=[]){if(adds.length===0||removes.length===0){return}const addedPaths=new Set(adds.map(entry=>applyPathMigrations(entry.path,migrations)));const conflicts=[...new Set(removes.map(entry=>applyPathMigrations(entry,migrations)).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length===0){return}throw new PmCliError(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${conflicts.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,EXIT_CODE.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function normalizeLinkedPath(value){return value.split(path.sep).join("/")}function anchorLinkedPath(value,workspaceRoot,invocationRoot=process.cwd()){const trimmed=value.trim();if(isRemoteLinkedArtifactReference(trimmed)){return trimmed}if(path.isAbsolute(trimmed)||/^[A-Za-z]:[\\/]/.test(trimmed)){return normalizeLinkedPath(trimmed.replaceAll("\\",path.sep))}const invocationRelativeToWorkspace=path.relative(workspaceRoot,invocationRoot);if(invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)){return normalizeLinkedPath(path.normalize(trimmed))}return normalizeLinkedPath(path.relative(workspaceRoot,path.resolve(invocationRoot,trimmed)))}async function expandAddGlobEntries(entries,workspaceRoot=process.cwd(),invocationRoot=process.cwd()){const expanded=[];for(const entry of entries){if(path.resolve(invocationRoot,entry.pattern)===path.resolve(invocationRoot))continue;const absolutePattern=path.isAbsolute(entry.pattern);const matches=await glob(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:true,dot:true,expandDirectories:false,followSymbolicLinks:true});const sortedMatches=[...new Set(matches.map(match=>anchorLinkedPath(match,workspaceRoot,invocationRoot)))].sort((left,right)=>left.localeCompare(right));for(const matchedPath of sortedMatches){expanded.push({path:matchedPath,scope:entry.scope,note:entry.note})}}return expanded}function applyStandaloneNote(adds,note,hasAddFlags){if(note===void 0){return adds}if(!hasAddFlags){throw new PmCliError("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",EXIT_CODE.USAGE)}const trimmed=note.trim();if(trimmed.length===0){return adds}return adds.map(entry=>entry.note===void 0?{...entry,note:trimmed}:entry)}function artifactKey(value){return`${value.path}::${value.scope}`}function sortLinkedArtifacts(artifacts){return[...artifacts].sort((left,right)=>{const byPath=left.path.localeCompare(right.path);if(byPath!==0)return byPath;return left.scope.localeCompare(right.scope)})}function dedupeLinkedArtifacts(artifacts){return[...new Map(artifacts.map(entry=>[artifactKey(entry),entry])).values()].map(entry=>({...entry,note:entry.note?.trim()||void 0}))}async function validateLinkedPaths(paths,workspaceRoot=process.cwd()){const uniquePaths=[...new Set(paths)].sort((left,right)=>left.localeCompare(right));const existingFiles=[];const missingPaths=[];const nonFilePaths=[];const remoteReferences=[];for(const relativePath of uniquePaths){if(isRemoteLinkedArtifactReference(relativePath)){remoteReferences.push(relativePath.trim());continue}const resolvedPath=path.isAbsolute(relativePath)?relativePath:path.resolve(workspaceRoot,relativePath);try{const stats=await fs.stat(resolvedPath);if(stats.isFile()){existingFiles.push(relativePath)}else{nonFilePaths.push(relativePath)}}catch(error){if(typeof error==="object"&&error!==null&&"code"in error&&isFileAbsentError(error)){missingPaths.push(relativePath);continue}nonFilePaths.push(relativePath)}}return{checked:uniquePaths.length,existing_files:existingFiles,missing_paths:missingPaths,non_file_paths:nonFilePaths,remote_references:remoteReferences}}function applyLinkedArtifactMigrations(current,adds,removes,migrations){let count=0;for(let index=0;index<current.length;index+=1){const migratedPath=applyPathMigrations(current[index].path,migrations);if(migratedPath!==current[index].path){current[index]={...current[index],path:migratedPath};count+=1}}const migratedAdds=adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);if(migratedPath!==entry.path)count+=1;return{...entry,path:migratedPath}});return{adds:migratedAdds,removes:removes.map(entry=>applyPathMigrations(entry,migrations)),count}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable){const merged=dedupeLinkedArtifacts(current);for(const add of adds){const index=merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope);if(index<0){merged.push(add)}else if(add.note!==void 0){merged[index]={...merged[index],note:add.note}}}if(removes.length>0){for(let index=merged.length-1;index>=0;index-=1){if(removes.includes(merged[index].path))merged.splice(index,1)}}return appendStable?merged:sortLinkedArtifacts(merged)}async function buildLinkedArtifactResult(params){const paths=params.artifacts.map(entry=>entry.path);return{id:params.id,artifacts:params.artifacts,changed:params.changed,count:params.artifacts.length,migrations_applied:params.migrationsApplied&&params.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed?await validateLinkedPaths(paths,params.workspaceRoot):void 0}}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config;const stdinResolver=createStdinTokenResolver();const pmRoot=resolvePmRoot(process.cwd(),global2.path);const workspaceRoot=resolveWorkspaceRoot(pmRoot);const invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const resolvedAdds=await stdinResolver.resolveList(options.add,"--add");const resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob");const resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove");const resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate");const parsedAdds=parseAddEntries(resolvedAdds,config.bareNoun).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)}));const addGlobs=parseAddGlobEntries(resolvedAddGlobs);const expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot);const adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,parsedAdds.length>0||addGlobs.length>0);const removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot));const migrations=parseMigrateEntries(resolvedMigrations);assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations);const shouldMutate=adds.length>0||removes.length>0||migrations.length>0;if(!shouldMutate){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located){throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND)}const loaded=await readLocatedItem(located,{schema:settings.schema});const artifacts2=loaded.document.metadata[metadataKey]??[];return buildLinkedArtifactResult({id:located.id,artifacts:artifacts2,changed:false,options,workspaceRoot})}const author=resolveAuthor(options.author,settings.author_default);const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:true,mutate(document){const metadata=document.metadata;const current=metadata[metadataKey]??[];const next=[...current];const migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations);const normalized=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===true);if(normalized.length>0){metadata[metadataKey]=normalized}else{delete metadata[metadataKey]}const changed=!stableValueEquals(current,normalized);return{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}});const artifacts=result.item[metadataKey]??[];const migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:"));const migrationCount=migrationWarning?Number(migrationWarning.slice("path_migrations_applied:".length)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot})}function renameArtifactsResultKey(result,key){const out={};for(const[field,value]of Object.entries(result)){out[field==="artifacts"?key:field]=value}return out}export{LINKED_ARTIFACT_ADD_GLOB_KEYS,LINKED_ARTIFACT_ADD_KEYS,LINKED_ARTIFACT_MIGRATE_KEYS,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths};
2
2
  //# sourceMappingURL=linked-artifacts.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d248fcfa-d007-526a-9849-9ea8352acaa1")}catch(e2){}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const MATERIAL_FIELD_GROUPS_BY_RESULT=new WeakMap;function registerOutputMaterialFieldGroups(result,fieldGroups){MATERIAL_FIELD_GROUPS_BY_RESULT.set(result,new Set(fieldGroups))}const PM_READ_ROW_JQ_SELECTOR='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end';const PM_READ_ROW_CONTRACTS={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}};const PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function assertProjectionModeChoice(compactRequested,fullRequested,compactFlag){if(compactRequested&&fullRequested){throw new PmCliError(`${compactFlag} cannot be combined with --full`,EXIT_CODE.USAGE)}}function createOutputOmissionReceipt(declaredGroups,includedGroupNames=new Set){const omittedFieldGroups=declaredGroups.filter(group=>!includedGroupNames.has(group.name)).map(group=>({...group}));return{has_omissions:omittedFieldGroups.length>0,omitted_field_group_count:omittedFieldGroups.length,omitted_field_groups:omittedFieldGroups}}function resolveModePairedOutputOmissionReceipt(command,mode){const contract=PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS.find(candidate=>candidate.command===command);if(contract===void 0){throw new TypeError(`Unknown mode-paired output command: ${command}`)}if(mode===contract.complete_mode){return createOutputOmissionReceipt([])}const groups=contract.omissions_by_mode[mode];if(groups===void 0){throw new TypeError(`Unknown ${command} output mode: ${mode}`)}return createOutputOmissionReceipt(groups)}const CONTEXT_FIELD_GROUPS=[{name:"hierarchy",restore_with:"--depth standard"},{name:"activity",restore_with:"--depth standard"},{name:"progress",restore_with:"--depth standard"},{name:"blockers",restore_with:"--depth standard"},{name:"recently_created",restore_with:"--depth standard"},{name:"unparented",restore_with:"--depth standard"},{name:"files",restore_with:"--depth deep"},{name:"workload",restore_with:"--depth standard"},{name:"staleness",restore_with:"--depth deep"},{name:"tests",restore_with:"--depth deep"},{name:"workspace_memory",restore_with:"--depth deep"}];function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}const READ_ROW_TOON_ENCODINGS=new Set([void 0,"tabular_when_uniform"]);const READ_ROW_KINDS=new Set(["collection","none"]);const READ_ROW_FIELD_MODES=new Set(["supported","unsupported"]);function isUniqueNonEmptyStringArray(value,allowEmpty){return Array.isArray(value)&&(allowEmpty||value.length>0)&&value.every(entry=>typeof entry==="string"&&entry.length>0)&&new Set(value).size===value.length}function isReadRowContract(value){return isRecord(value)&&typeof value.command==="string"&&value.command.trim().length>0&&READ_ROW_KINDS.has(value.row_kind)&&isUniqueNonEmptyStringArray(value.row_keys,true)&&(value.continuation_row_keys===void 0||isUniqueNonEmptyStringArray(value.continuation_row_keys,false))&&READ_ROW_FIELD_MODES.has(value.fields)&&READ_ROW_TOON_ENCODINGS.has(value.toon_encoding)&&(value.row_kind==="collection"?value.row_keys.length>0&&typeof value.jq_selector==="string"&&value.jq_selector.trim().length>0:value.row_keys.length===0&&value.jq_selector===void 0)}const GRAPH_ROW_KEYS={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]};const READ_RESULT_SENTINEL_KEYS={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function resolveReadRowContract(command,result){const rawRootCommand=command.trim().toLowerCase().split(/\s+/u,1)[0];const rootCommand=rawRootCommand?.startsWith("list-")?"list":rawRootCommand;if(rootCommand==="graph"){const subcommand=typeof result.subcommand==="string"?result.subcommand:"";if(subcommand.length===0)return void 0;const rowKeys=GRAPH_ROW_KEYS[subcommand];if(rowKeys===void 0)return void 0;const activeRowKeys=rowKeys.filter(key=>Array.isArray(result[key])||isRecord(result[key]));return{command:"graph",row_kind:activeRowKeys.length>0?"collection":"none",row_keys:activeRowKeys,fields:"unsupported",...activeRowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}}const declaration=PM_READ_ROW_CONTRACTS[rootCommand];const sentinelKeys=READ_RESULT_SENTINEL_KEYS[rootCommand];return declaration===void 0||sentinelKeys===void 0||!sentinelKeys.some(key=>Object.hasOwn(result,key))?void 0:(()=>{const rowKeys=declaration.row_keys.filter(key=>{const value=key.split(".").reduce((current,segment)=>isRecord(current)?current[segment]:void 0,result);return Array.isArray(value)||isRecord(value)});return{command:rootCommand,row_kind:rowKeys.length>0?"collection":"none",row_keys:rowKeys,fields:declaration.fields,...rowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}})()}function resolveDeclaredProjectionReceipt(result){if(!isRecord(result.projection))return void 0;if(typeof result.projection.mode!=="string"||result.projection.mode.trim().length===0){return void 0}const declared=result.projection.declared_field_groups;const included=result.projection.included_field_groups;if(!Array.isArray(declared)||!Array.isArray(included))return void 0;const declaredGroups=declared.filter(entry=>isRecord(entry)&&typeof entry.name==="string"&&entry.name.trim().length>0&&typeof entry.restore_with==="string"&&entry.restore_with.trim().length>0);const includedNames=included.filter(entry=>typeof entry==="string");if(declaredGroups.length!==declared.length||includedNames.length!==included.length){return void 0}const declaredNames=new Set(declaredGroups.map(group=>group.name));if(declaredNames.size!==declaredGroups.length||new Set(includedNames).size!==includedNames.length||includedNames.some(name=>!declaredNames.has(name))){return void 0}return createOutputOmissionReceipt(declaredGroups,new Set(includedNames))}function resolveContextReceipt(result){if(!Array.isArray(result.sections_included))return void 0;const receipt=createOutputOmissionReceipt(CONTEXT_FIELD_GROUPS,new Set(result.sections_included.filter(section=>typeof section==="string")));if(isRecord(result.summary)&&result.summary.scope==="matching_items"){receipt.summary_scope="matching_items"}return receipt}function resolveGetReceipt(result){if(!isRecord(result.item))return void 0;const item=result.item;const itemGroups=["comments","notes","learnings","files","tests","docs","reminders","events"];const resultGroups=["body","children","claim_state","linked","schedule"];const materialGroups=MATERIAL_FIELD_GROUPS_BY_RESULT.get(result);const ownerFor=name=>itemGroups.includes(name)||name==="body"?item:result;const groups=["body",...itemGroups,...resultGroups.slice(1)].filter(name=>materialGroups===void 0||materialGroups.has(name)||Object.hasOwn(ownerFor(name),name)).map(name=>({name,restore_with:`--fields ${name}`}));return createOutputOmissionReceipt(groups,new Set(groups.flatMap(({name})=>!Object.hasOwn(ownerFor(name),name)?[]:[name])))}function resolveListOrSearchReceipt(result){if(!isRecord(result.projection))return void 0;return createOutputOmissionReceipt([{name:"full_item_fields",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_item_fields"]:[]))}function resolveHealthReceipt(result){if(!isRecord(result.projection))return createOutputOmissionReceipt([]);if(typeof result.projection.mode!=="string")return void 0;return createOutputOmissionReceipt([{name:"full_check_details",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_check_details"]:[]))}function resolveContractsReceipt(result){if(!isRecord(result.selected)||typeof result.selected.summary!=="boolean"){return void 0}return createOutputOmissionReceipt([{name:"full_contract_catalog",restore_with:"--full"}],new Set(result.selected.summary?[]:["full_contract_catalog"]))}function resolveOutputOmissionReceipt(command,result){const declaredReceipt=resolveDeclaredProjectionReceipt(result);if(declaredReceipt!==void 0)return declaredReceipt;const[rootCommand]=command.split(/\s+/u,1);if(rootCommand==="context")return resolveContextReceipt(result);if(rootCommand==="get")return resolveGetReceipt(result);if(rootCommand==="list"||rootCommand.startsWith("list-")){return resolveListOrSearchReceipt(result)}if(rootCommand==="search"){return resolveListOrSearchReceipt(result)??createOutputOmissionReceipt([{name:"projection_metadata",restore_with:"--full"}])}if(rootCommand==="health")return resolveHealthReceipt(result);if(rootCommand==="contracts")return resolveContractsReceipt(result);return void 0}function attachOutputOmissionReceipt(command,result){if(command===void 0||!isRecord(result)){return result}const receipt=resolveOutputOmissionReceipt(command,result);const declaredRowContract=result.row_contract;const rowContract=isReadRowContract(declaredRowContract)?declaredRowContract:resolveReadRowContract(command,result);const disclosedResult=rowContract!==void 0?{...result,row_contract:rowContract}:Object.hasOwn(result,"row_contract")?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result;if(isRecord(disclosedResult.omission_receipt))return disclosedResult;return receipt===void 0?disclosedResult:{...disclosedResult,omission_receipt:receipt}}export{PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,PM_READ_ROW_CONTRACTS,PM_READ_ROW_JQ_SELECTOR,assertProjectionModeChoice,attachOutputOmissionReceipt,createOutputOmissionReceipt,isReadRowContract,registerOutputMaterialFieldGroups,resolveModePairedOutputOmissionReceipt,resolveOutputOmissionReceipt,resolveReadRowContract};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b3353f90-b9b8-5ef5-918c-b56ec8e747c2")}catch(e2){}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const MATERIAL_FIELD_GROUPS_BY_RESULT=new WeakMap;function registerOutputMaterialFieldGroups(result,fieldGroups){MATERIAL_FIELD_GROUPS_BY_RESULT.set(result,new Set(fieldGroups))}const PM_READ_ROW_JQ_SELECTOR='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end';const PM_READ_ROW_CONTRACTS={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}};const PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function assertProjectionModeChoice(compactRequested,fullRequested,compactFlag){if(compactRequested&&fullRequested){throw new PmCliError(`${compactFlag} cannot be combined with --full`,EXIT_CODE.USAGE)}}function createOutputOmissionReceipt(declaredGroups,includedGroupNames=new Set){const omittedFieldGroups=declaredGroups.filter(group=>!includedGroupNames.has(group.name)).map(group=>({...group}));return{has_omissions:omittedFieldGroups.length>0,omitted_field_group_count:omittedFieldGroups.length,omitted_field_groups:omittedFieldGroups}}function resolveModePairedOutputOmissionReceipt(command,mode){const contract=PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS.find(candidate=>candidate.command===command);if(contract===void 0){throw new TypeError(`Unknown mode-paired output command: ${command}`)}if(mode===contract.complete_mode){return createOutputOmissionReceipt([])}const groups=contract.omissions_by_mode[mode];if(groups===void 0){throw new TypeError(`Unknown ${command} output mode: ${mode}`)}return createOutputOmissionReceipt(groups)}const CONTEXT_FIELD_GROUPS=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}const READ_ROW_TOON_ENCODINGS=new Set([void 0,"tabular_when_uniform"]);const READ_ROW_KINDS=new Set(["collection","none"]);const READ_ROW_FIELD_MODES=new Set(["supported","unsupported"]);function isUniqueNonEmptyStringArray(value,allowEmpty){return Array.isArray(value)&&(allowEmpty||value.length>0)&&value.every(entry=>typeof entry==="string"&&entry.length>0)&&new Set(value).size===value.length}function isReadRowContract(value){return isRecord(value)&&typeof value.command==="string"&&value.command.trim().length>0&&READ_ROW_KINDS.has(value.row_kind)&&isUniqueNonEmptyStringArray(value.row_keys,true)&&(value.continuation_row_keys===void 0||isUniqueNonEmptyStringArray(value.continuation_row_keys,false))&&READ_ROW_FIELD_MODES.has(value.fields)&&READ_ROW_TOON_ENCODINGS.has(value.toon_encoding)&&(value.row_kind==="collection"?value.row_keys.length>0&&typeof value.jq_selector==="string"&&value.jq_selector.trim().length>0:value.row_keys.length===0&&value.jq_selector===void 0)}const GRAPH_ROW_KEYS={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]};const READ_RESULT_SENTINEL_KEYS={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function resolveReadRowContract(command,result){const rawRootCommand=command.trim().toLowerCase().split(/\s+/u,1)[0];const rootCommand=rawRootCommand?.startsWith("list-")?"list":rawRootCommand;if(rootCommand==="graph"){const subcommand=typeof result.subcommand==="string"?result.subcommand:"";if(subcommand.length===0)return void 0;const rowKeys=GRAPH_ROW_KEYS[subcommand];if(rowKeys===void 0)return void 0;const activeRowKeys=rowKeys.filter(key=>Array.isArray(result[key])||isRecord(result[key]));return{command:"graph",row_kind:activeRowKeys.length>0?"collection":"none",row_keys:activeRowKeys,fields:"unsupported",...activeRowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}}const declaration=PM_READ_ROW_CONTRACTS[rootCommand];const sentinelKeys=READ_RESULT_SENTINEL_KEYS[rootCommand];return declaration===void 0||sentinelKeys===void 0||!sentinelKeys.some(key=>Object.hasOwn(result,key))?void 0:(()=>{const rowKeys=declaration.row_keys.filter(key=>{const value=key.split(".").reduce((current,segment)=>isRecord(current)?current[segment]:void 0,result);return Array.isArray(value)||isRecord(value)});return{command:rootCommand,row_kind:rowKeys.length>0?"collection":"none",row_keys:rowKeys,fields:declaration.fields,...rowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}})()}function resolveDeclaredProjectionReceipt(result){if(!isRecord(result.projection))return void 0;if(typeof result.projection.mode!=="string"||result.projection.mode.trim().length===0){return void 0}const declared=result.projection.declared_field_groups;const included=result.projection.included_field_groups;if(!Array.isArray(declared)||!Array.isArray(included))return void 0;const declaredGroups=declared.filter(entry=>isRecord(entry)&&typeof entry.name==="string"&&entry.name.trim().length>0&&typeof entry.restore_with==="string"&&entry.restore_with.trim().length>0);const includedNames=included.filter(entry=>typeof entry==="string");if(declaredGroups.length!==declared.length||includedNames.length!==included.length){return void 0}const declaredNames=new Set(declaredGroups.map(group=>group.name));if(declaredNames.size!==declaredGroups.length||new Set(includedNames).size!==includedNames.length||includedNames.some(name=>!declaredNames.has(name))){return void 0}return createOutputOmissionReceipt(declaredGroups,new Set(includedNames))}function resolveContextReceipt(result){if(!Array.isArray(result.sections_included))return void 0;const receipt=createOutputOmissionReceipt(CONTEXT_FIELD_GROUPS,new Set(result.sections_included.filter(section=>typeof section==="string")));if(isRecord(result.summary)&&result.summary.scope==="matching_items"){receipt.summary_scope="matching_items"}return receipt}function resolveGetReceipt(result){if(!isRecord(result.item))return void 0;const item=result.item;const itemGroups=["comments","notes","learnings","files","tests","docs","reminders","events"];const resultGroups=["body","children","claim_state","linked","schedule"];const materialGroups=MATERIAL_FIELD_GROUPS_BY_RESULT.get(result);const ownerFor=name=>itemGroups.includes(name)||name==="body"?item:result;const groups=["body",...itemGroups,...resultGroups.slice(1)].filter(name=>materialGroups===void 0||materialGroups.has(name)||Object.hasOwn(ownerFor(name),name)).map(name=>({name,restore_with:`--fields ${name}`}));return createOutputOmissionReceipt(groups,new Set(groups.flatMap(({name})=>!Object.hasOwn(ownerFor(name),name)?[]:[name])))}function resolveListOrSearchReceipt(result){if(!isRecord(result.projection))return void 0;return createOutputOmissionReceipt([{name:"full_item_fields",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_item_fields"]:[]))}function resolveHealthReceipt(result){if(!isRecord(result.projection))return createOutputOmissionReceipt([]);if(typeof result.projection.mode!=="string")return void 0;return createOutputOmissionReceipt([{name:"full_check_details",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_check_details"]:[]))}function resolveContractsReceipt(result){if(!isRecord(result.selected)||typeof result.selected.summary!=="boolean"){return void 0}return createOutputOmissionReceipt([{name:"full_contract_catalog",restore_with:"--full"}],new Set(result.selected.summary?[]:["full_contract_catalog"]))}function resolveOutputOmissionReceipt(command,result){const declaredReceipt=resolveDeclaredProjectionReceipt(result);if(declaredReceipt!==void 0)return declaredReceipt;const[rootCommand]=command.split(/\s+/u,1);if(rootCommand==="context")return resolveContextReceipt(result);if(rootCommand==="get")return resolveGetReceipt(result);if(rootCommand==="list"||rootCommand.startsWith("list-")){return resolveListOrSearchReceipt(result)}if(rootCommand==="search"){return resolveListOrSearchReceipt(result)??createOutputOmissionReceipt([{name:"projection_metadata",restore_with:"--full"}])}if(rootCommand==="health")return resolveHealthReceipt(result);if(rootCommand==="contracts")return resolveContractsReceipt(result);return void 0}function attachOutputOmissionReceipt(command,result){if(command===void 0||!isRecord(result)){return result}const receipt=resolveOutputOmissionReceipt(command,result);const declaredRowContract=result.row_contract;const rowContract=isReadRowContract(declaredRowContract)?declaredRowContract:resolveReadRowContract(command,result);const disclosedResult=rowContract!==void 0?{...result,row_contract:rowContract}:Object.hasOwn(result,"row_contract")?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result;if(isRecord(disclosedResult.omission_receipt))return disclosedResult;return receipt===void 0?disclosedResult:{...disclosedResult,omission_receipt:receipt}}export{PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,PM_READ_ROW_CONTRACTS,PM_READ_ROW_JQ_SELECTOR,assertProjectionModeChoice,attachOutputOmissionReceipt,createOutputOmissionReceipt,isReadRowContract,registerOutputMaterialFieldGroups,resolveModePairedOutputOmissionReceipt,resolveOutputOmissionReceipt,resolveReadRowContract};
2
2
  //# sourceMappingURL=output-projection.js.map