@tekmidian/pai 0.66.8 → 0.66.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { a as slugify, i as parseSessionFilename, n as decodeEncodedDir, r as mi
3
3
  import "./config-DjZELvoA.mjs";
4
4
  import "./config-Dpe2JlbY.mjs";
5
5
  import "./worktree-CwMRTa0H.mjs";
6
- import { n as ensurePaiMarker, r as readPaiMarker, t as discoverPaiMarkers } from "./pai-marker-1B7iC7oq.mjs";
6
+ import { n as ensurePaiMarker, r as readPaiMarker, t as discoverPaiMarkers } from "./pai-marker-BFOlchq2.mjs";
7
7
  import { d as estimateTokens, l as buildOutline, p as parseHeadings, r as detectTier, u as chunkMarkdown } from "./helpers-B9LHRJ8R.mjs";
8
8
  import { i as populateSlugs, n as buildFtsQuery } from "./search-cPDj-9fO.mjs";
9
9
  import { n as rerankResults, t as configureRerankerModel } from "./reranker-BTiOia8Y.mjs";
@@ -342,5 +342,5 @@ function discoverPaiMarkers(searchDirs) {
342
342
  }
343
343
 
344
344
  //#endregion
345
- export { unregistrableReason as a, pruneWorktreeProjects as i, ensurePaiMarker as n, worktreeReason as o, readPaiMarker as r, discoverPaiMarkers as t };
346
- //# sourceMappingURL=pai-marker-1B7iC7oq.mjs.map
345
+ export { unregistrableReason as a, pruneWorktreeProjects as i, ensurePaiMarker as n, readPaiMarker as r, discoverPaiMarkers as t };
346
+ //# sourceMappingURL=pai-marker-BFOlchq2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"pai-marker-1B7iC7oq.mjs","names":[],"sources":["../src/registry/registrable.ts","../src/registry/pai-marker.ts"],"sourcesContent":["/**\n * registrable.ts — directories that must never become registered projects.\n *\n * A project is a durable thing. The registry, however, has been accepting\n * whatever directory a session happened to start in, and some of those\n * directories are disposable by construction. Measured on the real registry,\n * 2026-08-04:\n *\n * 08 - Others/MDF/Infrastruktur/.claude/worktrees/cool-haibt 1 session\n * 08 - Others/MDF/Infrastruktur/.claude/worktrees/strange-haibt 7 sessions\n * /private/tmp/ops-webui dead\n * /private/tmp/claude-501/-Users-…-AIBroker/aae854c6-… dead\n *\n * The worktrees are agent isolation directories, created to be removed. The temp\n * paths are exactly what their name says. Registering them attributes session\n * history to a location with no future, and lets `pai <name>` route someone into\n * a directory a cleanup can delete underneath them.\n *\n * So this refuses at the point of registration rather than reclassifying\n * afterwards. It is a guard, not a policy about what health should call things —\n * it stops the set growing while the vocabulary question (dead vs duplicate vs\n * misnamed vs ephemeral) is decided separately.\n *\n * Found by the AIBroker session while we were dividing up the dead-path work.\n */\n\nimport { readFileSync, statSync } from \"node:fs\";\nimport { dirname, resolve, sep } from \"node:path\";\nimport { readWorkersSection } from \"../workers/config.js\";\nimport { workersLogDir } from \"../workers/paths.js\";\nimport { worktreesDir } from \"../workers/worktree.js\";\nimport type { RegistryBackend } from \"../storage/registry-interface.js\";\n\n/**\n * The `gitdir:` target of a linked worktree, or undefined. A linked worktree's\n * `.git` is a FILE (\"gitdir: <main>/.git/worktrees/<name>\"); a normal repo's is\n * a directory and a submodule's points under `.git/modules/`.\n */\nfunction linkedWorktreeGitdir(root: string): string | undefined {\n const dotGit = resolve(root, \".git\");\n try {\n if (!statSync(dotGit).isFile()) return undefined;\n const m = readFileSync(dotGit, \"utf8\").match(/^gitdir:\\s*(.+?)\\s*$/m);\n return m && m[1].includes(`${sep}worktrees${sep}`) ? m[1] : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** True when `root` is a linked git worktree (its `.git` is a `gitdir:` file). */\nexport function isLinkedWorktree(root: string): boolean {\n return linkedWorktreeGitdir(root) !== undefined;\n}\n\n/** The main repo a linked worktree belongs to, when resolvable. */\nexport function mainRepoOf(root: string): string | undefined {\n const gitdir = linkedWorktreeGitdir(root);\n // <main>/.git/worktrees/<name> -> <main>\n return gitdir ? dirname(dirname(dirname(gitdir))) : undefined;\n}\n\n/** The worker worktrees root from the workers config; undefined if unreadable. */\nfunction workerWorktreesRoot(): string | undefined {\n try {\n return resolve(worktreesDir(workersLogDir(readWorkersSection().workers)));\n } catch {\n return undefined;\n }\n}\n\n/** Path fragments that mark a location as disposable, with why. */\nconst EPHEMERAL: ReadonlyArray<{ fragment: string; because: string }> = [\n {\n // Agent worktrees. `.claude/worktrees/<name>` is created for isolation during\n // one task and removed afterwards.\n fragment: `${sep}.claude${sep}worktrees${sep}`,\n because: \"a git worktree created for agent isolation — it is meant to be removed\",\n },\n {\n // Worker log dirs and their worktrees, current (`<pai home>/logs/workers`)\n // and legacy (`~/.claude/logs/workers`) layouts, including the dir itself.\n fragment: `${sep}logs${sep}workers${sep}`,\n because: \"a worker log directory or worktree — it is meant to be removed\",\n },\n {\n fragment: `${sep}private${sep}tmp${sep}`,\n because: \"a system temp directory\",\n },\n {\n fragment: `${sep}var${sep}folders${sep}`,\n because: \"a macOS per-user temp directory\",\n },\n];\n\n/** Why a path is a (linked or worker) git worktree, or undefined. */\nexport function worktreeReason(\n rootPath: string,\n worktreesRoot: string | undefined = workerWorktreesRoot()\n): string | undefined {\n if (isLinkedWorktree(rootPath)) {\n const main = mainRepoOf(rootPath);\n return `a linked git worktree${main ? ` of ${main}` : \"\"}`;\n }\n const abs = resolve(rootPath);\n if (worktreesRoot && (abs === worktreesRoot || abs.startsWith(worktreesRoot + sep))) {\n return \"a worker worktree\";\n }\n return undefined;\n}\n\n/**\n * Why this path cannot be a project, or undefined if it can.\n *\n * Returns the reason rather than a boolean so the caller can tell the user which\n * rule caught them — \"refused\" without a reason invites someone to work around it\n * rather than move their project somewhere durable.\n */\nexport function unregistrableReason(\n rootPath: string,\n worktreesRoot: string | undefined = workerWorktreesRoot()\n): string | undefined {\n const wt = worktreeReason(rootPath, worktreesRoot);\n if (wt) return wt;\n\n // Compare with trailing separators so a fragment cannot match a partial\n // directory name: `/tmp/` must not match `/tmpdir/`.\n const padded = rootPath.endsWith(sep) ? rootPath : rootPath + sep;\n\n for (const { fragment, because } of EPHEMERAL) {\n if (padded.includes(fragment)) return because;\n }\n\n // A bare `/tmp/...` too. Kept separate from the list above because on macOS\n // /tmp is a symlink to /private/tmp, so both spellings reach the same place and\n // only one of them contains \"private\".\n if (padded.startsWith(`${sep}tmp${sep}`)) return \"a system temp directory\";\n\n return undefined;\n}\n\n/**\n * Remove registry rows whose root is unregistrable (linked worktree, worker\n * worktree/log dir, temp dir; rows registered before the guard existed). Returns\n * the slugs removed. Sessions on those rows are worker/agent scratch history.\n */\nexport async function pruneWorktreeProjects(\n backend: RegistryBackend,\n worktreesRoot: string | undefined = workerWorktreesRoot()\n): Promise<string[]> {\n const removed: string[] = [];\n for (const p of await backend.listProjects({})) {\n if (unregistrableReason(p.root_path, worktreesRoot)) {\n await backend.deleteProjectCascade(p.id);\n removed.push(p.slug);\n }\n }\n return removed;\n}\n","/**\n * PAI.md marker file management.\n *\n * Each registered project gets a `Notes/PAI.md` file with a YAML frontmatter\n * `pai:` block that PAI manages. The rest of the file (body content, other\n * frontmatter keys) is user-owned and never modified by PAI.\n *\n * YAML parsing/updating is done with simple regex — no external dependency.\n */\n\nimport {\n existsSync,\n readFileSync,\n writeFileSync,\n mkdirSync,\n readdirSync,\n statSync,\n} from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { isLinkedWorktree } from \"./registrable.js\";\n\n// ---------------------------------------------------------------------------\n// Container directories\n// ---------------------------------------------------------------------------\n\n/**\n * Directories that hold projects but are not themselves projects.\n *\n * Running a single Claude session from ~/Desktop is enough for the scanner to\n * register it as a project, after which every scan recreates a `Notes/PAI.md`\n * inside it. The user gets a Notes folder on their Desktop that reappears\n * however many times they delete it, containing a marker file that is\n * otherwise empty.\n *\n * The session is still worth tracking — it just belongs in the central notes\n * directory (~/.claude/projects/<encoded>/Notes) rather than as a folder\n * dropped into the user's Desktop.\n */\nconst CONTAINER_DIRS = [\n \"Desktop\",\n \"Documents\",\n \"Downloads\",\n \"Movies\",\n \"Music\",\n \"Pictures\",\n \"Public\",\n \"Library\",\n \"Applications\",\n];\n\n/**\n * True when a path is a place projects live rather than a project itself:\n * the home directory, a standard user container, or a system temp root.\n *\n * Only ever used to decline *creating* a marker. An existing marker is left\n * alone — the user may have put one there deliberately.\n */\nexport function isContainerDirectory(projectRoot: string): boolean {\n // Strip trailing slashes, but never strip the root itself down to \"\".\n const strip = (s: string): string => s.replace(/(?!^)\\/+$/, \"\");\n\n const p = strip(resolve(projectRoot));\n const home = strip(resolve(homedir()));\n\n if (p === home || p === \"/\") return true;\n if (p === \"/tmp\" || p === \"/private/tmp\" || p === \"/var/tmp\") return true;\n\n for (const dir of CONTAINER_DIRS) {\n if (p === join(home, dir)) return true;\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface PaiMarker {\n /** Absolute path to the PAI.md file */\n path: string;\n /** The `slug` value from the `pai:` frontmatter block */\n slug: string;\n /** Absolute path to the project root (parent of Notes/) */\n projectRoot: string;\n}\n\n// ---------------------------------------------------------------------------\n// Template content (mirrors templates/pai-project.template.md)\n// ---------------------------------------------------------------------------\n\nconst TEMPLATE = `---\npai:\n slug: \"\\${SLUG}\"\n registered: \"\\${DATE}\"\n last_indexed: null\n status: active\n---\n\n# \\${DISPLAY_NAME}\n\n<!-- Everything below the YAML frontmatter is yours — PAI never modifies content here. -->\n<!-- Use this file for project notes, decisions, preferences, or anything you want. -->\n<!-- PAI only reads and updates the \\`pai:\\` block in the frontmatter above. -->\n`;\n\nfunction isoDate(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nfunction renderTemplate(slug: string, displayName: string): string {\n return TEMPLATE.replace(/\\$\\{SLUG\\}/g, slug)\n .replace(/\\$\\{DATE\\}/g, isoDate())\n .replace(/\\$\\{DISPLAY_NAME\\}/g, displayName);\n}\n\n// ---------------------------------------------------------------------------\n// YAML frontmatter helpers (regex-based, no external dependency)\n// ---------------------------------------------------------------------------\n\n/**\n * Split a markdown file with YAML frontmatter into its parts.\n *\n * Returns { frontmatter, body } where:\n * frontmatter — content between the opening and closing `---` delimiters\n * body — everything after the closing `---` line\n *\n * Returns null if the file does not begin with a `---` frontmatter block.\n */\nfunction parseFrontmatter(\n content: string\n): { frontmatter: string; body: string } | null {\n if (!content.startsWith(\"---\")) return null;\n\n // Skip past the opening \"---\" and its line ending\n const afterOpen = content.slice(3);\n const eolMatch = afterOpen.match(/^\\r?\\n/);\n if (!eolMatch) return null;\n\n const rest = afterOpen.slice(eolMatch[0].length);\n\n // Find closing \"---\" on its own line\n const closeMatch = rest.match(/^([\\s\\S]*?)\\n---[ \\t]*(\\r?\\n|$)/m);\n if (!closeMatch) return null;\n\n const frontmatter = closeMatch[1];\n const body = rest.slice(closeMatch[0].length);\n\n return { frontmatter, body };\n}\n\n/**\n * Extract a simple scalar YAML value from a block of YAML text.\n *\n * extractYamlValue(' slug: \"my-proj\"', \"slug\") → \"my-proj\"\n * extractYamlValue(' slug: my-proj', \"slug\") → \"my-proj\"\n * extractYamlValue(' last_indexed: null', \"last_indexed\") → \"null\"\n */\nfunction extractYamlValue(yamlBlock: string, key: string): string | null {\n const re = new RegExp(\n `^[ \\\\t]*${key}[ \\\\t]*:[ \\\\t]*\"?([^\"\\\\n\\\\r]*?)\"?[ \\\\t]*$`,\n \"m\"\n );\n const match = yamlBlock.match(re);\n if (!match) return null;\n return match[1].trim() || null;\n}\n\n/**\n * Replace the `pai:` mapping block inside a frontmatter string with\n * `newPaiBlock`. If no `pai:` block is found, appends it at the end.\n *\n * The regex captures the `pai:` key and all immediately-following indented\n * lines (the mapping values), then replaces the whole group.\n *\n * Edge case: the last indented line may not have a trailing newline when it\n * is the final line of the frontmatter string. We handle this by matching\n * lines that end with \\n OR with end-of-string.\n */\nfunction replacePaiBlock(frontmatter: string, newPaiBlock: string): string {\n // Normalise: ensure the frontmatter string ends with \\n so the regex\n // always finds a clean boundary after the last indented line.\n const fm = frontmatter.endsWith(\"\\n\") ? frontmatter : frontmatter + \"\\n\";\n\n // Match \"pai:\\n\" followed by any number of indented lines (each ending \\n).\n const paiRe = /^pai:[ \\t]*\\r?\\n(?:[ \\t]+[^\\r\\n]*\\r?\\n)*/m;\n if (paiRe.test(fm)) {\n // Replace and strip the extra trailing \\n we may have added.\n const replaced = fm.replace(paiRe, newPaiBlock);\n return frontmatter.endsWith(\"\\n\") ? replaced : replaced.replace(/\\n$/, \"\");\n }\n // pai: key not found — append it\n return fm + newPaiBlock;\n}\n\n/**\n * Build the canonical `pai:` YAML block (with a trailing newline).\n */\nfunction buildPaiBlock(\n slug: string,\n registered: string,\n lastIndexed: string | null,\n status: string\n): string {\n const lastIndexedStr =\n lastIndexed === null ? \"null\" : `\"${lastIndexed}\"`;\n return (\n `pai:\\n` +\n ` slug: \"${slug}\"\\n` +\n ` registered: \"${registered}\"\\n` +\n ` last_indexed: ${lastIndexedStr}\\n` +\n ` status: ${status}\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Create or update `<projectRoot>/Notes/PAI.md`.\n *\n * - File absent: creates `Notes/` if needed, writes from template.\n * - File present: updates only the `pai:` frontmatter block; body and all\n * other frontmatter keys are preserved verbatim.\n *\n * @param projectRoot Absolute path to the project root directory.\n * @param slug PAI slug for this project.\n * @param displayName Human-readable name (defaults to slug if omitted).\n */\nexport function ensurePaiMarker(\n projectRoot: string,\n slug: string,\n displayName?: string\n): void {\n // A linked worktree shares its tracked files with the main repo: writing the\n // slug here lands in the main repo's PAI.md when the branch is merged.\n if (isLinkedWorktree(projectRoot)) return;\n\n const notesDir = join(projectRoot, \"Notes\");\n const markerPath = join(notesDir, \"PAI.md\");\n const name = displayName ?? slug;\n\n // --- File does not exist — create from template ---\n if (!existsSync(markerPath)) {\n // Never create a Notes/ folder inside a container directory. Doing so is\n // what puts a Notes folder on the user's Desktop that comes back every\n // time it is deleted.\n if (isContainerDirectory(projectRoot)) return;\n\n mkdirSync(notesDir, { recursive: true });\n writeFileSync(markerPath, renderTemplate(slug, name), \"utf8\");\n return;\n }\n\n // --- File exists — update only the `pai:` block ---\n const raw = readFileSync(markerPath, \"utf8\");\n const parsed = parseFrontmatter(raw);\n\n if (!parsed) {\n // No YAML frontmatter — prepend a fresh one, treat the whole file as body.\n const paiBlock = buildPaiBlock(slug, isoDate(), null, \"active\");\n const newContent = `---\\n${paiBlock}---\\n\\n${raw}`;\n writeFileSync(markerPath, newContent, \"utf8\");\n return;\n }\n\n const { frontmatter, body } = parsed;\n\n // Preserve existing `registered` date so we don't reset it on re-scan.\n const existingRegistered =\n extractYamlValue(frontmatter, \"registered\") ?? isoDate();\n\n // Preserve existing `last_indexed` value (may be \"null\" string or a date).\n const rawLastIndexed = extractYamlValue(frontmatter, \"last_indexed\");\n const lastIndexed =\n rawLastIndexed === null || rawLastIndexed === \"null\"\n ? null\n : rawLastIndexed;\n\n // Preserve existing `status`.\n const existingStatus = extractYamlValue(frontmatter, \"status\") ?? \"active\";\n\n const newPaiBlock = buildPaiBlock(\n slug,\n existingRegistered,\n lastIndexed,\n existingStatus\n );\n\n const newFrontmatter = replacePaiBlock(frontmatter, newPaiBlock);\n\n // Ensure the frontmatter block ends with exactly one newline before the\n // closing --- delimiter.\n const fmWithNewline = newFrontmatter.endsWith(\"\\n\")\n ? newFrontmatter\n : newFrontmatter + \"\\n\";\n\n // Reconstruct the full file. Preserve whatever separator the body has.\n const newContent = `---\\n${fmWithNewline}---\\n${body}`;\n writeFileSync(markerPath, newContent, \"utf8\");\n}\n\n/**\n * Read PAI marker data from `<projectRoot>/Notes/PAI.md`.\n * Returns null if the file does not exist or contains no `pai:` block.\n */\nexport function readPaiMarker(\n projectRoot: string\n): { slug: string; registered: string; status: string } | null {\n const markerPath = join(projectRoot, \"Notes\", \"PAI.md\");\n if (!existsSync(markerPath)) return null;\n\n const raw = readFileSync(markerPath, \"utf8\");\n const parsed = parseFrontmatter(raw);\n if (!parsed) return null;\n\n const slug = extractYamlValue(parsed.frontmatter, \"slug\");\n if (!slug) return null;\n\n const registered =\n extractYamlValue(parsed.frontmatter, \"registered\") ?? \"\";\n const status =\n extractYamlValue(parsed.frontmatter, \"status\") ?? \"active\";\n\n return { slug, registered, status };\n}\n\n/**\n * Scan a list of parent directories for `<child>/Notes/PAI.md` marker files.\n * Each directory in `searchDirs` is scanned one level deep — its immediate\n * child directories are checked for a `Notes/PAI.md` file.\n *\n * Returns an array of PaiMarker objects for every valid marker found.\n * Invalid or malformed markers are silently skipped.\n *\n * @param searchDirs Absolute paths to parent directories.\n */\nexport function discoverPaiMarkers(searchDirs: string[]): PaiMarker[] {\n const results: PaiMarker[] = [];\n\n for (const dir of searchDirs) {\n if (!existsSync(dir)) continue;\n\n let children: string[];\n try {\n children = readdirSync(dir);\n } catch {\n continue;\n }\n\n for (const child of children) {\n if (child.startsWith(\".\")) continue;\n const childPath = join(dir, child);\n try {\n if (!statSync(childPath).isDirectory()) continue;\n } catch {\n continue;\n }\n\n const markerData = readPaiMarker(childPath);\n if (!markerData) continue;\n\n results.push({\n path: join(childPath, \"Notes\", \"PAI.md\"),\n slug: markerData.slug,\n projectRoot: childPath,\n });\n }\n }\n\n return results;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAS,qBAAqB,MAAkC;CAC9D,MAAM,SAAS,QAAQ,MAAM,OAAO;AACpC,KAAI;AACF,MAAI,CAAC,SAAS,OAAO,CAAC,QAAQ,CAAE,QAAO;EACvC,MAAM,IAAI,aAAa,QAAQ,OAAO,CAAC,MAAM,wBAAwB;AACrE,SAAO,KAAK,EAAE,GAAG,SAAS,GAAG,IAAI,WAAW,MAAM,GAAG,EAAE,KAAK;SACtD;AACN;;;;AAKJ,SAAgB,iBAAiB,MAAuB;AACtD,QAAO,qBAAqB,KAAK,KAAK;;;AAIxC,SAAgB,WAAW,MAAkC;CAC3D,MAAM,SAAS,qBAAqB,KAAK;AAEzC,QAAO,SAAS,QAAQ,QAAQ,QAAQ,OAAO,CAAC,CAA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MACA,oBATA,mBAAmB,QAAQ,mBAAmB,SAC1C,OACA,gBAGiB,iBAAiB,aAAa,SAAS,IAAI,SAOjE,CAE+D;AAUhE,eAAc,YADK,QALG,eAAe,SAAS,KAAK,GAC/C,iBACA,iBAAiB,KAGoB,OAAO,QACV,OAAO;;;;;;AAO/C,SAAgB,cACd,aAC6D;CAC7D,MAAM,aAAa,KAAK,aAAa,SAAS,SAAS;AACvD,KAAI,CAAC,WAAW,WAAW,CAAE,QAAO;CAGpC,MAAM,SAAS,iBADH,aAAa,YAAY,OAAO,CACR;AACpC,KAAI,CAAC,OAAQ,QAAO;CAEpB,MAAM,OAAO,iBAAiB,OAAO,aAAa,OAAO;AACzD,KAAI,CAAC,KAAM,QAAO;AAOlB,QAAO;EAAE;EAAM,YAJb,iBAAiB,OAAO,aAAa,aAAa,IAAI;EAI7B,QAFzB,iBAAiB,OAAO,aAAa,SAAS,IAAI;EAEjB;;;;;;;;;;;;AAarC,SAAgB,mBAAmB,YAAmC;CACpE,MAAM,UAAuB,EAAE;AAE/B,MAAK,MAAM,OAAO,YAAY;AAC5B,MAAI,CAAC,WAAW,IAAI,CAAE;EAEtB,IAAI;AACJ,MAAI;AACF,cAAW,YAAY,IAAI;UACrB;AACN;;AAGF,OAAK,MAAM,SAAS,UAAU;AAC5B,OAAI,MAAM,WAAW,IAAI,CAAE;GAC3B,MAAM,YAAY,KAAK,KAAK,MAAM;AAClC,OAAI;AACF,QAAI,CAAC,SAAS,UAAU,CAAC,aAAa,CAAE;WAClC;AACN;;GAGF,MAAM,aAAa,cAAc,UAAU;AAC3C,OAAI,CAAC,WAAY;AAEjB,WAAQ,KAAK;IACX,MAAM,KAAK,WAAW,SAAS,SAAS;IACxC,MAAM,WAAW;IACjB,aAAa;IACd,CAAC;;;AAIN,QAAO"}
1
+ {"version":3,"file":"pai-marker-BFOlchq2.mjs","names":[],"sources":["../src/registry/registrable.ts","../src/registry/pai-marker.ts"],"sourcesContent":["/**\n * registrable.ts — directories that must never become registered projects.\n *\n * A project is a durable thing. The registry, however, has been accepting\n * whatever directory a session happened to start in, and some of those\n * directories are disposable by construction. Measured on the real registry,\n * 2026-08-04:\n *\n * 08 - Others/MDF/Infrastruktur/.claude/worktrees/cool-haibt 1 session\n * 08 - Others/MDF/Infrastruktur/.claude/worktrees/strange-haibt 7 sessions\n * /private/tmp/ops-webui dead\n * /private/tmp/claude-501/-Users-…-AIBroker/aae854c6-… dead\n *\n * The worktrees are agent isolation directories, created to be removed. The temp\n * paths are exactly what their name says. Registering them attributes session\n * history to a location with no future, and lets `pai <name>` route someone into\n * a directory a cleanup can delete underneath them.\n *\n * So this refuses at the point of registration rather than reclassifying\n * afterwards. It is a guard, not a policy about what health should call things —\n * it stops the set growing while the vocabulary question (dead vs duplicate vs\n * misnamed vs ephemeral) is decided separately.\n *\n * Found by the AIBroker session while we were dividing up the dead-path work.\n */\n\nimport { readFileSync, statSync } from \"node:fs\";\nimport { dirname, resolve, sep } from \"node:path\";\nimport { readWorkersSection } from \"../workers/config.js\";\nimport { workersLogDir } from \"../workers/paths.js\";\nimport { worktreesDir } from \"../workers/worktree.js\";\nimport type { RegistryBackend } from \"../storage/registry-interface.js\";\n\n/**\n * The `gitdir:` target of a linked worktree, or undefined. A linked worktree's\n * `.git` is a FILE (\"gitdir: <main>/.git/worktrees/<name>\"); a normal repo's is\n * a directory and a submodule's points under `.git/modules/`.\n */\nfunction linkedWorktreeGitdir(root: string): string | undefined {\n const dotGit = resolve(root, \".git\");\n try {\n if (!statSync(dotGit).isFile()) return undefined;\n const m = readFileSync(dotGit, \"utf8\").match(/^gitdir:\\s*(.+?)\\s*$/m);\n return m && m[1].includes(`${sep}worktrees${sep}`) ? m[1] : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** True when `root` is a linked git worktree (its `.git` is a `gitdir:` file). */\nexport function isLinkedWorktree(root: string): boolean {\n return linkedWorktreeGitdir(root) !== undefined;\n}\n\n/** The main repo a linked worktree belongs to, when resolvable. */\nexport function mainRepoOf(root: string): string | undefined {\n const gitdir = linkedWorktreeGitdir(root);\n // <main>/.git/worktrees/<name> -> <main>\n return gitdir ? dirname(dirname(dirname(gitdir))) : undefined;\n}\n\n/** The worker worktrees root from the workers config; undefined if unreadable. */\nfunction workerWorktreesRoot(): string | undefined {\n try {\n return resolve(worktreesDir(workersLogDir(readWorkersSection().workers)));\n } catch {\n return undefined;\n }\n}\n\n/** Path fragments that mark a location as disposable, with why. */\nconst EPHEMERAL: ReadonlyArray<{ fragment: string; because: string }> = [\n {\n // Agent worktrees. `.claude/worktrees/<name>` is created for isolation during\n // one task and removed afterwards.\n fragment: `${sep}.claude${sep}worktrees${sep}`,\n because: \"a git worktree created for agent isolation — it is meant to be removed\",\n },\n {\n // Worker log dirs and their worktrees, current (`<pai home>/logs/workers`)\n // and legacy (`~/.claude/logs/workers`) layouts, including the dir itself.\n fragment: `${sep}logs${sep}workers${sep}`,\n because: \"a worker log directory or worktree — it is meant to be removed\",\n },\n {\n fragment: `${sep}private${sep}tmp${sep}`,\n because: \"a system temp directory\",\n },\n {\n fragment: `${sep}var${sep}folders${sep}`,\n because: \"a macOS per-user temp directory\",\n },\n];\n\n/** Why a path is a (linked or worker) git worktree, or undefined. */\nexport function worktreeReason(\n rootPath: string,\n worktreesRoot: string | undefined = workerWorktreesRoot()\n): string | undefined {\n if (isLinkedWorktree(rootPath)) {\n const main = mainRepoOf(rootPath);\n return `a linked git worktree${main ? ` of ${main}` : \"\"}`;\n }\n const abs = resolve(rootPath);\n if (worktreesRoot && (abs === worktreesRoot || abs.startsWith(worktreesRoot + sep))) {\n return \"a worker worktree\";\n }\n return undefined;\n}\n\n/**\n * Why this path cannot be a project, or undefined if it can.\n *\n * Returns the reason rather than a boolean so the caller can tell the user which\n * rule caught them — \"refused\" without a reason invites someone to work around it\n * rather than move their project somewhere durable.\n */\nexport function unregistrableReason(\n rootPath: string,\n worktreesRoot: string | undefined = workerWorktreesRoot()\n): string | undefined {\n const wt = worktreeReason(rootPath, worktreesRoot);\n if (wt) return wt;\n\n // Compare with trailing separators so a fragment cannot match a partial\n // directory name: `/tmp/` must not match `/tmpdir/`.\n const padded = rootPath.endsWith(sep) ? rootPath : rootPath + sep;\n\n for (const { fragment, because } of EPHEMERAL) {\n if (padded.includes(fragment)) return because;\n }\n\n // A bare `/tmp/...` too. Kept separate from the list above because on macOS\n // /tmp is a symlink to /private/tmp, so both spellings reach the same place and\n // only one of them contains \"private\".\n if (padded.startsWith(`${sep}tmp${sep}`)) return \"a system temp directory\";\n\n return undefined;\n}\n\n/**\n * Remove registry rows whose root is unregistrable (linked worktree, worker\n * worktree/log dir, temp dir; rows registered before the guard existed). Returns\n * the slugs removed. Sessions on those rows are worker/agent scratch history.\n */\nexport async function pruneWorktreeProjects(\n backend: RegistryBackend,\n worktreesRoot: string | undefined = workerWorktreesRoot()\n): Promise<string[]> {\n const removed: string[] = [];\n for (const p of await backend.listProjects({})) {\n if (unregistrableReason(p.root_path, worktreesRoot)) {\n await backend.deleteProjectCascade(p.id);\n removed.push(p.slug);\n }\n }\n return removed;\n}\n","/**\n * PAI.md marker file management.\n *\n * Each registered project gets a `Notes/PAI.md` file with a YAML frontmatter\n * `pai:` block that PAI manages. The rest of the file (body content, other\n * frontmatter keys) is user-owned and never modified by PAI.\n *\n * YAML parsing/updating is done with simple regex — no external dependency.\n */\n\nimport {\n existsSync,\n readFileSync,\n writeFileSync,\n mkdirSync,\n readdirSync,\n statSync,\n} from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { isLinkedWorktree } from \"./registrable.js\";\n\n// ---------------------------------------------------------------------------\n// Container directories\n// ---------------------------------------------------------------------------\n\n/**\n * Directories that hold projects but are not themselves projects.\n *\n * Running a single Claude session from ~/Desktop is enough for the scanner to\n * register it as a project, after which every scan recreates a `Notes/PAI.md`\n * inside it. The user gets a Notes folder on their Desktop that reappears\n * however many times they delete it, containing a marker file that is\n * otherwise empty.\n *\n * The session is still worth tracking — it just belongs in the central notes\n * directory (~/.claude/projects/<encoded>/Notes) rather than as a folder\n * dropped into the user's Desktop.\n */\nconst CONTAINER_DIRS = [\n \"Desktop\",\n \"Documents\",\n \"Downloads\",\n \"Movies\",\n \"Music\",\n \"Pictures\",\n \"Public\",\n \"Library\",\n \"Applications\",\n];\n\n/**\n * True when a path is a place projects live rather than a project itself:\n * the home directory, a standard user container, or a system temp root.\n *\n * Only ever used to decline *creating* a marker. An existing marker is left\n * alone — the user may have put one there deliberately.\n */\nexport function isContainerDirectory(projectRoot: string): boolean {\n // Strip trailing slashes, but never strip the root itself down to \"\".\n const strip = (s: string): string => s.replace(/(?!^)\\/+$/, \"\");\n\n const p = strip(resolve(projectRoot));\n const home = strip(resolve(homedir()));\n\n if (p === home || p === \"/\") return true;\n if (p === \"/tmp\" || p === \"/private/tmp\" || p === \"/var/tmp\") return true;\n\n for (const dir of CONTAINER_DIRS) {\n if (p === join(home, dir)) return true;\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface PaiMarker {\n /** Absolute path to the PAI.md file */\n path: string;\n /** The `slug` value from the `pai:` frontmatter block */\n slug: string;\n /** Absolute path to the project root (parent of Notes/) */\n projectRoot: string;\n}\n\n// ---------------------------------------------------------------------------\n// Template content (mirrors templates/pai-project.template.md)\n// ---------------------------------------------------------------------------\n\nconst TEMPLATE = `---\npai:\n slug: \"\\${SLUG}\"\n registered: \"\\${DATE}\"\n last_indexed: null\n status: active\n---\n\n# \\${DISPLAY_NAME}\n\n<!-- Everything below the YAML frontmatter is yours — PAI never modifies content here. -->\n<!-- Use this file for project notes, decisions, preferences, or anything you want. -->\n<!-- PAI only reads and updates the \\`pai:\\` block in the frontmatter above. -->\n`;\n\nfunction isoDate(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nfunction renderTemplate(slug: string, displayName: string): string {\n return TEMPLATE.replace(/\\$\\{SLUG\\}/g, slug)\n .replace(/\\$\\{DATE\\}/g, isoDate())\n .replace(/\\$\\{DISPLAY_NAME\\}/g, displayName);\n}\n\n// ---------------------------------------------------------------------------\n// YAML frontmatter helpers (regex-based, no external dependency)\n// ---------------------------------------------------------------------------\n\n/**\n * Split a markdown file with YAML frontmatter into its parts.\n *\n * Returns { frontmatter, body } where:\n * frontmatter — content between the opening and closing `---` delimiters\n * body — everything after the closing `---` line\n *\n * Returns null if the file does not begin with a `---` frontmatter block.\n */\nfunction parseFrontmatter(\n content: string\n): { frontmatter: string; body: string } | null {\n if (!content.startsWith(\"---\")) return null;\n\n // Skip past the opening \"---\" and its line ending\n const afterOpen = content.slice(3);\n const eolMatch = afterOpen.match(/^\\r?\\n/);\n if (!eolMatch) return null;\n\n const rest = afterOpen.slice(eolMatch[0].length);\n\n // Find closing \"---\" on its own line\n const closeMatch = rest.match(/^([\\s\\S]*?)\\n---[ \\t]*(\\r?\\n|$)/m);\n if (!closeMatch) return null;\n\n const frontmatter = closeMatch[1];\n const body = rest.slice(closeMatch[0].length);\n\n return { frontmatter, body };\n}\n\n/**\n * Extract a simple scalar YAML value from a block of YAML text.\n *\n * extractYamlValue(' slug: \"my-proj\"', \"slug\") → \"my-proj\"\n * extractYamlValue(' slug: my-proj', \"slug\") → \"my-proj\"\n * extractYamlValue(' last_indexed: null', \"last_indexed\") → \"null\"\n */\nfunction extractYamlValue(yamlBlock: string, key: string): string | null {\n const re = new RegExp(\n `^[ \\\\t]*${key}[ \\\\t]*:[ \\\\t]*\"?([^\"\\\\n\\\\r]*?)\"?[ \\\\t]*$`,\n \"m\"\n );\n const match = yamlBlock.match(re);\n if (!match) return null;\n return match[1].trim() || null;\n}\n\n/**\n * Replace the `pai:` mapping block inside a frontmatter string with\n * `newPaiBlock`. If no `pai:` block is found, appends it at the end.\n *\n * The regex captures the `pai:` key and all immediately-following indented\n * lines (the mapping values), then replaces the whole group.\n *\n * Edge case: the last indented line may not have a trailing newline when it\n * is the final line of the frontmatter string. We handle this by matching\n * lines that end with \\n OR with end-of-string.\n */\nfunction replacePaiBlock(frontmatter: string, newPaiBlock: string): string {\n // Normalise: ensure the frontmatter string ends with \\n so the regex\n // always finds a clean boundary after the last indented line.\n const fm = frontmatter.endsWith(\"\\n\") ? frontmatter : frontmatter + \"\\n\";\n\n // Match \"pai:\\n\" followed by any number of indented lines (each ending \\n).\n const paiRe = /^pai:[ \\t]*\\r?\\n(?:[ \\t]+[^\\r\\n]*\\r?\\n)*/m;\n if (paiRe.test(fm)) {\n // Replace and strip the extra trailing \\n we may have added.\n const replaced = fm.replace(paiRe, newPaiBlock);\n return frontmatter.endsWith(\"\\n\") ? replaced : replaced.replace(/\\n$/, \"\");\n }\n // pai: key not found — append it\n return fm + newPaiBlock;\n}\n\n/**\n * Build the canonical `pai:` YAML block (with a trailing newline).\n */\nfunction buildPaiBlock(\n slug: string,\n registered: string,\n lastIndexed: string | null,\n status: string\n): string {\n const lastIndexedStr =\n lastIndexed === null ? \"null\" : `\"${lastIndexed}\"`;\n return (\n `pai:\\n` +\n ` slug: \"${slug}\"\\n` +\n ` registered: \"${registered}\"\\n` +\n ` last_indexed: ${lastIndexedStr}\\n` +\n ` status: ${status}\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Create or update `<projectRoot>/Notes/PAI.md`.\n *\n * - File absent: creates `Notes/` if needed, writes from template.\n * - File present: updates only the `pai:` frontmatter block; body and all\n * other frontmatter keys are preserved verbatim.\n *\n * @param projectRoot Absolute path to the project root directory.\n * @param slug PAI slug for this project.\n * @param displayName Human-readable name (defaults to slug if omitted).\n */\nexport function ensurePaiMarker(\n projectRoot: string,\n slug: string,\n displayName?: string\n): void {\n // A linked worktree shares its tracked files with the main repo: writing the\n // slug here lands in the main repo's PAI.md when the branch is merged.\n if (isLinkedWorktree(projectRoot)) return;\n\n const notesDir = join(projectRoot, \"Notes\");\n const markerPath = join(notesDir, \"PAI.md\");\n const name = displayName ?? slug;\n\n // --- File does not exist — create from template ---\n if (!existsSync(markerPath)) {\n // Never create a Notes/ folder inside a container directory. Doing so is\n // what puts a Notes folder on the user's Desktop that comes back every\n // time it is deleted.\n if (isContainerDirectory(projectRoot)) return;\n\n mkdirSync(notesDir, { recursive: true });\n writeFileSync(markerPath, renderTemplate(slug, name), \"utf8\");\n return;\n }\n\n // --- File exists — update only the `pai:` block ---\n const raw = readFileSync(markerPath, \"utf8\");\n const parsed = parseFrontmatter(raw);\n\n if (!parsed) {\n // No YAML frontmatter — prepend a fresh one, treat the whole file as body.\n const paiBlock = buildPaiBlock(slug, isoDate(), null, \"active\");\n const newContent = `---\\n${paiBlock}---\\n\\n${raw}`;\n writeFileSync(markerPath, newContent, \"utf8\");\n return;\n }\n\n const { frontmatter, body } = parsed;\n\n // Preserve existing `registered` date so we don't reset it on re-scan.\n const existingRegistered =\n extractYamlValue(frontmatter, \"registered\") ?? isoDate();\n\n // Preserve existing `last_indexed` value (may be \"null\" string or a date).\n const rawLastIndexed = extractYamlValue(frontmatter, \"last_indexed\");\n const lastIndexed =\n rawLastIndexed === null || rawLastIndexed === \"null\"\n ? null\n : rawLastIndexed;\n\n // Preserve existing `status`.\n const existingStatus = extractYamlValue(frontmatter, \"status\") ?? \"active\";\n\n const newPaiBlock = buildPaiBlock(\n slug,\n existingRegistered,\n lastIndexed,\n existingStatus\n );\n\n const newFrontmatter = replacePaiBlock(frontmatter, newPaiBlock);\n\n // Ensure the frontmatter block ends with exactly one newline before the\n // closing --- delimiter.\n const fmWithNewline = newFrontmatter.endsWith(\"\\n\")\n ? newFrontmatter\n : newFrontmatter + \"\\n\";\n\n // Reconstruct the full file. Preserve whatever separator the body has.\n const newContent = `---\\n${fmWithNewline}---\\n${body}`;\n writeFileSync(markerPath, newContent, \"utf8\");\n}\n\n/**\n * Read PAI marker data from `<projectRoot>/Notes/PAI.md`.\n * Returns null if the file does not exist or contains no `pai:` block.\n */\nexport function readPaiMarker(\n projectRoot: string\n): { slug: string; registered: string; status: string } | null {\n const markerPath = join(projectRoot, \"Notes\", \"PAI.md\");\n if (!existsSync(markerPath)) return null;\n\n const raw = readFileSync(markerPath, \"utf8\");\n const parsed = parseFrontmatter(raw);\n if (!parsed) return null;\n\n const slug = extractYamlValue(parsed.frontmatter, \"slug\");\n if (!slug) return null;\n\n const registered =\n extractYamlValue(parsed.frontmatter, \"registered\") ?? \"\";\n const status =\n extractYamlValue(parsed.frontmatter, \"status\") ?? \"active\";\n\n return { slug, registered, status };\n}\n\n/**\n * Scan a list of parent directories for `<child>/Notes/PAI.md` marker files.\n * Each directory in `searchDirs` is scanned one level deep — its immediate\n * child directories are checked for a `Notes/PAI.md` file.\n *\n * Returns an array of PaiMarker objects for every valid marker found.\n * Invalid or malformed markers are silently skipped.\n *\n * @param searchDirs Absolute paths to parent directories.\n */\nexport function discoverPaiMarkers(searchDirs: string[]): PaiMarker[] {\n const results: PaiMarker[] = [];\n\n for (const dir of searchDirs) {\n if (!existsSync(dir)) continue;\n\n let children: string[];\n try {\n children = readdirSync(dir);\n } catch {\n continue;\n }\n\n for (const child of children) {\n if (child.startsWith(\".\")) continue;\n const childPath = join(dir, child);\n try {\n if (!statSync(childPath).isDirectory()) continue;\n } catch {\n continue;\n }\n\n const markerData = readPaiMarker(childPath);\n if (!markerData) continue;\n\n results.push({\n path: join(childPath, \"Notes\", \"PAI.md\"),\n slug: markerData.slug,\n projectRoot: childPath,\n });\n }\n }\n\n return results;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAS,qBAAqB,MAAkC;CAC9D,MAAM,SAAS,QAAQ,MAAM,OAAO;AACpC,KAAI;AACF,MAAI,CAAC,SAAS,OAAO,CAAC,QAAQ,CAAE,QAAO;EACvC,MAAM,IAAI,aAAa,QAAQ,OAAO,CAAC,MAAM,wBAAwB;AACrE,SAAO,KAAK,EAAE,GAAG,SAAS,GAAG,IAAI,WAAW,MAAM,GAAG,EAAE,KAAK;SACtD;AACN;;;;AAKJ,SAAgB,iBAAiB,MAAuB;AACtD,QAAO,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CAAC;;;AAIN,QAAO"}
@@ -4,13 +4,13 @@ import { b as OWNER_LABEL_PREFIX, c as migrateConfigFile, d as readMainConfigRaw
4
4
  import { a as schedulerLogPath, c as migratePaiFile, d as resolvePaiFile, i as paiSocketPath, l as paiHomeDir, n as daemonLogPath, o as PaiFileMigrationError, s as migratePaiDir, u as paiHomePath } from "./runtime-paths-DkZoxofH.mjs";
5
5
  import { A as initWorkersYaml, B as stripModelVariant, F as relocateWorkersYaml, I as workersYamlLegacyNotice, L as workersYamlPath, M as migrateWorkersToYaml, N as needsWorkersYamlRelocation, P as parseWorkersYamlDocument, R as DEFAULT_CONTEXT_WINDOW, S as nativeAnthropicProvider, T as readWorkersSection, _ as expandHome$1, d as PROVIDER_TAGS, j as inlineWorkersYamlKeys, l as MODEL_CAPABILITIES, p as WorkersConfigError, t as ANTHROPIC_NATIVE, v as getProviderOrNative, x as maskKey, y as isModelCapability, z as contextWindowFromModelId } from "./config-Dpe2JlbY.mjs";
6
6
  import { D as isLive, E as isChatPane, F as setWorkerLabel, H as ensureNoMcpConfig, I as waitForTerminalStatus, M as ownsPid, O as loadStatus, P as saveStatus, R as longInlinePromptHint, U as eventsPath, W as ledgerPath, _ as appendLedger, g as pendingResults, h as pendingGate, k as loadStatuses, m as formatPending, n as discardWorker, q as workersLogDir, r as gcWorktrees, s as mergeWorker, u as verifyWorker, y as UNLABELED, z as parseRunnerArgs } from "./worktree-CwMRTa0H.mjs";
7
- import { a as unregistrableReason, n as ensurePaiMarker, o as worktreeReason } from "./pai-marker-1B7iC7oq.mjs";
7
+ import { a as unregistrableReason, n as ensurePaiMarker } from "./pai-marker-BFOlchq2.mjs";
8
8
  import { t as STOP_WORDS } from "./stop-words-LtkS-Pej.mjs";
9
9
  import { t as applyRecencyBoost } from "./search-cPDj-9fO.mjs";
10
10
  import { c as resolveFromModule, i as retryTransient, n as embedChunksWithBackend, r as indexProjectWithBackend, s as packageRoot } from "./postgres-CCAGq1qp.mjs";
11
11
  import { a as getStorageBackend, c as MergeError, f as humanDuration, i as getRegistryBackend, l as federationDbPath, o as oldRegistryPath, r as createStorageBackend, s as registryDbPath, u as oldFederationPath } from "./factory-yElzJc6f.mjs";
12
12
  import { c as detectBackends, d as OLLAMA_DEFAULT_MODEL, f as OLLAMA_DEFAULT_URL, i as measureThroughput, o as BACKEND_IDS, p as OLLAMA_ID, s as createBackend, u as provisionOllama } from "./embedding-gate-DqbKvn56.mjs";
13
- import { At as claudeProjectsDir, Ct as loadScanConfig, Dt as saveScanConfig, Et as resolveHome, Ft as formatDetection, It as formatDetectionJson, Mt as scanTranscriptFolders, Nt as transcriptFiles, Ot as upsertProject, Pt as detectProject, St as cmdScan, a as sessionKeepaliveLedgerSummary, bt as reexecBackground, ct as findLatestNote, jt as findMovedProjects, kt as upsertSession, l as resolveDaemonPid, lt as findNotesDir$1, o as parseSessionUsage, ot as appendCheckpointToNote, r as loadSessionKeepaliveState, rt as extractAndStoreTriples, s as totalUsageTokens, st as applyContinue, t as readContextHandoverCache, ut as readBodyFile, vt as migrateIdentityFile, w as migrateSummaryCooldowns, wt as migrateScanConfig, y as migrateWorkQueue } from "./context-handover-cache-DFqxNh-H.mjs";
13
+ import { At as claudeProjectsDir, Ct as loadScanConfig, Dt as saveScanConfig, Et as resolveHome, Ft as formatDetection, It as formatDetectionJson, Mt as scanTranscriptFolders, Nt as transcriptFiles, Ot as upsertProject, Pt as detectProject, St as cmdScan, a as sessionKeepaliveLedgerSummary, bt as reexecBackground, ct as findLatestNote, jt as findMovedProjects, kt as upsertSession, l as resolveDaemonPid, lt as findNotesDir$1, o as parseSessionUsage, ot as appendCheckpointToNote, r as loadSessionKeepaliveState, rt as extractAndStoreTriples, s as totalUsageTokens, st as applyContinue, t as readContextHandoverCache, ut as readBodyFile, vt as migrateIdentityFile, w as migrateSummaryCooldowns, wt as migrateScanConfig, y as migrateWorkQueue } from "./context-handover-cache-5qnqzWqp.mjs";
14
14
  import { A as ensureProxyRunning, I as pinNotices, L as projectLaunchConfig, R as describeMcp, _ as clickrControlsArgv, c as waitOn, d as sayToWorker, g as openPaneForWorker, h as openFollowPane, i as usageContextTokens, j as stopProxy, k as DEFAULT_PROXY_PORT, l as handoffFromInside, m as closeEndedPanes, n as runWorker, o as parseWorkerReport, p as checkPaneForWorker, r as testProvider, v as markControlsHeld, x as requestKill, y as callerDescription, z as expandMcpNames } from "./run-BZNdpUGQ.mjs";
15
15
  import { t as PaiClient } from "./ipc-client-DVZ_EGnu.mjs";
16
16
  import { A as getConfigValueOp, C as setWorkersEnabled, D as useProvider, E as updateProvider, M as setConfigValueOp, N as unsetConfigValueOp, O as MainConfigOpsError, S as setProviderModel, T as unsetClass, _ as removeProvider, a as followWorkers, b as setClass, c as statusLineOutput, d as addProvider, f as classTargetText, g as modelPrefsText, h as describeProviders, i as fallbackStatusText, j as listConfigOp, k as formatConfigGetOutput, l as readSpecPrompt, m as describeModels, n as fallbackOn, o as psOutput, p as describeCapabilities, r as fallbackStatus, s as replayOutput, t as fallbackOff, u as resolveSpecPath, v as resolveProviderName, w as unsetCapabilityPreference, x as setProviderEnabled, y as setCapabilityPreference } from "./fallback-2yWDDYiT.mjs";
@@ -1904,7 +1904,7 @@ async function cmdHere(name, opts = {}) {
1904
1904
  console.log(dim$1(`Would create ${finalSlug} (${name}) at ${target}`));
1905
1905
  return;
1906
1906
  }
1907
- const unregistrable = worktreeReason(target);
1907
+ const unregistrable = unregistrableReason(target);
1908
1908
  if (unregistrable) {
1909
1909
  console.error(err(`Not registering ${target}: it is ${unregistrable}.`));
1910
1910
  process.exitCode = 1;
@@ -7197,7 +7197,7 @@ function cmdLogs(opts) {
7197
7197
  }
7198
7198
  function registerDaemonCommands(daemonCmd) {
7199
7199
  daemonCmd.command("serve").description("Start the PAI daemon in the foreground").action(async () => {
7200
- const { serve } = await import("./daemon-WrncnGua.mjs");
7200
+ const { serve } = await import("./daemon-4VZOwUXe.mjs");
7201
7201
  const { loadConfig: lc, ensureConfigDir } = await import("./config-yomayAwe.mjs");
7202
7202
  ensureConfigDir();
7203
7203
  await serve(lc());
@@ -17154,7 +17154,7 @@ async function cmdActive(opts) {
17154
17154
  ], rows));
17155
17155
  }
17156
17156
  async function cmdAutoRoute(opts) {
17157
- const { autoRoute, formatAutoRouteJson } = await import("./auto-route-DCxTKz19.mjs");
17157
+ const { autoRoute, formatAutoRouteJson } = await import("./auto-route-UD9PySwP.mjs");
17158
17158
  const { getRegistryBackend, createStorageBackend } = await import("./factory-DjtXElOI.mjs");
17159
17159
  const { loadConfig } = await import("./config-yomayAwe.mjs");
17160
17160
  const config = loadConfig();
@@ -22039,4 +22039,4 @@ claude() {
22039
22039
 
22040
22040
  //#endregion
22041
22041
  export { drainStdio as n, buildProgram as t };
22042
- //# sourceMappingURL=program-cWqZI0_L.mjs.map
22042
+ //# sourceMappingURL=program-D_Ks5nkL.mjs.map