@unbrained/pm-cli 2026.11.17 → 2026.11.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2VH6COJE.js +125 -0
- package/dist/cli-bundle/chunks/{chunk-2WHXFKMY.js → chunk-7ETRLLK3.js} +31 -31
- package/dist/cli-bundle/chunks/{chunk-FXSLODOK.js → chunk-7LCJA54R.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DXSZL3T6.js → chunk-AGU7632B.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-X5TFNFTS.js → chunk-CGTVDSAR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ACLBUVQG.js → chunk-FJQCORYR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ABFHWRLE.js → chunk-JBPXNG6P.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QZNL5XDT.js → chunk-L2ZLH3LZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XPBADEUK.js → chunk-LGWP5D7V.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KIQNEOKJ.js → chunk-MUGGRKK3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3IU2S5UQ.js → chunk-OD2I3SFQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4FIN2XWC.js → chunk-QK7RAN7R.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-77MGDTK4.js → chunk-S3RMFLEG.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-QANUQMDL.js → chunk-SSZBVRIN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VLKCFZY6.js → chunk-T3E3WNHO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ADKDFCVT.js → chunk-TA5VN4ME.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RXNBNF6O.js → chunk-TS2CZE3O.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7K2RUKMK.js → chunk-VETSGCF4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-36R3JTAD.js → chunk-WKHS4QC6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O4ZSIMNC.js → chunk-XDIJK6VW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XP35IEHT.js → chunk-YJI2Y5N6.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-7RVMVXTE.js → item-revision-BV5BUBCR.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-E2ST3A3X.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-3PKQOAYK.js → mutation-admission-5AWMXMCB.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-TPZLHFHQ.js → register-list-query-RJT7YBRF.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-JG5AEBRJ.js → register-mutation-6KTMJGYF.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-3CNXP46P.js → register-operations-W24TA3HZ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-4N56VL2P.js → register-setup-QK67WUX6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2MQNIDKG.js → chunk-3H3SVHAT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GD2YWUAD.js → chunk-6OZ7BKWJ.js} +54 -54
- package/dist/cli-bundle/focused-chunks/{chunk-XJS4COL2.js → chunk-DWCFZVT2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SESMRMEE.js → chunk-EO4XM3XJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BNLLST32.js → chunk-IGMFXB5W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VBA4BIHN.js → chunk-LZR3JKYT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-6JQXDGHM.js → chunk-ONHUG7IL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YWPLBFPC.js → chunk-PNCCTZKI.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-T3NMYMW4.js +27 -0
- package/dist/cli-bundle/focused-chunks/{item-revision-U7GDVAH7.js → item-revision-NS2V4WON.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-7C4BH47O.js → item-transaction-NENC4HYI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-SKXVITP5.js → mutation-admission-DZIBDJAE.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +58 -58
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +1 -1
- package/dist/core/fs/file-glob.js +2 -0
- package/dist/core/shared/secret-rules.d.ts +83 -4
- package/dist/core/shared/secret-rules.js +5 -4
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/mutation-guard.d.ts +25 -4
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/docs/COMMANDS.md +33 -0
- package/docs/DEFECT_RECURRENCE.md +3 -2
- package/docs/MUTATION_INTEGRITY.md +187 -7
- package/marketplace.json +1 -1
- package/package.json +1 -3
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-AM26RAG7.js +0 -124
- package/dist/cli-bundle/chunks/item-transaction-NVX6P3FK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZDY5L2C2.js +0 -26
- package/node_modules/fdir/LICENSE +0 -7
- package/node_modules/fdir/README.md +0 -91
- package/node_modules/fdir/dist/index.cjs +0 -588
- package/node_modules/fdir/dist/index.d.cts +0 -155
- package/node_modules/fdir/dist/index.d.mts +0 -155
- package/node_modules/fdir/dist/index.mjs +0 -570
- package/node_modules/fdir/package.json +0 -106
- package/node_modules/picomatch/LICENSE +0 -21
- package/node_modules/picomatch/README.md +0 -743
- package/node_modules/picomatch/index.js +0 -17
- package/node_modules/picomatch/lib/constants.js +0 -184
- package/node_modules/picomatch/lib/parse.js +0 -1425
- package/node_modules/picomatch/lib/picomatch.js +0 -361
- package/node_modules/picomatch/lib/scan.js +0 -403
- package/node_modules/picomatch/lib/utils.js +0 -72
- package/node_modules/picomatch/package.json +0 -83
- package/node_modules/picomatch/posix.js +0 -3
- package/node_modules/tinyglobby/LICENSE +0 -21
- package/node_modules/tinyglobby/README.md +0 -25
- package/node_modules/tinyglobby/dist/index.cjs +0 -335
- package/node_modules/tinyglobby/dist/index.d.cts +0 -148
- package/node_modules/tinyglobby/dist/index.d.mts +0 -148
- package/node_modules/tinyglobby/dist/index.mjs +0 -307
- package/node_modules/tinyglobby/package.json +0 -70
|
@@ -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]="
|
|
2
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw))return!0;const firstCommaIndex=raw.indexOf(","),leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length),equalsIndex=leadingSegment.indexOf("=");return 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))?!1:leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value)if(character==="("&&(depth+=1),character===")"&&(depth-=1),depth<0)return!1;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;const label=trimmed.slice(0,delimiterIndex).trim(),destination=trimmed.slice(delimiterIndex+1).trim();if(!(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)))return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){return raw?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};if(assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS),!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){return raw?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){return raw?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"),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);if(assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS),!kv.path)throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE);return kv.path}return trimmed}):[]}function parseMigrateEntries(raw){return raw?raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim(),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)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=>storedLinkedPath(applyPathMigrations(entry.path,migrations)))),conflicts=[...new Set(removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length!==0)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);return invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)?normalizeLinkedPath(path.normalize(trimmed)):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),matches=await glob(entry.pattern,{cwd:invocationRoot,absolute:absolutePattern,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),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();return trimmed.length===0?adds: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);return byPath!==0?byPath: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)),existingFiles=[],missingPaths=[],nonFilePaths=[],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{(await fs.stat(resolvedPath)).isFile()?existingFiles.push(relativePath):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);migratedPath!==current[index].path&&(count+=1);const storedPath=storedLinkedPath(migratedPath);storedPath!==current[index].path&&(current[index]={...current[index],path:storedPath})}return{adds:adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);return migratedPath!==entry.path&&(count+=1),{...entry,path:storedLinkedPath(migratedPath)}}),removes:removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))),count}}function storedLinkedPath(value){return value.replaceAll("\\","/")}function storedLinkKey(entry){return`${entry.scope}\0${storedLinkedPath(entry.path)}`}function linkedArtifactOutcomes(baseline,merged,adds){const before=new Map(baseline.map(entry=>[storedLinkKey(entry),entry.note])),after=new Map(merged.map(entry=>[storedLinkKey(entry),entry.note])),outcomes=new Map;for(const add of adds){const key=storedLinkKey(add);outcomes.has(key)||outcomes.set(key,{path:storedLinkedPath(add.path),scope:add.scope,outcome:classifyLinkOutcome(before.has(key),before.get(key),after.get(key))})}return[...outcomes.values()]}function classifyLinkOutcome(existed,prior,final){return existed?final===prior?"unchanged":prior===void 0?"note_added":final?.startsWith(`${prior}${LINKED_ARTIFACT_NOTE_JOINER}`)?"note_appended":"note_replaced":"added"}function applyLinkedArtifactAdd(state,add,noteConflict){const index=state.merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope),stored=state.merged[index];if(stored===void 0){state.merged.push(add),add.note!==void 0&&state.notedHere.add(add);return}const revision=reviseLinkedNote(stored.note,add.note,noteConflict);if(revision.conflict)state.conflicts.push({path:add.path,scope:add.scope,existing_note:stored.note,requested_note:add.note,source:state.notedHere.has(stored)?"this_write":"stored"});else if(revision.note!==stored.note){const revised={...stored,note:revision.note};state.merged[index]=revised,state.notedHere.add(revised)}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable,noteConflict){const baseline=dedupeLinkedArtifacts(current),state={merged:[...baseline],notedHere:new Set,conflicts:[]};for(const add of adds)applyLinkedArtifactAdd(state,add,noteConflict);const{merged}=state,outcomes=linkedArtifactOutcomes(baseline,merged,adds);if(removes.length>0)for(let index=merged.length-1;index>=0;index-=1)removes.includes(merged[index].path)&&merged.splice(index,1);return{entries:appendStable?merged:sortLinkedArtifacts(merged),outcomes,conflicts:state.conflicts}}async function buildLinkedArtifactResult(params){const returned=params.mutation?.entries??params.artifacts,validated=params.options.validatePaths?params.artifacts:returned,{counts,receipts}=linkedCollectionMutationFields(params.mutation);return{id:params.id,artifacts:returned,changed:params.changed,count:returned.length,...counts,migrations_applied:params.migrationsApplied&¶ms.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed&&validated.length>0?await validateLinkedPaths(validated.map(entry=>entry.path),params.workspaceRoot):void 0,...receipts}}function countRemovedLinkedArtifacts(before,after,migrations){const remaining=new Map;for(const entry of after){const key=artifactKey(entry);remaining.set(key,(remaining.get(key)??0)+1)}let removed=0;for(const entry of before){const key=artifactKey({...entry,path:storedLinkedPath(applyPathMigrations(entry.path,migrations))}),left=remaining.get(key)??0;left>0?remaining.set(key,left-1):removed+=1}return removed}function findMisreadNoteSegment(entry,bareNoun){const segments=/[\n\r]|^\s*[-*+`]/u.test(entry)?[]:splitStructuredEntrySegments(entry),noteIndex=segments.findIndex(segment=>segment.key?.toLowerCase()==="note");if(noteIndex<0)return;const fields=segments.slice(0,noteIndex).map(segment=>segment.raw.trim()),keys=new Set(segments.slice(0,noteIndex).map(segment=>segment.key?.toLowerCase())),prose=[segments[noteIndex].value];let misread;for(const segment of segments.slice(noteIndex+1)){const key=segment.key?.toLowerCase();if((key==="path"||key==="scope")&&!keys.has(key)){fields.push(segment.raw.trim()),keys.add(key);continue}misread??=segment.key===void 0?void 0:{segment:segment.text.trim(),key:segment.key},prose.push(segment.text)}if(misread===void 0)return;const note=prose.join(",").trim(),rewritten=[...fields,`note=${JSON.stringify(note)}`].join(",");try{parseAddEntries([rewritten],bareNoun)}catch{return}return{entry:rewritten,note,...misread}}function firstRefusedAddEntry(entries,bareNoun){return entries.findIndex(entry=>{try{return parseAddEntries([entry],bareNoun),!1}catch{return!0}})+1}function repeatFlag(flag,values,literalKey){return(values??[]).flatMap(value=>[flag,literalKey!==void 0&&value.trim()==="-"?`${literalKey}=-`:value])}function noteRecoveryRetryArgs(params){const{options}=params,noteConflict=params.noteConflict??options.noteConflict;return[...resolvePmCommandScopeArgs(params.global),...params.guards.map(guard=>`--expect-hash=${guard}`),params.config.metadataKey,params.id,...repeatFlag("--add",params.entries.map((entry,index)=>index===params.position-1?params.rewritten:entry),"path"),...repeatFlag("--add-glob",params.resolved.addGlob,"pattern"),...repeatFlag("--remove",params.resolved.remove,"path"),...repeatFlag("--migrate",params.resolved.migrate),...options.note===void 0?[]:["--note",options.note],...noteConflict===void 0?[]:["--note-conflict",noteConflict],...params.config.supportsAppendStable&&options.appendStable===!0?["--append-stable"]:[],...options.validatePaths===!0?["--validate-paths"]:[],...options.fullHistory===!0?["--full-history"]:[],...options.author?["--author",options.author]:[],...options.message?["--message",options.message]:[],...options.force===!0?["--force"]:[]]}function misreadKeyHint(key){return LINKED_ARTIFACT_ADD_KEYS.some(allowed=>allowed===key.toLowerCase())?`If "${key}" was meant as a key, give it once per entry.`:`If "${key}" was meant as a key, it is not one of: ${LINKED_ARTIFACT_ADD_KEYS.join(", ")}.`}function parseAddEntriesWithNoteRecovery(params){try{return parseAddEntries(params.entries,params.config.bareNoun)}catch(error){const entries=params.entries,cause=error,position=firstRefusedAddEntry(entries,params.config.bareNoun),misread=findMisreadNoteSegment(entries[position-1],params.config.bareNoun);if(misread===void 0)throw error;const guards=activeItemRevisionExpectations(params.pmRoot),retryArgs=guards===void 0?void 0:noteRecoveryRetryArgs({...params,entries,position,rewritten:misread.entry,guards});throw new PmCliError(`--add read the note segment "${misread.segment}" as a new key "${misread.key}", so the ${params.config.bareNoun} link was refused (${cause.message})`,EXIT_CODE.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:entries[position-1],required:`Retry with the note quoted so its commas stay prose (${retryArgs===void 0?`as ${misread.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${misreadKeyHint(misread.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...retryArgs===void 0?{}:{nextSteps:[renderPmCommand(retryArgs)]},details:{entry_index:position,misread_segment:misread.segment,misread_key:misread.key,note:misread.note,rewritten_entry:misread.entry,cause:cause.context.code??"invalid_argument_value"},...retryArgs===void 0?{}:{recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}}})}}function linkedCollectionMutationFields(mutation){return mutation===void 0?{counts:{},receipts:{}}:{counts:{total_count:mutation.total_count,returned_count:mutation.returned_count,has_more:mutation.has_more},receipts:{mutation_receipt:mutation.mutation_receipt,omission_receipt:mutation.omission_receipt}}}async function readLinkedArtifacts(params){const{settings,config}=params,located=await locateItem(params.pmRoot,params.id,settings.id_prefix,settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Item ${params.id} not found`,EXIT_CODE.NOT_FOUND);const artifacts=(await readLocatedItem(located,{schema:settings.schema})).document.metadata[config.metadataKey]??[],mutation=params.writeRequested?projectLinkedCollectionMutation({collectionKey:config.metadataKey,stored:artifacts,written:[],removedCount:0,fullHistory:params.options.fullHistory===!0}):void 0;return buildLinkedArtifactResult({id:located.id,artifacts,changed:!1,options:params.options,workspaceRoot:params.workspaceRoot,mutation})}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config,stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot),invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate"),parsedAdds=parseAddEntriesWithNoteRecovery({id,pmRoot,entries:resolvedAdds,resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config}).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)})),addGlobs=parseAddGlobEntries(resolvedAddGlobs),expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot),hasAddFlags=parsedAdds.length>0||addGlobs.length>0,adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,hasAddFlags),noteConflict=parseNoteConflictMode(options.noteConflict,hasAddFlags),removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot)),migrations=parseMigrateEntries(resolvedMigrations);if(assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations),!(adds.length>0||removes.length>0||migrations.length>0))return readLinkedArtifacts({id,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,options,workspaceRoot,config,writeRequested:addGlobs.length>0});const author=resolveAuthor(options.author,settings.author_default);let before=[],removedCount=0,linkOutcomes=[];const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:!0,mutate(document){const metadata=document.metadata,current=metadata[metadataKey]??[],next=[...current],migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations),merge=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===!0,noteConflict);if(merge.conflicts.length>0){const guards=activeItemRevisionExpectations(pmRoot);throw buildNoteConflictError({itemId:document.metadata.id,noun:config.bareNoun,conflicts:merge.conflicts,retryArgs:mode=>guards===void 0?void 0:noteRecoveryRetryArgs({id:document.metadata.id,entries:resolvedAdds??[],position:0,rewritten:"",resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config,guards,noteConflict:mode}),render:renderPmCommand})}const normalized=merge.entries;linkOutcomes=merge.outcomes,normalized.length>0?metadata[metadataKey]=normalized:delete metadata[metadataKey];const changed=!stableValueEquals(current,normalized);return before=current,removedCount=countRemovedLinkedArtifacts(current,normalized,migrations),{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}}),artifacts=result.item[metadataKey]??[],migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:")),migrationCount=migrationWarning?Number(migrationWarning.slice(24)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot,mutation:projectLinkedCollectionMutation({collectionKey:metadataKey,stored:artifacts,written:writtenLinkedEntries(before,artifacts),removedCount,fullHistory:options.fullHistory===!0,linkOutcomes})})}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_NOTE_CONFLICT_MODES,LINKED_ARTIFACT_NOTE_JOINER,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,buildNoteConflictError,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,findMisreadNoteSegment,linkedCollectionMutationFields,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseNoteConflictMode,parseRemoveEntries,projectLinkedCollectionMutation,renameArtifactsResultKey,reviseLinkedNote,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,writtenLinkedEntries};
|
|
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]="13ad37f7-4c20-57f1-840a-b2c25dcac090")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{expandFileGlob}from"../core/fs/file-glob.js";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,createStdinTokenResolver,looksLikeGenericKeyValueEntry,parseCsvKv,splitStructuredEntrySegments}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";import{renderPmCommand,resolvePmCommandScopeArgs}from"./command-line.js";import{activeItemRevisionExpectations}from"../core/store/item-mutation-precondition.js";const LINKED_ARTIFACT_NOTE_CONFLICT_MODES=["refuse","replace","append"],LINKED_ARTIFACT_NOTE_JOINER="; ";function parseNoteConflictMode(raw,hasAddFlags){if(raw===void 0)return"refuse";const mode=raw.trim().toLowerCase();if(!LINKED_ARTIFACT_NOTE_CONFLICT_MODES.some(allowed=>allowed===mode))throw new PmCliError(`--note-conflict must be one of ${LINKED_ARTIFACT_NOTE_CONFLICT_MODES.join(", ")}; got "${raw}"`,EXIT_CODE.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:raw,required:`Pass --note-conflict ${LINKED_ARTIFACT_NOTE_CONFLICT_MODES.join("|")}.`});if(!hasAddFlags)throw new PmCliError("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",EXIT_CODE.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return mode}function reviseLinkedNote(existing,requested,mode){if(requested===void 0||requested===existing)return{note:existing,outcome:"unchanged",conflict:!1};if(existing===void 0)return{note:requested,outcome:"note_added",conflict:!1};if(mode==="replace")return{note:requested,outcome:"note_replaced",conflict:!1};if(mode==="append"){const joiner=LINKED_ARTIFACT_NOTE_JOINER;return`${joiner}${existing}${joiner}`.includes(`${joiner}${requested}${joiner}`)?{note:existing,outcome:"unchanged",conflict:!1}:{note:`${existing}${LINKED_ARTIFACT_NOTE_JOINER}${requested}`,outcome:"note_appended",conflict:!1}}return{note:existing,outcome:"unchanged",conflict:!0}}function buildNoteConflictError(params){const first=params.conflicts[0],more=params.conflicts.length>1?` and ${params.conflicts.length-1} more`:"",append=params.retryArgs("append"),replace=params.retryArgs("replace"),message=first.source==="stored"?`${params.itemId} already links ${params.noun} ${first.path} with the note "${first.existing_note}"${more}; the add was refused so that note is kept`:`The add names ${params.noun} ${first.path} on ${params.itemId} with two notes, "${first.existing_note}" and then "${first.requested_note}"${more}; the add was refused because they disagree`;return new PmCliError(message,EXIT_CODE.CONFLICT,{code:"linked_artifact_note_conflict",item_id:params.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...append===void 0||replace===void 0?{}:{nextSteps:[params.render(append),params.render(replace)],recovery:{suggested_retry:params.render(append),suggested_retry_args:append}},details:{conflicts:params.conflicts.map(conflict=>({...conflict}))}})}const LINKED_ARTIFACT_ADD_KEYS=["path","scope","note"],LINKED_ARTIFACT_ADD_GLOB_KEYS=["pattern","glob","path","scope","note"],LINKED_ARTIFACT_REMOVE_KEYS=["path"],LINKED_ARTIFACT_MIGRATE_KEYS=["from","to"],LINKED_ARTIFACT_REMOVE_UNSUPPORTED_KEYS=new Set(["note","scope"]);function persistedLinkedForm(entry){return JSON.parse(JSON.stringify(entry))}function writtenLinkedEntries(before,after){const unmatched=before.map(persistedLinkedForm);return after.filter(entry=>{const persisted=persistedLinkedForm(entry),index=unmatched.findIndex(candidate=>stableValueEquals(candidate,persisted));return index>=0&&unmatched.splice(index,1),index<0})}function projectLinkedCollectionMutation(params){const entries=params.fullHistory?[...params.stored]:[...params.written],withheld=entries.length<params.stored.length;return{entries,total_count:params.stored.length,returned_count:entries.length,has_more:withheld,mutation_receipt:{changed_count:params.written.length,removed_count:params.removedCount,full_history_included:!withheld,...params.linkOutcomes&¶ms.linkOutcomes.length>0?{link_outcomes:[...params.linkOutcomes]}:{}},omission_receipt:{has_omissions:withheld,omitted_field_group_count:withheld?1:0,omitted_field_groups:withheld?[{name:`${params.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}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(`
|
|
2
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(raw))return!0;const firstCommaIndex=raw.indexOf(","),leadingSegment=raw.slice(0,firstCommaIndex>=0?firstCommaIndex:raw.length),equalsIndex=leadingSegment.indexOf("=");return 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))?!1:leadingSegment.includes("=")||looksLikeGenericKeyValueEntry(raw)}function hasBalancedParentheses(value){let depth=0;for(const character of value)if(character==="("&&(depth+=1),character===")"&&(depth-=1),depth<0)return!1;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;const label=trimmed.slice(0,delimiterIndex).trim(),destination=trimmed.slice(delimiterIndex+1).trim();if(!(label.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(destination)))return{path:destination,scope:"project",note:label}}function parseAddEntries(raw,bareNoun){return raw?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};if(assertNoUnknownCsvKeys(kv,"--add",LINKED_ARTIFACT_ADD_KEYS),!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){return raw?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){return raw?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"),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);if(assertNoUnknownCsvKeys(kv,"--remove",LINKED_ARTIFACT_REMOVE_KEYS),!kv.path)throw new PmCliError("--remove key/value form requires path=<value>",EXIT_CODE.USAGE);return kv.path}return trimmed}):[]}function parseMigrateEntries(raw){return raw?raw.map(entry=>{const kv=parseCsvKv(entry,"--migrate");assertNoUnknownCsvKeys(kv,"--migrate",LINKED_ARTIFACT_MIGRATE_KEYS);const from=kv.from?.trim(),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)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=>storedLinkedPath(applyPathMigrations(entry.path,migrations)))),conflicts=[...new Set(removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))).filter(entry=>addedPaths.has(entry)))].sort((left,right)=>left.localeCompare(right));if(conflicts.length!==0)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);return invocationRelativeToWorkspace.startsWith(`..${path.sep}`)||invocationRelativeToWorkspace===".."||path.isAbsolute(invocationRelativeToWorkspace)?normalizeLinkedPath(path.normalize(trimmed)):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 matches=await expandFileGlob(entry.pattern,invocationRoot),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();return trimmed.length===0?adds: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);return byPath!==0?byPath: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)),existingFiles=[],missingPaths=[],nonFilePaths=[],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{(await fs.stat(resolvedPath)).isFile()?existingFiles.push(relativePath):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);migratedPath!==current[index].path&&(count+=1);const storedPath=storedLinkedPath(migratedPath);storedPath!==current[index].path&&(current[index]={...current[index],path:storedPath})}return{adds:adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);return migratedPath!==entry.path&&(count+=1),{...entry,path:storedLinkedPath(migratedPath)}}),removes:removes.map(entry=>storedLinkedPath(applyPathMigrations(entry,migrations))),count}}function storedLinkedPath(value){return value.replaceAll("\\","/")}function storedLinkKey(entry){return`${entry.scope}\0${storedLinkedPath(entry.path)}`}function linkedArtifactOutcomes(baseline,merged,adds){const before=new Map(baseline.map(entry=>[storedLinkKey(entry),entry.note])),after=new Map(merged.map(entry=>[storedLinkKey(entry),entry.note])),outcomes=new Map;for(const add of adds){const key=storedLinkKey(add);outcomes.has(key)||outcomes.set(key,{path:storedLinkedPath(add.path),scope:add.scope,outcome:classifyLinkOutcome(before.has(key),before.get(key),after.get(key))})}return[...outcomes.values()]}function classifyLinkOutcome(existed,prior,final){return existed?final===prior?"unchanged":prior===void 0?"note_added":final?.startsWith(`${prior}${LINKED_ARTIFACT_NOTE_JOINER}`)?"note_appended":"note_replaced":"added"}function applyLinkedArtifactAdd(state,add,noteConflict){const index=state.merged.findIndex(entry=>entry.path===add.path&&entry.scope===add.scope),stored=state.merged[index];if(stored===void 0){state.merged.push(add),add.note!==void 0&&state.notedHere.add(add);return}const revision=reviseLinkedNote(stored.note,add.note,noteConflict);if(revision.conflict)state.conflicts.push({path:add.path,scope:add.scope,existing_note:stored.note,requested_note:add.note,source:state.notedHere.has(stored)?"this_write":"stored"});else if(revision.note!==stored.note){const revised={...stored,note:revision.note};state.merged[index]=revised,state.notedHere.add(revised)}}function mergeLinkedArtifactChanges(current,adds,removes,appendStable,noteConflict){const baseline=dedupeLinkedArtifacts(current),state={merged:[...baseline],notedHere:new Set,conflicts:[]};for(const add of adds)applyLinkedArtifactAdd(state,add,noteConflict);const{merged}=state,outcomes=linkedArtifactOutcomes(baseline,merged,adds);if(removes.length>0)for(let index=merged.length-1;index>=0;index-=1)removes.includes(merged[index].path)&&merged.splice(index,1);return{entries:appendStable?merged:sortLinkedArtifacts(merged),outcomes,conflicts:state.conflicts}}async function buildLinkedArtifactResult(params){const returned=params.mutation?.entries??params.artifacts,validated=params.options.validatePaths?params.artifacts:returned,{counts,receipts}=linkedCollectionMutationFields(params.mutation);return{id:params.id,artifacts:returned,changed:params.changed,count:returned.length,...counts,migrations_applied:params.migrationsApplied&¶ms.migrationsApplied>0?params.migrationsApplied:void 0,validation:params.options.validatePaths||params.changed&&validated.length>0?await validateLinkedPaths(validated.map(entry=>entry.path),params.workspaceRoot):void 0,...receipts}}function countRemovedLinkedArtifacts(before,after,migrations){const remaining=new Map;for(const entry of after){const key=artifactKey(entry);remaining.set(key,(remaining.get(key)??0)+1)}let removed=0;for(const entry of before){const key=artifactKey({...entry,path:storedLinkedPath(applyPathMigrations(entry.path,migrations))}),left=remaining.get(key)??0;left>0?remaining.set(key,left-1):removed+=1}return removed}function findMisreadNoteSegment(entry,bareNoun){const segments=/[\n\r]|^\s*[-*+`]/u.test(entry)?[]:splitStructuredEntrySegments(entry),noteIndex=segments.findIndex(segment=>segment.key?.toLowerCase()==="note");if(noteIndex<0)return;const fields=segments.slice(0,noteIndex).map(segment=>segment.raw.trim()),keys=new Set(segments.slice(0,noteIndex).map(segment=>segment.key?.toLowerCase())),prose=[segments[noteIndex].value];let misread;for(const segment of segments.slice(noteIndex+1)){const key=segment.key?.toLowerCase();if((key==="path"||key==="scope")&&!keys.has(key)){fields.push(segment.raw.trim()),keys.add(key);continue}misread??=segment.key===void 0?void 0:{segment:segment.text.trim(),key:segment.key},prose.push(segment.text)}if(misread===void 0)return;const note=prose.join(",").trim(),rewritten=[...fields,`note=${JSON.stringify(note)}`].join(",");try{parseAddEntries([rewritten],bareNoun)}catch{return}return{entry:rewritten,note,...misread}}function firstRefusedAddEntry(entries,bareNoun){return entries.findIndex(entry=>{try{return parseAddEntries([entry],bareNoun),!1}catch{return!0}})+1}function repeatFlag(flag,values,literalKey){return(values??[]).flatMap(value=>[flag,literalKey!==void 0&&value.trim()==="-"?`${literalKey}=-`:value])}function noteRecoveryRetryArgs(params){const{options}=params,noteConflict=params.noteConflict??options.noteConflict;return[...resolvePmCommandScopeArgs(params.global),...params.guards.map(guard=>`--expect-hash=${guard}`),params.config.metadataKey,params.id,...repeatFlag("--add",params.entries.map((entry,index)=>index===params.position-1?params.rewritten:entry),"path"),...repeatFlag("--add-glob",params.resolved.addGlob,"pattern"),...repeatFlag("--remove",params.resolved.remove,"path"),...repeatFlag("--migrate",params.resolved.migrate),...options.note===void 0?[]:["--note",options.note],...noteConflict===void 0?[]:["--note-conflict",noteConflict],...params.config.supportsAppendStable&&options.appendStable===!0?["--append-stable"]:[],...options.validatePaths===!0?["--validate-paths"]:[],...options.fullHistory===!0?["--full-history"]:[],...options.author?["--author",options.author]:[],...options.message?["--message",options.message]:[],...options.force===!0?["--force"]:[]]}function misreadKeyHint(key){return LINKED_ARTIFACT_ADD_KEYS.some(allowed=>allowed===key.toLowerCase())?`If "${key}" was meant as a key, give it once per entry.`:`If "${key}" was meant as a key, it is not one of: ${LINKED_ARTIFACT_ADD_KEYS.join(", ")}.`}function parseAddEntriesWithNoteRecovery(params){try{return parseAddEntries(params.entries,params.config.bareNoun)}catch(error){const entries=params.entries,cause=error,position=firstRefusedAddEntry(entries,params.config.bareNoun),misread=findMisreadNoteSegment(entries[position-1],params.config.bareNoun);if(misread===void 0)throw error;const guards=activeItemRevisionExpectations(params.pmRoot),retryArgs=guards===void 0?void 0:noteRecoveryRetryArgs({...params,entries,position,rewritten:misread.entry,guards});throw new PmCliError(`--add read the note segment "${misread.segment}" as a new key "${misread.key}", so the ${params.config.bareNoun} link was refused (${cause.message})`,EXIT_CODE.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:entries[position-1],required:`Retry with the note quoted so its commas stay prose (${retryArgs===void 0?`as ${misread.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${misreadKeyHint(misread.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...retryArgs===void 0?{}:{nextSteps:[renderPmCommand(retryArgs)]},details:{entry_index:position,misread_segment:misread.segment,misread_key:misread.key,note:misread.note,rewritten_entry:misread.entry,cause:cause.context.code??"invalid_argument_value"},...retryArgs===void 0?{}:{recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}}})}}function linkedCollectionMutationFields(mutation){return mutation===void 0?{counts:{},receipts:{}}:{counts:{total_count:mutation.total_count,returned_count:mutation.returned_count,has_more:mutation.has_more},receipts:{mutation_receipt:mutation.mutation_receipt,omission_receipt:mutation.omission_receipt}}}async function readLinkedArtifacts(params){const{settings,config}=params,located=await locateItem(params.pmRoot,params.id,settings.id_prefix,settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Item ${params.id} not found`,EXIT_CODE.NOT_FOUND);const artifacts=(await readLocatedItem(located,{schema:settings.schema})).document.metadata[config.metadataKey]??[],mutation=params.writeRequested?projectLinkedCollectionMutation({collectionKey:config.metadataKey,stored:artifacts,written:[],removedCount:0,fullHistory:params.options.fullHistory===!0}):void 0;return buildLinkedArtifactResult({id:located.id,artifacts,changed:!1,options:params.options,workspaceRoot:params.workspaceRoot,mutation})}async function runLinkedArtifacts(id,options,global2,config){const{metadataKey}=config,stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path),workspaceRoot=resolveWorkspaceRoot(pmRoot),invocationRoot=process.cwd();await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddGlobs=await stdinResolver.resolveList(options.addGlob,"--add-glob"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),resolvedMigrations=await stdinResolver.resolveList(options.migrate,"--migrate"),parsedAdds=parseAddEntriesWithNoteRecovery({id,pmRoot,entries:resolvedAdds,resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config}).map(entry=>({...entry,path:anchorLinkedPath(entry.path,workspaceRoot,invocationRoot)})),addGlobs=parseAddGlobEntries(resolvedAddGlobs),expandedGlobAdds=await expandAddGlobEntries(addGlobs,workspaceRoot,invocationRoot),hasAddFlags=parsedAdds.length>0||addGlobs.length>0,adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,hasAddFlags),noteConflict=parseNoteConflictMode(options.noteConflict,hasAddFlags),removes=parseRemoveEntries(resolvedRemoves).map(entry=>anchorLinkedPath(entry,workspaceRoot,invocationRoot)),migrations=parseMigrateEntries(resolvedMigrations);if(assertLinkedArtifactMutationIsUnambiguous(adds,removes,migrations),!(adds.length>0||removes.length>0||migrations.length>0))return readLinkedArtifacts({id,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,options,workspaceRoot,config,writeRequested:addGlobs.length>0});const author=resolveAuthor(options.author,settings.author_default);let before=[],removedCount=0,linkOutcomes=[];const result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,skipNoop:!0,mutate(document){const metadata=document.metadata,current=metadata[metadataKey]??[],next=[...current],migrated=applyLinkedArtifactMigrations(next,adds,removes,migrations),merge=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===!0,noteConflict);if(merge.conflicts.length>0){const guards=activeItemRevisionExpectations(pmRoot);throw buildNoteConflictError({itemId:document.metadata.id,noun:config.bareNoun,conflicts:merge.conflicts,retryArgs:mode=>guards===void 0?void 0:noteRecoveryRetryArgs({id:document.metadata.id,entries:resolvedAdds??[],position:0,rewritten:"",resolved:{addGlob:resolvedAddGlobs,remove:resolvedRemoves,migrate:resolvedMigrations},options,global:global2,config,guards,noteConflict:mode}),render:renderPmCommand})}const normalized=merge.entries;linkOutcomes=merge.outcomes,normalized.length>0?metadata[metadataKey]=normalized:delete metadata[metadataKey];const changed=!stableValueEquals(current,normalized);return before=current,removedCount=countRemovedLinkedArtifacts(current,normalized,migrations),{changedFields:changed?[metadataKey]:[],warnings:changed&&migrated.count>0?[`path_migrations_applied:${migrated.count}`]:[]}}}),artifacts=result.item[metadataKey]??[],migrationWarning=result.warnings.find(warning=>warning.startsWith("path_migrations_applied:")),migrationCount=migrationWarning?Number(migrationWarning.slice(24)):0;return buildLinkedArtifactResult({id:result.item.id,artifacts,changed:result.changedFields.includes(metadataKey),migrationsApplied:migrationCount,options,workspaceRoot,mutation:projectLinkedCollectionMutation({collectionKey:metadataKey,stored:artifacts,written:writtenLinkedEntries(before,artifacts),removedCount,fullHistory:options.fullHistory===!0,linkOutcomes})})}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_NOTE_CONFLICT_MODES,LINKED_ARTIFACT_NOTE_JOINER,LINKED_ARTIFACT_REMOVE_KEYS,anchorLinkedPath,applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,buildNoteConflictError,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,findMisreadNoteSegment,linkedCollectionMutationFields,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseNoteConflictMode,parseRemoveEntries,projectLinkedCollectionMutation,renameArtifactsResultKey,reviseLinkedNote,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,writtenLinkedEntries};
|
|
3
3
|
//# sourceMappingURL=linked-artifacts.js.map
|
|
@@ -19,11 +19,23 @@ stale_in_progress_hours:number;}
|
|
|
19
19
|
export interface SecretGuardFinding{
|
|
20
20
|
/** Stable detector identifier suitable for tests and telemetry. */
|
|
21
21
|
rule:(typeof SECRET_RULES)[number]["mutationRule"];
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Object path or argument index containing the match. A property name that a
|
|
24
|
+
* rule matches is never repeated in a path: its segment is the positional
|
|
25
|
+
* placeholder `[key <n>]`, its index among the object's own entries
|
|
26
|
+
* (pm-x07qz2). Other property names appear as written, including a name
|
|
27
|
+
* that merely equals a value another rule flags.
|
|
28
|
+
*/
|
|
23
29
|
path:string;
|
|
30
|
+
/** The match is in the property name at `path`, not in the value it holds. */
|
|
31
|
+
property_name?:true;
|
|
24
32
|
/** Detection-only transformations, without original or decoded coordinate values. */
|
|
25
33
|
normalizations?:SecretNormalizationKind[];
|
|
26
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* The value could not be inspected completely and requires explicit review:
|
|
36
|
+
* remaining encoded input exceeded the finite inspection envelope, or the
|
|
37
|
+
* value was too large for the rule's pattern to judge.
|
|
38
|
+
*/
|
|
27
39
|
normalization_incomplete?:true;}
|
|
28
40
|
/** Result of a non-blocking or bypassed mutation guard evaluation. */
|
|
29
41
|
export interface MutationGuardResult{
|
|
@@ -39,7 +51,12 @@ override_applied:boolean;}
|
|
|
39
51
|
export interface EvaluateMutationGuardOptions{
|
|
40
52
|
/** Effective mutation author after normal CLI/SDK precedence resolution. */
|
|
41
53
|
author:string;
|
|
42
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* Arbitrary mutation payload. String leaves and property names are
|
|
56
|
+
* inspected on their own, and a leaf under a property whose name ends with a
|
|
57
|
+
* credential key is also judged as that key's value, as in its JSON spelling
|
|
58
|
+
* `{"<name>": <value>}`.
|
|
59
|
+
*/
|
|
43
60
|
payload:unknown;
|
|
44
61
|
/** Workspace guard settings. */
|
|
45
62
|
settings:MutationGuardSettings;
|
|
@@ -60,7 +77,11 @@ history_scope:MutationHistoryScope;}
|
|
|
60
77
|
* mutation occurs.
|
|
61
78
|
*/
|
|
62
79
|
export declare const PM_MUTATION_ACTION_CONTRACTS:readonly[{readonly action:"append";readonly history_scope:"item";},{readonly action:"claim";readonly history_scope:"item";},{readonly action:"close";readonly history_scope:"item";},{readonly action:"close-many";readonly history_scope:"item";},{readonly action:"close-task";readonly history_scope:"item";},{readonly action:"comments";readonly history_scope:"conditional";},{readonly action:"config";readonly history_scope:"conditional";},{readonly action:"copy";readonly history_scope:"item";},{readonly action:"create";readonly history_scope:"item";},{readonly action:"delete";readonly history_scope:"item";},{readonly action:"deps";readonly history_scope:"conditional";},{readonly action:"discover";readonly history_scope:"item";},{readonly action:"docs";readonly history_scope:"conditional";},{readonly action:"files";readonly history_scope:"conditional";},{readonly action:"focus";readonly history_scope:"conditional";},{readonly action:"gc";readonly history_scope:"conditional";},{readonly action:"history-compact";readonly history_scope:"history";},{readonly action:"history-author-acknowledge";readonly history_scope:"workspace";},{readonly action:"history-redact";readonly history_scope:"history";},{readonly action:"history-repair";readonly history_scope:"history";},{readonly action:"init";readonly history_scope:"workspace";},{readonly action:"install";readonly history_scope:"conditional";},{readonly action:"learnings";readonly history_scope:"conditional";},{readonly action:"notes";readonly history_scope:"conditional";},{readonly action:"package";readonly history_scope:"conditional";},{readonly action:"pause-task";readonly history_scope:"item";},{readonly action:"plan";readonly history_scope:"conditional";},{readonly action:"profile";readonly history_scope:"conditional";},{readonly action:"release";readonly history_scope:"item";},{readonly action:"restore";readonly history_scope:"item";},{readonly action:"schema";readonly history_scope:"conditional";},{readonly action:"start-task";readonly history_scope:"item";},{readonly action:"templates";readonly history_scope:"conditional";},{readonly action:"test";readonly history_scope:"conditional";},{readonly action:"test-all";readonly history_scope:"conditional";},{readonly action:"update";readonly history_scope:"item";},{readonly action:"update-many";readonly history_scope:"item";},{readonly action:"upgrade";readonly history_scope:"conditional";}];
|
|
63
|
-
/**
|
|
80
|
+
/**
|
|
81
|
+
* Detect credential-shaped string leaves, property names and credential-named
|
|
82
|
+
* members without returning matched values: a flagged property name appears
|
|
83
|
+
* in a path only as its positional placeholder.
|
|
84
|
+
*/
|
|
64
85
|
export declare function scanMutationSecrets(payload:unknown):SecretGuardFinding[];
|
|
65
86
|
/**
|
|
66
87
|
* Enforce shared provenance and secret policy before a mutation is dispatched.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d6059407-bf03-5ae8-8b01-e3e7c5b28030")}catch{}})();import{SECRET_RULES,findSecretRuleMatches}from"../core/shared/secret-rules.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const PM_MUTATION_ACTION_CONTRACTS=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],MUTATION_ACTION_CONTRACTS_BY_NAME=new Map(PM_MUTATION_ACTION_CONTRACTS.map(contract=>[contract.action,contract]));function stringLeaves(value,path="$",seen=new WeakSet){return typeof value=="string"?[{path,value}]:typeof value!="object"||value===null?[]:seen.has(value)?[]:(seen.add(value),Array.isArray(value)?value.flatMap((entry,index)=>stringLeaves(entry,`${path}[${index}]`,seen)):Object.entries(value).flatMap(([key,entry])=>stringLeaves(entry,`${path}.${key}`,seen)))}function preflightRuleMatch(rule,value){const matches=findSecretRuleMatches(rule,value),first=matches.next().value;if(!first||rule.mutationRule!=="absolute_home_path"||first.normalization_incomplete)return first;for(const later of matches)if(later.normalization_incomplete)return{...first,normalizations:[...new Set([first.normalizations,later.normalizations].flatMap(kinds=>kinds??[]))],normalization_incomplete:!0};return first}function scanMutationSecrets(payload){const findings=[];for(const leaf of stringLeaves(payload))for(const rule of SECRET_RULES){const match=preflightRuleMatch(rule,leaf.value);if(match){const finding={rule:rule.mutationRule,path:leaf.path};match.normalizations&&(finding.normalizations=match.normalizations),match.normalization_incomplete&&(finding.normalization_incomplete=!0),findings.push(finding)}}return findings.filter((finding,index,all)=>all.findIndex(candidate=>candidate.rule===finding.rule&&candidate.path===finding.path)===index)}function evaluateMutationGuard(options){const author=options.author.trim()||"unknown";if(options.settings.require_attributed_author&&author.toLowerCase()==="unknown")throw new PmCliError("Mutation author is required by workspace policy.",EXIT_CODE.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(options.settings.secret_guard==="off")return{author,findings:[],warnings:[],override_applied:!1};let findings;try{findings=scanMutationSecrets(options.payload)}catch{return{author,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(findings.length===0)return{author,findings,warnings:[],override_applied:!1};const ruleSummary=[...new Set(findings.map(finding=>finding.rule))].sort().join(",");if(options.settings.secret_guard==="block"&&options.force!==!0)throw new PmCliError(`Mutation blocked by secret guard (${ruleSummary}). No detected value was logged.`,EXIT_CODE.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author,findings,warnings:[`secret_guard_detected:${findings.length}:rules=${ruleSummary}`,...options.settings.secret_guard==="block"&&options.force===!0?["secret_guard_force_override"]:[]],override_applied:options.settings.secret_guard==="block"&&options.force===!0}}function isMutationAction(action){return MUTATION_ACTION_CONTRACTS_BY_NAME.has(action.trim().toLowerCase())}function listMutationActions(){return[...MUTATION_ACTION_CONTRACTS_BY_NAME.keys()].sort((left,right)=>left.localeCompare(right))}function getMutationActionContract(action){return MUTATION_ACTION_CONTRACTS_BY_NAME.get(action.trim().toLowerCase())}export{PM_MUTATION_ACTION_CONTRACTS,evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,scanMutationSecrets};
|
|
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]="6175fcf6-186d-50f6-8642-ba3432cf4b64")}catch{}})();import{SECRET_RULES,acceptsStructuredValue,findSecretRuleMatches,structuredKeyShape}from"../core/shared/secret-rules.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const PM_MUTATION_ACTION_CONTRACTS=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],MUTATION_ACTION_CONTRACTS_BY_NAME=new Map(PM_MUTATION_ACTION_CONTRACTS.map(contract=>[contract.action,contract])),ARRAY_INDEX=/^(?:0|[1-9]\d*)$/u,MAX_ARRAY_INDEX=2**32-2;function isArrayIndex(key){return ARRAY_INDEX.test(key)&&Number(key)<=MAX_ARRAY_INDEX}function ruleMatches(value){const matches=[];for(const rule of SECRET_RULES){const match=preflightRuleMatch(rule,value);match&&matches.push({rule,match})}return matches}function nameMatches(name,cache){let matches=cache.names.get(name);return matches===void 0&&(matches=ruleMatches(name),cache.names.set(name,matches)),matches}function ownEntries(value,cache){let entries=cache.entries.get(value);return entries===void 0&&(entries=Array.isArray(value)?Object.getOwnPropertyNames(value).filter(isArrayIndex).map(name=>({name,value:value[Number(name)],segment:`[${name}]`,nameMatches:[]})):Object.entries(value).map(([name,entry],position)=>{const matches=nameMatches(name,cache);return{name,value:entry,segment:matches.length>0?`[key ${position}]`:`.${name}`,nameMatches:matches}}),cache.entries.set(value,entries)),entries}function findingFor({rule,match},path,propertyName){const finding={rule:rule.mutationRule,path};return propertyName&&(finding.property_name=!0),match.normalizations&&(finding.normalizations=match.normalizations),match.normalization_incomplete&&(finding.normalization_incomplete=!0),finding}function pushReversed(pending,children){for(let index=children.length-1;index>=0;index-=1)pending.push(children[index])}function preflightRuleMatch(rule,value){try{return firstRuleMatch(rule,value)}catch(error){return judgeTooLarge(error)}}function judgeTooLarge(error){if(!(error instanceof RangeError))throw error;return{index:0,normalization_incomplete:!0}}function firstRuleMatch(rule,value){const matches=findSecretRuleMatches(rule,value),first=matches.next().value;if(!first||rule.mutationRule!=="absolute_home_path"||first.normalization_incomplete)return first;for(const later of matches)if(later.normalization_incomplete)return{...first,normalizations:[...new Set([first.normalizations,later.normalizations].flatMap(kinds=>kinds??[]))],normalization_incomplete:!0};return first}function scanStringLeaves(payload,cache){const findings=[],seen=new WeakSet,pending=[{value:payload,path:"$"}];for(let step=pending.pop();step!==void 0;step=pending.pop()){const{value,path}=step;if(typeof value=="string")for(const match of ruleMatches(value))findings.push(findingFor(match,path,!1));else if(typeof value=="object"&&value!==null&&!seen.has(value)){seen.add(value);const entries=ownEntries(value,cache);for(const entry of entries)for(const match of entry.nameMatches)findings.push(findingFor(match,`${path}${entry.segment}`,!0));pushReversed(pending,entries.map(entry=>({value:entry.value,path:`${path}${entry.segment}`})))}}return findings}const KEY_NAMED_RULES=SECRET_RULES.filter(rule=>"structured"in rule),NO_KEY_CONTEXT=KEY_NAMED_RULES.map(()=>({named:!1,exact:!1})),CAMEL_BOUNDARY=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/gu,CREDENTIAL_SUFFIX_WORDS=3;function keyWords(name){return name.replace(CAMEL_BOUNDARY,"_")}function nameSpellings(name){const suffixSplits=[...name.matchAll(CAMEL_BOUNDARY)].map(match=>match.index).slice(-CREDENTIAL_SUFFIX_WORDS).map(boundary=>`${keyWords(name.slice(0,boundary))}_${name.slice(boundary)}`);return[...new Set([name,keyWords(name),...suffixSplits])]}function memberKeyShapes(name){const spellings=nameSpellings(name);return KEY_NAMED_RULES.map(rule=>{const shapes=spellings.map(spelling=>structuredKeyShape(rule,spelling));return shapes.includes("exact")?"exact":shapes.includes("prefixed")?"prefixed":void 0})}const NO_JUDGMENTS=KEY_NAMED_RULES.map(()=>{});function memberChildSteps(value,path,contexts,cache){const entries=ownEntries(value,cache);if(Array.isArray(value)){const judgments=contexts.map(({named,exact})=>exact?"lenient":named?"compact":void 0);return entries.map(entry=>({value:entry.value,path:`${path}${entry.segment}`,contexts,judgments}))}return entries.map(({name,value:entry,segment})=>{const shapes=memberKeyShapes(name);return{value:entry,path:`${path}${segment}`,contexts:contexts.map(({named,exact},index)=>({named:named||shapes[index]!==void 0,exact:exact||shapes[index]==="exact"})),judgments:shapes.map((shape,index)=>shape==="exact"?"lenient":shape==="prefixed"||contexts[index].named?"compact":void 0)}})}function scanPayloadMembers(payload,cache){const findings=[],visited=new WeakMap,pending=[{value:payload,path:"$",contexts:NO_KEY_CONTEXT,judgments:NO_JUDGMENTS}];for(let step=pending.pop();step!==void 0;step=pending.pop()){const{value,path,contexts,judgments}=step;if(typeof value=="string"){judgments.forEach((judgment,index)=>{const rule=KEY_NAMED_RULES[index];if(judgment===void 0)return;let accepted;try{accepted=acceptsStructuredValue(rule,value,judgment==="compact")}catch(error){judgeTooLarge(error),findings.push({rule:rule.mutationRule,path,normalization_incomplete:!0});return}accepted&&findings.push({rule:rule.mutationRule,path})});continue}if(typeof value!="object"||value===null)continue;const signature=contexts.map(({named,exact})=>exact?"e":named?"n":"-").join(""),signatures=visited.get(value)??new Set;signatures.has(signature)||(visited.set(value,signatures.add(signature)),pushReversed(pending,memberChildSteps(value,path,contexts,cache)))}return findings}function scanMutationSecrets(payload){const reported=new Set,cache={entries:new WeakMap,names:new Map};return[...scanStringLeaves(payload,cache),...scanPayloadMembers(payload,cache)].filter(finding=>{const key=`${finding.rule}\0${finding.path}\0${finding.property_name===!0}`;return reported.has(key)?!1:(reported.add(key),!0)})}function evaluateMutationGuard(options){const author=options.author.trim()||"unknown";if(options.settings.require_attributed_author&&author.toLowerCase()==="unknown")throw new PmCliError("Mutation author is required by workspace policy.",EXIT_CODE.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(options.settings.secret_guard==="off")return{author,findings:[],warnings:[],override_applied:!1};let findings;try{findings=scanMutationSecrets(options.payload)}catch{return{author,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(findings.length===0)return{author,findings,warnings:[],override_applied:!1};const ruleSummary=[...new Set(findings.map(finding=>finding.rule))].sort().join(",");if(options.settings.secret_guard==="block"&&options.force!==!0)throw new PmCliError(`Mutation blocked by secret guard (${ruleSummary}). No detected value was logged.`,EXIT_CODE.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author,findings,warnings:[`secret_guard_detected:${findings.length}:rules=${ruleSummary}`,...options.settings.secret_guard==="block"&&options.force===!0?["secret_guard_force_override"]:[]],override_applied:options.settings.secret_guard==="block"&&options.force===!0}}function isMutationAction(action){return MUTATION_ACTION_CONTRACTS_BY_NAME.has(action.trim().toLowerCase())}function listMutationActions(){return[...MUTATION_ACTION_CONTRACTS_BY_NAME.keys()].sort((left,right)=>left.localeCompare(right))}function getMutationActionContract(action){return MUTATION_ACTION_CONTRACTS_BY_NAME.get(action.trim().toLowerCase())}export{PM_MUTATION_ACTION_CONTRACTS,evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,scanMutationSecrets};
|
|
2
2
|
//# sourceMappingURL=mutation-guard.js.map
|