@unbrained/pm-cli 2026.9.15 → 2026.9.17
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 +2 -2
- package/CHANGELOG.md +58 -0
- package/dist/cli/error-guidance.d.ts +1 -1
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +149 -149
- package/dist/cli-bundle/chunks/{chunk-3RB6Z7XE.js → chunk-5ZY4WE3F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UKLOSZV6.js → chunk-C3MFMGCR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WLJJ4MAU.js → chunk-CPFBDM53.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YMMLKKEP.js → chunk-DN2RIHRN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5P5PYCZX.js → chunk-E67MIO3Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3AHONKLL.js → chunk-G2IJF244.js} +48 -48
- package/dist/cli-bundle/chunks/{chunk-RM2OGG65.js → chunk-LD2FH2YE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RKPUO75B.js → chunk-Q6KPZGMP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y2P3DSSO.js → chunk-T526C5DX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BOZ4HVYL.js → chunk-UF75LUAK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J4DRE3WN.js → chunk-UJSB6NO6.js} +76 -76
- package/dist/cli-bundle/chunks/{chunk-WDF7PP4P.js → chunk-YZXB4XGA.js} +4 -4
- package/dist/cli-bundle/chunks/{register-list-query-IWSPNFFD.js → register-list-query-ISM35VIX.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-3DVF4R64.js → register-mutation-KHMBJJS6.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-LXP3MECQ.js → register-operations-HHDROJD6.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-KFQSNBDX.js → register-setup-YAURJMY5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-533DCWPY.js → chunk-267N774W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZHX3433X.js → chunk-5FSGN4MP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BMATJLPT.js → chunk-5KYHDFDN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SHF57M2H.js → chunk-7S7XWMXC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-AXDAIBT3.js → chunk-7ZC4CKOX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JKJYXCT6.js → chunk-BFUXTNZU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PBJC2ZNA.js → chunk-G4TKJZ4A.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZOE2NSJB.js → chunk-GKSAMNBG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-63YRRGKX.js → chunk-IVWUQE7T.js} +51 -51
- package/dist/cli-bundle/focused-chunks/{chunk-6C3CUU2G.js → chunk-JZSLDLR4.js} +20 -20
- package/dist/cli-bundle/focused-chunks/{chunk-YBQTVE5S.js → chunk-LNM3BS45.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5SBU4QDC.js → chunk-NOK652OP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OGGF2RBL.js → chunk-OCTTDZOU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MD7ADLME.js → chunk-OWDDVMAP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UACMCSCC.js → chunk-WUMGGQYN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4YTDKIPF.js → chunk-Z4PWEIMX.js} +21 -21
- package/dist/cli-bundle/main.js +11 -10
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +2 -2
- 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 +40 -40
- 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 +2 -2
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/store/tracker-preflight.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/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init.d.ts +22 -1
- package/dist/sdk/init.js +1 -1
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-budget.d.ts +2 -0
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +4 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/docs/MERGE_SAFETY.md +13 -2
- package/docs/PACKED_FIRST_RUN.md +46 -0
- package/docs/QUICKSTART.md +16 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +14 -0
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- package/marketplace.json +2 -2
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
package/dist/sdk/init.d.ts
CHANGED
|
@@ -139,7 +139,28 @@ export interface InitConciseResult {
|
|
|
139
139
|
/** Value that configures or reports hint for this contract. */
|
|
140
140
|
hint: string;
|
|
141
141
|
}
|
|
142
|
-
/**
|
|
142
|
+
/** Minimal first-run display with actionable warnings and a full-result recovery hint. */
|
|
143
|
+
export interface InitDisplayResult {
|
|
144
|
+
/** Whether initialization succeeded. */
|
|
145
|
+
ok: boolean;
|
|
146
|
+
/** Resolved tracker root, including explicitly selected or ancestor trackers. */
|
|
147
|
+
path: string;
|
|
148
|
+
/** Governance policy selected for this workspace. */
|
|
149
|
+
governance_preset: GovernancePreset;
|
|
150
|
+
/** Project telemetry consent and capture level. */
|
|
151
|
+
telemetry: string;
|
|
152
|
+
/** Number of created directories and schema files. */
|
|
153
|
+
created_count: number;
|
|
154
|
+
/** Concrete first commands, scoped to the selected tracker. */
|
|
155
|
+
next_steps: string[];
|
|
156
|
+
/** Non-routine warnings that require attention. */
|
|
157
|
+
warnings?: string;
|
|
158
|
+
/** How to retrieve the complete settings, setup details, and routine notices. */
|
|
159
|
+
details: string;
|
|
160
|
+
}
|
|
161
|
+
/** Select a compact display without changing the full initialization result. */
|
|
162
|
+
export declare function summarizeInitResult(result: InitResult, display: true): InitDisplayResult;
|
|
163
|
+
/** Preserve existing calls and utility-type consumers through the final compatibility overload. */
|
|
143
164
|
export declare function summarizeInitResult(result: InitResult): InitConciseResult;
|
|
144
165
|
/** Public contract for test only, shared by SDK and presentation-layer consumers. */
|
|
145
166
|
export declare const _testOnly: {
|
package/dist/sdk/init.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="55f7a34f-05d6-507f-a46c-1da0d957f2e3")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import readline from"node:readline/promises";import{stdin as input,stdout as output}from"node:process";import{getActiveExtensionRegistrations,runActiveOnWriteHooks}from"../core/extensions/index.js";import{pathExists,readFileIfExists}from"../core/fs/fs-utils.js";import{writeWorkspaceJsonWithHistory}from"../core/history/workspace-history.js";import{normalizePrefix}from"../core/item/id.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,ensureRuntimeSchemaFileScaffold,filePathForSchemaSection,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{parseItemTypesFile,serializeItemTypesFile,upsertItemType}from"../core/schema/item-types-file.js";import{normalizeTypePresetName,resolveTypePresetDefinitions,TYPE_PRESET_NAMES}from"../core/schema/type-presets.js";import{EXIT_CODE,GOVERNANCE_PRESET_DEFAULTS,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS}from"../core/shared/constants.js";import{readAuthorEnvironment,resolveAuthor}from"../core/shared/author.js";import{PmCliError}from"../core/shared/errors.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings,writeSettings}from"../core/store/settings.js";import{ensurePmGitignore}from"./workspace.js";import{renderPmCommand}from"./command-line.js";import{runExtension}from"./extension.js";import{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance}from"./init-agent-guidance.js";import{findGitWorkspaceRoot,installMergeFence}from"./merge/install.js";const INIT_INVOCATION_CWD=Symbol.for("pm.sdk.init-invocation-cwd");function summarizeInitResult(result){return{ok:result.ok,path:result.path,target:result.target,id_prefix:result.settings.id_prefix,governance_preset:result.governance_preset,telemetry:{enabled:result.settings.telemetry.enabled,capture_level:result.settings.telemetry.capture_level},output_format:result.settings.output.default_format,created_dirs_count:result.created_dirs.length,created_dirs:result.created_dirs,warnings:result.warnings,wizard_used:result.wizard_used,...result.registered_type_preset?{registered_type_preset:result.registered_type_preset}:{},...result.installed_packages?{installed_packages:result.installed_packages}:{},next_steps:result.next_steps,agent_guidance:result.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}const _testOnly={normalizeInitGovernancePreset,normalizeInitTypePreset,normalizeOptionalInitAuthor,normalizeInitAgentGuidanceMode,isPathLikeInitTarget,resolveInitInvocation,resolveInitPrefixInput,parseYesNoChoice,applyGovernancePreset,runInitWizard,setInitReadlineFactoryForTests,summarizeInstalledPackages,buildInitNextSteps,registerInitTypePreset,assertExplicitTrackerPathIsNotWorkspaceRoot,isLikelyWorkspaceRoot,installInitMergeFence};let createInitReadlineInterface=()=>readline.createInterface({input,output});function setInitReadlineFactoryForTests(factory){createInitReadlineInterface=factory??(()=>readline.createInterface({input,output}))}function cloneDefaults(){return structuredClone(SETTINGS_DEFAULTS)}const BUILTIN_GOVERNANCE_PRESETS=["minimal","default","strict"];function normalizeInitGovernancePreset(rawValue){if(rawValue===void 0){return void 0}const normalized=rawValue.trim().toLowerCase().replaceAll("-","_");if(normalized.length===0){throw new PmCliError("--preset must not be empty",EXIT_CODE.USAGE)}if(normalized==="minimal"||normalized==="default"||normalized==="strict"){return normalized}if(normalized==="lite"||normalized==="minimum"){return"minimal"}throw new PmCliError(`Invalid --preset value "${rawValue}". Allowed: ${BUILTIN_GOVERNANCE_PRESETS.join(", ")}`,EXIT_CODE.USAGE)}function normalizeInitTypePreset(rawValue){if(rawValue===void 0){return void 0}if(rawValue.trim().length===0){throw new PmCliError("--type-preset must not be empty",EXIT_CODE.USAGE)}try{return normalizeTypePresetName(rawValue)}catch{throw new PmCliError(`Invalid --type-preset value "${rawValue}". Allowed: ${TYPE_PRESET_NAMES.join(", ")}`,EXIT_CODE.USAGE)}}function normalizeOptionalInitAuthor(rawValue){if(rawValue===void 0){return void 0}const normalized=rawValue.trim();if(normalized.length===0){throw new PmCliError("--author must not be empty",EXIT_CODE.USAGE)}return normalized}function isPathLikeInitTarget(rawValue){if(rawValue===void 0){return false}const trimmed=rawValue.trim();if(trimmed.length===0){return false}return path.isAbsolute(trimmed)||/^[a-z]:/iu.test(trimmed)||trimmed.startsWith(".")||trimmed.includes("/")||trimmed.includes("\\")}function resolveInitInvocation(cwd,global2,prefixArg,workspaceArg){const normalizedWorkspace=workspaceArg?.trim();if(workspaceArg!==void 0&&normalizedWorkspace?.length===0){throw new PmCliError("--workspace must not be empty",EXIT_CODE.USAGE)}if(normalizedWorkspace!==void 0){if(global2.path!==void 0||isPathLikeInitTarget(prefixArg)){throw new PmCliError("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",EXIT_CODE.USAGE)}const workspaceRoot=path.resolve(cwd,normalizedWorkspace);const pmRoot2=path.join(workspaceRoot,".agents","pm");return{pmRoot:pmRoot2,prefixArg,target:{mode:"workspace-path",tracker_root:pmRoot2,workspace_root:workspaceRoot}}}if(global2.path===void 0&&isPathLikeInitTarget(prefixArg)){const positionalTarget=path.resolve(cwd,prefixArg.trim());return{pmRoot:positionalTarget,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:positionalTarget}}}const pmRoot=resolvePmRoot(cwd,global2.path);const currentTrackerRoot=path.join(path.resolve(cwd),".agents","pm");const discoveredWorkspaceRoot=path.dirname(path.dirname(pmRoot));const discovery=path.resolve(pmRoot)===currentTrackerRoot?"current":"ancestor";return{pmRoot,prefixArg,target:global2.path===void 0?{mode:"workspace-discovery",tracker_root:pmRoot,workspace_root:discoveredWorkspaceRoot,discovery,requested_cwd:path.resolve(cwd),...discovery==="ancestor"?{suggested_current_tracker_root:currentTrackerRoot}:{}}:{mode:"tracker-path",tracker_root:pmRoot}}}function resolveInitPrefixInput(positionalPrefix,flaggedPrefix){if(flaggedPrefix===void 0){return positionalPrefix}if(flaggedPrefix.trim().length===0){throw new PmCliError("--id-prefix must not be empty",EXIT_CODE.USAGE)}if(isPathLikeInitTarget(flaggedPrefix)){throw new PmCliError(`--id-prefix accepts an item ID prefix, not a tracker path: "${flaggedPrefix}".`,EXIT_CODE.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${flaggedPrefix}`,`pm --path ${flaggedPrefix} init`]})}if(positionalPrefix!==void 0&&normalizePrefix(positionalPrefix)!==normalizePrefix(flaggedPrefix)){throw new PmCliError(`Conflicting id prefixes: positional "${positionalPrefix}" and --id-prefix "${flaggedPrefix}".`,EXIT_CODE.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${normalizePrefix(positionalPrefix)}`,`pm init --id-prefix ${normalizePrefix(flaggedPrefix)}`]})}return flaggedPrefix}function normalizeInitAgentGuidanceMode(rawValue){if(rawValue===void 0){return"ask"}const normalized=rawValue.trim().toLowerCase().replaceAll("-","_");if(normalized.length===0){throw new PmCliError("--agent-guidance must not be empty",EXIT_CODE.USAGE)}if(normalized==="ask"||normalized==="add"||normalized==="skip"||normalized==="status"){return normalized}throw new PmCliError(`Invalid --agent-guidance value "${rawValue}". Allowed: ${INIT_AGENT_GUIDANCE_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseYesNoChoice(answer,currentDefault){const normalized=answer.trim().toLowerCase();if(normalized.length===0){return currentDefault}if(normalized==="y"||normalized==="yes"){return true}if(normalized==="n"||normalized==="no"){return false}return currentDefault}function applyGovernancePreset(settings,preset){const knobs=GOVERNANCE_PRESET_DEFAULTS[preset];settings.governance={preset,...knobs};settings.validation.parent_reference=knobs.parent_reference;settings.validation.metadata_profile=knobs.metadata_profile}function isInstalledPackageEntry(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function summarizeInstalledPackages(result){const details=result.details;return{installed_all:details.installed_all===true,installed_count:typeof details.installed_count==="number"?details.installed_count:0,packages:Array.isArray(details.packages)?details.packages.filter(isInstalledPackageEntry).map(entry=>({alias:typeof entry.alias==="string"?entry.alias:"",ok:entry.ok===true})):[]}}async function registerInitTypePreset(pmRoot,settings,preset){const schema=normalizeRuntimeSchemaSettings(settings.schema);const typesPath=filePathForSchemaSection(pmRoot,schema.files.types,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types);const parsed=parseItemTypesFile(await readFileIfExists(typesPath));let nextFile=parsed;const registered=[];const updated=[];for(const normalized of resolveTypePresetDefinitions(preset)){const upsert=upsertItemType(nextFile,normalized);nextFile=upsert.file;(upsert.replaced?updated:registered).push(upsert.definition.name)}await writeWorkspaceJsonWithHistory({pmRoot,filePath:typesPath,raw:serializeItemTypesFile(nextFile),op:"init:type-preset",author:resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms});return{name:preset,registered,updated,file:typesPath}}async function isLikelyWorkspaceRoot(candidate){const indicators=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",path.join(".agents","pm")];for(const indicator of indicators){if(await pathExists(path.join(candidate,indicator))){return true}}return false}async function assertExplicitTrackerPathIsNotWorkspaceRoot(pmRoot,explicitTrackerTarget,force){if(!explicitTrackerTarget||force){return}if(await pathExists(path.join(pmRoot,"settings.json"))){return}if(!await isLikelyWorkspaceRoot(pmRoot)){return}const nestedTracker=path.join(pmRoot,".agents","pm");throw new PmCliError(`Refusing to initialize tracker files directly in workspace root "${pmRoot}".`,EXIT_CODE.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${nestedTracker} init --yes`,"pm init --yes",`pm --pm-path ${pmRoot} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${nestedTracker} init --yes`}})}async function ensureInitDirectories(pmRoot,subdirs){const createdDirs=[];const warnings=[];for(const subdir of subdirs){const target=subdir?path.join(pmRoot,subdir):pmRoot;const existed=await pathExists(target);await fs.mkdir(target,{recursive:true});if(existed){warnings.push(`already_exists:${target}`)}else{createdDirs.push(target)}warnings.push(...await runActiveOnWriteHooks({path:target,scope:"project",op:"init:ensure_dir"}))}return{createdDirs,warnings}}async function runInitWizard(initialPrefix,telemetryDefault){const rl=createInitReadlineInterface();try{output.write("pm init setup wizard (agent-optimized)\n");output.write("This walkthrough is non-destructive and each choice can be changed later with pm config.\n\n");output.write("1/3 Item ID prefix\n");output.write("Prefix is prepended to generated IDs (for example pm-a1b2).\n");const prefixAnswer=await rl.question(`Item ID prefix [${initialPrefix}]: `);const resolvedPrefix=prefixAnswer.trim().length>0?normalizePrefix(prefixAnswer):initialPrefix;output.write("\n2/3 Governance preset\n");output.write("minimal: no ownership blocking, progressive create defaults, close validation off.\n");output.write("default: ownership conflict warnings, progressive create defaults, close validation warn.\n");output.write("strict: ownership blocking, strict create defaults, close validation strict.\n");const presetAnswer=await rl.question("Governance preset [minimal/default/strict] (default: minimal): ");const presetChoice=presetAnswer.trim().length>0?presetAnswer.trim():"minimal";let resolvedPreset="minimal";try{resolvedPreset=normalizeInitGovernancePreset(presetChoice)}catch{output.write(`Unrecognized governance preset "${presetChoice}"; using minimal.
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="231597cc-2166-5029-9b3a-476587a33941")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import readline from"node:readline/promises";import{stdin as input,stdout as output}from"node:process";import{getActiveExtensionRegistrations,runActiveOnWriteHooks}from"../core/extensions/index.js";import{pathExists,readFileIfExists}from"../core/fs/fs-utils.js";import{writeWorkspaceJsonWithHistory}from"../core/history/workspace-history.js";import{normalizePrefix}from"../core/item/id.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,ensureRuntimeSchemaFileScaffold,filePathForSchemaSection,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{parseItemTypesFile,serializeItemTypesFile,upsertItemType}from"../core/schema/item-types-file.js";import{normalizeTypePresetName,resolveTypePresetDefinitions,TYPE_PRESET_NAMES}from"../core/schema/type-presets.js";import{EXIT_CODE,GOVERNANCE_PRESET_DEFAULTS,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS}from"../core/shared/constants.js";import{readAuthorEnvironment,resolveAuthor}from"../core/shared/author.js";import{PmCliError}from"../core/shared/errors.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings,writeSettings}from"../core/store/settings.js";import{ensurePmGitignore}from"./workspace.js";import{renderPmCommand}from"./command-line.js";import{runExtension}from"./extension.js";import{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance}from"./init-agent-guidance.js";import{findGitWorkspaceRoot,installMergeFence}from"./merge/install.js";const INIT_INVOCATION_CWD=Symbol.for("pm.sdk.init-invocation-cwd");function summarizeInitResult(result,display=false){if(display){const warnings=result.warnings.filter(warning=>!/^(?:already_exists:|updated:|registered_type_preset:)/u.test(warning));return{ok:result.ok,path:result.path,governance_preset:result.governance_preset,telemetry:`${result.settings.telemetry.enabled?"enabled":"disabled"} (${result.settings.telemetry.capture_level})`,created_count:result.created_dirs.length,next_steps:result.next_steps.slice(0,3),...warnings.length>0?{warnings:warnings.join("; ")}:{},details:`${renderPmCommand(["--pm-path",result.path,"init","--verbose"])} for full setup details and notices (or --json)`}}return{ok:result.ok,path:result.path,target:result.target,id_prefix:result.settings.id_prefix,governance_preset:result.governance_preset,telemetry:{enabled:result.settings.telemetry.enabled,capture_level:result.settings.telemetry.capture_level},output_format:result.settings.output.default_format,created_dirs_count:result.created_dirs.length,created_dirs:result.created_dirs,warnings:result.warnings,wizard_used:result.wizard_used,...result.registered_type_preset?{registered_type_preset:result.registered_type_preset}:{},...result.installed_packages?{installed_packages:result.installed_packages}:{},next_steps:result.next_steps,agent_guidance:result.agent_guidance,hint:"Re-run with --verbose for the full settings tree."}}const _testOnly={normalizeInitGovernancePreset,normalizeInitTypePreset,normalizeOptionalInitAuthor,normalizeInitAgentGuidanceMode,isPathLikeInitTarget,resolveInitInvocation,resolveInitPrefixInput,parseYesNoChoice,applyGovernancePreset,runInitWizard,setInitReadlineFactoryForTests,summarizeInstalledPackages,buildInitNextSteps,registerInitTypePreset,assertExplicitTrackerPathIsNotWorkspaceRoot,isLikelyWorkspaceRoot,installInitMergeFence};let createInitReadlineInterface=()=>readline.createInterface({input,output});function setInitReadlineFactoryForTests(factory){createInitReadlineInterface=factory??(()=>readline.createInterface({input,output}))}function cloneDefaults(){return structuredClone(SETTINGS_DEFAULTS)}const BUILTIN_GOVERNANCE_PRESETS=["minimal","default","strict"];function normalizeInitGovernancePreset(rawValue){if(rawValue===void 0){return void 0}const normalized=rawValue.trim().toLowerCase().replaceAll("-","_");if(normalized.length===0){throw new PmCliError("--preset must not be empty",EXIT_CODE.USAGE)}if(normalized==="minimal"||normalized==="default"||normalized==="strict"){return normalized}if(normalized==="lite"||normalized==="minimum"){return"minimal"}throw new PmCliError(`Invalid --preset value "${rawValue}". Allowed: ${BUILTIN_GOVERNANCE_PRESETS.join(", ")}`,EXIT_CODE.USAGE)}function normalizeInitTypePreset(rawValue){if(rawValue===void 0){return void 0}if(rawValue.trim().length===0){throw new PmCliError("--type-preset must not be empty",EXIT_CODE.USAGE)}try{return normalizeTypePresetName(rawValue)}catch{throw new PmCliError(`Invalid --type-preset value "${rawValue}". Allowed: ${TYPE_PRESET_NAMES.join(", ")}`,EXIT_CODE.USAGE)}}function normalizeOptionalInitAuthor(rawValue){if(rawValue===void 0){return void 0}const normalized=rawValue.trim();if(normalized.length===0){throw new PmCliError("--author must not be empty",EXIT_CODE.USAGE)}return normalized}function isPathLikeInitTarget(rawValue){if(rawValue===void 0){return false}const trimmed=rawValue.trim();if(trimmed.length===0){return false}return path.isAbsolute(trimmed)||/^[a-z]:/iu.test(trimmed)||trimmed.startsWith(".")||trimmed.includes("/")||trimmed.includes("\\")}function resolveInitInvocation(cwd,global2,prefixArg,workspaceArg){const normalizedWorkspace=workspaceArg?.trim();if(workspaceArg!==void 0&&normalizedWorkspace?.length===0){throw new PmCliError("--workspace must not be empty",EXIT_CODE.USAGE)}if(normalizedWorkspace!==void 0){if(global2.path!==void 0||isPathLikeInitTarget(prefixArg)){throw new PmCliError("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",EXIT_CODE.USAGE)}const workspaceRoot=path.resolve(cwd,normalizedWorkspace);const pmRoot2=path.join(workspaceRoot,".agents","pm");return{pmRoot:pmRoot2,prefixArg,target:{mode:"workspace-path",tracker_root:pmRoot2,workspace_root:workspaceRoot}}}if(global2.path===void 0&&isPathLikeInitTarget(prefixArg)){const positionalTarget=path.resolve(cwd,prefixArg.trim());return{pmRoot:positionalTarget,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:positionalTarget}}}const pmRoot=resolvePmRoot(cwd,global2.path);const currentTrackerRoot=path.join(path.resolve(cwd),".agents","pm");const discoveredWorkspaceRoot=path.dirname(path.dirname(pmRoot));const discovery=path.resolve(pmRoot)===currentTrackerRoot?"current":"ancestor";return{pmRoot,prefixArg,target:global2.path===void 0?{mode:"workspace-discovery",tracker_root:pmRoot,workspace_root:discoveredWorkspaceRoot,discovery,requested_cwd:path.resolve(cwd),...discovery==="ancestor"?{suggested_current_tracker_root:currentTrackerRoot}:{}}:{mode:"tracker-path",tracker_root:pmRoot}}}function resolveInitPrefixInput(positionalPrefix,flaggedPrefix){if(flaggedPrefix===void 0){return positionalPrefix}if(flaggedPrefix.trim().length===0){throw new PmCliError("--id-prefix must not be empty",EXIT_CODE.USAGE)}if(isPathLikeInitTarget(flaggedPrefix)){throw new PmCliError(`--id-prefix accepts an item ID prefix, not a tracker path: "${flaggedPrefix}".`,EXIT_CODE.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${flaggedPrefix}`,`pm --path ${flaggedPrefix} init`]})}if(positionalPrefix!==void 0&&normalizePrefix(positionalPrefix)!==normalizePrefix(flaggedPrefix)){throw new PmCliError(`Conflicting id prefixes: positional "${positionalPrefix}" and --id-prefix "${flaggedPrefix}".`,EXIT_CODE.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${normalizePrefix(positionalPrefix)}`,`pm init --id-prefix ${normalizePrefix(flaggedPrefix)}`]})}return flaggedPrefix}function normalizeInitAgentGuidanceMode(rawValue){if(rawValue===void 0){return"ask"}const normalized=rawValue.trim().toLowerCase().replaceAll("-","_");if(normalized.length===0){throw new PmCliError("--agent-guidance must not be empty",EXIT_CODE.USAGE)}if(normalized==="ask"||normalized==="add"||normalized==="skip"||normalized==="status"){return normalized}throw new PmCliError(`Invalid --agent-guidance value "${rawValue}". Allowed: ${INIT_AGENT_GUIDANCE_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseYesNoChoice(answer,currentDefault){const normalized=answer.trim().toLowerCase();if(normalized.length===0){return currentDefault}if(normalized==="y"||normalized==="yes"){return true}if(normalized==="n"||normalized==="no"){return false}return currentDefault}function applyGovernancePreset(settings,preset){const knobs=GOVERNANCE_PRESET_DEFAULTS[preset];settings.governance={preset,...knobs};settings.validation.parent_reference=knobs.parent_reference;settings.validation.metadata_profile=knobs.metadata_profile}function isInstalledPackageEntry(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function summarizeInstalledPackages(result){const details=result.details;return{installed_all:details.installed_all===true,installed_count:typeof details.installed_count==="number"?details.installed_count:0,packages:Array.isArray(details.packages)?details.packages.filter(isInstalledPackageEntry).map(entry=>({alias:typeof entry.alias==="string"?entry.alias:"",ok:entry.ok===true})):[]}}async function registerInitTypePreset(pmRoot,settings,preset){const schema=normalizeRuntimeSchemaSettings(settings.schema);const typesPath=filePathForSchemaSection(pmRoot,schema.files.types,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types);const parsed=parseItemTypesFile(await readFileIfExists(typesPath));let nextFile=parsed;const registered=[];const updated=[];for(const normalized of resolveTypePresetDefinitions(preset)){const upsert=upsertItemType(nextFile,normalized);nextFile=upsert.file;(upsert.replaced?updated:registered).push(upsert.definition.name)}await writeWorkspaceJsonWithHistory({pmRoot,filePath:typesPath,raw:serializeItemTypesFile(nextFile),op:"init:type-preset",author:resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms});return{name:preset,registered,updated,file:typesPath}}async function isLikelyWorkspaceRoot(candidate){const indicators=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",path.join(".agents","pm")];for(const indicator of indicators){if(await pathExists(path.join(candidate,indicator))){return true}}return false}async function assertExplicitTrackerPathIsNotWorkspaceRoot(pmRoot,explicitTrackerTarget,force){if(!explicitTrackerTarget||force){return}if(await pathExists(path.join(pmRoot,"settings.json"))){return}if(!await isLikelyWorkspaceRoot(pmRoot)){return}const nestedTracker=path.join(pmRoot,".agents","pm");throw new PmCliError(`Refusing to initialize tracker files directly in workspace root "${pmRoot}".`,EXIT_CODE.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${nestedTracker} init --yes`,"pm init --yes",`pm --pm-path ${pmRoot} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${nestedTracker} init --yes`}})}async function ensureInitDirectories(pmRoot,subdirs){const createdDirs=[];const warnings=[];for(const subdir of subdirs){const target=subdir?path.join(pmRoot,subdir):pmRoot;const existed=await pathExists(target);await fs.mkdir(target,{recursive:true});if(existed){warnings.push(`already_exists:${target}`)}else{createdDirs.push(target)}warnings.push(...await runActiveOnWriteHooks({path:target,scope:"project",op:"init:ensure_dir"}))}return{createdDirs,warnings}}async function runInitWizard(initialPrefix,telemetryDefault){const rl=createInitReadlineInterface();try{output.write("pm init setup wizard (agent-optimized)\n");output.write("This walkthrough is non-destructive and each choice can be changed later with pm config.\n\n");output.write("1/3 Item ID prefix\n");output.write("Prefix is prepended to generated IDs (for example pm-a1b2).\n");const prefixAnswer=await rl.question(`Item ID prefix [${initialPrefix}]: `);const resolvedPrefix=prefixAnswer.trim().length>0?normalizePrefix(prefixAnswer):initialPrefix;output.write("\n2/3 Governance preset\n");output.write("minimal: no ownership blocking, progressive create defaults, close validation off.\n");output.write("default: ownership conflict warnings, progressive create defaults, close validation warn.\n");output.write("strict: ownership blocking, strict create defaults, close validation strict.\n");const presetAnswer=await rl.question("Governance preset [minimal/default/strict] (default: minimal): ");const presetChoice=presetAnswer.trim().length>0?presetAnswer.trim():"minimal";let resolvedPreset="minimal";try{resolvedPreset=normalizeInitGovernancePreset(presetChoice)}catch{output.write(`Unrecognized governance preset "${presetChoice}"; using minimal.
|
|
2
2
|
`)}output.write("\n3/3 Project telemetry\n");output.write("Telemetry helps improve reliability and can be disabled anytime via pm config.\n");const telemetryLabel=telemetryDefault?"Y/n":"y/N";const telemetryAnswer=await rl.question(`Enable telemetry for this project? [${telemetryLabel}] `);const telemetryEnabled=parseYesNoChoice(telemetryAnswer,telemetryDefault);output.write("\n");return{prefix:resolvedPrefix,preset:resolvedPreset,telemetry_enabled:telemetryEnabled}}finally{rl.close()}}function normalizeInitCommandOptions(options){return{presetFromOption:normalizeInitGovernancePreset(options.preset),useDefaults:options.defaults===true,authorFromOption:normalizeOptionalInitAuthor(options.author),installBundledPackages:options.withPackages===true,agentGuidanceMode:normalizeInitAgentGuidanceMode(options.agentGuidance),typePreset:normalizeInitTypePreset(options.typePreset)}}function collectExistingSettingsPendingChanges(params){const pendingChanges=[];if(params.prefixArg!==void 0&¶ms.settings.id_prefix!==params.normalizedPrefix){pendingChanges.push("id_prefix")}if(params.presetFromOption!==void 0&¶ms.settings.governance.preset!==params.presetFromOption){pendingChanges.push("governance_preset")}if(params.authorFromOption!==void 0&¶ms.settings.author_default!==params.authorFromOption){pendingChanges.push("author_default")}return pendingChanges}function assertExistingSettingsUpdateAllowed(settingsPath,pendingChanges,force,target){if(pendingChanges.length===0||force){return}const ancestorDiscovery=target.discovery==="ancestor";throw new PmCliError(`${ancestorDiscovery?`No tracker exists in ${target.requested_cwd}; pm init found an ancestor tracker at ${target.tracker_root}. `:""}Refusing to update existing tracker settings at ${settingsPath} without --force.`,EXIT_CODE.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${pendingChanges.join(", ")}`,why:ancestorDiscovery?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:target.tracker_root,requested_path:target.requested_cwd,suggested_path:target.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...ancestorDiscovery?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...ancestorDiscovery?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function applyExistingSettingsUpdates(params){let changed=false;if(params.prefixArg!==void 0&¶ms.settings.id_prefix!==params.normalizedPrefix){params.settings.id_prefix=params.normalizedPrefix;params.warnings.push(`updated:id_prefix:${params.normalizedPrefix}`);changed=true}if(params.presetFromOption!==void 0&¶ms.settings.governance.preset!==params.presetFromOption){applyGovernancePreset(params.settings,params.presetFromOption);params.warnings.push(`updated:governance_preset:${params.presetFromOption}`);changed=true}if(params.authorFromOption!==void 0&¶ms.settings.author_default!==params.authorFromOption){params.settings.author_default=params.authorFromOption;params.warnings.push(`updated:author_default:${params.authorFromOption}`);changed=true}return changed}async function loadExistingInitSettings(params){const settings=await readSettings(params.pmRoot);params.warnings.push(`already_exists:${params.settingsPath}`);const pendingChanges=collectExistingSettingsPendingChanges({settings,normalizedPrefix:params.normalizedPrefix,prefixArg:params.prefixArg,presetFromOption:params.normalizedOptions.presetFromOption,authorFromOption:params.normalizedOptions.authorFromOption});assertExistingSettingsUpdateAllowed(params.settingsPath,pendingChanges,params.options.force===true,params.target);if(applyExistingSettingsUpdates({settings,normalizedPrefix:params.normalizedPrefix,prefixArg:params.prefixArg,presetFromOption:params.normalizedOptions.presetFromOption,authorFromOption:params.normalizedOptions.authorFromOption,warnings:params.warnings})){await writeSettings(params.pmRoot,settings)}return{settings,normalizedPrefix:params.normalizedPrefix,chosenPreset:params.normalizedOptions.presetFromOption,wizardUsed:false}}async function createNewInitSettings(params){let normalizedPrefix=params.normalizedPrefix;let chosenPreset=params.normalizedOptions.presetFromOption;let chosenTelemetryEnabled;let wizardUsed=false;if(params.normalizedOptions.presetFromOption===void 0&&!params.normalizedOptions.useDefaults&&process.stdin.isTTY===true&&process.stdout.isTTY===true){const wizardChoices=await runInitWizard(normalizedPrefix,SETTINGS_DEFAULTS.telemetry.enabled);normalizedPrefix=wizardChoices.prefix;chosenPreset=wizardChoices.preset;chosenTelemetryEnabled=wizardChoices.telemetry_enabled;wizardUsed=true}const effectivePreset=chosenPreset??"minimal";const settings=cloneDefaults();settings.id_prefix=normalizedPrefix;applyGovernancePreset(settings,effectivePreset);const environmentAuthor=readAuthorEnvironment()?.trim()||void 0;settings.author_default=params.normalizedOptions.authorFromOption??environmentAuthor??"";if(chosenTelemetryEnabled!==void 0){settings.telemetry.enabled=chosenTelemetryEnabled;settings.telemetry.first_run_prompt_completed=true}await writeSettings(params.pmRoot,settings);return{settings,normalizedPrefix,chosenPreset,wizardUsed}}async function resolveInitSettings(params){if(params.settingsExists){return await loadExistingInitSettings(params)}return await createNewInitSettings({pmRoot:params.pmRoot,normalizedPrefix:params.normalizedPrefix,normalizedOptions:params.normalizedOptions})}async function applyInitAgentGuidance(params){const agentGuidanceResult=await runInitAgentGuidance({pm_root:params.pmRoot,cwd:params.cwd,mode:params.agentGuidanceMode,interactive:process.stdin.isTTY===true&&process.stdout.isTTY===true,settings:params.settings});params.warnings.push(...agentGuidanceResult.warnings);if(agentGuidanceResult.settings_changed){await writeSettings(params.pmRoot,params.settings)}return{...agentGuidanceResult.summary,next_steps:agentGuidanceResult.next_steps}}async function ensureInitRuntimeSchemaFiles(pmRoot,settings){const createdDirs=[];const warnings=[];const runtimeSchemaScaffold=await ensureRuntimeSchemaFileScaffold(pmRoot,settings.schema);for(const createdPath of runtimeSchemaScaffold.created_paths){createdDirs.push(createdPath);warnings.push(...await runActiveOnWriteHooks({path:createdPath,scope:"project",op:"init:runtime_schema_file"}))}return{createdDirs,warnings}}async function maybeRegisterInitTypePreset(params){if(params.typePreset===void 0){return void 0}const registeredTypePreset=await registerInitTypePreset(params.pmRoot,params.settings,params.typePreset);params.warnings.push(`registered_type_preset:${params.typePreset}`);params.warnings.push(...await runActiveOnWriteHooks({path:registeredTypePreset.file,scope:"project",op:"init:type_preset"}));return registeredTypePreset}async function ensureInitTypeDirectories(params){const typeRegistry=resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations());const customTypeFolders=typeRegistry.folders.filter(folder=>!PM_REQUIRED_SUBDIRS.includes(folder));const scaffold=await ensureInitDirectories(params.pmRoot,customTypeFolders);params.createdDirs.push(...scaffold.createdDirs);params.warnings.push(...scaffold.warnings)}function resolveInitWorkspaceRoot(target){const trackerRoot=path.resolve(target.tracker_root);const agentsRoot=path.dirname(trackerRoot);if(path.basename(trackerRoot)==="pm"&&path.basename(agentsRoot)===".agents"){return path.dirname(agentsRoot)}return target.workspace_root}async function maybeInstallInitBundledPackages(installBundledPackages,global2,pmRoot,warnings){if(!installBundledPackages){return void 0}const packageInstallResult=await runExtension("all",{install:true,project:true},{...global2,path:pmRoot});warnings.push(...packageInstallResult.warnings);const installedPackages=summarizeInstalledPackages(packageInstallResult);const failedAliases=installedPackages.packages.filter(entry=>!entry.ok).map(entry=>entry.alias);if(!installedPackages.installed_all||failedAliases.length>0){throw new PmCliError(`pm init --with-packages did not install all bundled packages successfully${failedAliases.length>0?`: ${failedAliases.join(", ")}`:"."}`,EXIT_CODE.GENERIC_FAILURE)}return installedPackages}function buildInitNextSteps(params){const pmCommand=args=>renderPmCommand([...params.target.mode==="workspace-discovery"?[]:["--pm-path",params.target.tracker_root],...args]);const nextSteps=[`Create your first item: ${pmCommand(["create","--type","Task","--title","<title>"])}`,`List active items: ${pmCommand(["list"])}`,`Get agent-friendly project context: ${pmCommand(["context"])}`];if(!params.installBundledPackages){nextSteps.push(`Add optional packages for richer workflows: ${pmCommand(["install","calendar","--project"])}, ${pmCommand(["install","templates","--project"])}, ${pmCommand(["install","guide-shell","--project"])}`);nextSteps.push(`Or install everything bundled: ${pmCommand(["init","--with-packages"])} (idempotent on re-run)`)}else{nextSteps.push(`Explore newly-available commands: ${pmCommand(["cal"])}, ${pmCommand(["templates"])}, ${pmCommand(["guide"])}`)}if(params.registeredTypePreset){nextSteps.push(`Inspect registered preset types: ${pmCommand(["schema","list"])}, ${pmCommand(["schema","show",params.registeredTypePreset.registered[0]??params.registeredTypePreset.updated[0]])}`)}nextSteps.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(const guidanceNextStep of params.agentGuidanceNextSteps){const scopedGuidance=params.target.mode==="workspace-discovery"?guidanceNextStep:guidanceNextStep.replace(/\bpm (?=[a-z])/g,()=>`${pmCommand([])} `);if(!nextSteps.includes(scopedGuidance)){nextSteps.push(scopedGuidance)}}return nextSteps}async function installInitMergeFence(pmRoot,gitWorkspaceRoot,warnings,install=installMergeFence){if(gitWorkspaceRoot===null){warnings.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{const mergeFence=await install({pmRoot,workspaceRoot:gitWorkspaceRoot});if(mergeFence.gitattributes.changed){warnings.push(`updated:merge_fence:${mergeFence.gitattributes.path}`)}}catch(error){if(!(error instanceof PmCliError)){throw error}warnings.push(`merge_fence_skipped:install_failed:${error.context.code??"pm_error"}:${error.message}:run pm merge install after resolving the Git repository error`)}}async function ensureInitWorkspaceGitignore(workspaceRoot,pmRoot,agentGuidanceMode,warnings){if(workspaceRoot===void 0||workspaceRoot===null||agentGuidanceMode==="status"){return}const gitignore=await ensurePmGitignore(workspaceRoot,{pmRoot});if(gitignore.changed){warnings.push(`updated:gitignore:${gitignore.path}`)}}async function runInit(prefixArg,global2,options={}){const invocationCwd=global2[INIT_INVOCATION_CWD];const cwd=typeof invocationCwd==="string"?invocationCwd:process.cwd();const invocation=resolveInitInvocation(cwd,global2,prefixArg,options.workspace);const pmRoot=invocation.pmRoot;prefixArg=resolveInitPrefixInput(invocation.prefixArg,options.idPrefix);const normalizedOptions=normalizeInitCommandOptions(options);await assertExplicitTrackerPathIsNotWorkspaceRoot(pmRoot,invocation.target.mode==="tracker-path",options.force===true);const createdDirs=[];const warnings=[];const settingsPath=path.join(pmRoot,"settings.json");const settingsExists=await pathExists(settingsPath);let settingsResolution;if(settingsExists){settingsResolution=await resolveInitSettings({pmRoot,settingsPath,settingsExists,normalizedPrefix:normalizePrefix(prefixArg),prefixArg,options,normalizedOptions,warnings,target:invocation.target})}const baseDirs=await ensureInitDirectories(pmRoot,PM_REQUIRED_SUBDIRS);createdDirs.push(...baseDirs.createdDirs);warnings.push(...baseDirs.warnings);settingsResolution??=await resolveInitSettings({pmRoot,settingsPath,settingsExists,normalizedPrefix:normalizePrefix(prefixArg),prefixArg,options,normalizedOptions,warnings,target:invocation.target});let{settings}=settingsResolution;const configuredWorkspaceRoot=resolveInitWorkspaceRoot(invocation.target);const gitWorkspaceRoot=await findGitWorkspaceRoot(configuredWorkspaceRoot??path.dirname(pmRoot));const workspaceRoot=configuredWorkspaceRoot??gitWorkspaceRoot;const agentGuidance=await applyInitAgentGuidance({pmRoot,cwd:workspaceRoot??cwd,agentGuidanceMode:normalizedOptions.agentGuidanceMode,settings,warnings});const schemaFiles=await ensureInitRuntimeSchemaFiles(pmRoot,settings);createdDirs.push(...schemaFiles.createdDirs);warnings.push(...schemaFiles.warnings);const registeredTypePreset=await maybeRegisterInitTypePreset({pmRoot,settings,typePreset:normalizedOptions.typePreset,warnings});if(registeredTypePreset){settings=await readSettings(pmRoot)}await ensureInitTypeDirectories({pmRoot,settings,createdDirs,warnings});await ensureInitWorkspaceGitignore(workspaceRoot,pmRoot,normalizedOptions.agentGuidanceMode,warnings);if(!settingsExists&&options.mergeFence!==false&&normalizedOptions.agentGuidanceMode!=="status"){await installInitMergeFence(pmRoot,gitWorkspaceRoot,warnings)}const installedPackages=await maybeInstallInitBundledPackages(normalizedOptions.installBundledPackages,global2,pmRoot,warnings);const nextSteps=buildInitNextSteps({installBundledPackages:normalizedOptions.installBundledPackages,registeredTypePreset,agentGuidanceNextSteps:agentGuidance.next_steps,target:invocation.target});return{ok:true,path:pmRoot,target:invocation.target,settings,created_dirs:createdDirs,warnings,governance_preset:settings.governance.preset,wizard_used:settingsResolution.wizardUsed,...registeredTypePreset?{registered_type_preset:registeredTypePreset}:{},...installedPackages?{installed_packages:installedPackages}:{},next_steps:nextSteps,agent_guidance:agentGuidance}}export{INIT_INVOCATION_CWD,_testOnly,runInit,summarizeInitResult};
|
|
3
3
|
//# sourceMappingURL=init.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6b9c865a-c932-5394-b068-6fcf0dce5d3a")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";import{access,readFile,realpath,writeFile}from"node:fs/promises";import{constants}from"node:fs";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{pathExists}from"../../core/fs/fs-utils.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{acquireLock}from"../../core/lock/lock.js";import{resolvePmPackageRootFromModule}from"../../core/packages/root.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{resolvePmRoot}from"../../core/store/paths.js";import{readSettings,resolveGovernanceKnobs}from"../../core/store/settings.js";import{isPathOutsideRoot}from"../workspace.js";import{resolveSourceContextWritePolicy}from"../environment/source-context.js";const execFileAsync=promisify(execFile);const PM_GITATTRIBUTES_START="# pm-cli:merge-drivers:start";const PM_GITATTRIBUTES_END="# pm-cli:merge-drivers:end";const PM_GITATTRIBUTES_V2_START="# pm-cli:merge-drivers:v2:start";const PM_GITATTRIBUTES_V2_END="# pm-cli:merge-drivers:v2:end";const MERGE_FENCE_LOCK_ID="merge-fence";function quoteMergeDriverArgument(value){return`'${value.replaceAll("'",`'"'"'`)}'`}async function resolveMergeDriverCliCommand(){const packageRoot=resolvePmPackageRootFromModule(import.meta.url,["../../.."]);let executable=process.execPath;const runtimeIdentity=await realpath(process.execPath);for(const directory of(process.env.PATH??"").split(path.delimiter)){if(!path.isAbsolute(directory))continue;const candidate=path.join(directory,path.basename(process.execPath));try{await access(candidate,constants.X_OK);if(candidate!==runtimeIdentity&&await realpath(candidate)===runtimeIdentity){executable=candidate;break}}catch{}}return`${quoteMergeDriverArgument(executable)} ${quoteMergeDriverArgument(path.join(packageRoot,"dist","cli.js"))}`}const MERGE_DRIVER_DEFINITIONS=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function resolveMergeInstallContext(options){const explicitPath=options.explicitPath?.trim();const sourceWorkspaceRoot=options.environment.PM_SOURCE_WORKSPACE_ROOT?.trim();const sourcePmRoot=options.environment.PM_SOURCE_PM_PATH?.trim();const sourcePolicy=resolveSourceContextWritePolicy(options.environment);const sourceCoordinatesAvailable=Boolean(sourceWorkspaceRoot&&sourcePmRoot);const sourceContextSelected=explicitPath===void 0&&sourceCoordinatesAvailable&&(options.dryRun||sourcePolicy.source_writes_allowed);if(explicitPath!==void 0){const pmRoot=resolvePmRoot(options.cwd,explicitPath);return{pm_root:pmRoot,workspace_start:pmRoot,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:false,source_policy:sourcePolicy}}if(sourceContextSelected){return{pm_root:path.resolve(sourcePmRoot),workspace_start:path.resolve(sourceWorkspaceRoot),source_coordinates_available:true,source_context_selected:true,source_policy:sourcePolicy}}return{pm_root:sourceCoordinatesAvailable?resolvePmRoot(options.cwd,".agents/pm"):resolvePmRoot(options.cwd),workspace_start:options.cwd,source_coordinates_available:sourceCoordinatesAvailable,source_context_selected:false,source_policy:sourcePolicy}}async function findGitWorkspaceRoot(cwd){try{const{stdout}=await execFileAsync("git",["rev-parse","--show-toplevel"],{cwd,encoding:"utf8",windowsHide:true,timeout:1e4});return await realpath(stdout.trim())}catch{return null}}async function resolveGitWorkspaceRoot(cwd){const workspaceRoot=await findGitWorkspaceRoot(cwd);if(workspaceRoot===null){throw new PmCliError("pm merge install requires a git repository (merge drivers are git configuration).",EXIT_CODE.USAGE)}return workspaceRoot}function toPosixRelative(fromPath,toPath){return path.relative(fromPath,toPath).replaceAll("\\","/")}function quoteGitAttributePattern(value){return`"${value.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function readSingleQuotedArgument(command,offset){if(command[offset]!=="'"){return null}let value="";for(let index=offset+1;index<command.length;index+=1){if(command.startsWith(`'"'"'`,index)){value+="'";index+=4;continue}if(command[index]==="'"){return{value,nextOffset:index+1}}value+=command[index]}return null}async function isPortableMergeDriverCommand(configured,expectedSuffix){const nodeArgument=readSingleQuotedArgument(configured,0);if(nodeArgument===null||configured[nodeArgument.nextOffset]!==" "){return false}const cliArgument=readSingleQuotedArgument(configured,nodeArgument.nextOffset+1);if(cliArgument===null||configured.slice(cliArgument.nextOffset)!==expectedSuffix||!/^node(?:\.exe)?$/iu.test(path.basename(nodeArgument.value))||path.basename(cliArgument.value)!=="cli.js"||path.basename(path.dirname(cliArgument.value))!=="dist"){return false}if(!await pathExists(nodeArgument.value)||!await pathExists(cliArgument.value)){return false}try{const packageRoot=path.dirname(path.dirname(cliArgument.value));const manifest=JSON.parse(await readFile(path.join(packageRoot,"package.json"),"utf8"));const pmBin=typeof manifest.bin==="object"&&manifest.bin!==null&&"pm"in manifest.bin?manifest.bin.pm:void 0;return manifest.name==="@unbrained/pm-cli"&&(manifest.bin==="dist/cli.js"||pmBin==="dist/cli.js")}catch{return false}}function buildMergeAttributePatterns(trackerRelativeRoot,typeFolders){const prefix=trackerRelativeRoot.length>0?`${trackerRelativeRoot}/`:"";const patterns=[`${quoteGitAttributePattern(`${prefix}**/*.toon`)} merge=pm-item-toon`,`${quoteGitAttributePattern(`${prefix}**/*.md`)} merge=pm-item-markdown`];for(const folder of typeFolders){patterns.push(`${quoteGitAttributePattern(`${prefix}${folder}/*.toon`)} merge=pm-item-toon`);patterns.push(`${quoteGitAttributePattern(`${prefix}${folder}/*.md`)} merge=pm-item-markdown`)}patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.jsonl`)} merge=pm-relationship`);patterns.push(`${quoteGitAttributePattern(`${prefix}history/*.jsonl`)} merge=pm-history`);patterns.push(`${quoteGitAttributePattern(`${prefix}settings.json`)} merge=pm-json`);patterns.push(`${quoteGitAttributePattern(`${prefix}**/*.json`)} merge=pm-json`);patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/**`)} -merge`);patterns.push(`${quoteGitAttributePattern(`${prefix}extensions/.managed-extensions.json`)} merge=pm-json`);return patterns}function removeManagedBlock(content,startMarker,endMarker){const start=content.indexOf(startMarker);const end=content.indexOf(endMarker);return start>=0&&end>start?`${content.slice(0,start)}${content.slice(end+endMarker.length)}`:content.replace(startMarker,"").replace(endMarker,"")}async function reconcileGitattributesBlock(workspaceRoot,patterns,dryRun){const gitattributesPath=path.join(workspaceRoot,".gitattributes");let current="";try{current=await readFile(gitattributesPath,"utf8")}catch(error){if(!(error instanceof Error&&"code"in error&&isFileMissingError(error))){throw error}}const block=[PM_GITATTRIBUTES_V2_START,...patterns,PM_GITATTRIBUTES_V2_END].join("\n");const withoutManagedBlock=removeManagedBlock(removeManagedBlock(current,PM_GITATTRIBUTES_V2_START,PM_GITATTRIBUTES_V2_END),PM_GITATTRIBUTES_START,PM_GITATTRIBUTES_END);const prefix=withoutManagedBlock.trimEnd();const next=`${prefix.length>0?`${prefix}
|
|
2
2
|
|
|
3
3
|
`:""}${block}
|
|
4
|
-
`;if(next===current){return{path:gitattributesPath,changed:false}}if(!dryRun){await writeFile(gitattributesPath,next,"utf8")}return{path:gitattributesPath,changed:true}}function resolveProjectMergeTypeFolders(settings){const registry=resolveItemTypeRegistry(settings,null);return[...new Set(Object.values(registry.type_to_folder))].sort((left,right)=>left.localeCompare(right))}async function auditMergeAttributeFence(pmRoot,typeFolders){const resolvedRoot=path.resolve(pmRoot);let fenceDirectory=null;let fenceContent="";let directory=resolvedRoot;for(let depth=0;depth<8;depth+=1){const candidate=path.join(directory,".gitattributes");try{const raw=await readFile(candidate,"utf8");if(raw.includes(PM_GITATTRIBUTES_V2_START)||raw.includes(PM_GITATTRIBUTES_START)){fenceDirectory=directory;fenceContent=raw;break}}catch{}const parent=path.dirname(directory);if(parent===directory){break}directory=parent}if(fenceDirectory===null){return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"}}const fencePath=path.join(fenceDirectory,".gitattributes");const usesV2=fenceContent.includes(PM_GITATTRIBUTES_V2_START);const startMarker=usesV2?PM_GITATTRIBUTES_V2_START:PM_GITATTRIBUTES_START;const endMarker=usesV2?PM_GITATTRIBUTES_V2_END:PM_GITATTRIBUTES_END;const start=fenceContent.indexOf(startMarker);const end=fenceContent.indexOf(endMarker);const committed=end>start?fenceContent.slice(start+startMarker.length,end).split("\n").map(line=>line.trim()).filter(line=>line.length>0):[];const expected=buildMergeAttributePatterns(toPosixRelative(fenceDirectory,resolvedRoot),typeFolders);const committedSet=new Set(committed);const expectedSet=new Set(expected);const missing=expected.filter(line=>!committedSet.has(line));const stale=committed.filter(line=>!expectedSet.has(line));return{status:missing.length>0||stale.length>0?"drift":"ok",path:fencePath,missing_patterns:missing,stale_patterns:stale,schema_scope:"project"}}async function auditMergeDriverConfiguration(workspaceRoot){const cliCommand=resolveMergeDriverCliCommand();const missingKeys=[];const driftedKeys=[];for(const definition of MERGE_DRIVER_DEFINITIONS){const key=`merge.${definition.key}.driver`;const expectedSuffix=` merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`;const expected=`${cliCommand}${expectedSuffix}`;try{const{stdout}=await execFileAsync("git",["config","--local","--get",key],{cwd:workspaceRoot,encoding:"utf8",windowsHide:true,timeout:1e4});const configured=stdout.trim();if(configured!==expected&&!await isPortableMergeDriverCommand(configured,expectedSuffix)){driftedKeys.push(key)}}catch{missingKeys.push(key)}}return{status:missingKeys.length>0?"missing":driftedKeys.length>0?"drift":"ok",missing_keys:missingKeys,drifted_keys:driftedKeys}}async function refreshMergeAttributeFenceIfInstalled(pmRoot){let workspaceRoot;try{workspaceRoot=await resolveGitWorkspaceRoot(path.resolve(pmRoot))}catch{return{status:"no_git"}}const trackerRelativeRoot=toPosixRelative(workspaceRoot,path.resolve(pmRoot));const lockSettings=await readSettings(pmRoot);const owner=resolveAuthor(void 0,lockSettings.author_default);const releaseLock=await acquireLock(pmRoot,MERGE_FENCE_LOCK_ID,lockSettings.locks.ttl_seconds,owner,false,resolveGovernanceKnobs(lockSettings).force_required_for_stale_lock,lockSettings.locks.wait_ms);try{const gitattributesPath=path.join(workspaceRoot,".gitattributes");let current;try{current=await readFile(gitattributesPath,"utf8")}catch(error){if(error instanceof Error&&"code"in error&&isFileMissingError(error)){return{status:"not_installed",path:gitattributesPath}}throw error}if(!current.includes(PM_GITATTRIBUTES_V2_START)&&!current.includes(PM_GITATTRIBUTES_START)){return{status:"not_installed",path:gitattributesPath}}const settings=await readSettings(pmRoot);const typeFolders=resolveProjectMergeTypeFolders(settings);const outcome=await reconcileGitattributesBlock(workspaceRoot,buildMergeAttributePatterns(trackerRelativeRoot,typeFolders),false);return{status:outcome.changed?"refreshed":"unchanged",path:outcome.path}}finally{await releaseLock()}}async function runMergeInstall(options,global2){const context=resolveMergeInstallContext({cwd:process.cwd(),explicitPath:global2.path,dryRun:options.dryRun===true,environment:process.env});const pmRoot=context.pm_root;await assertInitializedTracker(pmRoot);const workspaceRoot=await resolveGitWorkspaceRoot(context.workspace_start);return installMergeFence({pmRoot,workspaceRoot,dryRun:options.dryRun===true})}async function installMergeFence(options){const pmRoot=path.resolve(options.pmRoot);const workspaceRoot=path.resolve(options.workspaceRoot);const dryRun=options.dryRun===true;let canonicalPmRoot;let canonicalWorkspaceRoot;try{[canonicalPmRoot,canonicalWorkspaceRoot]=await Promise.all([realpath(pmRoot),realpath(workspaceRoot)])}catch(error){throw new PmCliError(`Cannot resolve tracker root ${pmRoot} or workspace root ${workspaceRoot}: ${String(error)}`,EXIT_CODE.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}const trackerRelativeRoot=toPosixRelative(canonicalWorkspaceRoot,canonicalPmRoot);if(isPathOutsideRoot(trackerRelativeRoot)){throw new PmCliError(`Tracker root ${pmRoot} is outside the git repository ${workspaceRoot}; there is nothing to configure for this repository.`,EXIT_CODE.USAGE)}const settings=await readSettings(canonicalPmRoot);const typeFolders=resolveProjectMergeTypeFolders(settings);const patterns=buildMergeAttributePatterns(trackerRelativeRoot,typeFolders);const gitConfigEntries=[];const cliCommand=resolveMergeDriverCliCommand();for(const definition of MERGE_DRIVER_DEFINITIONS){gitConfigEntries.push({key:`merge.${definition.key}.name`,value:definition.name});gitConfigEntries.push({key:`merge.${definition.key}.driver`,value:`${cliCommand} merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`})}if(!dryRun){try{for(const entry of gitConfigEntries){await execFileAsync("git",["config","--local",entry.key,entry.value],{cwd:canonicalWorkspaceRoot,encoding:"utf8",windowsHide:true,timeout:1e4})}}catch{throw new PmCliError(`Cannot install repository-local merge drivers in ${canonicalWorkspaceRoot}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,EXIT_CODE.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}}const gitattributes=await reconcileGitattributesBlock(canonicalWorkspaceRoot,patterns,dryRun);return{ok:true,dry_run:dryRun,workspace_root:canonicalWorkspaceRoot,pm_root:canonicalPmRoot,gitattributes:{path:gitattributes.path,changed:gitattributes.changed,patterns,schema_scope:"project"},git_config:gitConfigEntries,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:nowIso()}}export{PM_GITATTRIBUTES_END,PM_GITATTRIBUTES_START,PM_GITATTRIBUTES_V2_END,PM_GITATTRIBUTES_V2_START,auditMergeAttributeFence,auditMergeDriverConfiguration,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall};
|
|
4
|
+
`;if(next===current){return{path:gitattributesPath,changed:false}}if(!dryRun){await writeFile(gitattributesPath,next,"utf8")}return{path:gitattributesPath,changed:true}}function resolveProjectMergeTypeFolders(settings){const registry=resolveItemTypeRegistry(settings,null);return[...new Set(Object.values(registry.type_to_folder))].sort((left,right)=>left.localeCompare(right))}async function auditMergeAttributeFence(pmRoot,typeFolders){const resolvedRoot=path.resolve(pmRoot);let fenceDirectory=null;let fenceContent="";let directory=resolvedRoot;for(let depth=0;depth<8;depth+=1){const candidate=path.join(directory,".gitattributes");try{const raw=await readFile(candidate,"utf8");if(raw.includes(PM_GITATTRIBUTES_V2_START)||raw.includes(PM_GITATTRIBUTES_START)){fenceDirectory=directory;fenceContent=raw;break}}catch{}const parent=path.dirname(directory);if(parent===directory){break}directory=parent}if(fenceDirectory===null){return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"}}const fencePath=path.join(fenceDirectory,".gitattributes");const usesV2=fenceContent.includes(PM_GITATTRIBUTES_V2_START);const startMarker=usesV2?PM_GITATTRIBUTES_V2_START:PM_GITATTRIBUTES_START;const endMarker=usesV2?PM_GITATTRIBUTES_V2_END:PM_GITATTRIBUTES_END;const start=fenceContent.indexOf(startMarker);const end=fenceContent.indexOf(endMarker);const committed=end>start?fenceContent.slice(start+startMarker.length,end).split("\n").map(line=>line.trim()).filter(line=>line.length>0):[];const expected=buildMergeAttributePatterns(toPosixRelative(fenceDirectory,resolvedRoot),typeFolders);const committedSet=new Set(committed);const expectedSet=new Set(expected);const missing=expected.filter(line=>!committedSet.has(line));const stale=committed.filter(line=>!expectedSet.has(line));return{status:missing.length>0||stale.length>0?"drift":"ok",path:fencePath,missing_patterns:missing,stale_patterns:stale,schema_scope:"project"}}async function auditMergeDriverConfiguration(workspaceRoot){const cliCommand=await resolveMergeDriverCliCommand();const missingKeys=[];const driftedKeys=[];for(const definition of MERGE_DRIVER_DEFINITIONS){const key=`merge.${definition.key}.driver`;const expectedSuffix=` merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`;const expected=`${cliCommand}${expectedSuffix}`;try{const{stdout}=await execFileAsync("git",["config","--local","--get",key],{cwd:workspaceRoot,encoding:"utf8",windowsHide:true,timeout:1e4});const configured=stdout.trim();if(configured!==expected&&!await isPortableMergeDriverCommand(configured,expectedSuffix)){driftedKeys.push(key)}}catch{missingKeys.push(key)}}return{status:missingKeys.length>0?"missing":driftedKeys.length>0?"drift":"ok",missing_keys:missingKeys,drifted_keys:driftedKeys}}async function refreshMergeAttributeFenceIfInstalled(pmRoot){let workspaceRoot;try{workspaceRoot=await resolveGitWorkspaceRoot(path.resolve(pmRoot))}catch{return{status:"no_git"}}const trackerRelativeRoot=toPosixRelative(workspaceRoot,path.resolve(pmRoot));const lockSettings=await readSettings(pmRoot);const owner=resolveAuthor(void 0,lockSettings.author_default);const releaseLock=await acquireLock(pmRoot,MERGE_FENCE_LOCK_ID,lockSettings.locks.ttl_seconds,owner,false,resolveGovernanceKnobs(lockSettings).force_required_for_stale_lock,lockSettings.locks.wait_ms);try{const gitattributesPath=path.join(workspaceRoot,".gitattributes");let current;try{current=await readFile(gitattributesPath,"utf8")}catch(error){if(error instanceof Error&&"code"in error&&isFileMissingError(error)){return{status:"not_installed",path:gitattributesPath}}throw error}if(!current.includes(PM_GITATTRIBUTES_V2_START)&&!current.includes(PM_GITATTRIBUTES_START)){return{status:"not_installed",path:gitattributesPath}}const settings=await readSettings(pmRoot);const typeFolders=resolveProjectMergeTypeFolders(settings);const outcome=await reconcileGitattributesBlock(workspaceRoot,buildMergeAttributePatterns(trackerRelativeRoot,typeFolders),false);return{status:outcome.changed?"refreshed":"unchanged",path:outcome.path}}finally{await releaseLock()}}async function runMergeInstall(options,global2){const context=resolveMergeInstallContext({cwd:process.cwd(),explicitPath:global2.path,dryRun:options.dryRun===true,environment:process.env});const pmRoot=context.pm_root;await assertInitializedTracker(pmRoot);const workspaceRoot=await resolveGitWorkspaceRoot(context.workspace_start);return installMergeFence({pmRoot,workspaceRoot,dryRun:options.dryRun===true})}async function installMergeFence(options){const pmRoot=path.resolve(options.pmRoot);const workspaceRoot=path.resolve(options.workspaceRoot);const dryRun=options.dryRun===true;let canonicalPmRoot;let canonicalWorkspaceRoot;try{[canonicalPmRoot,canonicalWorkspaceRoot]=await Promise.all([realpath(pmRoot),realpath(workspaceRoot)])}catch(error){throw new PmCliError(`Cannot resolve tracker root ${pmRoot} or workspace root ${workspaceRoot}: ${String(error)}`,EXIT_CODE.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}const trackerRelativeRoot=toPosixRelative(canonicalWorkspaceRoot,canonicalPmRoot);if(isPathOutsideRoot(trackerRelativeRoot)){throw new PmCliError(`Tracker root ${pmRoot} is outside the git repository ${workspaceRoot}; there is nothing to configure for this repository.`,EXIT_CODE.USAGE)}const settings=await readSettings(canonicalPmRoot);const typeFolders=resolveProjectMergeTypeFolders(settings);const patterns=buildMergeAttributePatterns(trackerRelativeRoot,typeFolders);const gitConfigEntries=[];const cliCommand=await resolveMergeDriverCliCommand();for(const definition of MERGE_DRIVER_DEFINITIONS){gitConfigEntries.push({key:`merge.${definition.key}.name`,value:definition.name});gitConfigEntries.push({key:`merge.${definition.key}.driver`,value:`${cliCommand} merge driver ${definition.artifact} "%O" "%A" "%B"${definition.itemPath===void 0?"":` --item-path ${definition.itemPath}`}`})}if(!dryRun){try{for(const entry of gitConfigEntries){await execFileAsync("git",["config","--local",entry.key,entry.value],{cwd:canonicalWorkspaceRoot,encoding:"utf8",windowsHide:true,timeout:1e4})}}catch{throw new PmCliError(`Cannot install repository-local merge drivers in ${canonicalWorkspaceRoot}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,EXIT_CODE.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}}const gitattributes=await reconcileGitattributesBlock(canonicalWorkspaceRoot,patterns,dryRun);return{ok:true,dry_run:dryRun,workspace_root:canonicalWorkspaceRoot,pm_root:canonicalPmRoot,gitattributes:{path:gitattributes.path,changed:gitattributes.changed,patterns,schema_scope:"project"},git_config:gitConfigEntries,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:nowIso()}}export{PM_GITATTRIBUTES_END,PM_GITATTRIBUTES_START,PM_GITATTRIBUTES_V2_END,PM_GITATTRIBUTES_V2_START,auditMergeAttributeFence,auditMergeDriverConfiguration,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall};
|
|
5
5
|
//# sourceMappingURL=install.js.map
|