@unbrained/pm-cli 2026.11.12 → 2026.11.14
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/register-mutation.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-MR3CRLA7.js → chunk-25BUKX4W.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5NY6EQSX.js → chunk-27FG6ROB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OBTU2BHJ.js → chunk-547OEGDR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6ESY4Y2B.js → chunk-5TGFB34A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GLPUIQDB.js → chunk-65SBMIK6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-T4UC3ZKL.js → chunk-AXTUB74T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KJL42AN5.js → chunk-BHH65KLL.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-C7M54YV6.js +122 -0
- package/dist/cli-bundle/chunks/chunk-DMWL3K4A.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-3DWEBVIK.js → chunk-DVN7CD5B.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FJNHTBJ2.js → chunk-DZ7CWUVM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GDS4DC5A.js → chunk-EXO4PM5J.js} +50 -44
- package/dist/cli-bundle/chunks/chunk-FRCNYOTG.js +9 -0
- package/dist/cli-bundle/chunks/chunk-HXECILIE.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-2K6GJUW7.js → chunk-IDFRGH4X.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-EALO2FPM.js → chunk-JSTBYDLL.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-MELSYAFE.js +124 -0
- package/dist/cli-bundle/chunks/{chunk-L3SA3354.js → chunk-OTM6PXZQ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-PC5DGK3C.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-UY7Z3ZHQ.js → chunk-PF3V443A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OFIXSWJS.js → chunk-U2HVJVA5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2DUUL53Z.js → chunk-V2OAXGHK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-U7MZIX3D.js → chunk-VERRDW3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-SYJT6TVZ.js → item-revision-VGIHIWZM.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-6OB6BGTD.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-T57TAVWI.js → mutation-admission-LL6SGQYU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-5XZXTPNG.js → register-list-query-MCNOV6ML.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-V6WJFL77.js → register-mutation-KYXLYHOK.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-6RQF6IAE.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-HCKCSQWQ.js → register-setup-XGPOFFD3.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-VIDXGF3T.js → stage-ZS7WNUD4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2A4JCFMI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IPIFI4NT.js → chunk-2T6MQ7NP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-32QYILXW.js +82 -0
- package/dist/cli-bundle/focused-chunks/{chunk-5OCUNAQN.js → chunk-3SUKWYR2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4WOF3Q6R.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-5IQPFV4Y.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GB2N4OM7.js → chunk-6C7NBJ7A.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BHYGUVAU.js → chunk-7KNF6RCV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NP5C2TQM.js → chunk-EAYRYXA6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LAIN47EJ.js → chunk-EH7JKGDH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3FN4ON2Z.js → chunk-EXCVUBAE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NSOXVVQX.js → chunk-FNLOLNPQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-HRLGC3P7.js +28 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VUNX6NBR.js → chunk-I7A5VP5E.js} +56 -56
- package/dist/cli-bundle/focused-chunks/{chunk-AXPRCCYM.js → chunk-JHC3X43E.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MKYNDWT3.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SPAEZKVA.js → chunk-RDTHL44U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GBW2EAAG.js → chunk-TA4EGVE6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-P6KYUJD4.js → chunk-UCCLV5GJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-W3RWCLEU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-W57DSFSU.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KN7RBRRH.js → chunk-YNYO7PMT.js} +22 -22
- package/dist/cli-bundle/focused-chunks/{item-revision-PWJNBW3F.js → item-revision-7J7WSCPC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-T6HXC3NS.js → item-transaction-F5YMCPRB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-CLPOLSXZ.js → mutation-admission-2NRQEAOG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-EKYWEU2Y.js → stage-2KVCKOGC.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-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/item/item-format-version.d.ts +6 -5
- package/dist/core/item/item-format-version.js +1 -1
- package/dist/core/item/item-format.js +1 -1
- package/dist/core/lock/lock.js +3 -3
- package/dist/core/output/linked-test-projection.js +6 -0
- package/dist/core/output/output.js +7 -5
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/session/session-state.js +1 -1
- package/dist/core/shared/author.js +2 -2
- package/dist/core/shared/secret-rules.d.ts +8 -2
- package/dist/core/shared/secret-rules.js +3 -3
- package/dist/core/shared/text-normalization.d.ts +24 -0
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/url-credentials.d.ts +33 -5
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/test/run-selectors.d.ts +3 -1
- package/dist/core/test/run-selectors.js +1 -1
- package/dist/sdk/annotations.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/completion/bash.js +1 -1
- package/dist/sdk/completion/fish.js +4 -1
- package/dist/sdk/completion/zsh.js +4 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/docs.d.ts +3 -1
- package/dist/sdk/docs.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.d.ts +8 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
- package/dist/sdk/files.d.ts +3 -1
- package/dist/sdk/files.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/guide-topics.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/claim.d.ts +5 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/linked-artifacts.d.ts +45 -3
- package/dist/sdk/linked-artifacts.js +2 -2
- package/dist/sdk/output/table-rows.d.ts +28 -4
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output.d.ts +1 -1
- package/dist/sdk/output.js +1 -1
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/test/batch.d.ts +5 -2
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/command-args.js +1 -1
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution.d.ts +10 -7
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/test/parsers.js +1 -1
- package/dist/sdk/test/prerequisites.d.ts +1 -1
- package/dist/sdk/test/prerequisites.js +1 -1
- package/dist/sdk/test/run-phases.d.ts +44 -0
- package/dist/sdk/test/run-phases.js +2 -0
- package/dist/types.d.ts +3 -1
- package/dist/types.js +1 -1
- package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -4
- package/docs/COMMANDS.md +22 -4
- package/docs/LINKED_TEST_EDITS.md +2 -1
- package/docs/MUTATION_INTEGRITY.md +56 -6
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +6 -3
- package/docs/README.md +2 -2
- package/docs/READ_OUTPUT_CONTRACTS.md +23 -2
- package/docs/SDK.md +18 -1
- package/docs/TESTING.md +64 -1
- package/docs/WORKSPACE_CONCURRENCY.md +5 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +8 -8
- package/marketplace.json +1 -1
- package/package.json +1 -2
- 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/CHANGELOG.md +0 -4782
- package/dist/cli-bundle/chunks/chunk-5NGGI7JC.js +0 -6
- package/dist/cli-bundle/chunks/chunk-A7L5IEYV.js +0 -20
- package/dist/cli-bundle/chunks/chunk-FOT5K5OM.js +0 -124
- package/dist/cli-bundle/chunks/chunk-PS2YAPXC.js +0 -9
- package/dist/cli-bundle/chunks/chunk-PZI6CR24.js +0 -116
- package/dist/cli-bundle/chunks/chunk-UTNPDAID.js +0 -31
- package/dist/cli-bundle/chunks/item-transaction-YXZ27UC6.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-5RAWXY2F.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AIYJHVKV.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-BB2GMKRB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-GAXO2UQX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HIKZYZ26.js +0 -82
- package/dist/cli-bundle/focused-chunks/chunk-MK7UQEE5.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-NY65XTX7.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-RXY6BFRW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TZO6L523.js +0 -2
|
@@ -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=>applyPathMigrations(entry.path,migrations))),conflicts=[...new Set(removes.map(entry=>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&&(current[index]={...current[index],path:migratedPath},count+=1)}return{adds:adds.map(entry=>{const migratedPath=applyPathMigrations(entry.path,migrations);return migratedPath!==entry.path&&(count+=1),{...entry,path:migratedPath}}),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);index<0?merged.push(add):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)removes.includes(merged[index].path)&&merged.splice(index,1);return appendStable?merged:sortLinkedArtifacts(merged)}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: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){return(values??[]).flatMap(value=>[flag,value])}function noteRecoveryRetryArgs(params){const{options}=params;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)),...repeatFlag("--add-glob",params.resolved.addGlob),...repeatFlag("--remove",params.resolved.remove),...repeatFlag("--migrate",params.resolved.migrate),...options.note===void 0?[]:["--note",options.note],...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),adds=applyStandaloneNote([...parsedAdds,...expandedGlobAdds],options.note,parsedAdds.length>0||addGlobs.length>0),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;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),normalized=mergeLinkedArtifactChanges(next,migrated.adds,migrated.removes,config.supportsAppendStable&&options.appendStable===!0);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})})}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,findMisreadNoteSegment,linkedCollectionMutationFields,looksLikeStructuredPathEntry,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,projectLinkedCollectionMutation,renameArtifactsResultKey,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]="6c72ddef-c0fa-5d0b-9e35-20e3ba3c8d73")}catch{}})();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,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 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};
|
|
3
3
|
//# sourceMappingURL=linked-artifacts.js.map
|
|
@@ -24,6 +24,20 @@ null_column_index?:number[];
|
|
|
24
24
|
column_order?:string[];
|
|
25
25
|
/** Missing field coordinates, expressed as [zero-based row, column name]. */
|
|
26
26
|
absent:Array<[number,string]>;}
|
|
27
|
+
/**
|
|
28
|
+
* An encoding block in the form the TOON host renders it (GH-1684). Empty
|
|
29
|
+
* `json_columns` and `absent` arrays are left out, and missing cells are
|
|
30
|
+
* grouped by column in `absent_rows`, so consumers recognize the block by its
|
|
31
|
+
* reserved `<collection>_encoding` key rather than by the arrays it carries.
|
|
32
|
+
* {@link decodePmTableRows} accepts this form and every earlier one.
|
|
33
|
+
*/
|
|
34
|
+
export interface PmRenderedTableCellEncoding extends Omit<PmTableCellEncoding,"json_columns"|"absent">{
|
|
35
|
+
/** Columns whose every present cell contains a JSON-serialized value; omitted when none. */
|
|
36
|
+
json_columns?:string[];
|
|
37
|
+
/** Missing field coordinates as [zero-based row, column name] pairs, as earlier releases rendered them. */
|
|
38
|
+
absent?:Array<[number,string]>;
|
|
39
|
+
/** Missing field coordinates grouped by column: column name to its zero-based row indexes. */
|
|
40
|
+
absent_rows?:Record<string,number[]>;}
|
|
27
41
|
/** Primitive rows accepted by the standard TOON tabular encoder. */
|
|
28
42
|
export interface PmEncodedTableRows{
|
|
29
43
|
/** Key-hoisted rows with primitive cells and null padding for absent keys. */
|
|
@@ -40,8 +54,18 @@ encoding:PmTableCellEncoding;}
|
|
|
40
54
|
*/
|
|
41
55
|
export declare function encodePmTableRows(rows:readonly Record<string,JsonValue>[],options?:{compact?:boolean;}):PmEncodedTableRows;
|
|
42
56
|
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
57
|
+
* Project an encoding for TOON delivery without losing a fact: empty
|
|
58
|
+
* `json_columns` and `absent` arrays are dropped, and absent coordinates are
|
|
59
|
+
* grouped by column. Grouping writes each column name once, so it is smaller
|
|
60
|
+
* whenever a column misses more than one cell, which is the shape of sparse
|
|
61
|
+
* focus rows such as unblocked `pm context` rows.
|
|
62
|
+
*/
|
|
63
|
+
export declare function projectPmTableEncodingForToon(encoding:PmTableCellEncoding):PmRenderedTableCellEncoding;
|
|
64
|
+
/**
|
|
65
|
+
* Restore rows emitted by {@link encodePmTableRows}, including the TOON form
|
|
66
|
+
* that omits empty metadata and groups absent cells by column. Metadata is
|
|
67
|
+
* explicit, so strings resembling JSON stay strings unless their column
|
|
68
|
+
* declares JSON. Malformed JSON cells throw instead of silently changing their
|
|
69
|
+
* meaning.
|
|
46
70
|
*/
|
|
47
|
-
export declare function decodePmTableRows(table:PmEncodedTableRows):Record<string,JsonValue>[];
|
|
71
|
+
export declare function decodePmTableRows(table:{rows:PmEncodedTableRows["rows"];encoding:PmRenderedTableCellEncoding;}):Record<string,JsonValue>[];
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bafcd4e4-ec0f-5340-89ce-b85d822b2323")}catch{}})();function encodePmTableRows(rows,options={}){const columns=[...new Set(rows.flatMap(row=>Object.keys(row)))],nullColumns=options.compact?columns.filter(column=>rows.every(row=>Object.hasOwn(row,column)&&row[column]===null)):[],listColumns=options.compact?columns.filter(column=>rows.every(row=>{if(!Object.hasOwn(row,column))return!0;const cell=row[column];return Array.isArray(cell)&&cell.every(value=>typeof value=="string"&&value!==""&&!value.includes(";"))})):[],lists=new Set(listColumns),nulls=new Set(nullColumns),jsonColumns=columns.filter(column=>!lists.has(column)&&rows.some(row=>{const cell=row[column];return cell!==null&&typeof cell=="object"})),nested=new Set(jsonColumns),absent=[];return{rows:rows.map((row,index)=>Object.fromEntries(columns.filter(column=>!nulls.has(column)).map(column=>{if(!Object.hasOwn(row,column))return absent.push([index,column]),[column,null];const cell=row[column];return lists.has(column)?[column,cell.join(";")]:[column,nested.has(column)?JSON.stringify(cell):cell]}))),encoding:{json_columns:jsonColumns,absent,...listColumns.length?{list_columns:Object.fromEntries(listColumns.map(column=>[column,";"]))}:{},...nullColumns.length?{null_columns:nullColumns,null_column_index:nullColumns.map(column=>columns.indexOf(column))}:{}}}}function projectPmTableEncodingForToon(encoding){const{json_columns:jsonColumns,absent,...declarations}=encoding,absentRows=new Map;for(const[row,column]of absent){const rows=absentRows.get(column)??[];rows.push(row),absentRows.set(column,rows)}return{...jsonColumns.length>0?{json_columns:jsonColumns}:{},...absentRows.size>0?{absent_rows:Object.fromEntries(absentRows)}:{},...declarations}}function restoreColumnOrder(encodedColumns,encoding){const nullColumns=encoding.null_columns??[],positions=encoding.null_column_index??[],columns=[...encodedColumns],insertions=nullColumns.map((column,index)=>({column,position:positions[index]})).filter(entry=>typeof entry.position=="number").sort((left,right)=>left.position-right.position);for(const{column,position}of insertions)columns.splice(Math.min(position,columns.length),0,column);for(const column of nullColumns)columns.includes(column)||columns.push(column);return columns}function decodePmTableRows(table){const nested=new Set(table.encoding.json_columns??[]),delimiters=new Map(Object.entries(table.encoding.list_columns??{})),absent=new Set([...(table.encoding.absent??[]).map(([row,column])=>JSON.stringify([row,column])),...Object.entries(table.encoding.absent_rows??{}).flatMap(([column,rows])=>rows.map(row=>JSON.stringify([row,column])))]);return table.rows.map((row,index)=>{const cells=new Map(Object.entries(row).flatMap(([column,cell])=>{if(absent.has(JSON.stringify([index,column])))return[];const delimiter=delimiters.get(column),value=delimiter!==void 0?cell===""?[]:String(cell).split(delimiter):nested.has(column)?JSON.parse(String(cell)):cell;return[[column,value]]}));for(const column of table.encoding.null_columns??[])cells.set(column,null);const columns=table.encoding.column_order??restoreColumnOrder(Object.keys(row),table.encoding);return Object.fromEntries(columns.filter(column=>cells.has(column)).map(column=>[column,cells.get(column)]))})}export{decodePmTableRows,encodePmTableRows,projectPmTableEncodingForToon};
|
|
2
2
|
//# sourceMappingURL=table-rows.js.map
|
package/dist/sdk/output.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Defines public output-control primitives for extension commands, exporters,
|
|
5
5
|
* renderers, and custom SDK-built hosts.
|
|
6
6
|
*/
|
|
7
|
-
export{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput,type SuppressedHostOutput,}from "../core/output/output-control.js";export{encodePmTableRows,decodePmTableRows,type PmTableCellEncoding,type PmEncodedTableRows,}from "./output/table-rows.js";export{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,}from "./output/list-envelope.js";export{assertWellFormedOutputText,toWellFormedText}from "../core/shared/output-unicode.js";
|
|
7
|
+
export{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput,type SuppressedHostOutput,}from "../core/output/output-control.js";export{encodePmTableRows,decodePmTableRows,type PmTableCellEncoding,type PmRenderedTableCellEncoding,type PmEncodedTableRows,}from "./output/table-rows.js";export{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,}from "./output/list-envelope.js";export{assertWellFormedOutputText,toWellFormedText}from "../core/shared/output-unicode.js";
|
|
8
8
|
/**
|
|
9
9
|
* Serialize object rows as newline-delimited JSON without adding a trailing
|
|
10
10
|
* newline. CLI hosts can append their final newline while SDK consumers can
|
package/dist/sdk/output.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e6c590de-c83e-59ca-9fdb-9a68cc88d545")}catch{}})();import{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput}from"../core/output/output-control.js";import{encodePmTableRows,decodePmTableRows}from"./output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"./output/list-envelope.js";import{assertWellFormedOutputText,toWellFormedText}from"../core/shared/output-unicode.js";function serializeNdjsonRows(rows){return rows.map((row,index)=>{if(typeof row!="object"||row===null||Array.isArray(row))throw new TypeError(`NDJSON row ${index} must be a non-null object.`);const serialized=JSON.stringify(row);if(serialized===void 0)throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);const projected=JSON.parse(serialized);if(typeof projected!="object"||projected===null||Array.isArray(projected))throw new TypeError(`NDJSON row ${index} must serialize to a non-null object.`);return serialized}).join(`
|
|
2
2
|
`)}function serializeNdjsonStream(rows,trailer){if(trailer.count!==rows.length)throw new TypeError(`NDJSON trailer count ${trailer.count} does not match ${rows.length} ${rows.length===1?"row":"rows"}.`);for(const[index,row]of rows.entries())if(typeof row=="object"&&row!==null&&!Array.isArray(row)&&Reflect.get(row,"record_type")==="pm.stream.trailer")throw new TypeError(`NDJSON row ${index} uses reserved record_type pm.stream.trailer`);return serializeNdjsonRows([...rows,{...trailer,record_type:"pm.stream.trailer"}])}export{SUPPRESS_HOST_OUTPUT_MARKER,assertWellFormedOutputText,decodePmTableRows,encodePmTableRows,isHostOutputSuppressed,projectPmBriefListEnvelope,projectPmBriefSearchEnvelope,serializeNdjsonRows,serializeNdjsonStream,suppressHostOutput,toWellFormedText};
|
|
3
3
|
//# sourceMappingURL=output.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="6c6e6cae-87e6-58df-9f59-b9e74a80de38")}catch{}})();import{readHistoryEntries}from"../core/history/read.js";import{redactIdentityCredentials}from"../core/shared/url-credentials.js";import{getHistoryPath}from"../core/store/paths.js";function classifyOwnershipSource(operation){return operation===void 0?"unknown":operation==="claim"?"claim":"assignment"}async function resolveItemOwnershipConflict(pmRoot,itemId,assignee){const latestOwnershipEntry=[...await Promise.resolve().then(()=>readHistoryEntries(getHistoryPath(pmRoot,itemId),itemId)).catch(()=>[])].reverse().find(entry=>entry.patch.some(operation=>operation.path==="/metadata/assignee")),assigneeOperation=latestOwnershipEntry?.patch.find(operation=>operation.path==="/metadata/assignee"),evidence=assigneeOperation!==void 0&&typeof assigneeOperation.value=="string"&&assigneeOperation.value.trim()===assignee.trim()?latestOwnershipEntry:void 0,source=classifyOwnershipSource(evidence?.op),holder=redactIdentityCredentials(assignee);return{phrase:source==="claim"?`claimed by ${holder}`:`assigned to ${holder}`,holder,source,since:evidence?.ts??null}}async function describeItemOwnershipConflict(pmRoot,itemId,assignee){return(await resolveItemOwnershipConflict(pmRoot,itemId,assignee)).phrase}export{describeItemOwnershipConflict,resolveItemOwnershipConflict};
|
|
2
2
|
//# sourceMappingURL=ownership-source.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0f06f072-47a7-560e-9291-72e47225a73c")}catch{}})();import{appendHistoryEntry,createHistoryEntry}from"../core/history/history.js";import{acquireLock}from"../core/lock/lock.js";import{enforceWorkflowMutation}from"../core/policy/workflow-policy-store.js";import{parseTags}from"../core/item/parse.js";import{normalizeStatusInput}from"../core/item/status.js";import{serializeItemDocument}from"../core/item/item-format.js";import{getHistoryPath}from"../core/store/paths.js";import{removeFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolveAuthor}from"../core/shared/author.js";import{nowIso}from"../core/shared/time.js";import{assertInitializedTracker}from"./environment/tracker-preflight.js";function toNonEmptyImportString(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function toEstimatedMinutesValue(value){if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}function toImportPriority(value){if(typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=4)return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(Number.isInteger(parsed)&&parsed>=0&&parsed<=4)return parsed}return 2}function toImportTags(value){if(Array.isArray(value)){const tags=value.filter(entry=>typeof entry=="string").map(entry=>entry.trim().toLowerCase()).filter(entry=>entry.length>0);return Array.from(new Set(tags)).sort((left,right)=>left.localeCompare(right))}return typeof value=="string"?parseTags(value):[]}function toImportStatus(value){const normalized=toNonEmptyImportString(value);if(normalized){const canonical=normalizeStatusInput(normalized);if(canonical)return canonical}return"open"}function toImportInteger(value){if(typeof value=="number"&&Number.isInteger(value))return value;if(typeof value!="string"||value.trim().length===0)return;const parsed=Number(value);return Number.isInteger(parsed)?parsed:void 0}function toImportBoolean(value){if(typeof value=="boolean")return value;if(typeof value=="number")return value===1?!0:value===0?!1:void 0;if(typeof value!="string")return;const normalized=value.trim().toLowerCase();return normalized==="true"||normalized==="1"?!0:normalized==="false"||normalized==="0"?!1:void 0}function toImportStringList(value){if(!Array.isArray(value))return;const entries=value.map(entry=>toNonEmptyImportString(entry)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportStringMap(value){return toImportValueMap(value,toNonEmptyImportString)}function toImportNumberMap(value){return toImportValueMap(value,toImportFiniteNumber)}function toImportConfidence(value,allowedTextValues){if(typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=100)return value;const normalized=toNonEmptyImportString(value)?.toLowerCase();if(!normalized)return;const candidate=normalized==="med"?"medium":normalized;if(allowedTextValues.some(entry=>entry===candidate))return candidate;const parsed=Number(candidate);return Number.isInteger(parsed)&&parsed>=0&&parsed<=100?parsed:void 0}function toImportNormalizedEnum(value,allowed){const normalized=toNonEmptyImportString(value)?.toLowerCase();if(!normalized)return;const candidate=normalized==="med"?"medium":normalized;return allowed.includes(candidate)?candidate:void 0}function toImportLinkScope(value){return toNonEmptyImportString(value)?.toLowerCase()==="global"?"global":"project"}function toImportLogEntries(value,options){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const entries=values.map(entry=>toImportLogEntry(entry,options)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportLinkedFiles(value,options={}){return toImportLinkedArtifacts(value,options,(pathValue,record)=>({path:pathValue,scope:toImportLinkScope(record?.scope),note:toNonEmptyImportString(record?.note)}))}function toImportLinkedDocs(value,options={}){return toImportLinkedArtifacts(value,options,(pathValue,record)=>({path:pathValue,scope:toImportLinkScope(record?.scope),note:toNonEmptyImportString(record?.note)}))}function toImportLinkedTests(value,options={}){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const entries=values.map(entry=>toImportLinkedTest(entry,options)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function selectImportAuthor(explicitAuthor,settingsAuthor){return resolveAuthor(explicitAuthor,settingsAuthor)}function isImportRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function normalizeImportCollection(value,allowScalar){return Array.isArray(value)?value:allowScalar?[value]:void 0}function firstNonEmptyImportString(record,keys){for(const key of keys){const value=toNonEmptyImportString(record[key]);if(value)return value}}function toImportValueMap(value,coerce){if(!isImportRecord(value))return;const entries=Object.entries(value).map(([key,entryValue])=>[key.trim(),coerce(entryValue)]).filter(entry=>entry[0].length>0&&entry[1]!==void 0);return entries.length>0?Object.fromEntries(entries):void 0}function toImportLogEntry(entry,options){if(typeof entry=="string")return toImportLogEntryFromText(entry,options);if(!isImportRecord(entry))return;const text=firstNonEmptyImportString(entry,options.textKeys??["text"]);if(!text)return;const createdAtKey=options.createdAtKey??"created_at",authorKey=options.authorKey??"author";return{created_at:(options.toIsoString?options.toIsoString(entry[createdAtKey]):toNonEmptyImportString(entry[createdAtKey]))??options.fallbackCreatedAt,author:toNonEmptyImportString(entry[authorKey])??options.fallbackAuthor,text}}function toImportLogEntryFromText(entry,options){const text=toNonEmptyImportString(entry);return text?{created_at:options.fallbackCreatedAt,author:options.fallbackAuthor,text}:void 0}function toImportLinkedArtifacts(value,options,build){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const pathKeys=options.pathKeys??["path"],entries=values.map(entry=>toImportLinkedArtifact(entry,pathKeys,build)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportLinkedArtifact(entry,pathKeys,build){if(typeof entry=="string"){const pathValue2=toNonEmptyImportString(entry);return pathValue2?build(pathValue2):void 0}if(!isImportRecord(entry))return;const pathValue=firstNonEmptyImportString(entry,pathKeys);return pathValue?build(pathValue,entry):void 0}function toImportLinkedTest(entry,options){if(typeof entry=="string"){const command2=toNonEmptyImportString(entry);return command2?{command:command2,scope:"project"}:void 0}if(!isImportRecord(entry))return;const command=firstNonEmptyImportString(entry,options.commandKeys??["command"]),testPath=firstNonEmptyImportString(entry,options.pathKeys??["path"]);if(!(!command&&(options.requireCommand===!0||!testPath)))return{...command?{command}:{},...testPath?{path:testPath}:{},scope:toImportLinkScope(entry.scope),timeout_seconds:toImportLinkedTestTimeout(entry.timeout_seconds,options),note:toNonEmptyImportString(entry.note),...options.includeExtendedAssertions===!0?toImportLinkedTestAssertions(entry):{}}}function toImportLinkedTestTimeout(value,options){const parsed=options.integerTimeout===!0?toImportInteger(value):toImportFiniteNumber(value);if(parsed===void 0)return;const minimum=options.timeoutMinimum??0;return options.timeoutExclusiveMinimum===!0?parsed>minimum?parsed:void 0:parsed>=minimum?parsed:void 0}function toImportFiniteNumber(value){if(typeof value=="number"&&Number.isFinite(value))return value;if(typeof value!="string"||value.trim().length===0)return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}function toImportLinkedTestAssertions(entry){return{pm_context_mode:toImportNormalizedEnum(entry.pm_context_mode,["schema","tracker","auto"]),env_set:toImportStringMap(entry.env_set),env_clear:toImportStringList(entry.env_clear),shared_host_safe:toImportBoolean(entry.shared_host_safe),assert_stdout_contains:toImportStringList(entry.assert_stdout_contains),assert_stdout_regex:toImportStringList(entry.assert_stdout_regex),assert_stderr_contains:toImportStringList(entry.assert_stderr_contains),assert_stderr_regex:toImportStringList(entry.assert_stderr_regex),assert_stdout_min_lines:toImportInteger(entry.assert_stdout_min_lines),assert_json_field_equals:toImportStringMap(entry.assert_json_field_equals),assert_json_field_gte:toImportNumberMap(entry.assert_json_field_gte)}}async function ensureTrackerInitialized(pmRoot){await assertInitializedTracker(pmRoot)}function emptyImportedDocument(){return{metadata:{},body:""}}async function commitImportedItem(params){const{pmRoot,id,itemPath,document,author,message,settings,conflictWarningPrefix}=params,historyPath=getHistoryPath(pmRoot,id),beforeDocument=emptyImportedDocument();try{const releaseLock=await acquireLock(pmRoot,id,settings.locks.ttl_seconds,author,!1,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms);try{const workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"import",author,before:null,after:document});await writeFileAtomic(itemPath,serializeItemDocument(document,{format:"toon"}));try{const entry=createHistoryEntry({nowIso:nowIso(),author,op:"import",before:beforeDocument,after:document,message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});return await appendHistoryEntry(historyPath,entry),{committed:!0,writeWarnings:[...workflowPolicy.warnings,...await runActiveOnWriteHooks({path:itemPath,scope:"project",op:"import",item_id:document.metadata.id,item_type:document.metadata.type,before:beforeDocument,after:document,changed_fields:["imported"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"import:history",item_id:document.metadata.id,item_type:document.metadata.type,before:beforeDocument,after:document,changed_fields:["imported"]})]}}catch(error){throw await removeFileIfExists(itemPath),error}}finally{await releaseLock()}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.CONFLICT&&!error.code?.startsWith("workflow_policy_"))return{committed:!1,conflictWarning:`${conflictWarningPrefix}:${id}`};throw error}}export{commitImportedItem,emptyImportedDocument,ensureTrackerInitialized,selectImportAuthor,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkScope,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString};
|
|
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]="2eb50875-5603-5474-bb1f-f1f983c5e29e")}catch{}})();import{appendHistoryEntry,createHistoryEntry}from"../core/history/history.js";import{acquireLock}from"../core/lock/lock.js";import{enforceWorkflowMutation}from"../core/policy/workflow-policy-store.js";import{parseTags}from"../core/item/parse.js";import{normalizeStatusInput}from"../core/item/status.js";import{serializeItemDocument}from"../core/item/item-format.js";import{getHistoryPath}from"../core/store/paths.js";import{removeFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolveAuthor}from"../core/shared/author.js";import{nowIso}from"../core/shared/time.js";import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{stampRequiredItemFormat}from"./environment/project-runtime-compatibility.js";function toNonEmptyImportString(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function toEstimatedMinutesValue(value){if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}function toImportPriority(value){if(typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=4)return value;if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(Number.isInteger(parsed)&&parsed>=0&&parsed<=4)return parsed}return 2}function toImportTags(value){if(Array.isArray(value)){const tags=value.filter(entry=>typeof entry=="string").map(entry=>entry.trim().toLowerCase()).filter(entry=>entry.length>0);return Array.from(new Set(tags)).sort((left,right)=>left.localeCompare(right))}return typeof value=="string"?parseTags(value):[]}function toImportStatus(value){const normalized=toNonEmptyImportString(value);if(normalized){const canonical=normalizeStatusInput(normalized);if(canonical)return canonical}return"open"}function toImportInteger(value){if(typeof value=="number"&&Number.isInteger(value))return value;if(typeof value!="string"||value.trim().length===0)return;const parsed=Number(value);return Number.isInteger(parsed)?parsed:void 0}function toImportBoolean(value){if(typeof value=="boolean")return value;if(typeof value=="number")return value===1?!0:value===0?!1:void 0;if(typeof value!="string")return;const normalized=value.trim().toLowerCase();return normalized==="true"||normalized==="1"?!0:normalized==="false"||normalized==="0"?!1:void 0}function toImportStringList(value){if(!Array.isArray(value))return;const entries=value.map(entry=>toNonEmptyImportString(entry)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportStringMap(value){return toImportValueMap(value,toNonEmptyImportString)}function toImportNumberMap(value){return toImportValueMap(value,toImportFiniteNumber)}function toImportConfidence(value,allowedTextValues){if(typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=100)return value;const normalized=toNonEmptyImportString(value)?.toLowerCase();if(!normalized)return;const candidate=normalized==="med"?"medium":normalized;if(allowedTextValues.some(entry=>entry===candidate))return candidate;const parsed=Number(candidate);return Number.isInteger(parsed)&&parsed>=0&&parsed<=100?parsed:void 0}function toImportNormalizedEnum(value,allowed){const normalized=toNonEmptyImportString(value)?.toLowerCase();if(!normalized)return;const candidate=normalized==="med"?"medium":normalized;return allowed.includes(candidate)?candidate:void 0}function toImportLinkScope(value){return toNonEmptyImportString(value)?.toLowerCase()==="global"?"global":"project"}function toImportLogEntries(value,options){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const entries=values.map(entry=>toImportLogEntry(entry,options)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportLinkedFiles(value,options={}){return toImportLinkedArtifacts(value,options,(pathValue,record)=>({path:pathValue,scope:toImportLinkScope(record?.scope),note:toNonEmptyImportString(record?.note)}))}function toImportLinkedDocs(value,options={}){return toImportLinkedArtifacts(value,options,(pathValue,record)=>({path:pathValue,scope:toImportLinkScope(record?.scope),note:toNonEmptyImportString(record?.note)}))}function toImportLinkedTests(value,options={}){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const entries=values.map(entry=>toImportLinkedTest(entry,options)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function selectImportAuthor(explicitAuthor,settingsAuthor){return resolveAuthor(explicitAuthor,settingsAuthor)}function isImportRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function normalizeImportCollection(value,allowScalar){return Array.isArray(value)?value:allowScalar?[value]:void 0}function firstNonEmptyImportString(record,keys){for(const key of keys){const value=toNonEmptyImportString(record[key]);if(value)return value}}function toImportValueMap(value,coerce){if(!isImportRecord(value))return;const entries=Object.entries(value).map(([key,entryValue])=>[key.trim(),coerce(entryValue)]).filter(entry=>entry[0].length>0&&entry[1]!==void 0);return entries.length>0?Object.fromEntries(entries):void 0}function toImportLogEntry(entry,options){if(typeof entry=="string")return toImportLogEntryFromText(entry,options);if(!isImportRecord(entry))return;const text=firstNonEmptyImportString(entry,options.textKeys??["text"]);if(!text)return;const createdAtKey=options.createdAtKey??"created_at",authorKey=options.authorKey??"author";return{created_at:(options.toIsoString?options.toIsoString(entry[createdAtKey]):toNonEmptyImportString(entry[createdAtKey]))??options.fallbackCreatedAt,author:toNonEmptyImportString(entry[authorKey])??options.fallbackAuthor,text}}function toImportLogEntryFromText(entry,options){const text=toNonEmptyImportString(entry);return text?{created_at:options.fallbackCreatedAt,author:options.fallbackAuthor,text}:void 0}function toImportLinkedArtifacts(value,options,build){const values=normalizeImportCollection(value,options.allowScalar===!0);if(!values)return;const pathKeys=options.pathKeys??["path"],entries=values.map(entry=>toImportLinkedArtifact(entry,pathKeys,build)).filter(entry=>entry!==void 0);return entries.length>0?entries:void 0}function toImportLinkedArtifact(entry,pathKeys,build){if(typeof entry=="string"){const pathValue2=toNonEmptyImportString(entry);return pathValue2?build(pathValue2):void 0}if(!isImportRecord(entry))return;const pathValue=firstNonEmptyImportString(entry,pathKeys);return pathValue?build(pathValue,entry):void 0}function toImportLinkedTest(entry,options){if(typeof entry=="string"){const command2=toNonEmptyImportString(entry);return command2?{command:command2,scope:"project"}:void 0}if(!isImportRecord(entry))return;const command=firstNonEmptyImportString(entry,options.commandKeys??["command"]),testPath=firstNonEmptyImportString(entry,options.pathKeys??["path"]);if(!(!command&&(options.requireCommand===!0||!testPath)))return{...command?{command}:{},...testPath?{path:testPath}:{},scope:toImportLinkScope(entry.scope),timeout_seconds:toImportLinkedTestTimeout(entry.timeout_seconds,options),note:toNonEmptyImportString(entry.note),...typeof entry.phase=="string"&&entry.phase.trim().toLowerCase()==="setup"?{phase:"setup"}:{},...options.includeExtendedAssertions===!0?toImportLinkedTestAssertions(entry):{}}}function toImportLinkedTestTimeout(value,options){const parsed=options.integerTimeout===!0?toImportInteger(value):toImportFiniteNumber(value);if(parsed===void 0)return;const minimum=options.timeoutMinimum??0;return options.timeoutExclusiveMinimum===!0?parsed>minimum?parsed:void 0:parsed>=minimum?parsed:void 0}function toImportFiniteNumber(value){if(typeof value=="number"&&Number.isFinite(value))return value;if(typeof value!="string"||value.trim().length===0)return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}function toImportLinkedTestAssertions(entry){return{pm_context_mode:toImportNormalizedEnum(entry.pm_context_mode,["schema","tracker","auto"]),env_set:toImportStringMap(entry.env_set),env_clear:toImportStringList(entry.env_clear),shared_host_safe:toImportBoolean(entry.shared_host_safe),assert_stdout_contains:toImportStringList(entry.assert_stdout_contains),assert_stdout_regex:toImportStringList(entry.assert_stdout_regex),assert_stderr_contains:toImportStringList(entry.assert_stderr_contains),assert_stderr_regex:toImportStringList(entry.assert_stderr_regex),assert_stdout_min_lines:toImportInteger(entry.assert_stdout_min_lines),assert_json_field_equals:toImportStringMap(entry.assert_json_field_equals),assert_json_field_gte:toImportNumberMap(entry.assert_json_field_gte)}}async function ensureTrackerInitialized(pmRoot){await assertInitializedTracker(pmRoot)}function emptyImportedDocument(){return{metadata:{},body:""}}async function commitImportedItem(params){const{pmRoot,id,itemPath,author,message,settings,conflictWarningPrefix}=params,document={...params.document,metadata:{...params.document.metadata}};stampRequiredItemFormat(document.metadata,pmRoot);const historyPath=getHistoryPath(pmRoot,id),beforeDocument=emptyImportedDocument();try{const releaseLock=await acquireLock(pmRoot,id,settings.locks.ttl_seconds,author,!1,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms);try{const workflowPolicy=await enforceWorkflowMutation({pmRoot,settings,operation:"import",author,before:null,after:document});await writeFileAtomic(itemPath,serializeItemDocument(document,{format:"toon"}));try{const entry=createHistoryEntry({nowIso:nowIso(),author,op:"import",before:beforeDocument,after:document,message,context:workflowPolicy.decisions.length===0?void 0:{workflow_policies:workflowPolicy.decisions}});return await appendHistoryEntry(historyPath,entry),{committed:!0,writeWarnings:[...workflowPolicy.warnings,...await runActiveOnWriteHooks({path:itemPath,scope:"project",op:"import",item_id:document.metadata.id,item_type:document.metadata.type,before:beforeDocument,after:document,changed_fields:["imported"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"import:history",item_id:document.metadata.id,item_type:document.metadata.type,before:beforeDocument,after:document,changed_fields:["imported"]})]}}catch(error){throw await removeFileIfExists(itemPath),error}}finally{await releaseLock()}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.CONFLICT&&!error.code?.startsWith("workflow_policy_"))return{committed:!1,conflictWarning:`${conflictWarningPrefix}:${id}`};throw error}}export{commitImportedItem,emptyImportedDocument,ensureTrackerInitialized,selectImportAuthor,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkScope,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString};
|
|
2
2
|
//# sourceMappingURL=package-import-adapters.js.map
|
package/dist/sdk/pagination.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="9c5d8732-3e10-5224-a558-e870397090f2")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS}from"./read-output/options.js";import{createHash}from"node:crypto";import{PmCliError}from"../core/shared/errors.js";import{EXIT_CODE}from"../core/shared/constants.js";import{stableStringify}from"../core/shared/serialization.js";import{isCompactedCursorArgument}from"../core/shared/text-normalization.js";import{decodeReadOutputContinuationCursor}from"./read-output/continuation.js";const QUERY_CURSOR_VERSION=1,MAX_CURSOR_LENGTH=4096,BASE64URL_PATTERN=/^[A-Za-z0-9_-]+$/;function optionKeyForFlag(flag){return flag.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(_,character)=>character.toUpperCase())}function selectCursorSemanticOptions(options,contracts){const universalFlags=[...Object.values(READ_OUTPUT_DIMENSION_FLAGS),...READ_OUTPUT_COMPOSITION_FLAGS],presentationKeys=new Set(universalFlags.flatMap(flag=>[optionKeyForFlag(flag),flag.slice(2).replaceAll("-","_")]));for(const contract of contracts)if(contract.cursor_semantics==="presentation"){presentationKeys.add(optionKeyForFlag(contract.flag));for(const alias of contract.aliases??[])presentationKeys.add(optionKeyForFlag(alias))}return Object.fromEntries(Object.entries(options).filter(([key])=>!presentationKeys.has(key)))}function createQueryFingerprint(command,contract){return createHash("sha256").update(command).update("\0").update(stableStringify(contract)).digest("hex").slice(0,24)}function encodeQueryCursor(fingerprint,afterId,afterIndex,snapshot){return Buffer.from(JSON.stringify({version:QUERY_CURSOR_VERSION,fingerprint,after_id:afterId,...afterIndex===void 0?{}:{after_index:afterIndex},...snapshot===void 0?{}:{snapshot}})).toString("base64url")}function invalidCursor(message,cursorFlag){return new PmCliError(message,EXIT_CODE.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the original query without ${cursorFlag} to obtain a fresh cursor.`]})}function compactedCursor(cursorFlag){return new PmCliError("Query cursor was shortened by output compaction: it contains an ellipsis, which no cursor encoder emits.",EXIT_CODE.USAGE,{code:"invalid_query_cursor",reason:"cursor_compacted",required:"Pass the whole cursor the previous page emitted; a shortened cursor cannot resume the query.",nextSteps:[`Re-read the previous page with a larger --output-budget (or --output-budget unbounded) and pass its whole next_cursor to ${cursorFlag}.`,`Or repeat the original query without ${cursorFlag} to obtain a fresh cursor.`]})}function isQueryCursorEnvelope(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const envelope=value;return envelope.version===QUERY_CURSOR_VERSION&&typeof envelope.fingerprint=="string"&&typeof envelope.after_id=="string"&&envelope.after_id.length>0&&(envelope.after_index===void 0||Number.isSafeInteger(envelope.after_index)&&envelope.after_index>=0)&&(envelope.snapshot===void 0||typeof envelope.snapshot=="string"&&envelope.snapshot.length>0)}function decodeQueryCursorEnvelope(cursor,cursorFlag="--after"){if(typeof cursor!="string")throw invalidCursor("Query cursor is malformed.",cursorFlag);const normalized=cursor.trim();if(isCompactedCursorArgument(normalized))throw compactedCursor(cursorFlag);if(normalized.length===0||normalized.length>MAX_CURSOR_LENGTH||!BASE64URL_PATTERN.test(normalized))throw invalidCursor("Query cursor is malformed.",cursorFlag);let parsed;try{parsed=JSON.parse(Buffer.from(normalized,"base64url").toString("utf8"))}catch{throw invalidCursor("Query cursor is malformed.",cursorFlag)}if(!isQueryCursorEnvelope(parsed)){let outputCursor=!1;try{decodeReadOutputContinuationCursor(normalized),outputCursor=!0}catch{}throw outputCursor?new PmCliError(`An output cursor must be continued with --output-cursor, not ${cursorFlag}.`,EXIT_CODE.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the same query, replacing ${cursorFlag} with --output-cursor ${normalized}; retain any producer ${cursorFlag} cursor from the original page.`]}):invalidCursor("Query cursor version or payload is unsupported.",cursorFlag)}return parsed}function decodeQueryCursorState(cursor,expectedFingerprint,cursorFlag="--after"){const envelope=decodeQueryCursorEnvelope(cursor,cursorFlag);if(envelope.fingerprint!==expectedFingerprint)throw invalidCursor(`Query cursor does not match the current filters, sort, or query (${envelope.fingerprint} != ${expectedFingerprint}).`,cursorFlag);return{after_id:envelope.after_id,...envelope.after_index===void 0?{}:{after_index:envelope.after_index},...envelope.snapshot===void 0?{}:{snapshot:envelope.snapshot}}}function decodeQueryCursor(cursor,expectedFingerprint){return decodeQueryCursorState(cursor,expectedFingerprint).after_id}function resolveQueryCursorStart(rows,cursor,fingerprint,readId,cursorFlag="--after"){if(cursor===void 0)return 0;const state=decodeQueryCursorState(cursor,fingerprint,cursorFlag),index=rows.findIndex(row=>readId(row)===state.after_id);if(index<0){if(state.after_index!==void 0)return Math.min(state.after_index,rows.length);throw invalidCursor(`Query cursor item ${state.after_id} is no longer present in this result set.`,cursorFlag)}return index+1}function paginateQueryRows(rows,options){if(options.cursor!==void 0&&decodeQueryCursorState(options.cursor,options.fingerprint).snapshot!==options.snapshot)throw invalidCursor("Query cursor does not match the requested snapshot.","--after");const pageStart=resolveQueryCursorStart(rows,options.cursor,options.fingerprint,options.readId),pageRows=rows.slice(pageStart,pageStart+options.limit),hasMore=pageRows.length>0&&pageStart+pageRows.length<rows.length,lastRow=pageRows.at(-1);return{rows:pageRows,has_more:hasMore,...hasMore&&lastRow!==void 0?{next_cursor:encodeQueryCursor(options.fingerprint,options.readId(lastRow),pageStart+pageRows.length-1,options.snapshot)}:{}}}const QUERY_CURSOR_CONTRACT=Object.freeze({version:QUERY_CURSOR_VERSION,max_length:MAX_CURSOR_LENGTH});export{QUERY_CURSOR_CONTRACT,createQueryFingerprint,decodeQueryCursor,decodeQueryCursorEnvelope,decodeQueryCursorState,encodeQueryCursor,paginateQueryRows,resolveQueryCursorStart,selectCursorSemanticOptions};
|
|
2
2
|
//# sourceMappingURL=pagination.js.map
|