qfai 2.4.0 → 2.5.0
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/README.md +24 -16
- package/assets/defaults/workflows/apply-settled.yml +2 -0
- package/assets/defaults/workflows/decide-design.yml +1 -6
- package/assets/defaults/workflows/decompose-epic.yml +1 -1
- package/assets/init/.claude/settings.json +1 -1
- package/assets/init/.qfai/assistant/agent/architecture-reviewer.md +1 -0
- package/assets/init/.qfai/assistant/agent/fullstack-engineer.md +6 -9
- package/assets/init/.qfai/assistant/agent/implementation-reviewer.md +9 -1
- package/assets/init/.qfai/assistant/agent/product-surface-reviewer.md +70 -4
- package/assets/init/.qfai/assistant/agent/requirements-reviewer.md +1 -0
- package/assets/init/.qfai/assistant/rule/constitution.md +3 -2
- package/assets/init/.qfai/assistant/rule/drift-protocol.md +5 -5
- package/assets/init/.qfai/assistant/rule/references/deliberation-record-template.md +23 -0
- package/assets/init/.qfai/assistant/rule/references/deliberation-record.md +36 -0
- package/assets/init/.qfai/assistant/rule/references/griller-recommendations.md +3 -3
- package/assets/init/.qfai/assistant/rule/references/launcher-preflight.md +27 -0
- package/assets/init/.qfai/assistant/rule/references/reviewer-findings.md +9 -0
- package/assets/init/.qfai/assistant/rule/references/reviewer-remit.md +23 -15
- package/assets/init/.qfai/assistant/rule/references/visual-reference-survey.md +146 -0
- package/assets/init/.qfai/assistant/rule/references/worker-edit-boundary.md +2 -0
- package/assets/init/.qfai/assistant/rule/research-first-protocol.md +49 -11
- package/assets/init/.qfai/assistant/rule/review-convergence.md +15 -16
- package/assets/init/.qfai/assistant/rule/shared-skill-delegation-baseline.md +3 -0
- package/assets/init/.qfai/assistant/rule/shared-skill-operating-baseline.md +13 -25
- package/assets/init/.qfai/assistant/rule/test-layers.md +8 -0
- package/assets/init/.qfai/assistant/rule/thinking.md +10 -5
- package/assets/init/.qfai/assistant/rule/ui-definition-protocol.md +4 -4
- package/assets/init/.qfai/assistant/rule/ui-procurement.md +50 -10
- package/assets/init/.qfai/assistant/rule/workflow.md +4 -3
- package/assets/init/.qfai/assistant/skill/qfai-configure/SKILL.md +3 -1
- package/assets/init/.qfai/assistant/skill/qfai-discussion/SKILL.md +22 -56
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/design-dna-intake.md +11 -14
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-coverage-checklist.md +1 -1
- package/assets/init/.qfai/assistant/skill/qfai-grilling/SKILL.md +6 -4
- package/assets/init/.qfai/assistant/skill/qfai-grilling/references/discussion-delegation.md +46 -0
- package/assets/init/.qfai/assistant/skill/qfai-grilling/references/glossary-check.md +23 -0
- package/assets/init/.qfai/assistant/skill/qfai-grilling/references/session-check.md +25 -0
- package/assets/init/.qfai/assistant/skill/qfai-implement/SKILL.md +12 -1
- package/assets/init/.qfai/assistant/skill/qfai-implement/references/parallelization-policy.md +2 -3
- package/assets/init/.qfai/assistant/skill/qfai-implement/references/ui-affecting.md +47 -8
- package/assets/init/.qfai/assistant/skill/qfai-maintain/SKILL.md +2 -0
- package/assets/init/.qfai/assistant/skill/qfai-migration-v1-to-v2/SKILL.md +1 -1
- package/assets/init/.qfai/assistant/skill/qfai-prototyping/SKILL.md +6 -2
- package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/generator-prompt.md +6 -9
- package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/reviewer-prompt.md +24 -15
- package/assets/init/.qfai/assistant/skill/qfai-run/SKILL.md +2 -2
- package/assets/init/.qfai/assistant/skill/qfai-run/references/extraction.md +2 -1
- package/assets/init/.qfai/assistant/skill/qfai-run/references/operator-screens.md +7 -3
- package/assets/init/.qfai/assistant/skill/qfai-run/references/stage-points.md +4 -1
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/business-ui-patterns.md +180 -0
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/contract-artifact-rules.md +14 -3
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/design-anti-patterns.md +14 -3
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/design-md-authoring.md +39 -24
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/design-md-brand-catalog.md +2 -2
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/marketing-ui-patterns.md +194 -0
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/requirements-decomposition.md +27 -3
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-execution-playbook.md +29 -22
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-phase-checklists.md +3 -3
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-pre-draft-grilling.md +4 -4
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-quality-gate.md +1 -1
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-triage.md +4 -2
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/spec-traceability-rules.md +6 -6
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/ui-contract-guide.md +87 -4
- package/assets/init/.qfai/assistant/skill/qfai-sdd/references/ui-design-contract-normalization.md +6 -7
- package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/contracts/api-contract.sample.yaml +3 -0
- package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/contracts/db-contract.sample.sql +3 -0
- package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/contracts/ui-contract.sample.yaml +40 -1
- package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/report/preflight_summary.md +10 -16
- package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/01_policy/constraint.md +10 -0
- package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/01_policy/initiative.md +5 -0
- package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/03_contract/tech.md +1 -0
- package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/decisions.md +8 -2
- package/assets/init/.qfai/assistant/skill/qfai-triage/SKILL.md +4 -0
- package/assets/init/.qfai/assistant/skill/qfai-verify/SKILL.md +4 -2
- package/assets/init/.qfai/assistant/skill/qfai-verify/references/context-load.md +2 -1
- package/assets/init/.qfai/assistant/skill/qfai-verify/references/verify-output-contract.md +4 -1
- package/assets/init/.qfai/assistant/step/common-design-md/STEP.md +11 -8
- package/assets/init/.qfai/assistant/step/common-gate-run/STEP.md +1 -1
- package/assets/init/.qfai/assistant/step/common-grilling-record/STEP.md +25 -60
- package/assets/init/.qfai/assistant/step/common-review-cycle/STEP.md +18 -6
- package/assets/init/.qfai/assistant/step/discussion-interview/STEP.md +45 -95
- package/assets/init/.qfai/assistant/step/discussion-research/STEP.md +11 -13
- package/assets/init/.qfai/assistant/step/implement-diagnose/STEP.md +2 -2
- package/assets/init/.qfai/assistant/step/implement-scaffold/STEP.md +52 -8
- package/assets/init/.qfai/assistant/step/implement-settled-edit/STEP.md +78 -0
- package/assets/init/.qfai/assistant/step/implement-sweep/STEP.md +3 -3
- package/assets/init/.qfai/assistant/step/implement-tdd/STEP.md +20 -2
- package/assets/init/.qfai/assistant/step/prototyping-grill/STEP.md +4 -0
- package/assets/init/.qfai/assistant/step/prototyping-handoff/STEP.md +3 -2
- package/assets/init/.qfai/assistant/step/prototyping-loop/STEP.md +6 -1
- package/assets/init/.qfai/assistant/step/sdd-contract/STEP.md +58 -11
- package/assets/init/.qfai/assistant/step/sdd-flow/STEP.md +41 -27
- package/assets/init/.qfai/assistant/step/sdd-story/STEP.md +2 -1
- package/assets/init/.qfai/assistant/step/sdd-triage/STEP.md +43 -26
- package/assets/init/.qfai/assistant/step/triage-answer/STEP.md +8 -3
- package/assets/init/.qfai/assistant/step/triage-close/STEP.md +12 -6
- package/assets/init/.qfai/assistant/step/triage-decompose/STEP.md +2 -1
- package/assets/init/.qfai/assistant/step/triage-operate/STEP.md +36 -6
- package/assets/init/.qfai/assistant/step/triage-security-intake/STEP.md +2 -0
- package/assets/init/.qfai/assistant/step/verify-commit/STEP.md +3 -1
- package/assets/init/.qfai/assistant/step/verify-context/STEP.md +3 -3
- package/assets/init/.qfai/assistant/step/verify-release-notes/STEP.md +11 -3
- package/assets/init/.qfai/assistant/step/verify-repo-gate/STEP.md +22 -0
- package/assets/init/root/.agents/rules/delegation-steering.md +4 -2
- package/assets/init/root/.agents/rules/distributed-surface.md +1 -1
- package/assets/init/root/.agents/rules/grilling.md +28 -76
- package/assets/init/root/.agents/rules/interface-clarity.md +98 -6
- package/assets/init/root/.gitattributes +7 -5
- package/assets/init/root/.github/workflows/qfai-docs.yml +1 -1
- package/assets/init/root/qfai.config.yaml +1 -1
- package/assets/mdschema/story/01_policy/constraint.mdschema.yml +46 -2
- package/assets/mdschema/story/01_policy/initiative.mdschema.yml +18 -0
- package/assets/mdschema/story/03_contract/tech.mdschema.yml +5 -2
- package/assets/uix-rev/strategy-review.md +1 -1
- package/dist/cli/index.cjs +3787 -7097
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.mjs +3647 -6970
- package/dist/cli/index.mjs.map +1 -1
- package/dist/graph/cli.cjs +966 -222
- package/dist/graph/cli.cjs.map +1 -1
- package/dist/graph/cli.mjs +942 -198
- package/dist/graph/cli.mjs.map +1 -1
- package/dist/graph/hook.cjs +999 -88
- package/dist/graph/hook.cjs.map +1 -1
- package/dist/graph/hook.mjs +996 -85
- package/dist/graph/hook.mjs.map +1 -1
- package/dist/hook/turn-end.cjs +15 -45
- package/dist/hook/turn-end.cjs.map +1 -1
- package/dist/hook/turn-end.mjs +15 -45
- package/dist/hook/turn-end.mjs.map +1 -1
- package/dist/index.cjs +15398 -18327
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -41
- package/dist/index.d.ts +32 -41
- package/dist/index.mjs +19276 -22214
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-artifact-rules.md +0 -53
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-completion-matrix.md +0 -133
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/example-mapping-guide.md +0 -18
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/oq-and-deferred-rules.md +0 -84
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui-bearing-playbook.md +0 -95
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/platform_baselines.md +0 -118
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/review_audit_playbook.md +0 -115
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/trend_scan_playbook.md +0 -81
- package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux_best_practices.md +0 -184
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/01_Context.md +0 -143
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/03_Story-Workshop.md +0 -104
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/04_Sources.md +0 -276
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/05_Scope.md +0 -36
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/06_REQ.md +0 -26
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/07_NFR.md +0 -24
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/08_Glossary.md +0 -23
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/09_Constraints.md +0 -60
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/11_OQ-Register.md +0 -38
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/prototyping.yaml +0 -8
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/00_index.md +0 -35
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/40_screen_contracts.md +0 -62
- package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/50_review_input_bundle.md +0 -38
- package/assets/init/.qfai/assistant/step/discussion-oq/STEP.md +0 -70
- package/assets/init/.qfai/assistant/step/discussion-pack/STEP.md +0 -199
- package/assets/init/.qfai/assistant/step/discussion-uiux/STEP.md +0 -82
- package/assets/uix-rev/contracts-review.md +0 -27
package/dist/graph/hook.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/graphHook.ts","../../src/core/init/fsGuards.ts","../../src/core/fs/errno.ts","../../src/core/graph/hooks.ts","../../src/core/graph/fallbackState.ts","../../src/core/graph/locks.ts","../../src/core/graph/layout.ts","../../src/core/graph/localFiles.ts","../../src/core/graph/storage.ts","../../src/core/graph/permissionRecords.ts","../../src/core/graph/codePreparation.ts","../../src/shared/assets.ts","../../src/core/graph/process.ts","../../src/core/graph/reuse.ts","../../src/core/graph/analysis.ts","../../src/core/graph/documents.ts","../../src/core/graph/documentReuse.ts","../../src/core/graph/query.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { findUnsafeHostFileComponent, readPinnedRegularFile } from \"../core/init/fsGuards.js\";\nimport {\n enforceGraphExploration,\n decodeGraphHookEvent,\n failedGraphHook,\n graphHookOutput,\n type GraphHookHost,\n} from \"../core/graph/hooks.js\";\nimport { classifyStoredGraphExploration } from \"../core/graph/fallbackState.js\";\nimport { GraphLocalStateError } from \"../core/graph/localFiles.js\";\n\nfunction hostName(value: unknown): value is GraphHookHost {\n return value === \"claude\" || value === \"codex\" || value === \"copilot\" || value === \"vscode\";\n}\n\nexport interface GraphHookIO {\n read(): unknown;\n output(text: string): void;\n error(text: string): void;\n fail(): void;\n}\n\nexport async function runInstalledGraphHook(\n root: string,\n args: string[],\n io: GraphHookIO = {\n read: () => JSON.parse(readFileSync(0, \"utf8\")) as unknown,\n output: (text) => {\n process.stdout.write(text);\n },\n error: (text) => {\n process.stderr.write(text);\n },\n fail: () => {\n process.exitCode = 2;\n },\n },\n): Promise<void> {\n let input: unknown;\n try {\n input = io.read();\n } catch {\n input = undefined;\n }\n const host = args[0] === \"shared\" ? wireHost(input) : args[0];\n if (!hostName(host)) {\n io.error(\"Graph protection unsupported: select a supported host adapter.\\n\");\n io.fail();\n return;\n }\n let decision = failedGraphHook();\n try {\n const components = [\".qfai\", \"tools\", \"graph-enforcement.json\"];\n if (!(await findUnsafeHostFileComponent(root, components))) {\n const text = await readPinnedRegularFile(path.join(root, ...components), 4096);\n if (text !== null) decision = enforceGraphExploration(input, JSON.parse(text) as unknown);\n }\n } catch {\n // A supported adapter emits denial for invalid input without echoing the payload.\n }\n if (decision.decision === \"deny\" && decision.state === \"configured\") {\n const event = decodeGraphHookEvent(input);\n if (event) {\n try {\n decision = await classifyStoredGraphExploration(root, event);\n } catch (cause: unknown) {\n decision = failedGraphHook();\n if (cause instanceof GraphLocalStateError)\n decision.message = `${cause.message} ${cause.recovery}`;\n }\n }\n }\n if (decision.decision === \"deny\")\n io.output(JSON.stringify(graphHookOutput(host, decision)) + \"\\n\");\n if (decision.state === \"failed\") {\n io.error(\"Graph protection failed. Repair the project hook and enforcement configuration.\\n\");\n io.fail();\n }\n}\n\nfunction wireHost(input: unknown): GraphHookHost | undefined {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) return undefined;\n const value = input as Record<string, unknown>;\n const snake = [\"tool_name\", \"tool_input\", \"session_id\"].some((key) => key in value);\n const camel = [\"toolName\", \"toolArgs\", \"sessionId\"].some((key) => key in value);\n if (snake === camel) return undefined;\n // The selected response format is not evidence of the physical host.\n return camel ? \"copilot\" : \"vscode\";\n}\n","import { constants } from \"node:fs\";\nimport type { Stats } from \"node:fs\";\nimport { access, lstat, open, readFile, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { isEnoent } from \"../fs/errno.js\";\n\n/**\n * The first component of `target` at or below `destRoot` that is a symbolic\n * link, or `null` when every one of them is an ordinary directory or file.\n */\nexport async function firstLinkedComponent(\n target: string,\n destRoot: string,\n): Promise<string | null> {\n const relative = path.relative(destRoot, target);\n let walked = destRoot;\n for (const segment of relative.split(path.sep)) {\n walked = path.join(walked, segment);\n const entry = await lstat(walked).catch(() => null);\n if (entry?.isSymbolicLink() === true) return walked;\n }\n return null;\n}\n\n/** File contents, or `null` when nothing is there. Other read faults throw. */\nexport async function readTextFileIfPresent(target: string): Promise<string | null> {\n try {\n return await readFile(target, \"utf-8\");\n } catch (err: unknown) {\n if (isEnoent(err)) {\n return null;\n }\n throw err;\n }\n}\n\nexport async function exists(target: string): Promise<boolean> {\n try {\n await access(target);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The bytes of a regular file no larger than `maxBytes`, read from the inode\n * the size was measured on, or `null` when the entry is not one.\n *\n * **The ceiling binds the entry that is read**, not the one a previous\n * `lstat` saw. Those are two pathname operations, and between them another\n * process can replace the path with a huge file or a FIFO — a bound checked on\n * the old inode does not bind the new one, and the read then exhausted memory\n * or never returned. One `open`, `fstat` on that handle, a bounded read from\n * it.\n *\n * A read fault is thrown rather than answered `null`: an ACL or a transient\n * `EIO` says the content could not be checked, and reporting that as \"not a\n * bounded regular file\" is a decision nobody made.\n */\nexport async function readPinnedRegularFile(\n filePath: string,\n maxBytes: number,\n): Promise<string | null> {\n let handle: FileHandle | undefined;\n try {\n handle = await open(filePath, OPEN_READ_FLAGS);\n const pinned = await handle.stat();\n if (!pinned.isFile() || pinned.size > maxBytes) {\n return null;\n }\n // Read to the end, not once: `read` may return fewer bytes than asked for,\n // and the unfilled tail stayed NUL — a correct flattened wrapper then\n // failed its own signature comparison and was left in place.\n //\n // And to `maxBytes + 1`, not to the size just measured. Another process\n // holding this inode from before the rename can append after the `fstat`,\n // and stopping at the old size read a **prefix** — which still matched the\n // target, so the repair went ahead and the cleanup deleted the sidecar with\n // the appended bytes in it. One byte past the ceiling is what distinguishes\n // \"this is the whole file\" from \"this is as much as I asked for\".\n const buffer = Buffer.alloc(maxBytes + 1);\n let filled = 0;\n while (filled < buffer.length) {\n const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);\n if (bytesRead === 0) break;\n filled += bytesRead;\n }\n if (filled > maxBytes) return null;\n return buffer.subarray(0, filled).toString(\"utf-8\");\n } catch (error: unknown) {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n // `ENXIO` is what `O_NONBLOCK` returns for a FIFO with no writer, in place\n // of blocking. Neither it nor a directory is a bounded regular file, and\n // `open` is simply where that shows up instead of `fstat`.\n if (code === \"ENXIO\" || code === \"EISDIR\") return null;\n throw error;\n } finally {\n await handle?.close();\n }\n}\n\n/**\n * One bounded read of a regular file: its bytes, and everything a replacement\n * has to put back.\n *\n * `mode`, `uid` and `gid` because an atomic replace writes a **new** inode;\n * `dev` and `ino` so the replacement can tell it is still about to replace the\n * file it read.\n */\nexport type PinnedFileRead = {\n content: Buffer;\n mode: number;\n uid: number;\n gid: number;\n dev: number;\n ino: number;\n};\n\n/**\n * The same read, returning the bytes.\n *\n * The restore copy writes back what it read, and decoding as UTF-8 first\n * replaces every invalid sequence with U+FFFD — irreversibly, since the sidecar\n * is removed straight after.\n *\n * `dev` / `ino` come off the same handle as the content, so a caller that\n * replaces the pathname afterwards can check that the entry it is about to\n * replace is still the inode it read.\n */\nexport async function readPinnedRegularFileBytes(\n filePath: string,\n maxBytes: number,\n): Promise<PinnedFileRead | null> {\n let handle: FileHandle | undefined;\n try {\n handle = await open(filePath, OPEN_READ_FLAGS);\n const pinned = await handle.stat();\n if (!pinned.isFile() || pinned.size > maxBytes) return null;\n const buffer = Buffer.alloc(maxBytes + 1);\n let filled = 0;\n while (filled < buffer.length) {\n const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);\n if (bytesRead === 0) break;\n filled += bytesRead;\n }\n if (filled > maxBytes) return null;\n // The metadata comes from this `fstat`, not from a separate `stat` on the\n // pathname. Two operations could land on two inodes: content read from a\n // replacement that somebody made `0600` for a reason, restored under the\n // `0644` the old entry carried, and readable by everyone.\n return {\n content: Buffer.from(buffer.subarray(0, filled)),\n mode: pinned.mode & 0o7777,\n uid: pinned.uid,\n gid: pinned.gid,\n dev: pinned.dev,\n ino: pinned.ino,\n };\n } catch (error: unknown) {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n if (code === \"ENXIO\" || code === \"EISDIR\") return null;\n throw error;\n } finally {\n await handle?.close();\n }\n}\n\n/**\n * Read-only, non-blocking where the platform defines it.\n *\n * Opening a FIFO for reading blocks until a writer appears, and the point of a\n * size check is not to be at the mercy of what is at the path. Windows has no\n * `O_NONBLOCK`, and no FIFOs in this sense either.\n */\nconst OPEN_READ_FLAGS =\n typeof constants.O_NONBLOCK === \"number\"\n ? constants.O_RDONLY | constants.O_NONBLOCK\n : constants.O_RDONLY;\n\n/** Message text for an unknown thrown value, without `[object Object]`. */\nexport function describeError(err: unknown): string {\n return err instanceof Error ? err.message : JSON.stringify(err);\n}\n\nexport function isEpermOnWindows(err: unknown, platform = process.platform): boolean {\n return (\n platform === \"win32\" &&\n typeof err === \"object\" &&\n err !== null &&\n \"code\" in err &&\n (err as { code: string }).code === \"EPERM\"\n );\n}\n\nexport async function safeLstat(target: string): Promise<Stats | undefined> {\n try {\n return await lstat(target);\n } catch {\n return undefined;\n }\n}\n\nasync function safeStat(target: string): Promise<Stats | undefined> {\n try {\n return await stat(target);\n } catch {\n return undefined;\n }\n}\n\n/**\n * A path component init must not write through, relative to the project, and\n * whether it is a symlink (a junction included) or not a directory.\n */\nexport type UnsafeComponent = { readonly relativePath: string; readonly symlink: boolean };\n\n/**\n * The first component of `relativeDir` under `destRoot` that must not be\n * written through, or `undefined` when the whole chain is safe.\n *\n * `.codex/agents` is a path an untrusted repository controls, and a directory\n * component of it can be a symlink out of the tree — a checked-in\n * `.codex/agents -> /home/user/.config` is enough. `mkdir` follows it,\n * `writeFile` follows it, and `removeSymlinkAt` cannot see it: that guard\n * looks at the leaf `<name>.toml` only. A plain `qfai init` would then write\n * every profile into that external directory, and `--force` would let it\n * delete the orphan profiles there. So every component is `lstat`-ed before\n * anything is written or removed, and one link anywhere in the chain skips the\n * step whole rather than writing part of it somewhere unexpected.\n *\n * A component that does not exist yet ends the walk: `mkdir` creates real\n * directories, and nothing below an absent parent can exist either.\n *\n * The answer names the component by its path relative to `destRoot`. An\n * absolute path carries the destination directory's own name, which on an\n * untrusted repository can hold a newline or an ANSI escape.\n */\nexport async function findUnsafeWrapperComponent(\n destRoot: string,\n relativeDir: string,\n): Promise<UnsafeComponent | undefined> {\n const segments = relativeDir.split(\"/\");\n for (let depth = 1; depth <= segments.length; depth += 1) {\n const relativePath = segments.slice(0, depth).join(\"/\");\n const stats = await safeLstat(path.join(destRoot, ...segments.slice(0, depth)));\n if (stats === undefined) {\n return undefined;\n }\n if (stats.isSymbolicLink()) {\n return { relativePath, symlink: true };\n }\n if (!stats.isDirectory()) {\n return { relativePath, symlink: false };\n }\n }\n return undefined;\n}\n\n/**\n * The first component of `relativeDir` under `destRoot` that `mkdir` cannot\n * pass: a symbolic link whose target is missing or is not a directory, or an\n * entry that is not a directory. A link to a directory that exists is passed,\n * because the instruction files are written through a shared directory on\n * purpose. `undefined` when the directory can be created or already exists.\n */\nexport async function findUnreachableHostDirComponent(\n destRoot: string,\n relativeDir: string,\n): Promise<UnsafeComponent | undefined> {\n const segments = relativeDir.split(\"/\");\n for (let depth = 1; depth <= segments.length; depth += 1) {\n const relativePath = segments.slice(0, depth).join(\"/\");\n const absolute = path.join(destRoot, ...segments.slice(0, depth));\n const stats = await safeLstat(absolute);\n if (stats === undefined) {\n return undefined;\n }\n if (stats.isSymbolicLink()) {\n if ((await safeStat(absolute))?.isDirectory() !== true) {\n return { relativePath, symlink: true };\n }\n } else if (!stats.isDirectory()) {\n return { relativePath, symlink: false };\n }\n }\n return undefined;\n}\n\n/**\n * The component that keeps a file init writes into a host directory, such as\n * a hook file or `.github/copilot-instructions.md`, from being read or\n * written: a directory on its path that is a symbolic link or not a directory,\n * or the file itself when it is a symbolic link, whether its target exists or\n * not. `undefined` when the path is safe.\n */\nexport async function findUnsafeHostFileComponent(\n destRoot: string,\n segments: readonly string[],\n): Promise<UnsafeComponent | undefined> {\n const parent = segments.slice(0, -1).join(\"/\");\n const unsafeParent =\n parent === \"\" ? undefined : await findUnsafeWrapperComponent(destRoot, parent);\n if (unsafeParent !== undefined) {\n return unsafeParent;\n }\n const leaf = await safeLstat(path.join(destRoot, ...segments));\n return leaf?.isSymbolicLink() === true\n ? { relativePath: segments.join(\"/\"), symlink: true }\n : undefined;\n}\n","/**\n * Shared errno helpers for Node.js fs error narrowing.\n *\n * Avoids ad-hoc `(err as { code?: string }).code === \"ENOENT\"` repetition\n * across init / config / prototyping commands. Future errno codes\n * (`EACCES`, `EBUSY`, `EPERM`, ...) extend this module rather than\n * sprouting new inline checks.\n */\n\n/**\n * True iff `err` is a Node.js fs error whose `code` is `\"ENOENT\"`\n * (file or directory does not exist).\n */\nexport function isEnoent(err: unknown): boolean {\n return hasErrnoCode(err) && err.code === \"ENOENT\";\n}\n\n/**\n * True iff `err` is a Node.js fs error whose `code` is `\"EPERM\"`.\n *\n * On Windows this is what `stat` raises for a **file** symlink whose target is\n * a directory: the link is intact and `readlink` returns the right target, but\n * the reparse tag is the wrong kind and the OS refuses to follow it. `git\n * worktree add` produces exactly that for `.claude/skills/*`, because at the\n * moment git writes the link its target does not yet exist in the new worktree\n * and it has no reftype hint. So a reader that treats EPERM as a filesystem\n * fault to propagate crashes on a condition that is structural damage to the\n * path it is inspecting.\n */\nexport function isEperm(err: unknown): boolean {\n return hasErrnoCode(err) && err.code === \"EPERM\";\n}\n\n/**\n * True iff `err` is a Node.js error-shaped object carrying a string\n * `code` (e.g. `\"ENOENT\"`, `\"EACCES\"`, `\"ENOSPC\"`). Narrowing helper\n * shared across the codebase so individual call sites do not sprout\n * ad-hoc `(err as { code?: string }).code` casts (CLAUDE.md\n * \"avoid bare `as` type assertions; prefer type narrowing\").\n */\nexport function hasErrnoCode(err: unknown): err is { code: string } {\n return (\n err !== null &&\n typeof err === \"object\" &&\n \"code\" in err &&\n typeof (err as { code?: unknown }).code === \"string\"\n );\n}\n","export type GraphHookHost = \"claude\" | \"codex\" | \"copilot\" | \"vscode\";\n\nexport interface GraphHookEvent {\n tool: string;\n command?: string;\n path?: string;\n session?: string;\n cwd?: string;\n workdir?: string;\n shell?: string;\n}\n\nexport interface GraphHookDecision {\n decision: \"allow\" | \"deny\";\n state: \"configured\" | \"failed\" | \"outside-boundary\";\n message: string;\n operation?: string;\n target?: string;\n domain?: \"code\" | \"documents\";\n exceptionEligible?: boolean;\n fallbackUnavailable?: true;\n}\n\ntype GraphSearchAuthorization = (decision: GraphHookDecision) => GraphHookDecision;\ntype GraphShell = \"posix\" | \"powershell\" | \"cmd\";\n\nexport function classifyGraphExploration(\n event: GraphHookEvent,\n authorize: GraphSearchAuthorization = (decision) => decision,\n): GraphHookDecision {\n if (event.tool === \"write_stdin\") return outsideBoundary();\n if (\n [\"rg\", \"grep\", \"grep_search\", \"search_files\", \"file_search\"].includes(event.tool.toLowerCase())\n ) {\n return authorize(denyExploration(event.tool, event.path ?? \".\"));\n }\n const shell: GraphShell =\n /(?:^|[\\\\/])(?:pwsh|powershell)(?:\\.exe)?$/i.test(event.shell ?? \"\") ||\n event.tool.toLowerCase() === \"powershell\" ||\n (event.tool === \"exec_command\" && !event.shell && process.platform === \"win32\")\n ? \"powershell\"\n : /(?:^|[\\\\/])cmd(?:\\.exe)?$/i.test(event.shell ?? \"\")\n ? \"cmd\"\n : \"posix\";\n const commands = shellPipelines(event.command ?? \"\", shell);\n if (!commands) return failedGraphHook();\n return (\n classifyCommands(commands, authorize) ?? {\n decision: \"allow\",\n state: \"configured\",\n message: \"No direct exploration was classified.\",\n }\n );\n}\n\nfunction classifyCommands(\n commands: string[][],\n authorize: GraphSearchAuthorization,\n depth = 0,\n): GraphHookDecision | undefined {\n const changesDirectory = commands.some(changesGraphDirectory);\n const scopedAuthorization: GraphSearchAuthorization = changesDirectory\n ? (decision) =>\n graphFallbackUnavailable(\n decision,\n \"The command changes its working directory.\",\n \"Run a single search from this project worktree, then retry the denied action.\",\n )\n : authorize;\n let boundary: GraphHookDecision | undefined;\n let allowed: GraphHookDecision | undefined;\n for (const words of commands) {\n const decision = classifyCommand(words, scopedAuthorization, depth);\n if (decision?.decision === \"deny\") return decision;\n if (decision?.state === \"outside-boundary\") boundary = decision;\n else if (decision) allowed = decision;\n }\n return boundary ?? allowed;\n}\n\nfunction changesGraphDirectory(words: string[]): boolean {\n let offset = 0;\n while (offset < words.length) {\n if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? \"\")) {\n offset += 1;\n continue;\n }\n if (![\"command\", \"builtin\", \"env\"].includes(words[offset]?.toLowerCase() ?? \"\")) break;\n offset += 1;\n if (words[offset] === \"-v\" || words[offset] === \"-V\") return false;\n while (words[offset]?.startsWith(\"-\")) offset += 1;\n }\n return [\"cd\", \"chdir\", \"pushd\", \"popd\", \"set-location\", \"sl\"].includes(\n words[offset]?.toLowerCase() ?? \"\",\n );\n}\n\nfunction classifyCommand(\n words: string[],\n authorize: GraphSearchAuthorization,\n depth = 0,\n): GraphHookDecision | undefined {\n if (depth > 16) return failedGraphHook();\n let offset = 0;\n while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? \"\")) offset += 1;\n if (offset > 0) return classifyCommand(words.slice(offset), authorize, depth + 1);\n const operation = words[0]\n ?.split(/[\\\\/]/)\n .at(-1)\n ?.replace(/\\.exe$/i, \"\")\n .toLowerCase();\n if (operation === \"env\" || operation === \"command\" || operation === \"builtin\") {\n let offset = 1;\n while (words[offset]?.startsWith(\"-\") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? \"\")) {\n offset += 1;\n }\n return classifyCommand(words.slice(offset), authorize, depth + 1);\n }\n if ([\"bash\", \"sh\", \"zsh\", \"pwsh\", \"powershell\", \"cmd\"].includes(operation ?? \"\")) {\n const switchIndex = words.findIndex((word) => /^(?:-[a-z]*c|\\/c|-command)$/i.test(word));\n const inner = switchIndex >= 0 ? words[switchIndex + 1] : undefined;\n if (!inner) return outsideBoundary();\n const shell =\n operation === \"pwsh\" || operation === \"powershell\"\n ? \"powershell\"\n : operation === \"cmd\"\n ? \"cmd\"\n : \"posix\";\n const commands = shellPipelines(inner, shell);\n return commands ? classifyCommands(commands, authorize, depth + 1) : failedGraphHook();\n }\n if (operation === \"rg\" || operation === \"grep\" || operation === \"findstr\") {\n let offset = 1;\n while (\n /^(?:-[RrinlIHsvwxcFoq]+|--(?:hidden|line-number|ignore-case|fixed-strings|recursive)|\\/[SIMOPVNLR]+)$/i.test(\n words[offset] ?? \"\",\n )\n )\n offset += 1;\n if (words[offset] === \"--\") offset += 1;\n const positional = words.slice(offset);\n const eligible =\n positional.length > 0 &&\n positional.length <= 2 &&\n !positional.some((word) => word.startsWith(\"-\") || /[$%`<>]/.test(word));\n const target = eligible ? (positional[1] ?? \".\") : JSON.stringify(positional);\n return authorize({ ...denyExploration(operation, target), exceptionEligible: eligible });\n }\n let gitCommand = 1;\n if (operation === \"git\") {\n while (words[gitCommand]?.startsWith(\"-\")) {\n const option = words[gitCommand];\n gitCommand += [\"-C\", \"-c\", \"--git-dir\", \"--work-tree\"].includes(option ?? \"\") ? 2 : 1;\n }\n }\n if (operation === \"git\" && words[gitCommand]?.toLowerCase() === \"grep\") {\n const paths = words.indexOf(\"--\");\n const targets = paths >= 0 ? words.slice(paths + 1) : [];\n const eligible =\n gitCommand === 1 &&\n targets.length <= 1 &&\n (paths >= 0 || words.length === 3) &&\n !targets.some((word) => /[$%`<>]/.test(word));\n return authorize({\n ...denyExploration(\n \"git grep\",\n eligible ? (targets[0] ?? \".\") : JSON.stringify(words.slice(1)),\n ),\n exceptionEligible: eligible,\n });\n }\n if (operation === \"select-string\") {\n const path = words.findIndex((word) => /^-(?:literalpath|path)$/i.test(word));\n const targets: string[] = [];\n for (let offset = path + 1; path >= 0 && offset < words.length; offset += 1) {\n const word = words[offset];\n if (word === undefined || word.startsWith(\"-\")) break;\n targets.push(word);\n }\n const eligible = targets.length === 1 && !targets.some((word) => /[,$%`<>]/.test(word));\n return authorize({\n ...denyExploration(\"Select-String\", eligible ? (targets[0] ?? \".\") : JSON.stringify(targets)),\n exceptionEligible: eligible,\n });\n }\n if (\n !operation ||\n [\n \"echo\",\n \"printf\",\n \"write-output\",\n \"cat\",\n \"get-content\",\n \"pnpm\",\n \"npm\",\n \"npx\",\n \"corepack\",\n \"node\",\n \"nodejs\",\n \"python\",\n \"python3\",\n \"uv\",\n \"git\",\n \"pwd\",\n \"get-location\",\n \"ls\",\n \"dir\",\n \"sort\",\n ].includes(operation)\n ) {\n return undefined;\n }\n return outsideBoundary();\n}\n\nfunction outsideBoundary(): GraphHookDecision {\n return {\n decision: \"allow\",\n state: \"outside-boundary\",\n message:\n \"Search inside scripts, aliases or continuing input is not verified by this pre-tool boundary.\",\n };\n}\n\nfunction shellPipelines(command: string, shell: GraphShell): string[][] | undefined {\n const commands: string[][] = [];\n let words: string[] = [];\n let word = \"\";\n let quote: string | undefined;\n const flushWord = () => {\n if (word.length) words.push(word);\n word = \"\";\n };\n for (let index = 0; index < command.length; index += 1) {\n const character = command[index];\n if (character === undefined) continue;\n const next = command[index + 1];\n const escaped =\n next !== undefined &&\n ((shell === \"posix\" &&\n character === \"\\\\\" &&\n (!quote || (quote === '\"' && ['\"', \"\\\\\", \"$\", \"`\", \"\\n\"].includes(next)))) ||\n (shell === \"powershell\" && character === \"`\" && quote !== \"'\") ||\n (shell === \"cmd\" && character === \"^\" && !quote));\n if (escaped) {\n if (next !== \"\\n\") word += next;\n index += 1;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n else word += character;\n } else if (character === '\"' || character === \"'\") {\n quote = character;\n } else if (character === \"|\" || character === \";\" || character === \"&\" || character === \"\\n\") {\n flushWord();\n if (words.length) commands.push(words);\n words = [];\n } else if (/\\s/.test(character)) {\n flushWord();\n } else {\n word += character;\n }\n }\n if (quote) return undefined;\n flushWord();\n if (words.length) commands.push(words);\n return commands;\n}\n\nfunction denyExploration(operation: string, target: string): GraphHookDecision {\n const domain = /(?:^|[\\\\/])(?:docs?|spec|adr|requirements)(?:[\\\\/]|$)|\\.md$/i.test(target)\n ? \"documents\"\n : \"code\";\n return {\n decision: \"deny\",\n state: \"configured\",\n operation,\n target,\n domain,\n message: `Exploration redirected: ${operation} over ${JSON.stringify(target)} was denied. Use ${domain === \"code\" ? 'CodeGraph for symbols, callers and change impact: node .qfai/tools/graph-cli.mjs code \"<question>\"' : 'Graphify for document concepts and rationale: node .qfai/tools/graph-cli.mjs documents \"<question>\"'}. Prepare the required analysis through the CLI. For AI-decided scoped search, run node .qfai/tools/graph-cli.mjs fallback --attempt-id <observed-UUID> --question \"<unresolved question>\" --reason \"<graph limitation>\". The fallback command attempts the relevant graph before granting a matching search. Human approval is not required for this search.`,\n };\n}\n\nexport function graphFallbackUnavailable(\n decision: GraphHookDecision,\n cause: string,\n recovery: string,\n): GraphHookDecision {\n return {\n ...decision,\n exceptionEligible: false,\n fallbackUnavailable: true,\n message: `Exploration redirected: ${decision.operation ?? \"search\"} was denied. Search fallback unavailable: ${cause} ${recovery} Use node .qfai/tools/graph-cli.mjs ${decision.domain === \"documents\" ? \"documents\" : \"code\"} \"<question>\" for graph exploration.`,\n };\n}\n\nexport function decodeGraphHookEvent(input: unknown): GraphHookEvent | undefined {\n if (!object(input)) return undefined;\n const snake = [\"tool_name\", \"tool_input\", \"session_id\"].some((key) => key in input);\n const camel = [\"toolName\", \"toolArgs\", \"sessionId\"].some((key) => key in input);\n if (snake && camel) return undefined;\n const tool = input.tool_name ?? input.toolName;\n let payload: unknown = input.tool_input ?? input.toolArgs;\n if (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch {\n return undefined;\n }\n }\n if (typeof tool !== \"string\" || !tool.trim() || !object(payload)) return undefined;\n const session = input.session_id ?? input.sessionId;\n if (\n (session !== undefined && (typeof session !== \"string\" || !session.trim())) ||\n (input.session_id !== undefined &&\n input.sessionId !== undefined &&\n input.session_id !== input.sessionId)\n )\n return undefined;\n const command = payload.command ?? payload.cmd;\n const target = payload.path ?? payload.includePattern;\n const workdir = payload.workdir;\n const shell = payload.shell;\n if (target !== undefined && (typeof target !== \"string\" || !target.trim())) return undefined;\n if (workdir !== undefined && (typeof workdir !== \"string\" || !workdir.trim())) return undefined;\n if (shell !== undefined && (typeof shell !== \"string\" || !shell.trim())) return undefined;\n if (\n [\"bash\", \"powershell\", \"exec_command\"].includes(tool.toLowerCase()) &&\n typeof command !== \"string\"\n )\n return undefined;\n return {\n tool,\n ...(typeof command === \"string\" ? { command } : {}),\n ...(typeof target === \"string\" ? { path: target } : {}),\n ...(typeof workdir === \"string\" ? { workdir } : {}),\n ...(typeof shell === \"string\" ? { shell } : {}),\n ...(typeof input.cwd === \"string\" ? { cwd: input.cwd } : {}),\n ...(typeof session === \"string\" ? { session } : {}),\n };\n}\n\nexport function failedGraphHook(): GraphHookDecision {\n return {\n decision: \"deny\",\n state: \"failed\",\n message:\n \"Graph protection failed: invalid pre-tool input. Repair hook configuration before direct exploration.\",\n };\n}\n\nexport function enforceGraphExploration(input: unknown, configuration: unknown): GraphHookDecision {\n if (\n !object(configuration) ||\n Object.keys(configuration).length !== 2 ||\n configuration.kind !== \"graph-enforcement\" ||\n configuration.denyExploration !== true\n )\n return failedGraphHook();\n const event = decodeGraphHookEvent(input);\n return event ? classifyGraphExploration(event) : failedGraphHook();\n}\n\nexport function graphHookOutput(\n host: GraphHookHost,\n decision: GraphHookDecision,\n): Record<string, unknown> {\n if (decision.decision === \"allow\") return {};\n return host === \"copilot\"\n ? { permissionDecision: \"deny\", permissionDecisionReason: decision.message }\n : {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: decision.message,\n },\n };\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { rename, unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n classifyGraphExploration,\n graphFallbackUnavailable,\n type GraphHookDecision,\n type GraphHookEvent,\n} from \"./hooks.js\";\nimport { withGraphLock } from \"./locks.js\";\nimport {\n graphStateDirectory,\n graphStateText,\n invalidGraphState,\n writeGraphLocalFile,\n} from \"./localFiles.js\";\nimport {\n fullGraphState,\n readGraphSearchRecords,\n type PendingGraphSearch,\n type GrantedGraphSearch,\n} from \"./permissionRecords.js\";\nimport { queryPreparedGraph } from \"./runner.js\";\nimport { runGraphProcess, type GraphProcess } from \"./process.js\";\nimport { assertGraphStoragePath } from \"./storage.js\";\n\nexport async function classifyStoredGraphExploration(\n root: string,\n event: GraphHookEvent,\n): Promise<GraphHookDecision> {\n const decision = classifyGraphExploration(event);\n if (decision.decision !== \"deny\" || decision.state !== \"configured\") return decision;\n if (decision.exceptionEligible === false)\n return decision.fallbackUnavailable\n ? decision\n : graphFallbackUnavailable(\n decision,\n \"The search target or operation cannot be scoped.\",\n \"Run a single search with one explicit project-relative target, then retry the denied action.\",\n );\n if (!event.cwd || !graphStateText(event.session, 4096))\n return graphFallbackUnavailable(\n decision,\n \"Observed session and worktree are required.\",\n \"Enable session and cwd in the host event, run qfai init, then retry the denied action from this project worktree.\",\n );\n if (path.resolve(event.cwd) !== path.resolve(root))\n return graphFallbackUnavailable(\n decision,\n \"The observed worktree differs from this project worktree.\",\n \"Run the denied action from this project worktree, or run qfai init in the intended worktree before retrying.\",\n );\n if (event.workdir && path.resolve(event.cwd, event.workdir) !== path.resolve(root))\n return graphFallbackUnavailable(\n decision,\n \"The requested workdir differs from this project worktree.\",\n \"Set workdir to this project worktree and retry the denied action.\",\n );\n if (!decision.target || !decision.operation || !decision.domain) return decision;\n const worktree = path.resolve(root);\n const session = event.session;\n return withGraphLock<GraphHookDecision>(root, \"state\", async () => {\n const directory = await graphStateDirectory(root);\n const records = await readGraphSearchRecords(root, directory);\n const classified = classifyGraphExploration(event, (candidate) => {\n if (candidate.decision !== \"deny\" || candidate.exceptionEligible === false) return candidate;\n const grant = records.find(\n (item) =>\n !item.draft &&\n item.record.kind === \"grant\" &&\n item.record.target === candidate.target &&\n item.record.operation === candidate.operation &&\n item.record.domain === candidate.domain &&\n item.record.worktree === worktree &&\n item.record.session === session &&\n Date.now() < item.record.expiresAt,\n );\n return grant?.record.kind === \"grant\"\n ? {\n ...candidate,\n decision: \"allow\",\n message: `AI-decided search fallback: ${grant.record.reason}`,\n }\n : candidate;\n });\n if (\n classified.decision !== \"deny\" ||\n classified.state !== \"configured\" ||\n classified.exceptionEligible === false ||\n !classified.target ||\n !classified.operation ||\n !classified.domain\n )\n return classified;\n const observed = {\n target: classified.target,\n operation: classified.operation,\n domain: classified.domain,\n worktree,\n session,\n };\n if (records.length >= 128) throw fullGraphState();\n const createdAt = Date.now();\n const pending: PendingGraphSearch = {\n ...observed,\n id: randomUUID(),\n kind: \"pending\",\n createdAt,\n expiresAt: createdAt + 600000,\n };\n await writeGraphLocalFile(path.join(directory, `${pending.id}.pending.json`), pending);\n return { ...classified, message: `${classified.message} Observed attempt: ${pending.id}.` };\n });\n}\n\nexport async function requestStoredGraphFallback(\n root: string,\n attemptId: string,\n question: string,\n reason: string,\n run: GraphProcess = runGraphProcess,\n) {\n const observed = await withGraphLock(root, \"state\", async () => {\n const directory = await graphStateDirectory(root);\n const records = await readGraphSearchRecords(root, directory);\n const pending = records.find(\n (item) => item.record.kind === \"pending\" && item.record.id === attemptId,\n );\n if (!pending || pending.record.kind !== \"pending\") throw invalidGraphState();\n return pending.record;\n });\n const graph = await queryPreparedGraph(root, { domain: observed.domain, question }, run);\n const publication = await withGraphLock(root, \"state\", async () => {\n const directory = await graphStateDirectory(root);\n const records = await readGraphSearchRecords(root, directory);\n const pending = records.find(\n (item) => item.record.kind === \"pending\" && item.record.id === attemptId,\n );\n if (!pending || JSON.stringify(pending.record) !== JSON.stringify(observed))\n throw invalidGraphState();\n if (records.length >= 128) throw fullGraphState();\n const createdAt = Date.now();\n const grant: GrantedGraphSearch = {\n ...observed,\n kind: \"grant\",\n reason,\n createdAt,\n expiresAt: createdAt + 60000,\n };\n const draft = path.join(directory, `${grant.id}.draft.json`);\n await writeGraphLocalFile(draft, grant);\n await unlink(pending.file);\n return { directory, draft, grant };\n });\n await assertGraphStoragePath(root, publication.directory);\n if (Date.now() >= publication.grant.expiresAt) throw invalidGraphState();\n await rename(\n publication.draft,\n path.join(publication.directory, `${publication.grant.id}.grant.json`),\n );\n const { target, operation, worktree, session, expiresAt } = publication.grant;\n return {\n status: \"ready\",\n permitted: true,\n domain: observed.domain,\n scope: { target, operation, worktree, session, reason, expiresAt },\n graph,\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { hasErrnoCode } from \"../fs/errno.js\";\nimport { graphEnvironmentKey } from \"./layout.js\";\nimport {\n graphStateDirectory,\n GraphLocalStateError,\n GRAPH_UUID,\n readGraphLocalFile,\n writeGraphLocalFile,\n} from \"./localFiles.js\";\n\nexport async function withGraphLock<T>(\n root: string,\n kind: \"analysis\" | \"state\",\n action: () => Promise<T>,\n): Promise<T> {\n const directory = await graphStateDirectory(root);\n const file = path.join(directory, `${kind}.lock`);\n const owner = {\n kind: \"graph-lock\",\n pid: process.pid,\n createdAt: Date.now(),\n token: randomUUID(),\n };\n try {\n await writeGraphLocalFile(file, owner);\n } catch (cause: unknown) {\n if (!hasErrnoCode(cause) || cause.code !== \"EEXIST\") throw cause;\n const text = await readGraphLocalFile(file);\n let active = false;\n try {\n const existing: unknown = text === undefined ? undefined : JSON.parse(text);\n if (typeof existing !== \"object\" || existing === null || Array.isArray(existing))\n throw new Error(\"Invalid graph lock metadata.\", { cause });\n const value = existing as Record<string, unknown>;\n if (\n Object.keys(value).length !== 4 ||\n value.kind !== \"graph-lock\" ||\n typeof value.pid !== \"number\" ||\n !Number.isSafeInteger(value.pid) ||\n value.pid <= 0 ||\n typeof value.createdAt !== \"number\" ||\n !Number.isSafeInteger(value.createdAt) ||\n value.createdAt < 0 ||\n typeof value.token !== \"string\" ||\n !GRAPH_UUID.test(value.token)\n )\n throw new Error(\"Invalid graph lock metadata.\", { cause });\n try {\n process.kill(value.pid, 0);\n active = true;\n } catch (liveness: unknown) {\n if (!hasErrnoCode(liveness) || liveness.code !== \"ESRCH\") active = true;\n }\n } catch {\n // Invalid metadata is retained for manual recovery.\n }\n throw new GraphLocalStateError(\n `Project graph ${kind} lock ${active ? \"is contended\" : \"requires manual recovery\"}.`,\n active\n ? `Retry after the active worktree ${kind} operation finishes; retain its lock.`\n : `Retain and inspect .qfai/tools/state/${graphEnvironmentKey()}/${kind}.lock; remove only a confirmed abandoned worktree lock before retrying.`,\n { cause },\n );\n }\n try {\n return await action();\n } finally {\n await releaseGraphLock(file, JSON.stringify(owner));\n }\n}\n\nasync function releaseGraphLock(file: string, owner: string): Promise<void> {\n const text = await readGraphLocalFile(file);\n if (text !== owner)\n throw new GraphLocalStateError(\n \"Project graph lock ownership changed.\",\n \"Retain the lock and repair the worktree graph state before retrying.\",\n );\n await unlink(file);\n}\n","import path from \"node:path\";\n\nexport const GRAPH_VERSIONS = { codegraph: \"1.6.2\", graphify: \"0.9.86\" } as const;\n\nexport interface GraphExecutionEnvironment {\n platform: string;\n architecture: string;\n}\n\nexport function graphExecutionEnvironment(): GraphExecutionEnvironment {\n return { platform: process.platform, architecture: process.arch };\n}\n\nexport function graphEnvironmentKey(\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n): string {\n if (!/^[a-z0-9]+$/i.test(environment.platform) || !/^[a-z0-9]+$/i.test(environment.architecture))\n throw new Error(\"Unsupported graph execution environment.\");\n return `${environment.platform}-${environment.architecture}`;\n}\n\nexport function graphRuntimePaths(\n root: string,\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n) {\n return graphRuntimeFiles(\n path.join(root, \".qfai\", \"tools\", \"runtimes\", graphEnvironmentKey(environment)),\n environment,\n );\n}\n\n/** The runtime files inside one runtime directory, the installed one or a staged copy of it. */\nexport function graphRuntimeFiles(\n directory: string,\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n) {\n return {\n directory,\n codegraph: path.join(\n directory,\n \"codegraph\",\n \"node_modules\",\n \"@colbymchenry\",\n \"codegraph\",\n \"npm-shim.js\",\n ),\n codegraphSdk: path.join(\n directory,\n \"codegraph\",\n \"node_modules\",\n \"@colbymchenry\",\n \"codegraph\",\n \"npm-sdk.js\",\n ),\n codegraphNode: path.join(\n directory,\n \"codegraph\",\n \"node_modules\",\n \"@colbymchenry\",\n `codegraph-${environment.platform}-${environment.architecture}`,\n environment.platform === \"win32\" ? \"node.exe\" : \"node\",\n ),\n python:\n environment.platform === \"win32\"\n ? path.join(directory, \"graphify\", \"Scripts\", \"python.exe\")\n : path.join(directory, \"graphify\", \"bin\", \"python\"),\n };\n}\n\nexport function graphAnalysisRoot(\n root: string,\n engine: \"codegraph\" | \"graphify\" | \"graphify-code\",\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n): string {\n return path.join(root, \".qfai\", \"tools\", \"analysis\", graphEnvironmentKey(environment), engine);\n}\n","import { lstat, mkdir, open } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../fs/errno.js\";\nimport { readPinnedRegularFileBytes } from \"../init/fsGuards.js\";\nimport { graphEnvironmentKey } from \"./layout.js\";\nimport { assertGraphStoragePath } from \"./storage.js\";\n\nexport const GRAPH_STATE_BYTES = 32768;\nexport const GRAPH_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\nexport class GraphLocalStateError extends Error {\n constructor(\n message: string,\n readonly recovery: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n }\n}\n\nexport async function graphStateDirectory(root: string): Promise<string> {\n const directory = path.join(root, \".qfai\", \"tools\", \"state\", graphEnvironmentKey());\n await assertGraphStoragePath(root, directory);\n await mkdir(directory, { recursive: true });\n await assertGraphStoragePath(root, directory);\n return directory;\n}\n\nexport function invalidGraphState(): GraphLocalStateError {\n return new GraphLocalStateError(\n \"Project graph permission state is invalid.\",\n \"Retain the local state and repair .qfai/tools/state before retrying the graph CLI or hook.\",\n );\n}\n\nexport function graphStateText(value: unknown, maximum: number): value is string {\n return (\n typeof value === \"string\" &&\n value.trim().length > 0 &&\n value.length <= maximum &&\n !value.includes(\"\\0\")\n );\n}\n\nexport async function readGraphLocalFile(file: string): Promise<string | undefined> {\n try {\n const before = await lstat(file);\n if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1)\n throw invalidGraphState();\n const pinned = await readPinnedRegularFileBytes(file, GRAPH_STATE_BYTES);\n const after = await lstat(file);\n if (\n !pinned ||\n before.dev !== pinned.dev ||\n before.ino !== pinned.ino ||\n after.dev !== pinned.dev ||\n after.ino !== pinned.ino ||\n !after.isFile() ||\n after.isSymbolicLink() ||\n after.nlink !== 1\n )\n throw invalidGraphState();\n return pinned.content.toString(\"utf8\");\n } catch (cause: unknown) {\n if (isEnoent(cause)) return undefined;\n throw cause;\n }\n}\n\nexport async function writeGraphLocalFile(file: string, value: unknown): Promise<void> {\n const text = JSON.stringify(value);\n if (Buffer.byteLength(text) > GRAPH_STATE_BYTES) throw invalidGraphState();\n const handle = await open(file, \"wx\", 0o600);\n try {\n await handle.writeFile(text, \"utf8\");\n } finally {\n await handle.close();\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { lstat, mkdir, readdir, rename, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../fs/errno.js\";\n\nexport async function assertGraphStoragePath(root: string, directory: string): Promise<void> {\n const relative = path.relative(root, directory);\n const parts = relative.split(path.sep);\n if (\n path.isAbsolute(relative) ||\n parts[0] !== \".qfai\" ||\n parts[1] !== \"tools\" ||\n parts.includes(\"..\")\n ) {\n throw new Error(\"Graph storage must stay inside project-local .qfai/tools.\");\n }\n for (let depth = 1; depth <= parts.length; depth += 1) {\n try {\n const stats = await lstat(path.join(root, ...parts.slice(0, depth)));\n if (stats.isSymbolicLink() || !stats.isDirectory())\n throw new Error(\n \"Graph storage has an unsafe path component; retain it and repair the project configuration.\",\n );\n } catch (cause: unknown) {\n if (isEnoent(cause)) return;\n throw cause;\n }\n }\n}\n\nexport async function assertIndependentAnalysis(directory: string): Promise<void> {\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const child = path.join(directory, entry.name);\n const stats = await lstat(child);\n if (stats.isSymbolicLink() || (stats.isFile() && stats.nlink > 1)) {\n throw new Error(\n \"Graph analysis contains a shared file or unsafe link; retain it and prepare an independent copy.\",\n );\n }\n if (stats.isDirectory()) await assertIndependentAnalysis(child);\n }\n}\n\nexport async function replaceGraphDirectory(\n staged: string,\n current: string,\n root: string,\n): Promise<void> {\n await assertGraphStoragePath(root, staged);\n await assertGraphStoragePath(root, current);\n const parent = path.dirname(current);\n await mkdir(parent, { recursive: true });\n const previous = path.join(parent, `.previous-${randomUUID()}`);\n let retained = false;\n try {\n await rename(current, previous);\n retained = true;\n } catch (cause: unknown) {\n if (!isEnoent(cause)) throw cause;\n }\n try {\n await rename(staged, current);\n } catch (cause: unknown) {\n if (retained) await rename(previous, current);\n throw cause;\n }\n if (retained) await rm(previous, { recursive: true, force: true });\n}\n","import { opendir, unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n GRAPH_UUID,\n graphStateText,\n invalidGraphState,\n readGraphLocalFile,\n GraphLocalStateError,\n} from \"./localFiles.js\";\n\ninterface ObservedScope {\n id: string;\n domain: \"code\" | \"documents\";\n target: string;\n operation: string;\n worktree: string;\n session: string;\n createdAt: number;\n expiresAt: number;\n}\n\nexport type PendingGraphSearch = ObservedScope & { kind: \"pending\" };\nexport type GrantedGraphSearch = ObservedScope & { kind: \"grant\"; reason: string };\nexport type GraphSearchRecord = PendingGraphSearch | GrantedGraphSearch;\nexport interface StoredGraphRecord {\n file: string;\n record: GraphSearchRecord;\n draft: boolean;\n}\n\nexport async function readGraphSearchRecords(\n root: string,\n directory: string,\n): Promise<StoredGraphRecord[]> {\n const records: StoredGraphRecord[] = [];\n const entries = await opendir(directory);\n for await (const entry of entries) {\n if (entry.name === \"state.lock\" || entry.name === \"analysis.lock\") continue;\n if (records.length >= 128) throw fullGraphState();\n const match = /^(.+)\\.(pending|grant|draft)\\.json$/.exec(entry.name);\n if (!match || !GRAPH_UUID.test(match[1] ?? \"\")) throw invalidGraphState();\n const file = path.join(directory, entry.name);\n const text = await readGraphLocalFile(file);\n if (text === undefined) throw invalidGraphState();\n let input: unknown;\n try {\n input = JSON.parse(text);\n } catch {\n throw invalidGraphState();\n }\n const record = parseGraphSearchRecord(input, root);\n if (\n !record ||\n record.id !== match[1] ||\n (match[2] === \"pending\" ? record.kind !== \"pending\" : record.kind !== \"grant\")\n )\n throw invalidGraphState();\n records.push({ file, record, draft: match[2] === \"draft\" });\n }\n const current: StoredGraphRecord[] = [];\n for (const item of records) {\n if (Date.now() >= item.record.expiresAt) await unlink(item.file);\n else current.push(item);\n }\n return current;\n}\n\nexport function fullGraphState(): GraphLocalStateError {\n return new GraphLocalStateError(\n \"Project graph permission state is full.\",\n \"Retry after pending attempts or search grants expire; retain valid worktree state.\",\n );\n}\n\nfunction parseGraphSearchRecord(input: unknown, root: string): GraphSearchRecord | undefined {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) return undefined;\n const value = input as Record<string, unknown>;\n const fields = [\n \"id\",\n \"kind\",\n \"domain\",\n \"target\",\n \"operation\",\n \"worktree\",\n \"session\",\n \"createdAt\",\n \"expiresAt\",\n ];\n if (value.kind === \"grant\") fields.push(\"reason\");\n if (\n Object.keys(value).length !== fields.length ||\n fields.some((field) => !Object.hasOwn(value, field)) ||\n typeof value.id !== \"string\" ||\n !GRAPH_UUID.test(value.id) ||\n (value.kind !== \"pending\" && value.kind !== \"grant\") ||\n (value.domain !== \"code\" && value.domain !== \"documents\") ||\n !graphStateText(value.target, 4096) ||\n !graphStateText(value.operation, 128) ||\n !graphStateText(value.worktree, 4096) ||\n value.worktree !== path.resolve(root) ||\n !graphStateText(value.session, 4096) ||\n typeof value.createdAt !== \"number\" ||\n typeof value.expiresAt !== \"number\" ||\n !Number.isSafeInteger(value.createdAt) ||\n value.createdAt < 0 ||\n value.createdAt > Date.now() ||\n !Number.isSafeInteger(value.expiresAt) ||\n value.expiresAt !== value.createdAt + (value.kind === \"pending\" ? 600000 : 60000)\n )\n return undefined;\n const scope: ObservedScope = {\n id: value.id,\n domain: value.domain,\n target: value.target,\n operation: value.operation,\n worktree: value.worktree,\n session: value.session,\n createdAt: value.createdAt,\n expiresAt: value.expiresAt,\n };\n if (value.kind === \"pending\") return { ...scope, kind: \"pending\" };\n return graphStateText(value.reason, 2048)\n ? { ...scope, kind: \"grant\", reason: value.reason }\n : undefined;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\nimport { codegraphEnvironment, type GraphProcess } from \"./process.js\";\nimport {\n publishCompletedCodeAnalysis,\n restoreCompletedCodeAnalysis,\n type GraphReuseEnvironment,\n} from \"./reuse.js\";\nimport { graphAnalysisRoot, graphRuntimePaths } from \"./layout.js\";\nimport {\n inspectCodeAnalysisAt,\n inspectCurrentCodeAnalysis,\n mirrorGraphCorpus,\n} from \"./analysis.js\";\nimport {\n assertGraphStoragePath,\n assertIndependentAnalysis,\n replaceGraphDirectory,\n} from \"./storage.js\";\n\nexport interface CodePreparation {\n status: \"prepared\" | \"failed\";\n source?: \"generated\" | \"restored\" | \"current\";\n recovery?: string;\n reuse?: \"published\" | \"unavailable\";\n}\n\nexport async function prepareCodeAnalysis(\n root: string,\n run: GraphProcess,\n environment?: GraphReuseEnvironment,\n): Promise<CodePreparation> {\n const current = graphAnalysisRoot(root, \"codegraph\");\n const staged = path.join(path.dirname(current), `.preparing-codegraph-${randomUUID()}`);\n let created = false;\n try {\n if (await inspectCurrentCodeAnalysis(root, run))\n return { status: \"prepared\", source: \"current\" };\n if ((await restoreCompletedCodeAnalysis(root, run, environment)) === \"restored\")\n return { status: \"prepared\", source: \"restored\" };\n await assertGraphStoragePath(root, staged);\n await mkdir(staged, { recursive: true });\n created = true;\n await mirrorGraphCorpus(root, staged);\n const runtime = graphRuntimePaths(root);\n const result = await run(\n runtime.codegraphNode,\n [\n \"--liftoff-only\",\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"codegraph-native.mjs\"),\n runtime.codegraphSdk,\n staged,\n ],\n { cwd: staged, env: codegraphEnvironment(root) },\n );\n if (result.exitCode !== 0 || !(await inspectCodeAnalysisAt(root, staged, run))) return failed();\n await assertIndependentAnalysis(staged);\n await replaceGraphDirectory(staged, current, root);\n return {\n status: \"prepared\",\n source: \"generated\",\n reuse: await publishCompletedCodeAnalysis(root, run, environment),\n };\n } catch {\n return failed();\n } finally {\n if (created) await rm(staged, { recursive: true, force: true });\n }\n}\n\nfunction failed(): CodePreparation {\n return {\n status: \"failed\",\n recovery: \"Repair the local CodeGraph runtime and prepare independent analysis.\",\n };\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * `assets/init` candidates for a module sitting at `baseDir`.\n *\n * Three depths, because this module is loaded from three: `src/shared/` and\n * `dist/shared/` are two levels below the package root, and `dist/index.mjs` —\n * the package's public entry, which `tsup` produces with `splitting: false`, so\n * this code is bundled into it — is one. Without the one-level candidate every\n * caller that reaches `validateProject` through the library entry rather than\n * the CLI got `Template assets not found` before any validator ran.\n *\n * **Ordered nearest-first**, because the shallower depths are not the\n * package's own directory once QFAI is installed: from\n * `<project>/node_modules/qfai/dist`, the three-level candidate is\n * `<project>/assets/init`. A consuming project with an unrelated `assets/init`\n * would otherwise be picked as the template root, and a wrong-but-present\n * directory is worse than a missing one — `canonicalSkillIds` would read an\n * empty shipped roster and `QFAI-LINK-001` would pass every broken wrapper\n * without looking at it.\n *\n * Exported for the test that pins those depths; `getInitAssetsDir` is the API.\n */\nexport function initAssetsCandidates(baseDir: string): string[] {\n return [\n path.resolve(baseDir, \"../assets/init\"),\n path.resolve(baseDir, \"../../assets/init\"),\n path.resolve(baseDir, \"../../../assets/init\"),\n ];\n}\n\n/**\n * Files a real `assets/init` tree always has.\n *\n * Existence alone does not identify the directory — the name is generic enough\n * that a consuming project can have one. Both halves of the tree `runInit`\n * copies are required, so an unrelated `assets/init` is rejected and the search\n * continues instead of silently rooting the whole template system somewhere\n * arbitrary.\n */\nconst INIT_ASSETS_SENTINELS = [\n path.join(\".qfai\", \"assistant\"),\n path.join(\"root\", \"qfai.config.yaml\"),\n];\n\nfunction isInitAssetsDir(candidate: string): boolean {\n return INIT_ASSETS_SENTINELS.every((sentinel) => existsSync(path.join(candidate, sentinel)));\n}\n\nexport function getInitAssetsDir(): string {\n const base = import.meta.url;\n const basePath = base.startsWith(\"file:\") ? fileURLToPath(base) : base;\n const baseDir = path.dirname(basePath);\n const candidates = initAssetsCandidates(baseDir);\n\n for (const candidate of candidates) {\n if (isInitAssetsDir(candidate)) {\n return candidate;\n }\n }\n\n throw new Error(\n [\n \"Template assets for init were not found.\",\n \"Checked paths:\",\n ...candidates.map((candidate) => `- ${candidate}`),\n ].join(\"\\n\"),\n );\n}\n","import { execFile } from \"node:child_process\";\nimport { access, lstat, realpath } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport {\n graphEnvironmentKey,\n graphExecutionEnvironment,\n type GraphExecutionEnvironment,\n} from \"./layout.js\";\nimport { assertGraphStoragePath } from \"./storage.js\";\nimport { isEnoent } from \"../fs/errno.js\";\n\nconst execute = promisify(execFile);\nexport const GRAPH_PYTHON_FLAGS = [\"-I\", \"-X\", \"utf8\"] as const;\n\nexport interface GraphProcessResult {\n exitCode: number;\n stdout: string;\n /** Set only for a failed process run with captureStderr; installer output can carry credentials. */\n stderr?: string;\n /** Why a process that did not exit on its own ended: it could not start, or it was stopped. */\n failure?: string;\n}\n\nexport type GraphProcess = (\n command: string,\n args: readonly string[],\n options: {\n cwd: string;\n env?: NodeJS.ProcessEnv;\n timeoutMs?: number;\n maxBufferBytes?: number;\n /** Keep a failed process's stderr in the result. Only version checks ask for it. */\n captureStderr?: boolean;\n },\n) => Promise<GraphProcessResult>;\n\nfunction privateEngineEnvironment(\n root: string,\n engine: \"codegraph\" | \"graphify\",\n execution: GraphExecutionEnvironment,\n): NodeJS.ProcessEnv {\n const environment: NodeJS.ProcessEnv = {};\n const allowed: Record<string, string> = {\n path: \"PATH\",\n systemroot: \"SystemRoot\",\n windir: \"WINDIR\",\n comspec: \"ComSpec\",\n pathext: \"PATHEXT\",\n tmp: \"TMP\",\n temp: \"TEMP\",\n lang: \"LANG\",\n lc_all: \"LC_ALL\",\n };\n for (const [name, value] of Object.entries(process.env)) {\n const canonical = allowed[name.toLowerCase()];\n if (canonical) environment[canonical] = value;\n }\n const home = path.join(root, \".qfai\", \"tools\", \"home\", graphEnvironmentKey(execution), engine);\n return {\n ...environment,\n HOME: home,\n USERPROFILE: home,\n APPDATA: path.join(home, \"AppData\", \"Roaming\"),\n LOCALAPPDATA: path.join(home, \"AppData\", \"Local\"),\n XDG_CONFIG_HOME: path.join(home, \".config\"),\n XDG_CACHE_HOME: path.join(home, \".cache\"),\n XDG_DATA_HOME: path.join(home, \".local\", \"share\"),\n XDG_STATE_HOME: path.join(home, \".local\", \"state\"),\n };\n}\n\nexport function graphifyEnvironment(\n root: string,\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n): NodeJS.ProcessEnv {\n return {\n ...privateEngineEnvironment(root, \"graphify\", environment),\n PYTHONUTF8: \"1\",\n PYTHONIOENCODING: \"utf-8\",\n GRAPHIFY_QUERY_LOG_DISABLE: \"1\",\n GRAPHIFY_OUT: \"graphify-out\",\n GRAPHIFY_ALLOW_LOCAL_PROVIDERS: \"0\",\n GRAPHIFY_NO_AUTO_REFRESH: \"1\",\n };\n}\n\nexport function codegraphEnvironment(\n root: string,\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n): NodeJS.ProcessEnv {\n const privateEnvironment = privateEngineEnvironment(root, \"codegraph\", environment);\n const home = privateEnvironment.HOME ?? \"\";\n return {\n ...privateEnvironment,\n CODEGRAPH_INSTALL_DIR: path.join(home, \".codegraph\"),\n CODEGRAPH_NO_DOWNLOAD: \"1\",\n CODEGRAPH_NO_UPDATE_CHECK: \"1\",\n CODEGRAPH_TELEMETRY: \"0\",\n CODEGRAPH_DIR: \".codegraph\",\n };\n}\n\nexport function graphifyCorpusEnvironment(root: string, analysis: string): NodeJS.ProcessEnv {\n return {\n ...graphifyEnvironment(root),\n GRAPHIFY_OUT: path.toNamespacedPath(path.join(analysis, \"graphify-out\")),\n };\n}\n\nexport async function graphifyConfigurationSafe(root: string): Promise<boolean> {\n const home = graphifyEnvironment(root).HOME;\n if (!home) return false;\n try {\n const configuration = path.join(home, \".graphify\");\n await assertGraphStoragePath(root, configuration);\n await lstat(path.join(configuration, \"providers.json\"));\n return false;\n } catch (cause: unknown) {\n return isEnoent(cause);\n }\n}\n\nexport const runGraphProcess: GraphProcess = async (command, args, options) => {\n try {\n const result = await execute(command, [...args], {\n cwd: options.cwd,\n ...(options.env ? { env: options.env } : {}),\n windowsHide: true,\n timeout: options.timeoutMs ?? 120_000,\n maxBuffer: options.maxBufferBytes ?? 4 * 1024 * 1024,\n });\n return { exitCode: 0, stdout: result.stdout };\n } catch (cause: unknown) {\n if (!(cause instanceof Error) || !(\"code\" in cause)) throw cause;\n // Installation and backend stderr can contain credentials. Callers report the step instead;\n // the preparation names the command a failed download can be rerun with by hand.\n const signal = \"signal\" in cause && typeof cause.signal === \"string\" ? cause.signal : undefined;\n const failure = signal\n ? `was stopped (${signal})`\n : typeof cause.code === \"string\"\n ? `could not start (${cause.code})`\n : undefined;\n return {\n exitCode: typeof cause.code === \"number\" ? cause.code : 1,\n stdout: \"\",\n ...(failure ? { failure } : {}),\n ...(options.captureStderr && \"stderr\" in cause && typeof cause.stderr === \"string\"\n ? { stderr: cause.stderr }\n : {}),\n };\n }\n};\n\nexport async function npmCommand(): Promise<{ command: string; prefix: string[] }> {\n const node = await realpath(process.execPath);\n const candidates = [\n path.join(path.dirname(node), \"node_modules\", \"npm\", \"bin\", \"npm-cli.js\"),\n path.resolve(path.dirname(node), \"..\", \"lib\", \"node_modules\", \"npm\", \"bin\", \"npm-cli.js\"),\n ];\n for (const candidate of candidates) {\n try {\n await access(candidate);\n return { command: process.execPath, prefix: [candidate] };\n } catch (cause: unknown) {\n if (!(cause instanceof Error) || !(\"code\" in cause) || cause.code !== \"ENOENT\") throw cause;\n }\n }\n // POSIX npm launchers are executable scripts. Windows uses the JS entry above.\n return { command: \"npm\", prefix: [] };\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n cp,\n lstat,\n mkdir,\n readFile,\n readdir,\n realpath,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { isEnoent } from \"../fs/errno.js\";\nimport {\n GRAPH_VERSIONS,\n graphAnalysisRoot,\n graphRuntimePaths,\n graphEnvironmentKey,\n} from \"./layout.js\";\nimport {\n excludedGraphInput,\n inspectCodeAnalysisAt,\n nativeCodeAnalysisCurrent,\n} from \"./analysis.js\";\nimport {\n assertGraphStoragePath,\n assertIndependentAnalysis,\n replaceGraphDirectory,\n} from \"./storage.js\";\nimport { codegraphEnvironment, type GraphProcess } from \"./process.js\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\n\nfunction verifiedNativeRelease(output: string): boolean {\n const release = /^v(\\d+\\.\\d+\\.\\d+)$/.exec(output.trim());\n return release?.[1] === \"24.16.0\";\n}\n\nexport interface GraphReuseEnvironment {\n platform: string;\n architecture: string;\n machine: string;\n}\n\nexport function graphReuseEnvironment(): GraphReuseEnvironment {\n return { platform: process.platform, architecture: process.arch, machine: os.hostname() };\n}\n\nexport async function restoreCompletedCodeAnalysis(\n root: string,\n run: GraphProcess,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<\"restored\" | \"cold\"> {\n // Other native bundle combinations use generation until independent-copy proof exists.\n if (environment.platform !== \"win32\" || environment.architecture !== \"x64\") return \"cold\";\n const nativeRuntime = await run(graphRuntimePaths(root).codegraphNode, [\"--version\"], {\n cwd: root,\n env: codegraphEnvironment(root),\n });\n if (nativeRuntime.exitCode !== 0 || !verifiedNativeRelease(nativeRuntime.stdout)) return \"cold\";\n const location = await completedAnalysisCache(root, \"codegraph\", run, environment);\n if (!location) return \"cold\";\n let candidates;\n try {\n candidates = await readdir(location.directory, { withFileTypes: true });\n } catch (cause: unknown) {\n if (isEnoent(cause)) return \"cold\";\n throw cause;\n }\n for (const entry of candidates) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name.startsWith(\".\")) continue;\n const candidate = path.join(location.directory, entry.name);\n if (!(await cacheDirectorySafe(location.repository, candidate))) continue;\n const metadata = await readSnapshotMetadata(candidate);\n if (\n !metadata ||\n Object.keys(metadata).some(\n (key) =>\n ![\"layout\", \"corpusPolicy\", \"repository\", \"engineVersion\", \"environment\"].includes(key),\n ) ||\n metadata.layout !== 1 ||\n metadata.corpusPolicy !== 1 ||\n metadata.repository !== location.repository ||\n metadata.engineVersion !== GRAPH_VERSIONS.codegraph ||\n !sameEnvironment(metadata.environment, environment)\n )\n continue;\n if (!(await safeCompletedCorpus(path.join(candidate, \"analysis\")))) continue;\n if (!(await safeCodegraphInputs(root, path.join(candidate, \"analysis\"), run))) continue;\n const current = graphAnalysisRoot(root, \"codegraph\");\n const staged = path.join(path.dirname(current), `.restoring-codegraph-${randomUUID()}`);\n await assertGraphStoragePath(root, staged);\n try {\n const cached = path.join(candidate, \"analysis\");\n await assertIndependentAnalysis(cached);\n await mkdir(path.dirname(staged), { recursive: true });\n await cp(cached, staged, { recursive: true, dereference: false });\n await assertIndependentAnalysis(staged);\n if (!(await inspectCodeAnalysisAt(root, staged, run))) continue;\n await replaceGraphDirectory(staged, current, root);\n return \"restored\";\n } finally {\n await rm(staged, { recursive: true, force: true });\n }\n }\n return \"cold\";\n}\n\nexport async function completedAnalysisCache(\n root: string,\n engine: \"codegraph\" | \"graphify\" | \"graphify-code\",\n run: GraphProcess,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<{ repository: string; directory: string } | undefined> {\n const git = await run(\"git\", [\"rev-parse\", \"--path-format=absolute\", \"--git-common-dir\"], {\n cwd: root,\n });\n if (git.exitCode !== 0 || !path.isAbsolute(git.stdout.trim())) return undefined;\n const repository = await realpath(git.stdout.trim());\n return {\n repository,\n directory: path.join(repository, \"qfai-graph-cache\", graphEnvironmentKey(environment), engine),\n };\n}\n\nexport async function publishCompletedCodeAnalysis(\n root: string,\n run: GraphProcess,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<\"published\" | \"unavailable\"> {\n let staged: string | undefined;\n try {\n if (environment.platform !== \"win32\" || environment.architecture !== \"x64\")\n return \"unavailable\";\n const native = await run(graphRuntimePaths(root).codegraphNode, [\"--version\"], {\n cwd: root,\n env: codegraphEnvironment(root),\n });\n if (native.exitCode !== 0 || !verifiedNativeRelease(native.stdout)) return \"unavailable\";\n const cache = await completedAnalysisCache(root, \"codegraph\", run, environment);\n if (!cache) return \"unavailable\";\n await ensureCacheDirectory(cache.repository, cache.directory);\n const analysis = graphAnalysisRoot(root, \"codegraph\");\n if (!(await safeCompletedCorpus(analysis)) || !(await safeCodegraphInputs(root, analysis, run)))\n return \"unavailable\";\n const identity = randomUUID();\n staged = path.join(cache.directory, `.publishing-${identity}`);\n await mkdir(staged);\n await cp(analysis, path.join(staged, \"analysis\"), { recursive: true, dereference: false });\n await assertIndependentAnalysis(path.join(staged, \"analysis\"));\n if (\n !(await safeCompletedCorpus(path.join(staged, \"analysis\"))) ||\n !(await safeCodegraphInputs(root, path.join(staged, \"analysis\"), run))\n )\n return \"unavailable\";\n if (!(await nativeCodeAnalysisCurrent(root, path.join(staged, \"analysis\"), run)))\n return \"unavailable\";\n await writeFile(\n path.join(staged, \"completed.json\"),\n JSON.stringify({\n layout: 1,\n corpusPolicy: 1,\n repository: cache.repository,\n engineVersion: GRAPH_VERSIONS.codegraph,\n environment,\n }) + \"\\n\",\n );\n await rename(staged, path.join(cache.directory, identity));\n return \"published\";\n } catch {\n return \"unavailable\";\n } finally {\n if (staged) await rm(staged, { recursive: true, force: true });\n }\n}\n\nexport async function ensureCacheDirectory(repository: string, directory: string): Promise<void> {\n const relative = path.relative(repository, directory);\n const parts = relative.split(path.sep);\n if (path.isAbsolute(relative) || parts.includes(\"..\") || parts[0] !== \"qfai-graph-cache\")\n throw new Error(\"Unsafe completed analysis path.\");\n for (let depth = 1; depth <= parts.length; depth += 1) {\n const component = path.join(repository, ...parts.slice(0, depth));\n let stats;\n try {\n stats = await lstat(component);\n } catch (cause: unknown) {\n if (!isEnoent(cause)) throw cause;\n await mkdir(component);\n stats = await lstat(component);\n }\n if (stats.isSymbolicLink() || !stats.isDirectory())\n throw new Error(\"Unsafe completed analysis path.\");\n }\n}\n\nexport async function cacheDirectorySafe(repository: string, candidate: string): Promise<boolean> {\n const relative = path.relative(repository, candidate);\n const parts = relative.split(path.sep);\n if (path.isAbsolute(relative) || parts.includes(\"..\") || parts[0] !== \"qfai-graph-cache\")\n return false;\n for (let depth = 1; depth <= parts.length; depth += 1) {\n const stats = await lstat(path.join(repository, ...parts.slice(0, depth)));\n if (stats.isSymbolicLink() || !stats.isDirectory()) return false;\n }\n return true;\n}\n\nexport async function readSnapshotMetadata(\n candidate: string,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const stats = await lstat(path.join(candidate, \"completed.json\"));\n if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1) return undefined;\n const metadata: unknown = JSON.parse(\n await readFile(path.join(candidate, \"completed.json\"), \"utf8\"),\n );\n return object(metadata) ? metadata : undefined;\n } catch (cause: unknown) {\n if (isEnoent(cause) || cause instanceof SyntaxError) return undefined;\n throw cause;\n }\n}\n\nexport function sameEnvironment(value: unknown, environment: GraphReuseEnvironment): boolean {\n return (\n object(value) &&\n Object.keys(value).length === 3 &&\n value.platform === environment.platform &&\n value.architecture === environment.architecture &&\n value.machine === environment.machine\n );\n}\n\nexport async function safeCompletedCorpus(\n directory: string,\n relative = \"\",\n engineDirectory = \".codegraph\",\n): Promise<boolean> {\n try {\n for (const entry of await readdir(path.join(directory, ...relative.split(\"/\")), {\n withFileTypes: true,\n })) {\n const next = relative ? `${relative}/${entry.name}` : entry.name;\n const input = next.startsWith(`${engineDirectory}/`)\n ? next.slice(engineDirectory.length + 1)\n : next;\n if (\n (next !== engineDirectory && excludedGraphInput(input)) ||\n /\\.(?:pid|lock)$/i.test(entry.name)\n )\n return false;\n const stats = await lstat(path.join(directory, ...next.split(\"/\")));\n if (stats.isSymbolicLink() || (stats.isFile() && stats.nlink !== 1)) return false;\n if (stats.isDirectory() && !(await safeCompletedCorpus(directory, next, engineDirectory)))\n return false;\n if (!stats.isDirectory() && !stats.isFile()) return false;\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function safeCodegraphInputs(\n root: string,\n analysis: string,\n run: GraphProcess,\n): Promise<boolean> {\n const runtime = graphRuntimePaths(root);\n const result = await run(\n runtime.codegraphNode,\n [\n \"--liftoff-only\",\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"codegraph-native.mjs\"),\n runtime.codegraphSdk,\n analysis,\n \"inventory\",\n ],\n { cwd: analysis, env: codegraphEnvironment(root) },\n );\n if (result.exitCode !== 0) return false;\n try {\n const inventory: unknown = JSON.parse(result.stdout);\n if (!object(inventory) || !Array.isArray(inventory.files)) return false;\n for (const file of inventory.files) {\n if (\n typeof file !== \"string\" ||\n !file ||\n path.posix.isAbsolute(file) ||\n path.win32.isAbsolute(file)\n )\n return false;\n const normalized = file.replaceAll(\"\\\\\", \"/\");\n const parts = normalized.split(\"/\");\n if (\n parts.some((part) => !part || part === \".\" || part === \"..\") ||\n excludedGraphInput(normalized)\n )\n return false;\n const stats = await lstat(path.join(analysis, ...parts));\n if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1) return false;\n }\n return true;\n } catch {\n return false;\n }\n}\n","import path from \"node:path\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\nimport { copyFile, lstat, mkdir, readdir, rm } from \"node:fs/promises\";\nimport { isEnoent } from \"../fs/errno.js\";\nimport { GRAPH_VERSIONS, graphRuntimePaths, graphAnalysisRoot } from \"./layout.js\";\nimport type { GraphProcess } from \"./process.js\";\nimport { codegraphEnvironment } from \"./process.js\";\nimport { assertGraphStoragePath, assertIndependentAnalysis } from \"./storage.js\";\nexport { graphAnalysisRoot } from \"./layout.js\";\n\nexport interface CodeAnalysisCoverage {\n complete: boolean;\n unsupported: string[];\n unreadable: string[];\n unparsed: string[];\n}\n\nexport async function inspectCodeCoverage(\n root: string,\n run: GraphProcess,\n): Promise<CodeAnalysisCoverage> {\n const unknown = { complete: false, unsupported: [], unreadable: [], unparsed: [] };\n const runtime = graphRuntimePaths(root);\n const analysis = graphAnalysisRoot(root, \"codegraph\");\n const result = await run(\n runtime.codegraphNode,\n [\n \"--liftoff-only\",\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"codegraph-native.mjs\"),\n runtime.codegraphSdk,\n analysis,\n \"coverage\",\n ],\n { cwd: analysis, env: codegraphEnvironment(root) },\n );\n if (result.exitCode !== 0) return unknown;\n let value: unknown;\n try {\n value = JSON.parse(result.stdout);\n } catch {\n return unknown;\n }\n if (\n !object(value) ||\n Object.keys(value).length !== 4 ||\n typeof value.complete !== \"boolean\" ||\n !stringArray(value.unsupported) ||\n !stringArray(value.unreadable) ||\n !stringArray(value.unparsed)\n )\n return unknown;\n return {\n complete:\n value.complete &&\n value.unsupported.length === 0 &&\n value.unreadable.length === 0 &&\n value.unparsed.length === 0,\n unsupported: value.unsupported,\n unreadable: value.unreadable,\n unparsed: value.unparsed,\n };\n}\n\nfunction stringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry: unknown) => typeof entry === \"string\");\n}\n\nexport async function inspectCurrentCodeAnalysis(\n root: string,\n run: GraphProcess,\n): Promise<boolean> {\n const analysis = graphAnalysisRoot(root, \"codegraph\");\n return inspectCodeAnalysisAt(root, analysis, run);\n}\n\nexport async function inspectCodeAnalysisAt(\n root: string,\n analysis: string,\n run: GraphProcess,\n): Promise<boolean> {\n await assertGraphStoragePath(root, analysis);\n try {\n if (!(await lstat(path.join(analysis, \".codegraph\", \"codegraph.db\"))).isFile()) return false;\n } catch (cause: unknown) {\n if (isEnoent(cause)) return false;\n throw cause;\n }\n await mirrorGraphCorpus(root, analysis);\n return nativeCodeAnalysisCurrent(root, analysis, run);\n}\n\nexport async function nativeCodeAnalysisCurrent(\n root: string,\n analysis: string,\n run: GraphProcess,\n): Promise<boolean> {\n const result = await run(\n process.execPath,\n [graphRuntimePaths(root).codegraph, \"status\", analysis, \"--json\"],\n { cwd: root, env: codegraphEnvironment(root) },\n );\n if (result.exitCode !== 0) return false;\n let value: unknown;\n try {\n value = JSON.parse(result.stdout);\n } catch (cause: unknown) {\n if (!(cause instanceof SyntaxError)) throw cause;\n return false;\n }\n if (!object(value) || !object(value.index) || !object(value.pendingChanges)) return false;\n const changes = value.pendingChanges;\n return (\n value.initialized === true &&\n value.version === GRAPH_VERSIONS.codegraph &&\n value.projectPath === analysis &&\n value.worktreeMismatch === null &&\n value.index.state === \"complete\" &&\n value.index.pendingRefs === 0 &&\n value.index.reindexRecommended === false &&\n value.index.builtWithVersion === GRAPH_VERSIONS.codegraph &&\n value.index.builtWithExtractionVersion !== undefined &&\n value.index.builtWithExtractionVersion === value.index.currentExtractionVersion &&\n [\"added\", \"modified\", \"removed\"].every((key) => changes[key] === 0)\n );\n}\n\nconst excludedDirectories = new Set([\n \".git\",\n \".codegraph\",\n \".codegraph-wsl\",\n \".graphify\",\n \"graphify-out\",\n \"node_modules\",\n \"dist\",\n \"tmp\",\n \".claude\",\n \".codex\",\n \".vscode\",\n \".ssh\",\n \".aws\",\n \".azure\",\n]);\n\nexport function excludedGraphInput(relative: string): boolean {\n const parts = relative.split(\"/\");\n const name = parts.at(-1) ?? \"\";\n return (\n parts.some((part) => excludedDirectories.has(part.toLowerCase())) ||\n /^\\.qfai\\/(?:tools|report|evidence|review|discussion)(?:\\/|$)/i.test(relative) ||\n relative.toLowerCase() === \".qfai/graph-processing.json\" ||\n /^(?:\\.npmrc|\\.pypirc|\\.netrc|\\.git-credentials)$/i.test(name) ||\n /^\\.env(?:\\.|$)/i.test(name) ||\n /\\.(?:pem|key|p12|pfx|keystore)$/i.test(name) ||\n /^(?:id_(?:rsa|dsa|ecdsa|ed25519)|credentials?(?:\\.|$)|secrets?(?:\\.|$)|\\.mcp\\.json$)/i.test(\n name,\n )\n );\n}\n\nexport async function mirrorGraphCorpus(\n root: string,\n destination: string,\n scope?: readonly string[],\n): Promise<void> {\n await assertGraphStoragePath(root, destination);\n await assertIndependentAnalysis(destination);\n const files = new Set<string>();\n await visit(\"\");\n await removeAbsent(\"\");\n\n async function visit(relative: string): Promise<void> {\n for (const entry of await readdir(path.join(root, ...relative.split(\"/\")), {\n withFileTypes: true,\n })) {\n const next = relative ? `${relative}/${entry.name}` : entry.name;\n if (excludedGraphInput(next) || entry.isSymbolicLink()) continue;\n if (\n scope &&\n !scope.some(\n (item) => item === next || next.startsWith(`${item}/`) || item.startsWith(`${next}/`),\n )\n )\n continue;\n if (entry.isDirectory()) {\n await visit(next);\n } else if (entry.isFile()) {\n const source = path.join(root, ...next.split(\"/\"));\n const stats = await lstat(source);\n if (!stats.isFile() || stats.nlink > 1) continue;\n const target = path.join(destination, ...next.split(\"/\"));\n await mkdir(path.dirname(target), { recursive: true });\n await copyFile(source, target);\n files.add(next);\n }\n }\n }\n\n async function removeAbsent(relative: string): Promise<void> {\n for (const entry of await readdir(path.join(destination, ...relative.split(\"/\")), {\n withFileTypes: true,\n })) {\n const next = relative ? `${relative}/${entry.name}` : entry.name;\n if (entry.name === \".codegraph\" || entry.name === \".git\" || entry.name === \"graphify-out\")\n continue;\n const target = path.join(destination, ...next.split(\"/\"));\n if (entry.isDirectory()) await removeAbsent(next);\n else if (!files.has(next)) await rm(target);\n }\n }\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n publishCompletedDocumentAnalysis,\n restoreCompletedDocumentAnalysis,\n safeDocumentCopy,\n} from \"./documentReuse.js\";\nimport type { GraphReuseEnvironment } from \"./reuse.js\";\nimport { withGraphLock } from \"./locks.js\";\nimport path from \"node:path\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\nimport { isEnoent } from \"../fs/errno.js\";\nimport { mirrorGraphCorpus } from \"./analysis.js\";\nimport { graphAnalysisRoot, graphRuntimePaths, GRAPH_VERSIONS } from \"./layout.js\";\nimport {\n GRAPH_PYTHON_FLAGS,\n graphifyConfigurationSafe,\n graphifyCorpusEnvironment,\n runGraphProcess,\n type GraphProcess,\n} from \"./process.js\";\nimport {\n assertGraphStoragePath,\n assertIndependentAnalysis,\n replaceGraphDirectory,\n} from \"./storage.js\";\n\nexport interface DocumentPreparation {\n status: \"prepared\" | \"not-ready\" | \"failed\";\n source?: \"current\" | \"restored\" | \"generated\";\n reuse?: \"published\" | \"unavailable\";\n recovery?: string;\n}\n\nexport interface DocumentScopeStatus {\n current: boolean;\n unsupported: string[];\n unreadable: string[];\n}\n\ninterface GraphProcessing {\n readonly backend: \"ollama\" | \"openai\";\n readonly model: string;\n readonly endpoint?: string;\n readonly scope?: string[];\n readonly credentialEnv?: string;\n}\n\nfunction notCurrent(): DocumentScopeStatus {\n return { current: false, unsupported: [], unreadable: [] };\n}\n\nexport interface ExternalProcessingRequest {\n readonly destination: string;\n readonly scope: readonly string[];\n readonly backend: string;\n readonly model: string;\n readonly worktree: string;\n}\n\nexport type ApproveExternalProcessing = (request: ExternalProcessingRequest) => Promise<boolean>;\n\nexport const DOCUMENT_PROCESSING_SETUP =\n 'Configure a selected local backend and model in .qfai/graph-processing.json using .agents/rules/graph-exploration.md, then run node .qfai/tools/graph-cli.mjs documents \"<question>\".';\n\nexport async function prepareGraphifyCodeAnalysis(\n root: string,\n run: GraphProcess = runGraphProcess,\n): Promise<DocumentPreparation> {\n if (!(await graphifyConfigurationSafe(root))) return providerConflict();\n const current = graphAnalysisRoot(root, \"graphify-code\");\n const staged = path.join(path.dirname(current), `.preparing-graphify-code-${randomUUID()}`);\n await assertGraphStoragePath(root, staged);\n await mkdir(staged, { recursive: true });\n try {\n await mirrorGraphCorpus(root, staged);\n const result = await run(\n graphRuntimePaths(root).python,\n [\n ...GRAPH_PYTHON_FLAGS,\n \"-m\",\n \"graphify\",\n \"extract\",\n path.toNamespacedPath(staged),\n \"--code-only\",\n \"--no-cluster\",\n \"--no-dedup\",\n \"--max-workers\",\n \"1\",\n \"--max-concurrency\",\n \"1\",\n ],\n { cwd: staged, env: graphifyCorpusEnvironment(root, staged) },\n );\n if (\n result.exitCode !== 0 ||\n !(await currentGraphifyCorpus(root, staged, graphRuntimePaths(root).python, run, \"ast\"))\n ) {\n return { status: \"failed\", recovery: \"Repair local Graphify code analysis.\" };\n }\n await writeFile(\n path.join(staged, \"graphify-out\", \"managed.json\"),\n JSON.stringify({ engineVersion: GRAPH_VERSIONS.graphify, scope: \"code\" }),\n );\n await assertIndependentAnalysis(staged);\n await replaceGraphDirectory(staged, current, root);\n return { status: \"prepared\" };\n } finally {\n await rm(staged, { recursive: true, force: true });\n }\n}\n\nexport async function prepareDocumentAnalysis(\n root: string,\n run: GraphProcess = runGraphProcess,\n approveExternal: ApproveExternalProcessing = () => Promise.resolve(false),\n environment?: GraphReuseEnvironment,\n): Promise<DocumentPreparation> {\n return withGraphLock(root, \"analysis\", () =>\n prepareDocumentAnalysisLocked(root, run, approveExternal, environment),\n );\n}\n\nexport async function prepareDocumentAnalysisLocked(\n root: string,\n run: GraphProcess = runGraphProcess,\n approveExternal: ApproveExternalProcessing = () => Promise.resolve(false),\n environment?: GraphReuseEnvironment,\n): Promise<DocumentPreparation> {\n if (!(await graphifyConfigurationSafe(root))) return providerConflict();\n if (await inspectDocumentAnalysis(root, run)) return { status: \"prepared\", source: \"current\" };\n const processing = await readGraphProcessing(root);\n if (!processing) {\n return {\n status: \"not-ready\",\n recovery: DOCUMENT_PROCESSING_SETUP,\n };\n }\n const inspect = async (analysis: string, refresh: boolean) =>\n (await inspectDocumentScopeAt(root, analysis, run, refresh)).current;\n if ((await restoreCompletedDocumentAnalysis(root, run, inspect, environment)) === \"restored\")\n return { status: \"prepared\", source: \"restored\" };\n const endpoint = processing.endpoint ?? \"http://127.0.0.1:11434/v1\";\n const selected = new URL(endpoint);\n const backend = processing.backend;\n const credential =\n typeof processing.credentialEnv === \"string\"\n ? process.env[processing.credentialEnv]\n : undefined;\n if (processing.credentialEnv !== undefined && !credential) {\n return {\n status: \"not-ready\",\n recovery:\n \"Set the explicitly selected credential environment variable before document processing.\",\n };\n }\n const local = [\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(selected.hostname);\n let scope: readonly string[] | undefined;\n if (processing.scope !== undefined) {\n if (!validDocumentScope(processing.scope))\n return { status: \"not-ready\", recovery: \"Select the exact document scope for processing.\" };\n scope = Object.freeze(processing.scope.map((item) => item.replaceAll(\"\\\\\", \"/\")));\n }\n if (!local) {\n if (!scope) {\n return {\n status: \"not-ready\",\n recovery: \"Select the exact document scope for external processing.\",\n };\n }\n const approval: unknown = await approveExternal(\n Object.freeze({\n destination: endpoint,\n scope,\n backend,\n model: processing.model,\n worktree: root,\n }),\n );\n if (approval !== true) {\n return {\n status: \"not-ready\",\n recovery:\n \"External document processing requires explicit human authorization of its destination and scope.\",\n };\n }\n }\n const current = graphAnalysisRoot(root, \"graphify\");\n const staged = path.join(path.dirname(current), `.preparing-graphify-${randomUUID()}`);\n await assertGraphStoragePath(root, staged);\n await mkdir(staged, { recursive: true });\n try {\n await mirrorGraphCorpus(root, staged, scope);\n const result = await run(\n graphRuntimePaths(root).python,\n [\n ...GRAPH_PYTHON_FLAGS,\n \"-m\",\n \"graphify\",\n \"extract\",\n path.toNamespacedPath(staged),\n \"--backend\",\n backend,\n \"--model\",\n processing.model,\n \"--no-cluster\",\n \"--no-dedup\",\n \"--max-workers\",\n \"1\",\n \"--max-concurrency\",\n \"1\",\n ],\n {\n cwd: staged,\n env: {\n ...graphifyCorpusEnvironment(root, staged),\n [backend === \"ollama\" ? \"OLLAMA_BASE_URL\" : \"OPENAI_BASE_URL\"]: endpoint,\n ...(credential\n ? { [backend === \"ollama\" ? \"OLLAMA_API_KEY\" : \"OPENAI_API_KEY\"]: credential }\n : {}),\n },\n },\n );\n if (\n result.exitCode !== 0 ||\n !(await currentGraphifyCorpus(root, staged, graphRuntimePaths(root).python, run))\n ) {\n return {\n status: \"failed\",\n recovery: \"Check the selected local model and repair Graphify document analysis.\",\n };\n }\n await writeFile(\n path.join(staged, \"graphify-out\", \"managed.json\"),\n JSON.stringify({ engineVersion: GRAPH_VERSIONS.graphify, scope: \"documents\", processing }),\n );\n await assertIndependentAnalysis(staged);\n await replaceGraphDirectory(staged, current, root);\n return {\n status: \"prepared\",\n source: \"generated\",\n reuse: await publishCompletedDocumentAnalysis(root, run, inspect, environment),\n };\n } finally {\n await rm(staged, { recursive: true, force: true });\n }\n}\n\nexport async function readGraphProcessing(root: string): Promise<GraphProcessing | undefined> {\n const processing = await readOptionalJson(path.join(root, \".qfai\", \"graph-processing.json\"));\n return validGraphProcessing(processing) ? processing : undefined;\n}\n\nfunction validGraphProcessing(processing: unknown): processing is GraphProcessing {\n const allowed = new Set([\"backend\", \"model\", \"endpoint\", \"scope\", \"credentialEnv\"]);\n if (\n !object(processing) ||\n Object.keys(processing).some((key) => !allowed.has(key)) ||\n (processing.backend !== \"ollama\" && processing.backend !== \"openai\") ||\n typeof processing.model !== \"string\" ||\n !processing.model.trim() ||\n (processing.scope !== undefined && !validDocumentScope(processing.scope)) ||\n (processing.credentialEnv !== undefined &&\n (typeof processing.credentialEnv !== \"string\" ||\n !/^[A-Z_][A-Z0-9_]*$/.test(processing.credentialEnv)))\n )\n return false;\n if (processing.endpoint !== undefined) {\n if (typeof processing.endpoint !== \"string\" || !processing.endpoint.trim()) return false;\n try {\n const endpoint = new URL(processing.endpoint);\n if (\n ![\"http:\", \"https:\"].includes(endpoint.protocol) ||\n endpoint.username ||\n endpoint.password ||\n endpoint.search ||\n endpoint.hash\n )\n return false;\n } catch {\n return false;\n }\n }\n return true;\n}\n\nexport async function inspectDocumentAnalysis(root: string, run: GraphProcess): Promise<boolean> {\n return (await inspectDocumentScope(root, run)).current;\n}\n\nexport async function inspectDocumentScope(\n root: string,\n run: GraphProcess,\n): Promise<DocumentScopeStatus> {\n const analysis = graphAnalysisRoot(root, \"graphify\");\n await assertGraphStoragePath(root, analysis);\n return inspectDocumentScopeAt(root, analysis, run);\n}\n\nasync function inspectDocumentScopeAt(\n root: string,\n analysis: string,\n run: GraphProcess,\n refresh = true,\n): Promise<DocumentScopeStatus> {\n const managed = await readOptionalJson(path.join(analysis, \"graphify-out\", \"managed.json\"));\n const selected = await readGraphProcessing(root);\n const processing = await processingForCompletedQuery(\n root,\n selected,\n object(managed) ? managed.processing : undefined,\n );\n if (\n !object(managed) ||\n Object.keys(managed).length !== 3 ||\n managed.engineVersion !== GRAPH_VERSIONS.graphify ||\n managed.scope !== \"documents\" ||\n !sameProcessing(managed.processing, processing)\n )\n return notCurrent();\n if (!(await safeDocumentCopy(root, analysis, run))) return notCurrent();\n const scope =\n object(processing) && validDocumentScope(processing.scope) ? processing.scope : undefined;\n if (refresh) await mirrorGraphCorpus(root, analysis, scope);\n return nativeGraphifyScope(root, analysis, graphRuntimePaths(root).python, run);\n}\n\nasync function processingForCompletedQuery(\n root: string,\n selected: unknown,\n recorded: unknown,\n): Promise<unknown> {\n if (selected !== undefined) return selected;\n try {\n await readFile(path.join(root, \".qfai\", \"graph-processing.json\"));\n return undefined;\n } catch (cause: unknown) {\n if (!isEnoent(cause)) throw cause;\n }\n if (!validGraphProcessing(recorded)) return undefined;\n return recorded;\n}\n\nasync function currentGraphifyCorpus(\n root: string,\n analysis: string,\n python: string,\n run: GraphProcess,\n kind: \"semantic\" | \"ast\" = \"semantic\",\n): Promise<boolean> {\n return (await nativeGraphifyScope(root, analysis, python, run, kind)).current;\n}\n\nasync function nativeGraphifyScope(\n root: string,\n analysis: string,\n python: string,\n run: GraphProcess,\n kind: \"semantic\" | \"ast\" = \"semantic\",\n): Promise<DocumentScopeStatus> {\n if (!(await graphifyConfigurationSafe(root))) return notCurrent();\n const result = await run(\n python,\n [\n ...GRAPH_PYTHON_FLAGS,\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"graphify-native.py\"),\n path.toNamespacedPath(analysis),\n kind,\n ],\n {\n cwd: analysis,\n env: graphifyCorpusEnvironment(root, analysis),\n },\n );\n if (result.exitCode !== 0) return notCurrent();\n let state: unknown;\n try {\n state = JSON.parse(result.stdout);\n } catch (cause: unknown) {\n if (!(cause instanceof SyntaxError)) throw cause;\n return notCurrent();\n }\n if (\n !object(state) ||\n typeof state.current !== \"boolean\" ||\n !stringArray(state.unsupported) ||\n !stringArray(state.unreadable)\n )\n return notCurrent();\n const sourcePath = (file: string) =>\n path.isAbsolute(file)\n ? path\n .relative(path.toNamespacedPath(analysis), path.toNamespacedPath(file))\n .split(path.sep)\n .join(\"/\")\n : file;\n return {\n current: state.current,\n unsupported: state.unsupported.map(sourcePath),\n unreadable: state.unreadable.map(sourcePath),\n };\n}\n\nasync function readOptionalJson(file: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(file, \"utf8\"));\n } catch (cause: unknown) {\n if (isEnoent(cause) || cause instanceof SyntaxError) return undefined;\n throw cause;\n }\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction sameProcessing(left: unknown, right: unknown): boolean {\n if (!object(left) || !object(right)) return false;\n const fields = [\"backend\", \"model\", \"endpoint\", \"credentialEnv\", \"scope\"];\n if (Object.keys(left).some((key) => !fields.includes(key))) return false;\n return fields.every((key) => JSON.stringify(left[key]) === JSON.stringify(right[key]));\n}\n\nfunction stringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item: unknown) => typeof item === \"string\");\n}\n\nfunction validDocumentScope(value: unknown): value is string[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every(\n (item: unknown) =>\n typeof item === \"string\" &&\n item !== \"\" &&\n !path.isAbsolute(item) &&\n !item.split(/[\\\\/]/).some((part) => part === \"..\" || part === \".\" || part === \"\"),\n )\n );\n}\n\nfunction providerConflict(): DocumentPreparation {\n return {\n status: \"not-ready\",\n recovery:\n \"Review private Graphify provider settings and unsafe home paths before processing; existing settings were retained.\",\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { cp, lstat, mkdir, readdir, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\nimport { excludedGraphInput } from \"./analysis.js\";\nimport { GRAPH_VERSIONS, graphAnalysisRoot, graphRuntimePaths } from \"./layout.js\";\nimport {\n GRAPH_PYTHON_FLAGS,\n graphifyEnvironment,\n graphifyCorpusEnvironment,\n type GraphProcess,\n} from \"./process.js\";\nimport {\n cacheDirectorySafe,\n completedAnalysisCache,\n ensureCacheDirectory,\n graphReuseEnvironment,\n readSnapshotMetadata,\n safeCompletedCorpus,\n sameEnvironment,\n type GraphReuseEnvironment,\n} from \"./reuse.js\";\nimport {\n assertGraphStoragePath,\n assertIndependentAnalysis,\n replaceGraphDirectory,\n} from \"./storage.js\";\n\ntype Inspect = (analysis: string, refresh: boolean) => Promise<boolean>;\n\nexport async function restoreCompletedDocumentAnalysis(\n root: string,\n run: GraphProcess,\n inspect: Inspect,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<\"restored\" | \"cold\"> {\n let staged: string | undefined;\n try {\n if (!(await compatible(root, run, environment))) return \"cold\";\n const cache = await completedAnalysisCache(root, \"graphify\", run, environment);\n if (!cache) return \"cold\";\n for (const entry of await readdir(cache.directory, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name.startsWith(\".\")) continue;\n const candidate = path.join(cache.directory, entry.name);\n if (!(await cacheDirectorySafe(cache.repository, candidate))) continue;\n const metadata = await readSnapshotMetadata(candidate);\n if (\n !metadata ||\n Object.keys(metadata).length !== 5 ||\n metadata.layout !== 1 ||\n metadata.corpusPolicy !== 1 ||\n metadata.repository !== cache.repository ||\n metadata.engineVersion !== GRAPH_VERSIONS.graphify ||\n !sameEnvironment(metadata.environment, environment)\n )\n continue;\n const analysis = path.join(candidate, \"analysis\");\n if (!(await safeDocumentCopy(root, analysis, run))) continue;\n const current = graphAnalysisRoot(root, \"graphify\");\n staged = path.join(path.dirname(current), `.restoring-graphify-${randomUUID()}`);\n await assertGraphStoragePath(root, staged);\n await mkdir(path.dirname(staged), { recursive: true });\n await cp(analysis, staged, { recursive: true, dereference: false });\n await assertIndependentAnalysis(staged);\n if (await inspect(staged, true)) {\n await replaceGraphDirectory(staged, current, root);\n return \"restored\";\n }\n await rm(staged, { recursive: true, force: true });\n staged = undefined;\n }\n } catch {\n return \"cold\";\n } finally {\n if (staged) await discard(staged);\n }\n return \"cold\";\n}\n\nexport async function publishCompletedDocumentAnalysis(\n root: string,\n run: GraphProcess,\n inspect: Inspect,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<\"published\" | \"unavailable\"> {\n let staged: string | undefined;\n try {\n if (!(await compatible(root, run, environment))) return \"unavailable\";\n const cache = await completedAnalysisCache(root, \"graphify\", run, environment);\n if (!cache) return \"unavailable\";\n await ensureCacheDirectory(cache.repository, cache.directory);\n const analysis = graphAnalysisRoot(root, \"graphify\");\n if (!(await safeDocumentCopy(root, analysis, run))) return \"unavailable\";\n const identity = randomUUID();\n staged = path.join(cache.directory, `.publishing-${identity}`);\n await mkdir(staged);\n const copy = path.join(staged, \"analysis\");\n await cp(analysis, copy, { recursive: true, dereference: false });\n await assertIndependentAnalysis(copy);\n if (!(await safeDocumentCopy(root, copy, run)) || !(await inspect(copy, false)))\n return \"unavailable\";\n await writeFile(\n path.join(staged, \"completed.json\"),\n JSON.stringify({\n layout: 1,\n corpusPolicy: 1,\n repository: cache.repository,\n engineVersion: GRAPH_VERSIONS.graphify,\n environment,\n }) + \"\\n\",\n );\n await rename(staged, path.join(cache.directory, identity));\n return \"published\";\n } catch {\n return \"unavailable\";\n } finally {\n if (staged) await discard(staged);\n }\n}\n\nasync function compatible(\n root: string,\n run: GraphProcess,\n environment: GraphReuseEnvironment,\n): Promise<boolean> {\n if (environment.platform !== \"win32\" || environment.architecture !== \"x64\") return false;\n const result = await run(\n graphRuntimePaths(root).python,\n [...GRAPH_PYTHON_FLAGS, \"-c\", \"import sys; print(sys.version.split()[0])\"],\n { cwd: root, env: graphifyEnvironment(root) },\n );\n return result.exitCode === 0 && result.stdout.trim() === \"3.12.13\";\n}\n\nexport async function safeDocumentCopy(\n root: string,\n analysis: string,\n run: GraphProcess,\n): Promise<boolean> {\n if (!(await safeCompletedCorpus(analysis, \"\", \"graphify-out\"))) return false;\n const result = await run(\n graphRuntimePaths(root).python,\n [\n ...GRAPH_PYTHON_FLAGS,\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"graphify-native.py\"),\n path.toNamespacedPath(analysis),\n \"inventory\",\n ],\n { cwd: analysis, env: graphifyCorpusEnvironment(root, analysis) },\n );\n if (result.exitCode !== 0) return false;\n try {\n const inventory: unknown = JSON.parse(result.stdout);\n if (\n typeof inventory !== \"object\" ||\n inventory === null ||\n Object.keys(inventory).length !== 1 ||\n !(\"files\" in inventory) ||\n !Array.isArray(inventory.files)\n )\n return false;\n for (const file of inventory.files) {\n if (typeof file !== \"string\" || path.posix.isAbsolute(file) || path.win32.isAbsolute(file))\n return false;\n const parts = file.replaceAll(\"\\\\\", \"/\").split(\"/\");\n if (\n parts.some((part) => !part || part === \".\" || part === \"..\") ||\n excludedGraphInput(parts.join(\"/\"))\n )\n return false;\n const stats = await lstat(path.join(analysis, ...parts));\n if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1) return false;\n }\n return true;\n } catch {\n return false;\n }\n}\n\nasync function discard(directory: string): Promise<void> {\n try {\n await rm(directory, { recursive: true, force: true });\n } catch {\n // An unfinished hidden candidate is never eligible for restoration.\n }\n}\n","import {\n GRAPH_PYTHON_FLAGS,\n codegraphEnvironment,\n graphifyCorpusEnvironment,\n runGraphProcess,\n type GraphProcess,\n} from \"./process.js\";\nimport { inspectCodeCoverage, inspectCurrentCodeAnalysis } from \"./analysis.js\";\nimport { graphAnalysisRoot, graphRuntimePaths } from \"./layout.js\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { findUnsafeHostFileComponent } from \"../init/fsGuards.js\";\nimport { inspectDocumentScope, readGraphProcessing } from \"./documents.js\";\n\nexport interface GraphQuestion {\n domain: \"code\" | \"documents\";\n question: string;\n}\n\nexport interface GraphAnswer {\n requestedScope: Readonly<GraphQuestion>;\n engine: \"codegraph\" | \"graphify\";\n status: \"answered\" | \"not-ready\" | \"failed\" | \"no-match\" | \"incomplete\";\n coverage?: {\n unsupported: string[];\n unreadable: string[];\n unparsed?: string[];\n complete?: boolean;\n };\n answer?: string;\n failure?: string;\n inferenceNotice?: string;\n recovery?: string;\n}\n\nexport async function readKnownGraphFile(root: string, relative: string): Promise<string> {\n const parts = relative.split(/[\\\\/]/);\n if (\n path.isAbsolute(relative) ||\n parts.some((part) => part === \"..\" || part === \"\" || part === \".\") ||\n (await findUnsafeHostFileComponent(root, parts))\n ) {\n throw new Error(\"Use an exact known source file inside the project.\");\n }\n return readFile(path.join(root, ...parts), \"utf8\");\n}\n\nexport async function continueGraphExploration(\n root: string,\n previous: GraphAnswer,\n unresolved: GraphQuestion,\n run: GraphProcess = runGraphProcess,\n): Promise<GraphAnswer> {\n const nextEngine = unresolved.domain === \"code\" ? \"codegraph\" : \"graphify\";\n if (\n previous.status !== \"answered\" ||\n previous.engine === nextEngine ||\n unresolved.question.trim() === \"\"\n ) {\n throw new Error(\n \"State the unresolved question in the other domain after an answered graph query.\",\n );\n }\n return exploreGraph(root, unresolved, run);\n}\n\nexport async function exploreGraph(\n root: string,\n request: GraphQuestion,\n run: GraphProcess = runGraphProcess,\n): Promise<GraphAnswer> {\n const requestedScope = Object.freeze({ ...request });\n try {\n return { ...(await exploreGraphScope(root, request, run)), requestedScope };\n } catch {\n const engine = request.domain === \"code\" ? \"codegraph\" : \"graphify\";\n return {\n requestedScope,\n engine,\n status: \"failed\",\n failure: `${engine === \"codegraph\" ? \"CodeGraph\" : \"Graphify\"} operation failed.`,\n recovery: `Repair ${engine === \"codegraph\" ? \"CodeGraph\" : \"Graphify\"} analysis and retry the graph query.`,\n };\n }\n}\n\nasync function exploreGraphScope(\n root: string,\n request: GraphQuestion,\n run: GraphProcess,\n): Promise<Omit<GraphAnswer, \"requestedScope\">> {\n const documentScope =\n request.domain === \"documents\" ? await inspectDocumentScope(root, run) : undefined;\n if (documentScope?.current) {\n const result = await run(\n graphRuntimePaths(root).python,\n [\n ...GRAPH_PYTHON_FLAGS,\n \"-m\",\n \"graphify\",\n \"query\",\n request.question,\n \"--graph\",\n path.toNamespacedPath(\n path.join(graphAnalysisRoot(root, \"graphify\"), \"graphify-out\", \"graph.json\"),\n ),\n ],\n {\n cwd: graphAnalysisRoot(root, \"graphify\"),\n env: graphifyCorpusEnvironment(root, graphAnalysisRoot(root, \"graphify\")),\n },\n );\n if (result.exitCode !== 0 && result.exitCode !== 4) {\n return {\n engine: \"graphify\",\n status: \"failed\",\n failure: \"Graphify query failed.\",\n recovery: \"Repair Graphify analysis and retry the graph query.\",\n };\n }\n const coverage = {\n unsupported: documentScope.unsupported,\n unreadable: documentScope.unreadable,\n };\n const inference = result.stdout.includes(\"[INFERRED]\")\n ? {\n inferenceNotice:\n \"Inferred relationships need source confirmation; they do not establish semantic correctness or complete coverage.\",\n }\n : {};\n if (coverage.unsupported.length > 0 || coverage.unreadable.length > 0) {\n return {\n engine: \"graphify\",\n status: \"incomplete\",\n answer: result.stdout,\n coverage,\n ...inference,\n recovery:\n \"Review unsupported and unreadable scope; this result does not establish absence.\",\n };\n }\n return {\n engine: \"graphify\",\n status: result.exitCode === 4 ? \"no-match\" : \"answered\",\n answer: result.stdout,\n coverage,\n ...inference,\n };\n }\n if (request.domain === \"code\" && (await inspectCurrentCodeAnalysis(root, run))) {\n const result = await run(\n process.execPath,\n [\n graphRuntimePaths(root).codegraph,\n \"context\",\n request.question,\n \"--path\",\n graphAnalysisRoot(root, \"codegraph\"),\n \"--format\",\n \"json\",\n \"--no-code\",\n ],\n {\n cwd: root,\n env: codegraphEnvironment(root),\n },\n );\n const context = nativeCodeContext(result.stdout, request.question);\n if (result.exitCode !== 0 || !context)\n return {\n engine: \"codegraph\",\n status: \"failed\",\n failure: \"CodeGraph query failed or returned unusable data.\",\n recovery: \"Repair CodeGraph analysis and retry the graph query.\",\n };\n const coverage = await inspectCodeCoverage(root, run);\n if (!coverage.complete)\n return {\n engine: \"codegraph\",\n status: \"incomplete\",\n answer: result.stdout,\n coverage,\n recovery:\n \"Review unknown, unsupported, unreadable and unparsed code scope; this result does not establish absence.\",\n };\n return {\n engine: \"codegraph\",\n status: context.empty ? \"no-match\" : \"answered\",\n answer: result.stdout,\n coverage,\n ...(context.empty\n ? {\n inferenceNotice:\n \"No match in this context search over the confirmed native code scope; this does not establish global absence.\",\n }\n : {}),\n };\n }\n return {\n engine: request.domain === \"code\" ? \"codegraph\" : \"graphify\",\n status: \"not-ready\",\n recovery:\n request.domain === \"documents\" && (await readGraphProcessing(root)) === undefined\n ? \"Select document processing in .qfai/graph-processing.json before preparing document analysis.\"\n : \"Prepare the requested graph analysis before querying it.\",\n };\n}\n\nfunction nativeCodeContext(stdout: string, question: string): { empty: boolean } | undefined {\n let value: unknown;\n try {\n value = JSON.parse(stdout);\n } catch {\n return undefined;\n }\n if (!object(value) || value.query !== question || typeof value.summary !== \"string\")\n return undefined;\n const arrays = [\"entryPoints\", \"nodes\", \"edges\", \"codeBlocks\", \"relatedFiles\"];\n if (arrays.some((key) => !Array.isArray(value[key])) || !object(value.stats)) return undefined;\n const stats = value.stats;\n const counts = [\"nodeCount\", \"edgeCount\", \"fileCount\", \"codeBlockCount\", \"totalCodeSize\"];\n if (counts.some((key) => !Number.isSafeInteger(stats[key]) || Number(stats[key]) < 0))\n return undefined;\n for (const [count, entries] of [\n [\"nodeCount\", \"nodes\"],\n [\"edgeCount\", \"edges\"],\n [\"fileCount\", \"relatedFiles\"],\n [\"codeBlockCount\", \"codeBlocks\"],\n ] as const) {\n const list = value[entries];\n if (!Array.isArray(list) || stats[count] !== list.length) return undefined;\n }\n const empty = stats.nodeCount === 0;\n if (\n empty &&\n (arrays.some((key) => Array.isArray(value[key]) && value[key].length !== 0) ||\n counts.some((key) => stats[key] !== 0))\n )\n return undefined;\n return { empty };\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,OAAOA,YAAU;;;ACDjB,SAAS,iBAAiB;AAE1B,SAAS,QAAQ,OAAO,MAAM,UAAU,YAAY;AAEpD,OAAO,UAAU;;;ACSV,SAAS,SAAS,KAAuB;AAC9C,SAAO,aAAa,GAAG,KAAK,IAAI,SAAS;AAC3C;AAyBO,SAAS,aAAa,KAAuC;AAClE,SACE,QAAQ,QACR,OAAO,QAAQ,YACf,UAAU,OACV,OAAQ,IAA2B,SAAS;AAEhD;;;ADeA,eAAsB,sBACpB,UACA,UACwB;AACxB,MAAI;AACJ,MAAI;AACF,aAAS,MAAM,KAAK,UAAU,eAAe;AAC7C,UAAM,SAAS,MAAM,OAAO,KAAK;AACjC,QAAI,CAAC,OAAO,OAAO,KAAK,OAAO,OAAO,UAAU;AAC9C,aAAO;AAAA,IACT;AAWA,UAAM,SAAS,OAAO,MAAM,WAAW,CAAC;AACxC,QAAI,SAAS;AACb,WAAO,SAAS,OAAO,QAAQ;AAC7B,YAAM,EAAE,UAAU,IAA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;AAC3B,YAAI,iBAAiB;AACnB,mBAAS,UAAU,GAAG,MAAM,OAAO,IAAI,MAAM,QAAQ;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AACA,MAAI,SAAS,aAAa;AACxB,OAAG,OAAO,KAAK,UAAU,gBAAgB,MAAM,QAAQ,CAAC,IAAI,IAAI;AAClE,MAAI,SAAS,UAAU,UAAU;AAC/B,OAAG,MAAM,mFAAmF;AAC5F,OAAG,KAAK;AAAA,EACV;AACF;AAEA,SAAS,SAAS,OAA2C;AAC3D,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,EAAG,QAAO;AAChF,QAAM,QAAQ;AACd,QAAM,QAAQ,CAAC,aAAa,cAAc,YAAY,EAAE,KAAK,CAAC,QAAQ,OAAO,KAAK;AAClF,QAAM,QAAQ,CAAC,YAAY,YAAY,WAAW,EAAE,KAAK,CAAC,QAAQ,OAAO,KAAK;AAC9E,MAAI,UAAU,MAAO,QAAO;AAE5B,SAAO,QAAQ,YAAY;AAC7B;","names":["path","offset","path","randomUUID","rename","unlink","path","randomUUID","path","path","lstat","mkdir","open","path","lstat","path","path","lstat","path","mkdir","lstat","open","path","randomUUID","unlink","path","path","unlink","randomUUID","mkdir","rm","path","path","path","access","lstat","path","path","randomUUID","lstat","mkdir","readFile","readdir","realpath","rename","rm","path","lstat","mkdir","readdir","rm","mkdir","readFile","rm","writeFile","randomUUID","randomUUID","cp","lstat","mkdir","readdir","rename","rm","writeFile","path","path","readFile","path","path","randomUUID","path"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/graphHook.ts","../../src/core/init/fsGuards.ts","../../src/core/fs/errno.ts","../../src/core/graph/hooks.ts","../../src/core/graph/fallbackState.ts","../../src/core/graph/locks.ts","../../src/core/graph/layout.ts","../../src/core/graph/localFiles.ts","../../src/core/graph/storage.ts","../../src/core/graph/permissionRecords.ts","../../src/core/graph/codePreparation.ts","../../src/shared/assets.ts","../../src/core/graph/process.ts","../../src/core/graph/reuse.ts","../../src/core/graph/analysis.ts","../../src/core/config.ts","../../src/shared/shippedWorkflowNames.ts","../../src/core/graph/documents.ts","../../src/core/graph/documentReuse.ts","../../src/core/graph/query.ts","../../src/core/graph/sessionWorktree.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { lstat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { findUnsafeHostFileComponent, readPinnedRegularFile } from \"../core/init/fsGuards.js\";\nimport {\n enforceGraphExploration,\n decodeGraphHookEvent,\n failedGraphHook,\n graphFallbackUnavailable,\n graphHookOutput,\n type GraphHookHost,\n} from \"../core/graph/hooks.js\";\nimport { classifyStoredGraphExploration } from \"../core/graph/fallbackState.js\";\nimport { GraphLocalStateError } from \"../core/graph/localFiles.js\";\nimport { resolveSessionWorktree } from \"../core/graph/sessionWorktree.js\";\nimport { isEnoent } from \"../core/fs/errno.js\";\n\nconst enforcement = [\".qfai\", \"tools\", \"graph-enforcement.json\"];\n\nfunction hostName(value: unknown): value is GraphHookHost {\n return value === \"claude\" || value === \"codex\" || value === \"copilot\" || value === \"vscode\";\n}\n\nexport interface GraphHookIO {\n read(): unknown;\n output(text: string): void;\n error(text: string): void;\n fail(): void;\n}\n\nexport async function runInstalledGraphHook(\n root: string,\n args: string[],\n io: GraphHookIO = {\n read: () => JSON.parse(readFileSync(0, \"utf8\")) as unknown,\n output: (text) => {\n process.stdout.write(text);\n },\n error: (text) => {\n process.stderr.write(text);\n },\n fail: () => {\n process.exitCode = 2;\n },\n },\n): Promise<void> {\n let input: unknown;\n try {\n input = io.read();\n } catch {\n input = undefined;\n }\n const host = args[0] === \"shared\" ? wireHost(input) : args[0];\n if (!hostName(host)) {\n io.error(\"Graph protection unsupported: select a supported host adapter.\\n\");\n io.fail();\n return;\n }\n let decision = failedGraphHook(\"configuration\");\n const event = decodeGraphHookEvent(input);\n let project = root;\n let uninitialised = false;\n try {\n // The session's own worktree, when nested under this checkout, is its project worktree.\n project = await resolveSessionWorktree(root, event?.cwd);\n uninitialised = project !== root && !(await hasEnforcement(project));\n const configured = uninitialised ? root : project;\n if (!(await findUnsafeHostFileComponent(configured, enforcement))) {\n const text = await readPinnedRegularFile(path.join(configured, ...enforcement), 4096);\n if (text !== null) decision = enforceGraphExploration(input, JSON.parse(text) as unknown);\n }\n } catch {\n // A supported adapter emits denial for invalid input without echoing the payload.\n }\n if (decision.decision === \"deny\" && decision.state === \"configured\" && uninitialised)\n decision = graphFallbackUnavailable(\n decision,\n `The session worktree ${project} has no graph protection; this hook belongs to ${root}.`,\n `Run qfai init in ${project}, then retry the denied action.`,\n );\n else if (decision.decision === \"deny\" && decision.state === \"configured\") {\n if (event) {\n try {\n decision = await classifyStoredGraphExploration(project, event);\n } catch (cause: unknown) {\n decision = failedGraphHook(\"state\");\n if (cause instanceof GraphLocalStateError)\n decision.message = `${cause.message} ${cause.recovery}`;\n }\n }\n }\n if (decision.decision === \"deny\")\n io.output(JSON.stringify(graphHookOutput(host, decision)) + \"\\n\");\n if (decision.state === \"failed\") {\n io.error(`${decision.message}\\n`);\n io.fail();\n }\n}\n\nasync function hasEnforcement(project: string) {\n // Any existing entry counts: an unsafe one then fails through the same checks as the root's.\n try {\n await lstat(path.join(project, ...enforcement));\n return true;\n } catch (cause: unknown) {\n if (isEnoent(cause)) return false;\n throw cause;\n }\n}\n\nfunction wireHost(input: unknown): GraphHookHost | undefined {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) return undefined;\n const value = input as Record<string, unknown>;\n const snake = [\"tool_name\", \"tool_input\", \"session_id\"].some((key) => key in value);\n const camel = [\"toolName\", \"toolArgs\", \"sessionId\"].some((key) => key in value);\n if (snake === camel) return undefined;\n // The selected response format is not evidence of the physical host.\n return camel ? \"copilot\" : \"vscode\";\n}\n","import { constants } from \"node:fs\";\nimport type { Stats } from \"node:fs\";\nimport { access, lstat, open, readFile, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { isEnoent } from \"../fs/errno.js\";\n\n/**\n * The first component of `target` at or below `destRoot` that is a symbolic\n * link, or `null` when every one of them is an ordinary directory or file.\n */\nexport async function firstLinkedComponent(\n target: string,\n destRoot: string,\n): Promise<string | null> {\n const relative = path.relative(destRoot, target);\n let walked = destRoot;\n for (const segment of relative.split(path.sep)) {\n walked = path.join(walked, segment);\n const entry = await lstat(walked).catch(() => null);\n if (entry?.isSymbolicLink() === true) return walked;\n }\n return null;\n}\n\n/** File contents, or `null` when nothing is there. Other read faults throw. */\nexport async function readTextFileIfPresent(target: string): Promise<string | null> {\n try {\n return await readFile(target, \"utf-8\");\n } catch (err: unknown) {\n if (isEnoent(err)) {\n return null;\n }\n throw err;\n }\n}\n\nexport async function exists(target: string): Promise<boolean> {\n try {\n await access(target);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The bytes of a regular file no larger than `maxBytes`, read from the inode\n * the size was measured on, or `null` when the entry is not one.\n *\n * **The ceiling binds the entry that is read**, not the one a previous\n * `lstat` saw. Those are two pathname operations, and between them another\n * process can replace the path with a huge file or a FIFO — a bound checked on\n * the old inode does not bind the new one, and the read then exhausted memory\n * or never returned. One `open`, `fstat` on that handle, a bounded read from\n * it.\n *\n * A read fault is thrown rather than answered `null`: an ACL or a transient\n * `EIO` says the content could not be checked, and reporting that as \"not a\n * bounded regular file\" is a decision nobody made.\n */\nexport async function readPinnedRegularFile(\n filePath: string,\n maxBytes: number,\n): Promise<string | null> {\n let handle: FileHandle | undefined;\n try {\n handle = await open(filePath, OPEN_READ_FLAGS);\n const pinned = await handle.stat();\n if (!pinned.isFile() || pinned.size > maxBytes) {\n return null;\n }\n // Read to the end, not once: `read` may return fewer bytes than asked for,\n // and the unfilled tail stayed NUL — a correct flattened wrapper then\n // failed its own signature comparison and was left in place.\n //\n // And to `maxBytes + 1`, not to the size just measured. Another process\n // holding this inode from before the rename can append after the `fstat`,\n // and stopping at the old size read a **prefix** — which still matched the\n // target, so the repair went ahead and the cleanup deleted the sidecar with\n // the appended bytes in it. One byte past the ceiling is what distinguishes\n // \"this is the whole file\" from \"this is as much as I asked for\".\n const buffer = Buffer.alloc(maxBytes + 1);\n let filled = 0;\n while (filled < buffer.length) {\n const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);\n if (bytesRead === 0) break;\n filled += bytesRead;\n }\n if (filled > maxBytes) return null;\n return buffer.subarray(0, filled).toString(\"utf-8\");\n } catch (error: unknown) {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n // `ENXIO` is what `O_NONBLOCK` returns for a FIFO with no writer, in place\n // of blocking. Neither it nor a directory is a bounded regular file, and\n // `open` is simply where that shows up instead of `fstat`.\n if (code === \"ENXIO\" || code === \"EISDIR\") return null;\n throw error;\n } finally {\n await handle?.close();\n }\n}\n\n/**\n * One bounded read of a regular file: its bytes, and everything a replacement\n * has to put back.\n *\n * `mode`, `uid` and `gid` because an atomic replace writes a **new** inode;\n * `dev` and `ino` so the replacement can tell it is still about to replace the\n * file it read.\n */\nexport type PinnedFileRead = {\n content: Buffer;\n mode: number;\n uid: number;\n gid: number;\n dev: number;\n ino: number;\n};\n\n/**\n * The same read, returning the bytes.\n *\n * The restore copy writes back what it read, and decoding as UTF-8 first\n * replaces every invalid sequence with U+FFFD — irreversibly, since the sidecar\n * is removed straight after.\n *\n * `dev` / `ino` come off the same handle as the content, so a caller that\n * replaces the pathname afterwards can check that the entry it is about to\n * replace is still the inode it read.\n */\nexport async function readPinnedRegularFileBytes(\n filePath: string,\n maxBytes: number,\n): Promise<PinnedFileRead | null> {\n let handle: FileHandle | undefined;\n try {\n handle = await open(filePath, OPEN_READ_FLAGS);\n const pinned = await handle.stat();\n if (!pinned.isFile() || pinned.size > maxBytes) return null;\n const buffer = Buffer.alloc(maxBytes + 1);\n let filled = 0;\n while (filled < buffer.length) {\n const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);\n if (bytesRead === 0) break;\n filled += bytesRead;\n }\n if (filled > maxBytes) return null;\n // The metadata comes from this `fstat`, not from a separate `stat` on the\n // pathname. Two operations could land on two inodes: content read from a\n // replacement that somebody made `0600` for a reason, restored under the\n // `0644` the old entry carried, and readable by everyone.\n return {\n content: Buffer.from(buffer.subarray(0, filled)),\n mode: pinned.mode & 0o7777,\n uid: pinned.uid,\n gid: pinned.gid,\n dev: pinned.dev,\n ino: pinned.ino,\n };\n } catch (error: unknown) {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n if (code === \"ENXIO\" || code === \"EISDIR\") return null;\n throw error;\n } finally {\n await handle?.close();\n }\n}\n\n/**\n * Read-only, non-blocking where the platform defines it.\n *\n * Opening a FIFO for reading blocks until a writer appears, and the point of a\n * size check is not to be at the mercy of what is at the path. Windows has no\n * `O_NONBLOCK`, and no FIFOs in this sense either.\n */\nconst OPEN_READ_FLAGS =\n typeof constants.O_NONBLOCK === \"number\"\n ? constants.O_RDONLY | constants.O_NONBLOCK\n : constants.O_RDONLY;\n\n/** Message text for an unknown thrown value, without `[object Object]`. */\nexport function describeError(err: unknown): string {\n return err instanceof Error ? err.message : JSON.stringify(err);\n}\n\nexport function isEpermOnWindows(err: unknown, platform = process.platform): boolean {\n return (\n platform === \"win32\" &&\n typeof err === \"object\" &&\n err !== null &&\n \"code\" in err &&\n (err as { code: string }).code === \"EPERM\"\n );\n}\n\nexport async function safeLstat(target: string): Promise<Stats | undefined> {\n try {\n return await lstat(target);\n } catch {\n return undefined;\n }\n}\n\nasync function safeStat(target: string): Promise<Stats | undefined> {\n try {\n return await stat(target);\n } catch {\n return undefined;\n }\n}\n\n/**\n * A path component init must not write through, relative to the project, and\n * whether it is a symlink (a junction included) or not a directory.\n */\nexport type UnsafeComponent = { readonly relativePath: string; readonly symlink: boolean };\n\n/**\n * The first component of `relativeDir` under `destRoot` that must not be\n * written through, or `undefined` when the whole chain is safe.\n *\n * `.codex/agents` is a path an untrusted repository controls, and a directory\n * component of it can be a symlink out of the tree — a checked-in\n * `.codex/agents -> /home/user/.config` is enough. `mkdir` follows it,\n * `writeFile` follows it, and `removeSymlinkAt` cannot see it: that guard\n * looks at the leaf `<name>.toml` only. A plain `qfai init` would then write\n * every profile into that external directory, and `--force` would let it\n * delete the orphan profiles there. So every component is `lstat`-ed before\n * anything is written or removed, and one link anywhere in the chain skips the\n * step whole rather than writing part of it somewhere unexpected.\n *\n * A component that does not exist yet ends the walk: `mkdir` creates real\n * directories, and nothing below an absent parent can exist either.\n *\n * The answer names the component by its path relative to `destRoot`. An\n * absolute path carries the destination directory's own name, which on an\n * untrusted repository can hold a newline or an ANSI escape.\n */\nexport async function findUnsafeWrapperComponent(\n destRoot: string,\n relativeDir: string,\n): Promise<UnsafeComponent | undefined> {\n const segments = relativeDir.split(\"/\");\n for (let depth = 1; depth <= segments.length; depth += 1) {\n const relativePath = segments.slice(0, depth).join(\"/\");\n const stats = await safeLstat(path.join(destRoot, ...segments.slice(0, depth)));\n if (stats === undefined) {\n return undefined;\n }\n if (stats.isSymbolicLink()) {\n return { relativePath, symlink: true };\n }\n if (!stats.isDirectory()) {\n return { relativePath, symlink: false };\n }\n }\n return undefined;\n}\n\n/**\n * The first component of `relativeDir` under `destRoot` that `mkdir` cannot\n * pass: a symbolic link whose target is missing or is not a directory, or an\n * entry that is not a directory. A link to a directory that exists is passed,\n * because the instruction files are written through a shared directory on\n * purpose. `undefined` when the directory can be created or already exists.\n */\nexport async function findUnreachableHostDirComponent(\n destRoot: string,\n relativeDir: string,\n): Promise<UnsafeComponent | undefined> {\n const segments = relativeDir.split(\"/\");\n for (let depth = 1; depth <= segments.length; depth += 1) {\n const relativePath = segments.slice(0, depth).join(\"/\");\n const absolute = path.join(destRoot, ...segments.slice(0, depth));\n const stats = await safeLstat(absolute);\n if (stats === undefined) {\n return undefined;\n }\n if (stats.isSymbolicLink()) {\n if ((await safeStat(absolute))?.isDirectory() !== true) {\n return { relativePath, symlink: true };\n }\n } else if (!stats.isDirectory()) {\n return { relativePath, symlink: false };\n }\n }\n return undefined;\n}\n\n/**\n * The component that keeps a file init writes into a host directory, such as\n * a hook file or `.github/copilot-instructions.md`, from being read or\n * written: a directory on its path that is a symbolic link or not a directory,\n * or the file itself when it is a symbolic link, whether its target exists or\n * not. `undefined` when the path is safe.\n */\nexport async function findUnsafeHostFileComponent(\n destRoot: string,\n segments: readonly string[],\n): Promise<UnsafeComponent | undefined> {\n const parent = segments.slice(0, -1).join(\"/\");\n const unsafeParent =\n parent === \"\" ? undefined : await findUnsafeWrapperComponent(destRoot, parent);\n if (unsafeParent !== undefined) {\n return unsafeParent;\n }\n const leaf = await safeLstat(path.join(destRoot, ...segments));\n return leaf?.isSymbolicLink() === true\n ? { relativePath: segments.join(\"/\"), symlink: true }\n : undefined;\n}\n","/**\n * Shared errno helpers for Node.js fs error narrowing.\n *\n * Avoids ad-hoc `(err as { code?: string }).code === \"ENOENT\"` repetition\n * across init / config / prototyping commands. Future errno codes\n * (`EACCES`, `EBUSY`, `EPERM`, ...) extend this module rather than\n * sprouting new inline checks.\n */\n\n/**\n * True iff `err` is a Node.js fs error whose `code` is `\"ENOENT\"`\n * (file or directory does not exist).\n */\nexport function isEnoent(err: unknown): boolean {\n return hasErrnoCode(err) && err.code === \"ENOENT\";\n}\n\n/**\n * True iff `err` is a Node.js fs error whose `code` is `\"EPERM\"`.\n *\n * On Windows this is what `stat` raises for a **file** symlink whose target is\n * a directory: the link is intact and `readlink` returns the right target, but\n * the reparse tag is the wrong kind and the OS refuses to follow it. `git\n * worktree add` produces exactly that for `.claude/skills/*`, because at the\n * moment git writes the link its target does not yet exist in the new worktree\n * and it has no reftype hint. So a reader that treats EPERM as a filesystem\n * fault to propagate crashes on a condition that is structural damage to the\n * path it is inspecting.\n */\nexport function isEperm(err: unknown): boolean {\n return hasErrnoCode(err) && err.code === \"EPERM\";\n}\n\n/**\n * True iff `err` is a Node.js error-shaped object carrying a string\n * `code` (e.g. `\"ENOENT\"`, `\"EACCES\"`, `\"ENOSPC\"`). Narrowing helper\n * shared across the codebase so individual call sites do not sprout\n * ad-hoc `(err as { code?: string }).code` casts (CLAUDE.md\n * \"avoid bare `as` type assertions; prefer type narrowing\").\n */\nexport function hasErrnoCode(err: unknown): err is { code: string } {\n return (\n err !== null &&\n typeof err === \"object\" &&\n \"code\" in err &&\n typeof (err as { code?: unknown }).code === \"string\"\n );\n}\n","import path from \"node:path\";\n\nexport type GraphHookHost = \"claude\" | \"codex\" | \"copilot\" | \"vscode\";\n\nexport interface GraphHookEvent {\n tool: string;\n command?: string;\n path?: string;\n session?: string;\n cwd?: string;\n workdir?: string;\n shell?: string;\n}\n\nexport interface GraphHookDecision {\n decision: \"allow\" | \"deny\";\n state: \"configured\" | \"failed\" | \"outside-boundary\";\n message: string;\n operation?: string;\n target?: string;\n domain?: \"code\" | \"documents\";\n exceptionEligible?: boolean;\n fallbackUnavailable?: true;\n}\n\ntype GraphSearchAuthorization = (decision: GraphHookDecision) => GraphHookDecision;\ntype GraphShell = \"posix\" | \"powershell\" | \"cmd\";\n\n/**\n * One command of a shell event; `upstream` is the pipeline stage whose output it reads,\n * and `join` the operator that joins it to the command before it.\n */\ninterface ShellCommand {\n words: string[];\n upstream?: ShellCommand;\n join?: ShellOperator;\n}\n\ntype ShellOperator = \"&&\" | \"||\" | \"|\" | \";\" | \"&\" | \"\\n\";\n\n/**\n * Where the shell stands when a command runs: the observed directory, a directory\n * inside it reached by an unconditional `cd` chain, or a place the text cannot tell.\n */\ntype ShellLocation = \"observed\" | \"unknown\" | { directory: string };\n\ninterface ShellScope {\n authorize: GraphSearchAuthorization;\n shell: GraphShell;\n directory?: string;\n}\n\ninterface CommandContext extends ShellScope {\n location: ShellLocation;\n redefined: boolean;\n}\n\nexport function classifyGraphExploration(\n event: GraphHookEvent,\n authorize: GraphSearchAuthorization = (decision) => decision,\n): GraphHookDecision {\n if (event.tool === \"write_stdin\") return outsideBoundary();\n if (\n [\"rg\", \"grep\", \"grep_search\", \"search_files\", \"file_search\"].includes(event.tool.toLowerCase())\n ) {\n return authorize(denyExploration(event.tool, event.path ?? \".\"));\n }\n const shell: GraphShell =\n /(?:^|[\\\\/])(?:pwsh|powershell)(?:\\.exe)?$/i.test(event.shell ?? \"\") ||\n event.tool.toLowerCase() === \"powershell\" ||\n (event.tool === \"exec_command\" && !event.shell && process.platform === \"win32\")\n ? \"powershell\"\n : /(?:^|[\\\\/])cmd(?:\\.exe)?$/i.test(event.shell ?? \"\")\n ? \"cmd\"\n : \"posix\";\n const directory = event.cwd ? path.resolve(event.cwd, event.workdir ?? \".\") : undefined;\n return (\n classifyShellText(\n event.command ?? \"\",\n { authorize, shell, ...(directory ? { directory } : {}) },\n 0,\n false,\n \"observed\",\n ) ?? {\n decision: \"allow\",\n state: \"configured\",\n message: \"No direct exploration was classified.\",\n }\n );\n}\n\n/** Classify one shell command line, including the command lists its substitutions run. */\nfunction classifyShellText(\n text: string,\n scope: ShellScope,\n depth: number,\n redefinedOutside: boolean,\n start: ShellLocation,\n substitution = false,\n): GraphHookDecision | undefined {\n if (depth > 16) return failedGraphHook(\"depth\");\n // Nested text, such as a `bash -c` argument or a substitution body, skips no\n // here-document body: what reads its output lies outside it.\n // A here-string is read as one string first, so a comment marker or a quote in its text is\n // data to the comment reader too.\n const source =\n scope.shell === \"powershell\"\n ? withoutPowerShellComments(powershellHereStrings(powerShellLines(text)))\n : text;\n const commands =\n source === undefined ? undefined : shellPipelines(source, scope.shell, depth > 0);\n // Text in a substitution that cannot be read as commands is no verdict of its own.\n if (source === undefined || !commands) {\n return substitution ? undefined : failedGraphHook(\"quote\");\n }\n const bodies = substitutionBodies(source, scope.shell, depth > 0);\n // A substitution whose end the scan cannot find may still run in the shell, which reads\n // comments the scan does not, so the command is denied rather than its body dropped.\n // SIMPLIFIED: this denies a valid command whose substitution holds an unmatched\n // parenthesis, or a comment after an untracked context (`inUntrackedContext`) with a quote\n // or a parenthesis. Lift when: those contexts are tracked as the quotes are.\n if (!bodies) return failedGraphHook(\"substitution\");\n return classifyCommands(\n commands,\n scope,\n depth,\n redefinedOutside,\n start,\n bodies.map(\n (body) => (location: ShellLocation, redefines: boolean) =>\n classifyShellText(body, scope, depth + 1, redefines, location, true),\n ),\n );\n}\n\n/**\n * PowerShell text with each here-string read as a plain string. The body of `@'...'@` is\n * literal, so it becomes `''`; a quote inside it, such as the apostrophe in `It's`, no longer\n * ends a string early. The body of `@\"...\"@` still expands `$(...)`, so it stays inside double\n * quotes with its own double quotes removed.\n */\nfunction powershellHereStrings(text: string): string {\n let output = \"\";\n let quote: string | undefined;\n for (let index = 0; index < text.length; index += 1) {\n const character = text[index] ?? \"\";\n if (character === \"`\" && quote !== \"'\") {\n output += character + (text[index + 1] ?? \"\");\n index += 1;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n output += character;\n continue;\n }\n // Only an `@'` or `@\"` outside a string opens one, and whichever opens first is the string.\n hereString.lastIndex = index;\n const match = character === \"@\" ? hereString.exec(text) : null;\n if (match) {\n output += match[1] === \"'\" ? \"''\" : `\"${(match[2] ?? \"\").replace(/\"/g, \"\")}\"`;\n index = hereString.lastIndex - 1;\n continue;\n }\n if (character === \"'\" || character === '\"') quote = character;\n output += character;\n }\n return output;\n}\n\n/** A PowerShell here-string: `@'` or `@\"` at a line end, closed by `'@` or `\"@` at a line start. */\nconst hereString = /@(['\"])[ \\t]*\\r?\\n([\\s\\S]*?)\\r?\\n\\1@/y;\n\ntype NestedClassification = (\n location: ShellLocation,\n redefined: boolean,\n) => GraphHookDecision | undefined;\n\nfunction classifyCommands(\n commands: ShellCommand[],\n scope: ShellScope,\n depth: number,\n redefinedOutside: boolean,\n start: ShellLocation,\n substitutions: NestedClassification[] = [],\n): GraphHookDecision | undefined {\n const redefined =\n redefinedOutside || commands.some((command) => redefinesCommands(command.words));\n // A substitution runs its own command list, so a search inside one is a search.\n // Only its denial counts here: what else it runs keeps the outer verdict. Which\n // command holds it is not tracked, so it runs from the start only while no command\n // in the list moves the shell anywhere else.\n const stays = commands.every((command) => {\n const operand = directoryOperand(command.words);\n if (operand === undefined) return true;\n return (\n !redefined &&\n operand !== null &&\n start === \"observed\" &&\n scope.directory !== undefined &&\n path.resolve(scope.directory, operand) === scope.directory\n );\n });\n for (const classify of substitutions) {\n const decision = classify(stays ? start : \"unknown\", redefined);\n if (decision?.decision === \"deny\") return decision;\n }\n let location = start;\n let boundary: GraphHookDecision | undefined;\n let allowed: GraphHookDecision | undefined;\n // Inside a `case`, a command that starts with a word ending in `)`, such as `y)`\n // or `\"a b\")`, is an arm: its pattern is not a command.\n let openCases = 0;\n for (const [index, command] of commands.entries()) {\n const words =\n openCases > 0 && command.words[0]?.endsWith(\")\") ? command.words.slice(1) : command.words;\n if (words[0] === \"case\") openCases += 1;\n else if (words[0] === \"esac\") openCases = Math.max(0, openCases - 1);\n // After a move, only an `&&` chain, or a pipeline inside one, runs where the move went:\n // `||`, `;`, `&` and a new line also run when the move failed.\n if (typeof location === \"object\" && index > 0 && command.join !== \"&&\" && command.join !== \"|\")\n location = \"unknown\";\n const operand = directoryOperand(words);\n if (operand !== undefined) {\n location = redefined\n ? \"unknown\"\n : movedLocation(location, operand, command, commands[index + 1], scope);\n }\n // A group reads the pipe before it only when its `}` redirects nothing: in\n // `git log | { grep fix; } < .env` the group reads `.env`.\n const upstream =\n words[0] === \"{\" && !groupClosesBare(commands, index) ? undefined : command.upstream;\n const decision = classifyCommand(words, { ...scope, location, redefined }, depth, upstream);\n if (decision?.decision === \"deny\") return decision;\n if (decision?.state === \"outside-boundary\") boundary = decision;\n else if (decision) allowed = decision;\n }\n return boundary ?? allowed;\n}\n\n/**\n * Whether a command defines a function or alias, or sets a variable a later\n * command may read, so a name in the same event may not run the program it names.\n */\nfunction redefinesCommands(words: string[]): boolean {\n const body = arithmeticForBody(words);\n if (body) return redefinesCommands(body);\n let offset = 0;\n for (;;) {\n const redirection = redirectionLength(words[offset]);\n if (redirection) offset += redirection;\n // A group's `{` defines nothing itself; the command it opens is read instead.\n else if (words[offset] === \"{\") offset += 1;\n else if ([\"builtin\", \"command\", \"env\"].includes(words[offset]?.toLowerCase() ?? \"\")) {\n offset += 1;\n while (words[offset]?.startsWith(\"-\")) {\n offset += /^-[uCS]$|^--(?:unset|chdir|split-string)$/.test(words[offset] ?? \"\") ? 2 : 1;\n }\n } else break;\n }\n const first = words[offset] ?? \"\";\n return (\n words.some((word) => word.includes(\"()\") || /^\\{[A-Za-z_][A-Za-z0-9_]*\\}[<>]/.test(word)) ||\n /^(?:[A-Za-z_][A-Za-z0-9_]*=|\\$|\\{\\w*\\}?[<>]?$|\\{\\w+\\}[<>])/.test(first) ||\n (first === \"printf\" && words.includes(\"-v\")) ||\n [\n \"time\",\n \"!\",\n \"if\",\n \"then\",\n \"do\",\n \"else\",\n \"elif\",\n \"while\",\n \"until\",\n \"case\",\n \"coproc\",\n \"read\",\n \"mapfile\",\n \"readarray\",\n \"getopts\",\n ].includes(first) ||\n [\n \"function\",\n \"alias\",\n \"export\",\n \"declare\",\n \"typeset\",\n \"readonly\",\n \"set\",\n \"setx\",\n \"set-alias\",\n \"new-alias\",\n \"sal\",\n \"nal\",\n \"set-item\",\n \"si\",\n \"set-variable\",\n \"sv\",\n \"filter\",\n \"new-item\",\n \"ni\",\n \"iex\",\n \"invoke-expression\",\n \"eval\",\n \"source\",\n \".\",\n \"hash\",\n ].includes(words[offset] === \".\" ? \".\" : (commandName(words.slice(offset)) ?? \"\"))\n );\n}\n\n/** A redirection's descriptor: a number, `&`, or a `{name}` the shell assigns a new one to. */\nconst redirectionSource = String.raw`(?:\\d*|&|\\{[A-Za-z_][A-Za-z0-9_]*\\})`;\nconst redirectionStart = new RegExp(String.raw`^${redirectionSource}(?:<|>)`);\nconst detachedRedirection = new RegExp(String.raw`^${redirectionSource}(?:<>|>{1,2}|<{1,3})[&|]?$`);\n\n/** How many words a leading redirection takes: one when its target is attached, else two. */\nfunction redirectionLength(word: string | undefined): number {\n if (!word || !redirectionStart.test(word)) return 0;\n return detachedRedirection.test(word) ? 2 : 1;\n}\n\n/**\n * The target of a command that changes the shell's directory: `undefined` when the\n * command changes none, `null` when its target cannot be read from the text. A `..`\n * segment is unreadable: the shell may resolve it from a CDPATH entry or through a\n * symbolic link, not lexically. `popd` returns to a directory the text does not name,\n * a `+N` operand rotates the directory stack, and a colon other than a drive letter's\n * names a PowerShell provider drive such as `env:`, not a folder.\n */\n/** Whether the `{` group opened at `index` closes with a bare `}`, which redirects nothing. */\nfunction groupClosesBare(commands: ShellCommand[], index: number): boolean {\n let depth = 0;\n for (const { words } of commands.slice(index)) {\n const opened = words.findIndex((word) => word !== \"{\");\n depth += opened < 0 ? words.length : opened;\n if (words[0]?.startsWith(\"}\")) {\n depth -= 1;\n if (depth <= 0) return words.length === 1 && words[0] === \"}\";\n }\n }\n return false;\n}\n\nfunction directoryOperand(words: string[]): string | null | undefined {\n let offset = 0;\n while (offset < words.length) {\n // `if cd /tmp` and `{ cd /tmp` move as `cd /tmp` does.\n if (\n /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? \"\") ||\n words[offset] === \"{\" ||\n COMPOUND_KEYWORDS.includes(words[offset] ?? \"\")\n ) {\n offset += 1;\n continue;\n }\n if (![\"command\", \"builtin\", \"env\"].includes(words[offset]?.toLowerCase() ?? \"\")) break;\n offset += 1;\n if (words[offset] === \"-v\" || words[offset] === \"-V\") return undefined;\n while (words[offset]?.startsWith(\"-\")) offset += 1;\n }\n const name = words[offset]?.toLowerCase() ?? \"\";\n if (![\"cd\", \"chdir\", \"pushd\", \"popd\", \"set-location\", \"sl\"].includes(name)) return undefined;\n const operands = words.slice(offset + 1);\n const target = operands[0];\n return name === \"popd\" ||\n operands.length !== 1 ||\n target === undefined ||\n target.startsWith(\"-\") ||\n target.startsWith(\"+\") ||\n (target.includes(\":\") && !/^[A-Za-z]:[\\\\/]/.test(target)) ||\n /[$`~%*?[\\]{}]/.test(target) ||\n target.split(/[\\\\/]/).includes(\"..\")\n ? null\n : target;\n}\n\n/**\n * Where the shell stands after a directory command. A move to the observed directory\n * itself changes nothing, whatever joins it. A move into a directory inside it is\n * followed only while the move runs unconditionally before what comes next: it is\n * not a pipeline stage, which runs in a subshell, no `||` joins it to the command\n * before it, which may skip it, and an `&&` joins it to the next command. Any other\n * move, or one whose target cannot be read, leaves the location unknown.\n *\n * A relative POSIX target that does not start with `.` is resolved from CDPATH when\n * that is set, so such a move is followed only while CDPATH is unset. Ceiling: the\n * hook reads its own environment, so a CDPATH that only the agent's shell sets is\n * not seen. Lift when a host reports the shell environment in the pre-tool event.\n */\nfunction movedLocation(\n location: ShellLocation,\n operand: string | null,\n command: ShellCommand,\n next: ShellCommand | undefined,\n scope: ShellScope,\n): ShellLocation {\n if (location === \"unknown\" || operand === null || !scope.directory) return \"unknown\";\n const from = location === \"observed\" ? scope.directory : location.directory;\n const directory = path.resolve(from, operand);\n if (location === \"observed\" && directory === scope.directory) return \"observed\";\n if (outside(scope.directory, directory)) return \"unknown\";\n if (command.join === \"|\" || command.join === \"||\" || (next !== undefined && next.join !== \"&&\"))\n return \"unknown\";\n if (\n scope.shell === \"posix\" &&\n !path.isAbsolute(operand) &&\n !operand.startsWith(\".\") &&\n process.env.CDPATH\n )\n return \"unknown\";\n return { directory };\n}\n\nfunction outside(root: string, target: string): boolean {\n const relative = path.relative(root, target);\n return relative === \"..\" || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);\n}\n\n/**\n * Hands a denied search to the fallback authorization from where the shell stands.\n * After a followed move, the search target is rebased to the project-relative path\n * it names, so the grant matches the scope the search actually reads. A `..` segment\n * is not rebased: through a symbolic link it resolves from the link's real location.\n */\nfunction authorizeAt(context: CommandContext, decision: GraphHookDecision): GraphHookDecision {\n const { location, directory, authorize } = context;\n if (location === \"observed\") return authorize(decision);\n if (location === \"unknown\" || !directory)\n return graphFallbackUnavailable(\n decision,\n \"The command changes its working directory.\",\n \"Run a single search from this project worktree, then retry the denied action.\",\n );\n if (!decision.exceptionEligible || decision.target === undefined || !decision.operation)\n return authorize(decision);\n if (decision.target.split(/[\\\\/]/).includes(\"..\"))\n return graphFallbackUnavailable(\n decision,\n \"The search target has a .. segment after a directory change.\",\n \"Run a single search from this project worktree, then retry the denied action.\",\n );\n const target = path.resolve(location.directory, decision.target);\n if (outside(directory, target))\n return graphFallbackUnavailable(\n decision,\n \"The search target resolves outside this project worktree.\",\n \"Run a single search with one explicit project-relative target, then retry the denied action.\",\n );\n const relative = path.relative(directory, target).split(path.sep).join(\"/\") || \".\";\n return authorize({ ...denyExploration(decision.operation, relative), exceptionEligible: true });\n}\n\n/** POSIX words that start a compound command or one of its parts, followed by a command. */\nconst COMPOUND_KEYWORDS: readonly string[] = [\n \"if\",\n \"then\",\n \"elif\",\n \"else\",\n \"while\",\n \"until\",\n \"do\",\n \"!\",\n \"time\",\n];\n\n/**\n * The loop body after the last part of a `for ((...))` header. The tokenizer splits the\n * header at its `;`, so its last part is a command whose words hold the closing `))`,\n * alone (`i++ ))`), at the end of a word (`i++))`) or before an unspaced `{` (`)){`).\n * Parentheses inside that part, as in `i+=$((1))`, are balanced, so the closing `))` is\n * the one that takes the count of `(` minus `)` to -2. The words after it, a `{ ...; }`\n * group or `do ...`, run as the loop body. Unquoted, a `)` that no `(` in the command\n * opened is a syntax error outside such a header, so no runnable command matches.\n * Ceiling: the tokenizer drops quotes, so `echo \"a))\" do rg ...` is read as a header and\n * denied. Keeping quote marks on words lifts this.\n */\nfunction arithmeticForBody(words: string[]): string[] | undefined {\n let depth = 0;\n for (const [index, word] of words.entries()) {\n for (let offset = 0; offset < word.length; offset += 1) {\n if (word[offset] === \"(\") depth += 1;\n else if (word[offset] === \")\") depth -= 1;\n if (depth > -2) continue;\n if (word[offset - 1] !== \")\") return undefined;\n const rest = word.slice(offset + 1);\n const body = rest === \"\" ? words.slice(index + 1) : [rest, ...words.slice(index + 1)];\n return body[0] === \"{\" || body[0] === \"do\" ? body : undefined;\n }\n }\n return undefined;\n}\n\nfunction classifyCommand(\n words: string[],\n context: CommandContext,\n depth: number,\n upstream?: ShellCommand,\n): GraphHookDecision | undefined {\n const { redefined } = context;\n if (depth > 16) return failedGraphHook(\"depth\");\n let offset = 0;\n while (offset < words.length) {\n const redirection = redirectionLength(words[offset]);\n if (redirection) offset += redirection;\n else if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? \"\")) offset += 1;\n else break;\n }\n if (offset > 0) {\n return classifyCommand(words.slice(offset), context, depth + 1);\n }\n const operation = commandName(words);\n // A compound-command keyword runs the command after it: `if grep ...`, `then grep ...`,\n // `do grep ...`, `! grep ...`, `time -p grep ...`. `fi` and `done` run nothing.\n if (COMPOUND_KEYWORDS.includes(words[0] ?? \"\")) {\n const skip = words[0] === \"time\" && words[1] === \"-p\" ? 2 : 1;\n return classifyCommand(words.slice(skip), context, depth + 1);\n }\n if (words[0] === \"fi\" || words[0] === \"done\") return undefined;\n const body = arithmeticForBody(words);\n if (body) return classifyCommand(body, context, depth + 1);\n // A `{ ...; }` group and a `case` command's first arm run the command after their\n // opening words. `classifyCommands` strips the pattern of each later arm. A group\n // keeps the pipeline stage before it, so `git log | { grep fix; }` is a filter.\n if (operation === \"{\") {\n return classifyCommand(words.slice(1), context, depth + 1, upstream);\n }\n if (operation === \"case\") {\n const subject = words.indexOf(\"in\");\n const arm = words.findIndex((word, index) => index > subject && word.endsWith(\")\"));\n return arm < 0 ? undefined : classifyCommand(words.slice(arm + 1), context, depth + 1);\n }\n if (operation === \"}\" || operation === \"esac\") return undefined;\n if (operation === \"env\" || operation === \"command\" || operation === \"builtin\") {\n let offset = 1;\n while (offset < words.length) {\n const redirection = redirectionLength(words[offset]);\n if (redirection) offset += redirection;\n else if (\n words[offset]?.startsWith(\"-\") ||\n /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? \"\")\n )\n offset += 1;\n else break;\n }\n return classifyCommand(words.slice(offset), context, depth + 1);\n }\n if ([\"bash\", \"sh\", \"zsh\", \"pwsh\", \"powershell\", \"cmd\"].includes(operation ?? \"\")) {\n const switchIndex = words.findIndex((word) => /^(?:-[a-z]*c|\\/c|-command)$/i.test(word));\n const inner = switchIndex >= 0 ? words[switchIndex + 1] : undefined;\n if (!inner) return outsideBoundary();\n const shell =\n operation === \"pwsh\" || operation === \"powershell\"\n ? \"powershell\"\n : operation === \"cmd\"\n ? \"cmd\"\n : \"posix\";\n return classifyShellText(\n inner,\n {\n authorize: context.authorize,\n shell,\n ...(context.directory ? { directory: context.directory } : {}),\n },\n depth + 1,\n redefined,\n context.location,\n );\n }\n if (!redefined && pipeFilter(words) && printsText(upstream)) return undefined;\n if (operation === \"rg\" || operation === \"grep\" || operation === \"findstr\") {\n let offset = 1;\n while (\n /^(?:-[RrinlIHsvwxcFoq]+|--(?:hidden|line-number|ignore-case|fixed-strings|recursive)|\\/[SIMOPVNLR]+)$/i.test(\n words[offset] ?? \"\",\n )\n )\n offset += 1;\n if (words[offset] === \"--\") offset += 1;\n const positional = words.slice(offset);\n const eligible =\n positional.length > 0 &&\n positional.length <= 2 &&\n !positional.some((word) => word.startsWith(\"-\") || /[$%`<>]/.test(word));\n const target = eligible ? (positional[1] ?? \".\") : JSON.stringify(positional);\n return authorizeAt(context, {\n ...denyExploration(operation, target),\n exceptionEligible: eligible,\n });\n }\n let gitCommand = 1;\n if (operation === \"git\") {\n while (words[gitCommand]?.startsWith(\"-\")) {\n const option = words[gitCommand];\n gitCommand += [\"-C\", \"-c\", \"--git-dir\", \"--work-tree\"].includes(option ?? \"\") ? 2 : 1;\n }\n }\n if (operation === \"git\" && words[gitCommand]?.toLowerCase() === \"grep\") {\n const paths = words.indexOf(\"--\");\n const targets = paths >= 0 ? words.slice(paths + 1) : [];\n const eligible =\n gitCommand === 1 &&\n targets.length <= 1 &&\n (paths >= 0 || words.length === 3) &&\n !targets.some((word) => /[$%`<>]/.test(word));\n return authorizeAt(context, {\n ...denyExploration(\n \"git grep\",\n eligible ? (targets[0] ?? \".\") : JSON.stringify(words.slice(1)),\n ),\n exceptionEligible: eligible,\n });\n }\n if (operation === \"select-string\") {\n const path = words.findIndex((word) => /^-(?:literalpath|path)$/i.test(word));\n const targets: string[] = [];\n for (let offset = path + 1; path >= 0 && offset < words.length; offset += 1) {\n const word = words[offset];\n if (word === undefined || word.startsWith(\"-\")) break;\n targets.push(word);\n }\n const eligible = targets.length === 1 && !targets.some((word) => /[,$%`<>]/.test(word));\n return authorizeAt(context, {\n ...denyExploration(\"Select-String\", eligible ? (targets[0] ?? \".\") : JSON.stringify(targets)),\n exceptionEligible: eligible,\n });\n }\n if (\n !operation ||\n [\n \"echo\",\n \"printf\",\n \"write-output\",\n \"cat\",\n \"get-content\",\n \"pnpm\",\n \"npm\",\n \"npx\",\n \"corepack\",\n \"node\",\n \"nodejs\",\n \"python\",\n \"python3\",\n \"uv\",\n \"git\",\n \"pwd\",\n \"get-location\",\n \"ls\",\n \"dir\",\n \"sort\",\n ].includes(operation)\n ) {\n return undefined;\n }\n return outsideBoundary();\n}\n\nfunction commandName(words: string[]): string | undefined {\n return words[0]\n ?.split(/[\\\\/]/)\n .at(-1)\n ?.replace(/\\.exe$/i, \"\")\n .toLowerCase();\n}\n\n/** A word the shell may expand or redirect, so what the command reads cannot be told from the text. */\nfunction unparsedWord(word: string): boolean {\n return /\\$(?!$)|[`<>]|%[^%\\s]+%/.test(word);\n}\n\n/**\n * Whether a pipeline stage prints only text that is not project file contents:\n * git, a package-manager command, a literal echo, or a sort or filter of such text.\n * Every other stage, including cat, Get-Content and Get-ChildItem, may hand the\n * next stage project files or their contents, so a search over it stays denied.\n */\nfunction printsText(command: ShellCommand | undefined): boolean {\n if (\n !command ||\n command.words.some(\n (word) =>\n /[(){}@]/.test(word) || (unparsedWord(word) && !/^\\d*>(?:&\\d|\\/dev\\/null)$/.test(word)),\n )\n )\n return false;\n const name = /[\\\\/=]/.test(command.words[0] ?? \"\") ? \"\" : (commandName(command.words) ?? \"\");\n const args = command.words.slice(1);\n if (name === \"git\") {\n return (\n gitTextCommands.has(args[0] ?? \"\") &&\n !args.some(\n (word) =>\n word === \"--no-index\" ||\n /^(?:\\/|[A-Za-z]:|\\\\|~|:\\/)|(?:^|[\\\\/:])\\.\\.(?:[\\\\/]|$)/.test(word),\n )\n );\n }\n if ([\"echo\", \"printf\", \"write-output\"].includes(name))\n return !args.some((word) => /[*?[!]/.test(word));\n if (name === \"pnpm\" || name === \"npm\") return packageTextCommands.has(args[0] ?? \"\");\n if (name === \"corepack\") {\n return [\"pnpm\", \"npm\"].includes(args[0] ?? \"\") && packageTextCommands.has(args[1] ?? \"\");\n }\n if (name === \"sort\" || name === \"uniq\") {\n const switches = name === \"sort\" ? /^-[rnufbdhMV]+$/ : /^-[cdiu]+$/;\n return args.every((word) => switches.test(word)) && printsText(command.upstream);\n }\n return pipeFilter(command.words) && printsText(command.upstream);\n}\n\n/** git subcommands that print names, status, history or differences, never a whole file. */\nconst gitTextCommands = new Set([\n \"status\",\n \"ls-files\",\n \"ls-tree\",\n \"log\",\n \"diff\",\n \"branch\",\n \"remote\",\n \"rev-list\",\n \"rev-parse\",\n \"shortlog\",\n \"worktree\",\n]);\n\n/** Package-manager commands whose own output is text; exec, dlx and unknown commands run binaries. */\nconst packageTextCommands = new Set([\n \"test\",\n \"t\",\n \"lint\",\n \"build\",\n \"typecheck\",\n \"check-types\",\n \"ls\",\n \"list\",\n \"why\",\n \"outdated\",\n \"audit\",\n \"install\",\n \"i\",\n \"ci\",\n \"view\",\n \"info\",\n]);\n\nconst grepSwitches = /^-[ivncowxEFGPqsHhIyzZLlbUa]+$/;\nconst rgSwitches = /^-[ivncowxFsSqaUNHlLIP]+$/;\nconst longSwitches = new Set([\n \"--ignore-case\",\n \"--invert-match\",\n \"--line-number\",\n \"--count\",\n \"--only-matching\",\n \"--word-regexp\",\n \"--line-regexp\",\n \"--extended-regexp\",\n \"--fixed-strings\",\n \"--perl-regexp\",\n \"--quiet\",\n \"--silent\",\n \"--no-filename\",\n \"--with-filename\",\n \"--smart-case\",\n \"--case-sensitive\",\n]);\nconst valueOptions = /^(?:-[emABC]|--(?:regexp|max-count|context|after-context|before-context))$/;\nconst attachedValueOptions =\n /^(?:-e.+|-[mABC]\\d+|--(?:regexp|max-count|context|after-context|before-context|color|colour)=.+)$/;\n\n/**\n * Whether a grep, rg, findstr or Select-String stage has a shape known to read\n * only its standard input: known options and a pattern, and no file operand.\n * Any other word, such as an unknown or abbreviated option, keeps it a search.\n */\nfunction pipeFilter(words: string[]): boolean {\n if (/[\\\\/=]/.test(words[0] ?? \"\")) return false;\n const name = commandName(words);\n const args = words.slice(1);\n if (args.some((word) => unparsedWord(word) || /[*?[\\]{}()~@!]/.test(word))) return false;\n if (name === \"findstr\") return findstrFilter(args);\n if (name === \"select-string\") return selectStringFilter(args);\n if (name !== \"grep\" && name !== \"rg\") return false;\n let patternGiven = false;\n const operands: string[] = [];\n for (let index = 0; index < args.length; index += 1) {\n const word = args[index] ?? \"\";\n if (word === \"--\") {\n operands.push(...args.slice(index + 1));\n break;\n }\n if (!word.startsWith(\"-\") || word === \"-\") operands.push(word);\n else if (valueOptions.test(word)) {\n if (word === \"-e\" || word === \"--regexp\") patternGiven = true;\n index += 1;\n if (index >= args.length) return false;\n } else if (attachedValueOptions.test(word)) {\n if (/^(?:-e|--regexp=)/.test(word)) patternGiven = true;\n } else if (!(name === \"grep\" ? grepSwitches : rgSwitches).test(word) && !longSwitches.has(word))\n return false;\n }\n const files = patternGiven ? operands : operands.slice(1);\n return (patternGiven || operands.length > 0) && files.every((word) => word === \"-\");\n}\n\nfunction findstrFilter(args: string[]): boolean {\n let patternGiven = false;\n const operands: string[] = [];\n for (const word of args) {\n if (/^\\/c:./i.test(word)) patternGiven = true;\n else if (word.startsWith(\"/\")) {\n if (!/^\\/[ivnxbelrmop]+$/i.test(word)) return false;\n } else if (word.startsWith(\"-\")) return false;\n else operands.push(word);\n }\n return operands.length === (patternGiven ? 0 : 1);\n}\n\n/** Select-String names a path by its second positional word, so only one is allowed. */\nfunction selectStringFilter(args: string[]): boolean {\n let patternGiven = false;\n let positional = 0;\n for (let index = 0; index < args.length; index += 1) {\n const word = args[index] ?? \"\";\n if (!word.startsWith(\"-\")) positional += 1;\n else if (/^-(?:pattern|context|encoding)$/i.test(word)) {\n if (/^-pattern$/i.test(word)) patternGiven = true;\n index += 1;\n if (index >= args.length) return false;\n } else if (\n !/^-(?:simplematch|casesensitive|notmatch|allmatches|list|quiet|raw|noemphasis)$/i.test(word)\n )\n return false;\n }\n return positional === (patternGiven ? 0 : 1);\n}\n\nfunction outsideBoundary(): GraphHookDecision {\n return {\n decision: \"allow\",\n state: \"outside-boundary\",\n message:\n \"Search inside scripts, aliases or continuing input is not verified by this pre-tool boundary.\",\n };\n}\n\n/**\n * PowerShell's built-in alias `sls` names Select-String. Only PowerShell resolves it:\n * elsewhere `sls` is another program, such as the Serverless Framework CLI.\n */\nfunction resolveAlias(words: string[], shell: GraphShell): string[] {\n return shell === \"powershell\" && words[0]?.toLowerCase() === \"sls\"\n ? [\"Select-String\", ...words.slice(1)]\n : words;\n}\n\n/**\n * A character after which a POSIX shell starts a new word. Only space, tab and newline are\n * blanks there: a carriage return, form feed or no-break space is part of the word, so a `#`\n * after one is not a comment.\n */\nconst WORD_BREAK = /[ \\t\\n;&|()]/;\n\n/**\n * Whether the `#` at `index`, read where no word has started yet, opens a comment. In a POSIX\n * shell an unquoted `#` at the start of a word runs to the end of its line, so a quote inside it\n * opens nothing and the next line is a command again. The caller must know no word is under way:\n * an escaped separator or a closed substitution before the `#` puts it inside a word.\n * PowerShell comments are removed before this reader runs: `withoutPowerShellComments`.\n * Ceiling: `cmd` has no comment inside a command line, so none is read there.\n */\nfunction startsComment(command: string, index: number, shell: GraphShell): boolean {\n if (shell !== \"posix\") return false;\n const previous = command[index - 1];\n return (\n (previous === undefined || WORD_BREAK.test(previous)) && !inUntrackedContext(command, index)\n );\n}\n\n/**\n * Whether the text before `index` may leave a context open that these readers do not track and\n * where the shell starts no comment or quotes differently: a backtick substitution, a `${...}`\n * expansion, a `((...))` or `$[...]` arithmetic, an ANSI-C `$'...'` string, whose `\\'` does not\n * close it, or an extended glob such as `@(...)`. A `#` after one is read as text, as it was\n * before comments were read, so a search after it is still classified.\n * Ceiling: any such opener earlier in the command turns comment reading off for the rest of it,\n * so a quote in a later comment there still fails closed as an unmatched quote. Tracking those\n * contexts as the quotes are tracked lifts this.\n */\nfunction inUntrackedContext(command: string, index: number): boolean {\n return /`|\\$\\{|\\$\\[|\\$'|\\(\\(|[?*+@!]\\(/.test(command.slice(0, index));\n}\n\n/**\n * The PowerShell text with each lone carriage return read as a line feed. PowerShell ends a\n * statement and a `#` line comment at either, while these readers split lines at `\\n` only.\n * Ceiling: the whole text is converted, quoted arguments too, so a carriage return inside a\n * `bash -c` argument, which Bash reads as an ordinary character, also splits there and may\n * deny more than Bash runs. Converting only outside quotes lifts this.\n */\nfunction powerShellLines(command: string): string {\n return command.replace(/\\r(?!\\n)/g, \"\\n\");\n}\n\n/** A character after which PowerShell starts a new token and no word of these readers is under way. */\nconst POWERSHELL_BREAK = /[ \\t\\n;|&]/;\n\n/**\n * Text after which this reader cannot be sure where a PowerShell string ends: a `@\"`/`@'`\n * here-string, a `$(` whose body may hold its own quotes inside a double-quoted string, or a\n * curly quote (U+2018 to U+201E), which PowerShell also reads as a quote.\n */\nconst POWERSHELL_UNTRACKED = /@[\"']|\\$\\(|[\\u2018-\\u201e]/;\n\n/**\n * The PowerShell text with its comments removed, so both readers see the same commands. A\n * `<# ... #>` block comment that starts a token is replaced by a space up to its `#>`, and a\n * `#` line comment that starts a token is removed up to the end of its line, so a quote inside\n * either opens nothing and a command after either is classified. A block comment with no `#>`\n * leaves the script unparsable, so the text is unreadable and fails closed.\n * Where the start of a token is not certain, inside a word, or after a context these readers\n * do not track (`inUntrackedContext`, `POWERSHELL_UNTRACKED`), a `<#` and its `#>` are\n * replaced by command separators instead, so what lies between and after them is still read as\n * commands, and a `#` there stays text.\n */\nfunction withoutPowerShellComments(command: string): string | undefined {\n let output = \"\";\n let quote: string | undefined;\n let wordStarted = false;\n for (let index = 0; index < command.length; index += 1) {\n const character = command[index] ?? \"\";\n if (character === \"`\" && quote !== \"'\") {\n output += character + (command[index + 1] ?? \"\");\n index += 1;\n wordStarted = true;\n continue;\n }\n if (quote) {\n output += character;\n if (character === quote) quote = undefined;\n continue;\n }\n const tracked = () =>\n !inUntrackedContext(command, index) && !POWERSHELL_UNTRACKED.test(command.slice(0, index));\n if (character === \"<\" && command[index + 1] === \"#\") {\n const end = command.indexOf(\"#>\", index + 2);\n if (end === -1) return undefined;\n output += !wordStarted && tracked() ? \" \" : `;${command.slice(index + 2, end)};`;\n index = end + 1;\n wordStarted = false;\n continue;\n }\n if (character === \"#\" && !wordStarted && tracked()) {\n const end = command.indexOf(\"\\n\", index);\n if (end === -1) break;\n index = end - 1;\n continue;\n }\n output += character;\n if (character === \"'\" || character === '\"') quote = character;\n wordStarted = !POWERSHELL_BREAK.test(character);\n }\n return output;\n}\n\n/** A file operand that names no device or process file: letters, digits and `._/-` only. */\nconst DATA_FILE = String.raw`(?!/dev/|/proc/)[\\w./-]+`;\n/** An operand of `cat` or `tee` on a data line: an option, a file, or a redirection to one. */\nconst DATA_OPERAND = String.raw`[ \\t]+(?:-[A-Za-z]+|>>?[ \\t]*${DATA_FILE}|>[ \\t]*/dev/null|${DATA_FILE})`;\n/**\n * A whole line that writes one here-document to files and nothing else: `cat` or `tee`,\n * plain operands, one `<<` or `<<-` with a quoted or escaped identifier delimiter. A line of this\n * shape hands its body to no shell, pipe, descriptor or later command, and the quoted\n * delimiter makes Bash read the body literally, with no expansion or line joining.\n */\nconst DATA_HEREDOC_LINE = new RegExp(\n String.raw`^[ \\t]*(?:cat|tee)(?:${DATA_OPERAND})*[ \\t]*<<-?[ \\t]*(?:(['\"])[A-Za-z_]\\w*\\1|\\\\[A-Za-z_]\\w*)(?:${DATA_OPERAND})*[ \\t]*$`,\n);\n/** A line that may come before a data line: blank, `mkdir -p` of plain paths, or another data line. */\nconst DATA_PRELUDE_LINE = new RegExp(\n String.raw`^[ \\t]*(?:mkdir[ \\t]+-p(?:[ \\t]+${DATA_FILE})+[ \\t]*)?$`,\n);\n\n/**\n * Splits a shell command into its pipelines. A nested command string, such as the\n * argument of `bash -c`, skips no here-document body: what reads its output is outside it.\n */\nfunction shellPipelines(\n command: string,\n shell: GraphShell,\n nested = false,\n): ShellCommand[] | undefined {\n const commands: ShellCommand[] = [];\n let words: string[] = [];\n let upstream: ShellCommand | undefined;\n let join: ShellOperator | undefined;\n let word = \"\";\n let quote: string | undefined;\n let afterRedirect: \"\" | \"<\" | \">\" = \"\";\n // Here-documents whose bodies start after the next unquoted newline.\n const heredocs: { delimiter: string; stripTabs: boolean; data: boolean }[] = [];\n // The spans of bodies already skipped as data, which later checks do not read.\n const skipped: [number, number][] = [];\n // An empty quote such as `''` starts a word that holds no character yet.\n let quotedWord = false;\n const flushWord = () => {\n if (word.length) words.push(word);\n word = \"\";\n quotedWord = false;\n };\n /**\n * Reads an unquoted `<<` or `<<-` operator and its delimiter word at `index`, pushes\n * both as words, and returns the index after the delimiter. Its body is skipped as data\n * only when the operator's whole line is a data line and every line before it, less\n * bodies already skipped, is a data line or a data prelude. Every other body stays\n * classified as shell text, as if no here-document were read.\n */\n const readHeredocOperator = (index: number): number => {\n if (word.length && !/^\\d+$/.test(word)) flushWord();\n let cursor = index + 2;\n const stripTabs = command[cursor] === \"-\";\n if (stripTabs) cursor += 1;\n words.push(`${word}<<${stripTabs ? \"-\" : \"\"}`);\n word = \"\";\n while (command[cursor] === \" \" || command[cursor] === \"\\t\") cursor += 1;\n let delimiter = \"\";\n let read = false;\n let delimiterQuote: string | undefined;\n while (cursor < command.length) {\n const character = command[cursor] ?? \"\";\n if (delimiterQuote) {\n if (character === delimiterQuote) delimiterQuote = undefined;\n else delimiter += character;\n } else if (character === '\"' || character === \"'\") {\n delimiterQuote = character;\n } else if (character === \"\\\\\" && cursor + 1 < command.length) {\n delimiter += command[cursor + 1] ?? \"\";\n cursor += 1;\n } else if (/[\\s;|&<>()]/.test(character)) {\n break;\n } else {\n delimiter += character;\n }\n read = true;\n cursor += 1;\n }\n if (delimiterQuote) {\n quote = delimiterQuote;\n return command.length;\n }\n if (!read) return cursor;\n words.push(delimiter);\n const lineStart = command.lastIndexOf(\"\\n\", index) + 1;\n const lineEnd = command.indexOf(\"\\n\", index);\n // The command text before the operator's line, less the bodies already skipped as data.\n let earlier = \"\";\n let from = 0;\n for (const [start, end] of skipped) {\n earlier += command.slice(from, start);\n from = end;\n }\n earlier += command.slice(from, lineStart);\n const line = command.slice(lineStart, lineEnd < 0 ? command.length : lineEnd);\n // A carriage return is an ordinary character to Bash, so a command holding one skips\n // nothing rather than risk ending a body on a different line than Bash does.\n const data =\n !nested &&\n !command.includes(\"\\r\") &&\n DATA_HEREDOC_LINE.test(line) &&\n earlier\n .split(\"\\n\")\n .every((prior) => DATA_PRELUDE_LINE.test(prior) || DATA_HEREDOC_LINE.test(prior));\n heredocs.push({ delimiter, stripTabs, data });\n return cursor;\n };\n /**\n * Skips the bodies of pending here-documents after the newline at `index`. A body\n * whose delimiter line never comes is not skipped, and when any body on the line is\n * not data none is skipped, so no text is hidden on a guess.\n */\n const skipHeredocs = (index: number): number => {\n let position = index + 1;\n const pending = heredocs.splice(0);\n if (!pending.every((heredoc) => heredoc.data)) return index;\n for (const { delimiter, stripTabs } of pending) {\n let closed = false;\n while (position < command.length && !closed) {\n const end = command.indexOf(\"\\n\", position);\n const line = command.slice(position, end < 0 ? command.length : end);\n position = end < 0 ? command.length : end + 1;\n closed = (stripTabs ? line.replace(/^\\t+/, \"\") : line) === delimiter;\n }\n if (!closed) return index;\n }\n skipped.push([index + 1, position]);\n return position - 1;\n };\n for (let index = 0; index < command.length; index += 1) {\n const character = command[index];\n if (character === undefined) continue;\n const next = command[index + 1];\n const escaped =\n next !== undefined &&\n ((shell === \"posix\" &&\n character === \"\\\\\" &&\n (!quote || (quote === '\"' && ['\"', \"\\\\\", \"$\", \"`\", \"\\n\"].includes(next)))) ||\n (shell === \"powershell\" && character === \"`\" && quote !== \"'\") ||\n (shell === \"cmd\" && character === \"^\" && !quote));\n const redirectBefore = afterRedirect;\n afterRedirect = \"\";\n if (escaped) {\n if (next !== \"\\n\") word += next;\n index += 1;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n else word += character;\n } else if (\n character === \"#\" &&\n !word.length &&\n !quotedWord &&\n startsComment(command, index, shell)\n ) {\n const end = command.indexOf(\"\\n\", index);\n index = (end === -1 ? command.length : end) - 1;\n } else if (character === '\"' || character === \"'\") {\n quote = character;\n quotedWord = true;\n } else if (\n (character === \"&\" || character === \"|\") &&\n (character === \"&\"\n ? redirectBefore !== \"\" && /[\\d-]/.test(next ?? \"\")\n : redirectBefore === \">\" && shell === \"posix\")\n ) {\n word += character;\n } else if (shell === \"posix\" && character === \"&\" && next === \">\") {\n flushWord();\n word = character;\n } else if (character === \"\\n\" && !words.length && !word.length && upstream) {\n index = skipHeredocs(index);\n continue;\n } else if (character === \"|\" || character === \";\" || character === \"&\" || character === \"\\n\") {\n flushWord();\n const stage: ShellCommand | undefined = words.length\n ? {\n words: resolveAlias(words, shell),\n ...(upstream ? { upstream } : {}),\n ...(join ? { join } : {}),\n }\n : undefined;\n if (stage) commands.push(stage);\n const pipe = character === \"|\" && next !== \"|\" && stage !== undefined;\n const operator: ShellOperator =\n (character === \"|\" || character === \"&\") && next === character\n ? character === \"|\"\n ? \"||\"\n : \"&&\"\n : character === \"|\" || character === \"&\" || character === \";\"\n ? character\n : \"\\n\";\n if ((character === \"|\" || character === \"&\") && next === character) index += 1;\n else if (pipe && shell === \"posix\" && next === \"&\") index += 1;\n // An empty line after an operator continues the command it joins.\n if (stage || join === undefined || operator !== \"\\n\") join = operator;\n upstream = pipe ? stage : undefined;\n words = [];\n if (character === \"\\n\") index = skipHeredocs(index);\n } else if (/\\s/.test(character)) {\n flushWord();\n } else if (\n shell === \"posix\" &&\n character === \"<\" &&\n next === \"<\" &&\n command[index + 2] !== \"<\" &&\n command[index - 1] !== \"<\"\n ) {\n index = readHeredocOperator(index) - 1;\n } else {\n if (\n (character === \">\" || character === \"<\") &&\n !/^(?:\\d*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$/.test(word) &&\n !/[<>]$/.test(word) &&\n word !== \"&\"\n ) {\n flushWord();\n }\n word += character;\n afterRedirect = character === \">\" || character === \"<\" ? character : \"\";\n }\n }\n if (quote) return undefined;\n flushWord();\n if (words.length) {\n commands.push({\n words: resolveAlias(words, shell),\n ...(upstream ? { upstream } : {}),\n ...(join ? { join } : {}),\n });\n }\n return commands;\n}\n\n/**\n * The bodies of the substitutions and groups a shell runs as commands: `$(...)` in\n * POSIX and PowerShell, `@(...)` and a grouping `(...)` in PowerShell, `<(...)`,\n * `>(...)`, zsh `=(...)`, a subshell `(...)` and backticks in POSIX. Quotes keep a\n * bare `(` literal, single quotes keep every opener literal, and an escaped opener\n * is not one. An arithmetic `$((...))` runs no command. A substitution whose end the\n * scan cannot find returns undefined: the shell may still close it, for example past a\n * quote in a comment, so the caller denies the command. A here-document\n * body is data, except the substitutions an unquoted delimiter's body expands:\n * `heredocData` says which bodies.\n */\nfunction substitutionBodies(text: string, shell: GraphShell, nested = false): string[] | undefined {\n if (shell === \"cmd\") return [];\n const { text: command, expanded } =\n shell === \"posix\" ? heredocData(text, nested) : { text, expanded: [] };\n const escape = shell === \"posix\" ? \"\\\\\" : \"`\";\n const bodies: string[] = [];\n let quote: string | undefined;\n // Whether no word is under way: true at the start and after an unquoted separator only, so an\n // escaped separator or a closed substitution before a `#` keeps it inside its word.\n let wordStart = true;\n for (let index = 0; index < command.length; index += 1) {\n const character = command[index];\n const next = command[index + 1];\n const atWordStart = wordStart;\n wordStart = false;\n if (character === escape && quote !== \"'\") {\n index += 1;\n continue;\n }\n if (quote === \"'\") {\n if (character === \"'\") quote = undefined;\n continue;\n }\n if (\n !quote &&\n atWordStart &&\n character === \"#\" &&\n shell === \"posix\" &&\n !inUntrackedContext(command, index)\n ) {\n const end = command.indexOf(\"\\n\", index);\n if (end === -1) break;\n index = end;\n wordStart = true;\n continue;\n }\n if (!quote && character !== undefined && WORD_BREAK.test(character)) {\n wordStart = true;\n // A bare `(` also starts a word, and may open a subshell or a grouping below.\n if (character !== \"(\") continue;\n }\n if (character === \"'\" && !quote) {\n quote = \"'\";\n continue;\n }\n if (character === '\"') {\n quote = quote ? undefined : '\"';\n continue;\n }\n const opens =\n next === \"(\" &&\n (character === \"$\" ||\n (!quote && shell === \"powershell\" && character === \"@\") ||\n (!quote && shell === \"posix\" && (character === \"<\" || character === \">\")));\n if (opens) {\n const end = closingParenthesis(command, index + 2, escape);\n if (end === undefined) return undefined;\n if (!(character === \"$\" && command[index + 2] === \"(\")) {\n bodies.push(command.slice(index + 2, end));\n }\n index = end;\n } else if (\n !quote &&\n character === \"(\" &&\n // The first `(` of a POSIX `((` arithmetic command opens no subshell; the scan moves\n // on to the second, whose body the comment reader then knows is arithmetic.\n !(shell === \"posix\" && command[index + 1] === \"(\") &&\n // A POSIX subshell starts a command, and zsh `=(...)` starts a word; any other\n // `(`, such as an array's in `name=(...)`, is data, scanned on.\n (shell === \"powershell\" ||\n commandPosition(command, index, 0) ||\n (command[index - 1] === \"=\" && /^$|[\\s;&|(]/.test(command[index - 2] ?? \"\")))\n ) {\n const end = closingParenthesis(command, index + 1, escape);\n if (end === undefined) return undefined;\n bodies.push(command.slice(index + 1, end));\n index = end;\n } else if (\n !quote &&\n shell === \"powershell\" &&\n character === \"{\" &&\n command[index - 1] !== \"@\"\n ) {\n // A script block, such as the one `ForEach-Object { rg foo $_ }` runs, holds commands.\n // A hashtable `@{...}` holds keys, and a brace this scan cannot close is text; the scan\n // goes on inside either, so a `$(...)` there is still read.\n const end = closingBrace(command, index + 1);\n if (end === undefined) continue;\n bodies.push(command.slice(index + 1, end));\n index = end;\n } else if (shell === \"posix\" && character === \"`\") {\n const end = closingBacktick(command, index + 1);\n if (end === undefined) return undefined;\n bodies.push(command.slice(index + 1, end).replace(/\\\\([`\\\\$])/g, \"$1\"));\n index = end;\n }\n }\n for (const body of expanded) {\n const nested = expandedSubstitutions(body);\n if (!nested) return undefined;\n bodies.push(...nested);\n }\n return bodies;\n}\n\n/** The index of the `}` that closes a PowerShell brace opened before `start`, outside quotes. */\nfunction closingBrace(command: string, start: number): number | undefined {\n let depth = 1;\n let quote: string | undefined;\n for (let index = start; index < command.length; index += 1) {\n const character = command[index];\n if (character === \"`\" && quote !== \"'\") index += 1;\n else if (quote) {\n if (character === quote) quote = undefined;\n } else if (character === \"'\" || character === '\"') quote = character;\n else if (character === \"{\") depth += 1;\n else if (character === \"}\") {\n depth -= 1;\n if (depth === 0) return index;\n }\n }\n return undefined;\n}\n\n/** The index of the backtick that closes one opened before `start`, or undefined. */\nfunction closingBacktick(command: string, start: number): number | undefined {\n let end = start;\n while (end < command.length && command[end] !== \"`\") end += command[end] === \"\\\\\" ? 2 : 1;\n return end < command.length ? end : undefined;\n}\n\n/**\n * The `$(...)` and backtick substitutions an unquoted here-document body expands.\n * Quotes in the body are text, so only a backslash keeps an opener literal.\n */\nfunction expandedSubstitutions(body: string): string[] | undefined {\n const bodies: string[] = [];\n for (let index = 0; index < body.length; index += 1) {\n const character = body[index];\n if (character === \"\\\\\") {\n index += 1;\n } else if (character === \"$\" && body[index + 1] === \"(\") {\n const end = closingParenthesis(body, index + 2, \"\\\\\");\n if (end === undefined) return undefined;\n if (body[index + 2] !== \"(\") bodies.push(body.slice(index + 2, end));\n index = end;\n } else if (character === \"`\") {\n const end = closingBacktick(body, index + 1);\n if (end === undefined) return undefined;\n bodies.push(body.slice(index + 1, end).replace(/\\\\([`\\\\$])/g, \"$1\"));\n index = end;\n }\n }\n return bodies;\n}\n\n/** A `<<` or `<<-` here-document operator and its delimiter, quoted or not; `<<<` is not one. */\nconst heredocOperator = /<<(?!<)(-?)[ \\t]*(?:'([^'\\n]*)'|\"([^\"\\n]*)\"|\\\\?([^\\s;|&<>()'\"]+))/y;\n\n/** A plain word of a message command line: an option, a value or a subcommand. */\nconst MESSAGE_WORD = String.raw`[ \\t]+[\\w./=:@-]+`;\n/**\n * A line that opens a here-document as the text of a message: `git commit` or `git tag`,\n * or `gh pr`, `gh issue` or `gh release` with `create`, `edit` or `comment`, plain\n * words, then `\"$(cat <<'EOF'` with a quoted or escaped identifier delimiter. The body\n * becomes an argument that names a message, so no shell runs it.\n */\nconst MESSAGE_HEREDOC_LINE = new RegExp(\n String.raw`^[ \\t]*(?:git[ \\t]+(?:commit|tag)|gh[ \\t]+(?:pr|issue|release)[ \\t]+(?:create|edit|comment))(?:${MESSAGE_WORD})*[ \\t]+\"\\$\\(cat[ \\t]+<<-?[ \\t]*(?:(['\"])[A-Za-z_]\\w*\\1|\\\\[A-Za-z_]\\w*)[ \\t]*$`,\n);\n/** The line that closes a message substitution: `)\"` and plain words. */\nconst MESSAGE_CLOSE_LINE = new RegExp(String.raw`^[ \\t]*\\)\"(?:${MESSAGE_WORD})*[ \\t]*$`);\n/** A line that may come before a message line: `git add` of plain paths. */\nconst MESSAGE_PRELUDE_LINE = new RegExp(String.raw`^[ \\t]*git[ \\t]+add(?:${MESSAGE_WORD})*[ \\t]*$`);\n\n/**\n * The text with each here-document body that is surely data, and its delimiter line,\n * removed. Such a body is text a command reads, such as a commit message, so a backtick\n * or `$(...)` in it starts no substitution here. A body is removed only in a closed\n * shape: its operator's whole line writes files (a data line) or opens a message\n * (`git commit -m \"$(cat <<'EOF'` and the like), every line before it is a data line,\n * a message line, its closing line or a prelude, the delimiter is a quoted or escaped\n * identifier, so Bash expands nothing in the body, the command holds no carriage return,\n * the delimiter line is present, and the text is not nested in another command. Every\n * other body is kept in the text and scanned, so a substitution in it is classified.\n * `expanded` stays for bodies a shell expands; a closed-shape body expands nothing.\n */\nfunction heredocData(command: string, nested = false): { text: string; expanded: string[] } {\n let output = \"\";\n let quote: string | undefined;\n let comment = false;\n let depth = 0;\n const outer: { quote: string | undefined; depth: number }[] = [];\n const expanded: string[] = [];\n let pending: (HeredocBody & { data: boolean })[] = [];\n // Where the current line starts in `output`, which holds no removed body.\n let lineOutput = 0;\n for (let index = 0; index < command.length; index += 1) {\n const character = command[index] ?? \"\";\n output += character;\n if (character === \"\\n\") {\n comment = false;\n if (!quote && pending.length) {\n const end = pending.every((body) => body.data)\n ? heredocEnd(command, index + 1, pending, expanded)\n : undefined;\n if (end !== undefined) index = end - 1;\n pending = [];\n }\n lineOutput = output.length;\n } else if (comment) {\n continue;\n } else if (quote === \"'\") {\n if (character === \"'\") quote = undefined;\n } else if (character === \"\\\\\") {\n output += command[index + 1] ?? \"\";\n // A continued line is still a line the earlier-line check must read.\n if (command[index + 1] === \"\\n\") lineOutput = output.length;\n index += 1;\n } else if (character === \"$\" && command[index + 1] === \"(\" && command[index + 2] !== \"(\") {\n outer.push({ quote, depth });\n quote = undefined;\n depth = 0;\n output += \"(\";\n index += 1;\n } else if (quote) {\n if (character === quote) quote = undefined;\n } else if (character === \"'\" || character === '\"') {\n quote = character;\n } else if (character === \"#\" && /^$|[\\s;|&(]/.test(command[index - 1] ?? \"\")) {\n comment = true;\n } else if (character === \"(\") {\n depth += 1;\n } else if (character === \")\") {\n const context = depth === 0 ? outer.pop() : undefined;\n if (context) ({ quote, depth } = context);\n else depth = Math.max(0, depth - 1);\n } else if (character === \"<\" && command[index - 1] !== \"<\") {\n heredocOperator.lastIndex = index;\n const match = heredocOperator.exec(command);\n if (!match) continue;\n const lineStart = command.lastIndexOf(\"\\n\", index) + 1;\n const lineEnd = command.indexOf(\"\\n\", index);\n const line = command.slice(lineStart, lineEnd < 0 ? command.length : lineEnd);\n const delimiter = match[2] ?? match[3] ?? match[4] ?? \"\";\n const expands = match[4] !== undefined && !match[0].includes(\"\\\\\");\n const data =\n !nested &&\n !expands &&\n !command.includes(\"\\r\") &&\n /^[A-Za-z_]\\w*$/.test(delimiter) &&\n (DATA_HEREDOC_LINE.test(line) || MESSAGE_HEREDOC_LINE.test(line)) &&\n output\n .slice(0, lineOutput)\n .split(\"\\n\")\n .every(\n (prior) =>\n DATA_PRELUDE_LINE.test(prior) ||\n DATA_HEREDOC_LINE.test(prior) ||\n MESSAGE_HEREDOC_LINE.test(prior) ||\n MESSAGE_CLOSE_LINE.test(prior) ||\n MESSAGE_PRELUDE_LINE.test(prior),\n );\n pending.push({ delimiter, stripTabs: !!match[1], expands, data });\n output += command.slice(index + 1, heredocOperator.lastIndex);\n index = heredocOperator.lastIndex - 1;\n }\n }\n return { text: output, expanded };\n}\n\ninterface HeredocBody {\n delimiter: string;\n stripTabs: boolean;\n /** An unquoted delimiter: the shell expands substitutions in the body. */\n expands: boolean;\n}\n\n/**\n * The index after the delimiter line that closes the last of `bodies`, or undefined.\n * The text of each body that expands is added to `expanded`. A line that starts with a\n * delimiter but holds more, such as `EOF)`, also returns undefined: inside a\n * substitution Bash may end the body there, so the body is kept.\n */\nfunction heredocEnd(\n command: string,\n start: number,\n bodies: HeredocBody[],\n expanded: string[],\n): number | undefined {\n let position = start;\n const texts: string[] = [];\n for (const { delimiter, stripTabs, expands } of bodies) {\n const bodyStart = position;\n let bodyEnd = position;\n let closed = false;\n while (!closed && position < command.length) {\n const end = command.indexOf(\"\\n\", position);\n const line = command.slice(position, end < 0 ? command.length : end).replace(/\\r$/, \"\");\n const stripped = stripTabs ? line.replace(/^\\t+/, \"\") : line;\n closed = stripped === delimiter;\n if (!closed && stripped.startsWith(delimiter)) return undefined;\n if (!closed) bodyEnd = end < 0 ? command.length : end;\n position = end < 0 ? command.length : end + 1;\n }\n if (!closed) return undefined;\n if (expands) texts.push(command.slice(bodyStart, bodyEnd));\n }\n expanded.push(...texts);\n return position;\n}\n\n/** A POSIX `case` or `esac` reserved word. */\nconst caseWord = /(case|esac)(?=$|[\\s;&|)])/y;\n\n/** Whether `index` starts a command: only blanks lie between it and `start` or an operator. */\nfunction commandPosition(command: string, index: number, start: number): boolean {\n let before = index - 1;\n while (before >= start && /[ \\t]/.test(command[before] ?? \"\")) before -= 1;\n return before < start || /[;&|(\\n]/.test(command[before] ?? \"\");\n}\n\n/**\n * The index of the `)` that closes a parenthesis opened before `start`, outside quotes.\n * In POSIX text a `)` that ends a `case` pattern, such as `x)` in\n * `case x in x) ...;; esac`, closes nothing. `case` and `esac` count only where a\n * command starts, so an argument such as `test/case` opens no case.\n * A comment runs as the shell reads it, so a `)` or a quote inside it closes and opens\n * nothing: in POSIX text a `#` that starts a word runs to the end of its line, unless an\n * untracked context or arithmetic comes before it (`inArithmeticOrUntracked`), and in PowerShell a `#` that\n * starts a token runs to the end of its line and a `<#` runs to its `#>`. A block comment\n * with no `#>` leaves no end.\n */\n/**\n * Whether a POSIX `#` at `index`, inside a parenthesis that opened just before `start`,\n * may sit in a context where the shell starts no comment: an untracked context before it,\n * or arithmetic, which a body cut from `((` no longer shows as `((`, so a body that opens\n * with `(` or holds `((` counts as arithmetic too.\n */\nfunction inArithmeticOrUntracked(command: string, start: number, index: number): boolean {\n return (\n inUntrackedContext(command, index) ||\n command[start] === \"(\" ||\n command[start - 2] === \"(\" ||\n command.slice(start, index).includes(\"((\")\n );\n}\n\nfunction closingParenthesis(command: string, start: number, escape: string): number | undefined {\n let depth = 1;\n let quote: string | undefined;\n /** The parenthesis depth at which each open `case` started. */\n const cases: number[] = [];\n const posix = escape === \"\\\\\";\n // Whether the character at `index` starts a word: after an unescaped blank, `;`, `&`,\n // `|`, `(` or newline outside quotes. A `)` does not start one, since the word goes on\n // after a closed substitution, and an escaped character keeps the word going.\n let wordStart = true;\n for (let index = start; index < command.length; index += 1) {\n const character = command[index] ?? \"\";\n const atWordStart = wordStart;\n wordStart = false;\n if (character === escape && quote !== \"'\") index += 1;\n else if (quote) {\n if (character === quote) quote = undefined;\n } else if (character === \"'\" || character === '\"') quote = character;\n else if (!posix && atWordStart && character === \"<\" && command[index + 1] === \"#\") {\n const end = command.indexOf(\"#>\", index + 2);\n if (end === -1) return undefined;\n index = end + 1;\n wordStart = true;\n } else if (\n character === \"#\" &&\n atWordStart &&\n (!posix || !inArithmeticOrUntracked(command, start, index))\n ) {\n const end = command.indexOf(\"\\n\", index);\n if (end === -1) return undefined;\n index = end - 1;\n wordStart = true;\n } else if (posix && /[ce]/.test(character) && commandPosition(command, index, start)) {\n caseWord.lastIndex = index;\n const word = caseWord.exec(command)?.[1];\n if (word === \"case\") cases.push(depth);\n else if (word === \"esac\" && cases.at(-1) === depth) cases.pop();\n if (word) index += word.length - 1;\n } else if (character === \"(\") depth += 1;\n else if (character === \")\") {\n if (cases.at(-1) === depth) continue;\n depth -= 1;\n if (depth === 0) return index;\n }\n if (!quote && /[ \\t\\n;&|(]/.test(character)) wordStart = true;\n }\n return undefined;\n}\n\nfunction denyExploration(operation: string, target: string): GraphHookDecision {\n const domain = /(?:^|[\\\\/])(?:docs?|spec|adr|requirements)(?:[\\\\/]|$)|\\.md$/i.test(target)\n ? \"documents\"\n : \"code\";\n return {\n decision: \"deny\",\n state: \"configured\",\n operation,\n target,\n domain,\n message: `Exploration redirected: ${operation} over ${JSON.stringify(target)} was denied. Use ${domain === \"code\" ? 'CodeGraph for symbols, callers and change impact: node .qfai/tools/graph-cli.mjs code \"<question>\"' : 'Graphify for document concepts and rationale: node .qfai/tools/graph-cli.mjs documents \"<question>\"'}. Prepare the required analysis through the CLI. For AI-decided scoped search, run node .qfai/tools/graph-cli.mjs fallback --attempt-id <observed-UUID> --question \"<unresolved question>\" --reason \"<graph limitation>\". The fallback command attempts the relevant graph before granting a matching search. Human approval is not required for this search.`,\n };\n}\n\nexport function graphFallbackUnavailable(\n decision: GraphHookDecision,\n cause: string,\n recovery: string,\n): GraphHookDecision {\n return {\n ...decision,\n exceptionEligible: false,\n fallbackUnavailable: true,\n message: `Exploration redirected: ${decision.operation ?? \"search\"} was denied. Search fallback unavailable: ${cause} ${recovery} Use node .qfai/tools/graph-cli.mjs ${decision.domain === \"documents\" ? \"documents\" : \"code\"} \"<question>\" for graph exploration.`,\n };\n}\n\nexport function decodeGraphHookEvent(input: unknown): GraphHookEvent | undefined {\n if (!object(input)) return undefined;\n const snake = [\"tool_name\", \"tool_input\", \"session_id\"].some((key) => key in input);\n const camel = [\"toolName\", \"toolArgs\", \"sessionId\"].some((key) => key in input);\n if (snake && camel) return undefined;\n const tool = input.tool_name ?? input.toolName;\n let payload: unknown = input.tool_input ?? input.toolArgs;\n if (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch {\n return undefined;\n }\n }\n if (typeof tool !== \"string\" || !tool.trim() || !object(payload)) return undefined;\n const session = input.session_id ?? input.sessionId;\n if (\n (session !== undefined && (typeof session !== \"string\" || !session.trim())) ||\n (input.session_id !== undefined &&\n input.sessionId !== undefined &&\n input.session_id !== input.sessionId)\n )\n return undefined;\n const command = payload.command ?? payload.cmd;\n const target = payload.path ?? payload.includePattern;\n const workdir = payload.workdir;\n const shell = payload.shell;\n if (target !== undefined && (typeof target !== \"string\" || !target.trim())) return undefined;\n if (workdir !== undefined && (typeof workdir !== \"string\" || !workdir.trim())) return undefined;\n if (shell !== undefined && (typeof shell !== \"string\" || !shell.trim())) return undefined;\n if (\n [\"bash\", \"powershell\", \"exec_command\"].includes(tool.toLowerCase()) &&\n typeof command !== \"string\"\n )\n return undefined;\n return {\n tool,\n ...(typeof command === \"string\" ? { command } : {}),\n ...(typeof target === \"string\" ? { path: target } : {}),\n ...(typeof workdir === \"string\" ? { workdir } : {}),\n ...(typeof shell === \"string\" ? { shell } : {}),\n ...(typeof input.cwd === \"string\" ? { cwd: input.cwd } : {}),\n ...(typeof session === \"string\" ? { session } : {}),\n };\n}\n\n/** Why the hook could not decide: what it names, and what the user does next. */\nexport type GraphHookFailure =\n \"configuration\" | \"input\" | \"state\" | \"quote\" | \"substitution\" | \"depth\";\n\nconst FAILURE_MESSAGES: Record<GraphHookFailure, string> = {\n configuration:\n \"Graph protection failed: .qfai/tools/graph-enforcement.json is missing or is not a valid enforcement configuration. Repair hook configuration with qfai init before direct exploration.\",\n input:\n \"Graph protection failed: the hook could not read the host's pre-tool event. Repair hook configuration so the hook receives the host's pre-tool event.\",\n state:\n \"Graph protection failed: the hook could not read its local search state. Retry, and run qfai doctor if it repeats.\",\n quote:\n \"Graph protection failed: the hook could not match the quotes in the command. Retry without an unmatched quote, heredoc or here-string.\",\n substitution:\n \"Graph protection failed: the hook could not find where a $(...), (...) or backtick substitution in the command ends. Close it, move any comment out of it, or run its inner command directly.\",\n depth:\n \"Graph protection failed: the command nests env, command or shell wrappers more than 16 levels deep. Run the inner command directly and retry.\",\n};\n\nexport function failedGraphHook(failure: GraphHookFailure): GraphHookDecision {\n return { decision: \"deny\", state: \"failed\", message: FAILURE_MESSAGES[failure] };\n}\n\nexport function enforceGraphExploration(input: unknown, configuration: unknown): GraphHookDecision {\n if (\n !object(configuration) ||\n Object.keys(configuration).length !== 2 ||\n configuration.kind !== \"graph-enforcement\" ||\n configuration.denyExploration !== true\n )\n return failedGraphHook(\"configuration\");\n const event = decodeGraphHookEvent(input);\n return event ? classifyGraphExploration(event) : failedGraphHook(\"input\");\n}\n\nexport function graphHookOutput(\n host: GraphHookHost,\n decision: GraphHookDecision,\n): Record<string, unknown> {\n if (decision.decision === \"allow\") return {};\n return host === \"copilot\"\n ? { permissionDecision: \"deny\", permissionDecisionReason: decision.message }\n : {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: decision.message,\n },\n };\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { rename, unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n classifyGraphExploration,\n graphFallbackUnavailable,\n type GraphHookDecision,\n type GraphHookEvent,\n} from \"./hooks.js\";\nimport { withGraphLock } from \"./locks.js\";\nimport {\n graphStateDirectory,\n graphStateText,\n invalidGraphState,\n writeGraphLocalFile,\n} from \"./localFiles.js\";\nimport {\n fullGraphState,\n readGraphSearchRecords,\n type PendingGraphSearch,\n type GrantedGraphSearch,\n} from \"./permissionRecords.js\";\nimport { queryPreparedGraph } from \"./runner.js\";\nimport { runGraphProcess, type GraphProcess } from \"./process.js\";\nimport { assertGraphStoragePath } from \"./storage.js\";\n\nexport async function classifyStoredGraphExploration(\n root: string,\n event: GraphHookEvent,\n): Promise<GraphHookDecision> {\n const decision = classifyGraphExploration(event);\n if (decision.decision !== \"deny\" || decision.state !== \"configured\") return decision;\n if (decision.exceptionEligible === false)\n return decision.fallbackUnavailable\n ? decision\n : graphFallbackUnavailable(\n decision,\n \"The search target or operation cannot be scoped.\",\n \"Run a single search with one explicit project-relative target, then retry the denied action.\",\n );\n if (!event.cwd || !graphStateText(event.session, 4096))\n return graphFallbackUnavailable(\n decision,\n \"Observed session and worktree are required.\",\n \"Enable session and cwd in the host event, run qfai init, then retry the denied action from this project worktree.\",\n );\n if (path.resolve(event.cwd) !== path.resolve(root))\n return graphFallbackUnavailable(\n decision,\n \"The observed worktree differs from this project worktree.\",\n \"Run the denied action from this project worktree, or run qfai init in the intended worktree before retrying.\",\n );\n if (event.workdir && path.resolve(event.cwd, event.workdir) !== path.resolve(root))\n return graphFallbackUnavailable(\n decision,\n \"The requested workdir differs from this project worktree.\",\n \"Set workdir to this project worktree and retry the denied action.\",\n );\n if (!decision.target || !decision.operation || !decision.domain) return decision;\n const worktree = path.resolve(root);\n const session = event.session;\n return withGraphLock<GraphHookDecision>(root, \"state\", async () => {\n const directory = await graphStateDirectory(root);\n const records = await readGraphSearchRecords(root, directory);\n const classified = classifyGraphExploration(event, (candidate) => {\n if (candidate.decision !== \"deny\" || candidate.exceptionEligible === false) return candidate;\n const grant = records.find(\n (item) =>\n !item.draft &&\n item.record.kind === \"grant\" &&\n item.record.target === candidate.target &&\n item.record.operation === candidate.operation &&\n item.record.domain === candidate.domain &&\n item.record.worktree === worktree &&\n item.record.session === session &&\n Date.now() < item.record.expiresAt,\n );\n return grant?.record.kind === \"grant\"\n ? {\n ...candidate,\n decision: \"allow\",\n message: `AI-decided search fallback: ${grant.record.reason}`,\n }\n : candidate;\n });\n if (\n classified.decision !== \"deny\" ||\n classified.state !== \"configured\" ||\n classified.exceptionEligible === false ||\n !classified.target ||\n !classified.operation ||\n !classified.domain\n )\n return classified;\n const observed = {\n target: classified.target,\n operation: classified.operation,\n domain: classified.domain,\n worktree,\n session,\n };\n if (records.length >= 128) throw fullGraphState();\n const createdAt = Date.now();\n const pending: PendingGraphSearch = {\n ...observed,\n id: randomUUID(),\n kind: \"pending\",\n createdAt,\n expiresAt: createdAt + 600000,\n };\n await writeGraphLocalFile(path.join(directory, `${pending.id}.pending.json`), pending);\n return { ...classified, message: `${classified.message} Observed attempt: ${pending.id}.` };\n });\n}\n\nexport async function requestStoredGraphFallback(\n root: string,\n attemptId: string,\n question: string,\n reason: string,\n run: GraphProcess = runGraphProcess,\n) {\n const observed = await withGraphLock(root, \"state\", async () => {\n const directory = await graphStateDirectory(root);\n const records = await readGraphSearchRecords(root, directory);\n const pending = records.find(\n (item) => item.record.kind === \"pending\" && item.record.id === attemptId,\n );\n if (!pending || pending.record.kind !== \"pending\") throw invalidGraphState();\n return pending.record;\n });\n const graph = await queryPreparedGraph(root, { domain: observed.domain, question }, run);\n const publication = await withGraphLock(root, \"state\", async () => {\n const directory = await graphStateDirectory(root);\n const records = await readGraphSearchRecords(root, directory);\n const pending = records.find(\n (item) => item.record.kind === \"pending\" && item.record.id === attemptId,\n );\n if (!pending || JSON.stringify(pending.record) !== JSON.stringify(observed))\n throw invalidGraphState();\n if (records.length >= 128) throw fullGraphState();\n const createdAt = Date.now();\n const grant: GrantedGraphSearch = {\n ...observed,\n kind: \"grant\",\n reason,\n createdAt,\n expiresAt: createdAt + 60000,\n };\n const draft = path.join(directory, `${grant.id}.draft.json`);\n await writeGraphLocalFile(draft, grant);\n await unlink(pending.file);\n return { directory, draft, grant };\n });\n await assertGraphStoragePath(root, publication.directory);\n if (Date.now() >= publication.grant.expiresAt) throw invalidGraphState();\n await rename(\n publication.draft,\n path.join(publication.directory, `${publication.grant.id}.grant.json`),\n );\n const { target, operation, worktree, session, expiresAt } = publication.grant;\n return {\n status: \"ready\",\n permitted: true,\n domain: observed.domain,\n scope: { target, operation, worktree, session, reason, expiresAt },\n graph,\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { hasErrnoCode } from \"../fs/errno.js\";\nimport { graphEnvironmentKey } from \"./layout.js\";\nimport {\n graphStateDirectory,\n GraphLocalStateError,\n GRAPH_UUID,\n readGraphLocalFile,\n writeGraphLocalFile,\n} from \"./localFiles.js\";\n\nexport async function withGraphLock<T>(\n root: string,\n kind: \"analysis\" | \"state\",\n action: () => Promise<T>,\n): Promise<T> {\n const directory = await graphStateDirectory(root);\n const file = path.join(directory, `${kind}.lock`);\n const owner = {\n kind: \"graph-lock\",\n pid: process.pid,\n createdAt: Date.now(),\n token: randomUUID(),\n };\n try {\n await writeGraphLocalFile(file, owner);\n } catch (cause: unknown) {\n if (!hasErrnoCode(cause) || cause.code !== \"EEXIST\") throw cause;\n const text = await readGraphLocalFile(file);\n let active = false;\n try {\n const existing: unknown = text === undefined ? undefined : JSON.parse(text);\n if (typeof existing !== \"object\" || existing === null || Array.isArray(existing))\n throw new Error(\"Invalid graph lock metadata.\", { cause });\n const value = existing as Record<string, unknown>;\n if (\n Object.keys(value).length !== 4 ||\n value.kind !== \"graph-lock\" ||\n typeof value.pid !== \"number\" ||\n !Number.isSafeInteger(value.pid) ||\n value.pid <= 0 ||\n typeof value.createdAt !== \"number\" ||\n !Number.isSafeInteger(value.createdAt) ||\n value.createdAt < 0 ||\n typeof value.token !== \"string\" ||\n !GRAPH_UUID.test(value.token)\n )\n throw new Error(\"Invalid graph lock metadata.\", { cause });\n try {\n process.kill(value.pid, 0);\n active = true;\n } catch (liveness: unknown) {\n if (!hasErrnoCode(liveness) || liveness.code !== \"ESRCH\") active = true;\n }\n } catch {\n // Invalid metadata is retained for manual recovery.\n }\n throw new GraphLocalStateError(\n `Project graph ${kind} lock ${active ? \"is contended\" : \"requires manual recovery\"}.`,\n active\n ? `Retry after the active worktree ${kind} operation finishes; retain its lock.`\n : `Retain and inspect .qfai/tools/state/${graphEnvironmentKey()}/${kind}.lock; remove only a confirmed abandoned worktree lock before retrying.`,\n { cause },\n );\n }\n try {\n return await action();\n } finally {\n await releaseGraphLock(file, JSON.stringify(owner));\n }\n}\n\nasync function releaseGraphLock(file: string, owner: string): Promise<void> {\n const text = await readGraphLocalFile(file);\n if (text !== owner)\n throw new GraphLocalStateError(\n \"Project graph lock ownership changed.\",\n \"Retain the lock and repair the worktree graph state before retrying.\",\n );\n await unlink(file);\n}\n","import path from \"node:path\";\n\nexport const GRAPH_VERSIONS = { codegraph: \"1.6.2\", graphify: \"0.9.86\" } as const;\n\nexport interface GraphExecutionEnvironment {\n platform: string;\n architecture: string;\n}\n\nexport function graphExecutionEnvironment(): GraphExecutionEnvironment {\n return { platform: process.platform, architecture: process.arch };\n}\n\nexport function graphEnvironmentKey(\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n): string {\n if (!/^[a-z0-9]+$/i.test(environment.platform) || !/^[a-z0-9]+$/i.test(environment.architecture))\n throw new Error(\"Unsupported graph execution environment.\");\n return `${environment.platform}-${environment.architecture}`;\n}\n\nexport function graphRuntimePaths(\n root: string,\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n) {\n return graphRuntimeFiles(\n path.join(root, \".qfai\", \"tools\", \"runtimes\", graphEnvironmentKey(environment)),\n environment,\n );\n}\n\n/** The runtime files inside one runtime directory, the installed one or a staged copy of it. */\nexport function graphRuntimeFiles(\n directory: string,\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n) {\n return {\n directory,\n codegraph: path.join(\n directory,\n \"codegraph\",\n \"node_modules\",\n \"@colbymchenry\",\n \"codegraph\",\n \"npm-shim.js\",\n ),\n codegraphSdk: path.join(\n directory,\n \"codegraph\",\n \"node_modules\",\n \"@colbymchenry\",\n \"codegraph\",\n \"npm-sdk.js\",\n ),\n codegraphNode: path.join(\n directory,\n \"codegraph\",\n \"node_modules\",\n \"@colbymchenry\",\n `codegraph-${environment.platform}-${environment.architecture}`,\n environment.platform === \"win32\" ? \"node.exe\" : \"node\",\n ),\n python:\n environment.platform === \"win32\"\n ? path.join(directory, \"graphify\", \"Scripts\", \"python.exe\")\n : path.join(directory, \"graphify\", \"bin\", \"python\"),\n };\n}\n\nexport function graphAnalysisRoot(\n root: string,\n engine: \"codegraph\" | \"graphify\" | \"graphify-code\",\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n): string {\n return path.join(root, \".qfai\", \"tools\", \"analysis\", graphEnvironmentKey(environment), engine);\n}\n","import { lstat, mkdir, open } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../fs/errno.js\";\nimport { readPinnedRegularFileBytes } from \"../init/fsGuards.js\";\nimport { graphEnvironmentKey } from \"./layout.js\";\nimport { assertGraphStoragePath } from \"./storage.js\";\n\nexport const GRAPH_STATE_BYTES = 32768;\nexport const GRAPH_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\nexport class GraphLocalStateError extends Error {\n constructor(\n message: string,\n readonly recovery: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n }\n}\n\nexport async function graphStateDirectory(root: string): Promise<string> {\n const directory = path.join(root, \".qfai\", \"tools\", \"state\", graphEnvironmentKey());\n await assertGraphStoragePath(root, directory);\n await mkdir(directory, { recursive: true });\n await assertGraphStoragePath(root, directory);\n return directory;\n}\n\nexport function invalidGraphState(): GraphLocalStateError {\n return new GraphLocalStateError(\n \"Project graph permission state is invalid.\",\n \"Retain the local state and repair .qfai/tools/state before retrying the graph CLI or hook.\",\n );\n}\n\nexport function graphStateText(value: unknown, maximum: number): value is string {\n return (\n typeof value === \"string\" &&\n value.trim().length > 0 &&\n value.length <= maximum &&\n !value.includes(\"\\0\")\n );\n}\n\nexport async function readGraphLocalFile(file: string): Promise<string | undefined> {\n try {\n const before = await lstat(file);\n if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1)\n throw invalidGraphState();\n const pinned = await readPinnedRegularFileBytes(file, GRAPH_STATE_BYTES);\n const after = await lstat(file);\n if (\n !pinned ||\n before.dev !== pinned.dev ||\n before.ino !== pinned.ino ||\n after.dev !== pinned.dev ||\n after.ino !== pinned.ino ||\n !after.isFile() ||\n after.isSymbolicLink() ||\n after.nlink !== 1\n )\n throw invalidGraphState();\n return pinned.content.toString(\"utf8\");\n } catch (cause: unknown) {\n if (isEnoent(cause)) return undefined;\n throw cause;\n }\n}\n\nexport async function writeGraphLocalFile(file: string, value: unknown): Promise<void> {\n const text = JSON.stringify(value);\n if (Buffer.byteLength(text) > GRAPH_STATE_BYTES) throw invalidGraphState();\n const handle = await open(file, \"wx\", 0o600);\n try {\n await handle.writeFile(text, \"utf8\");\n } finally {\n await handle.close();\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { lstat, mkdir, readdir, rename, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../fs/errno.js\";\n\nexport async function assertGraphStoragePath(root: string, directory: string): Promise<void> {\n const relative = path.relative(root, directory);\n const parts = relative.split(path.sep);\n if (\n path.isAbsolute(relative) ||\n parts[0] !== \".qfai\" ||\n parts[1] !== \"tools\" ||\n parts.includes(\"..\")\n ) {\n throw new Error(\"Graph storage must stay inside project-local .qfai/tools.\");\n }\n for (let depth = 1; depth <= parts.length; depth += 1) {\n try {\n const stats = await lstat(path.join(root, ...parts.slice(0, depth)));\n if (stats.isSymbolicLink() || !stats.isDirectory())\n throw new Error(\n \"Graph storage has an unsafe path component; retain it and repair the project configuration.\",\n );\n } catch (cause: unknown) {\n if (isEnoent(cause)) return;\n throw cause;\n }\n }\n}\n\nexport async function assertIndependentAnalysis(directory: string): Promise<void> {\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const child = path.join(directory, entry.name);\n const stats = await lstat(child);\n if (stats.isSymbolicLink() || (stats.isFile() && stats.nlink > 1)) {\n throw new Error(\n \"Graph analysis contains a shared file or unsafe link; retain it and prepare an independent copy.\",\n );\n }\n if (stats.isDirectory()) await assertIndependentAnalysis(child);\n }\n}\n\nexport async function replaceGraphDirectory(\n staged: string,\n current: string,\n root: string,\n): Promise<void> {\n await assertGraphStoragePath(root, staged);\n await assertGraphStoragePath(root, current);\n const parent = path.dirname(current);\n await mkdir(parent, { recursive: true });\n const previous = path.join(parent, `.previous-${randomUUID()}`);\n let retained = false;\n try {\n await rename(current, previous);\n retained = true;\n } catch (cause: unknown) {\n if (!isEnoent(cause)) throw cause;\n }\n try {\n await rename(staged, current);\n } catch (cause: unknown) {\n if (retained) await rename(previous, current);\n throw cause;\n }\n if (retained) await rm(previous, { recursive: true, force: true });\n}\n","import { opendir, unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n GRAPH_UUID,\n graphStateText,\n invalidGraphState,\n readGraphLocalFile,\n GraphLocalStateError,\n} from \"./localFiles.js\";\n\ninterface ObservedScope {\n id: string;\n domain: \"code\" | \"documents\";\n target: string;\n operation: string;\n worktree: string;\n session: string;\n createdAt: number;\n expiresAt: number;\n}\n\nexport type PendingGraphSearch = ObservedScope & { kind: \"pending\" };\nexport type GrantedGraphSearch = ObservedScope & { kind: \"grant\"; reason: string };\nexport type GraphSearchRecord = PendingGraphSearch | GrantedGraphSearch;\nexport interface StoredGraphRecord {\n file: string;\n record: GraphSearchRecord;\n draft: boolean;\n}\n\nexport async function readGraphSearchRecords(\n root: string,\n directory: string,\n): Promise<StoredGraphRecord[]> {\n const records: StoredGraphRecord[] = [];\n const entries = await opendir(directory);\n for await (const entry of entries) {\n if (entry.name === \"state.lock\" || entry.name === \"analysis.lock\") continue;\n if (records.length >= 128) throw fullGraphState();\n const match = /^(.+)\\.(pending|grant|draft)\\.json$/.exec(entry.name);\n if (!match || !GRAPH_UUID.test(match[1] ?? \"\")) throw invalidGraphState();\n const file = path.join(directory, entry.name);\n const text = await readGraphLocalFile(file);\n if (text === undefined) throw invalidGraphState();\n let input: unknown;\n try {\n input = JSON.parse(text);\n } catch {\n throw invalidGraphState();\n }\n const record = parseGraphSearchRecord(input, root);\n if (\n !record ||\n record.id !== match[1] ||\n (match[2] === \"pending\" ? record.kind !== \"pending\" : record.kind !== \"grant\")\n )\n throw invalidGraphState();\n records.push({ file, record, draft: match[2] === \"draft\" });\n }\n const current: StoredGraphRecord[] = [];\n for (const item of records) {\n if (Date.now() >= item.record.expiresAt) await unlink(item.file);\n else current.push(item);\n }\n return current;\n}\n\nexport function fullGraphState(): GraphLocalStateError {\n return new GraphLocalStateError(\n \"Project graph permission state is full.\",\n \"Retry after pending attempts or search grants expire; retain valid worktree state.\",\n );\n}\n\nfunction parseGraphSearchRecord(input: unknown, root: string): GraphSearchRecord | undefined {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) return undefined;\n const value = input as Record<string, unknown>;\n const fields = [\n \"id\",\n \"kind\",\n \"domain\",\n \"target\",\n \"operation\",\n \"worktree\",\n \"session\",\n \"createdAt\",\n \"expiresAt\",\n ];\n if (value.kind === \"grant\") fields.push(\"reason\");\n if (\n Object.keys(value).length !== fields.length ||\n fields.some((field) => !Object.hasOwn(value, field)) ||\n typeof value.id !== \"string\" ||\n !GRAPH_UUID.test(value.id) ||\n (value.kind !== \"pending\" && value.kind !== \"grant\") ||\n (value.domain !== \"code\" && value.domain !== \"documents\") ||\n !graphStateText(value.target, 4096) ||\n !graphStateText(value.operation, 128) ||\n !graphStateText(value.worktree, 4096) ||\n value.worktree !== path.resolve(root) ||\n !graphStateText(value.session, 4096) ||\n typeof value.createdAt !== \"number\" ||\n typeof value.expiresAt !== \"number\" ||\n !Number.isSafeInteger(value.createdAt) ||\n value.createdAt < 0 ||\n value.createdAt > Date.now() ||\n !Number.isSafeInteger(value.expiresAt) ||\n value.expiresAt !== value.createdAt + (value.kind === \"pending\" ? 600000 : 60000)\n )\n return undefined;\n const scope: ObservedScope = {\n id: value.id,\n domain: value.domain,\n target: value.target,\n operation: value.operation,\n worktree: value.worktree,\n session: value.session,\n createdAt: value.createdAt,\n expiresAt: value.expiresAt,\n };\n if (value.kind === \"pending\") return { ...scope, kind: \"pending\" };\n return graphStateText(value.reason, 2048)\n ? { ...scope, kind: \"grant\", reason: value.reason }\n : undefined;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\nimport { codegraphEnvironment, type GraphProcess } from \"./process.js\";\nimport {\n publishCompletedCodeAnalysis,\n restoreCompletedCodeAnalysis,\n type GraphReuseEnvironment,\n} from \"./reuse.js\";\nimport { graphAnalysisRoot, graphRuntimePaths } from \"./layout.js\";\nimport {\n GraphConfigUnreadableError,\n inspectCodeAnalysisAt,\n inspectCurrentCodeAnalysis,\n mirrorGraphCorpus,\n} from \"./analysis.js\";\nimport {\n assertGraphStoragePath,\n assertIndependentAnalysis,\n replaceGraphDirectory,\n} from \"./storage.js\";\n\nexport interface CodePreparation {\n status: \"prepared\" | \"failed\";\n source?: \"generated\" | \"restored\" | \"current\";\n recovery?: string;\n reuse?: \"published\" | \"unavailable\";\n}\n\nexport async function prepareCodeAnalysis(\n root: string,\n run: GraphProcess,\n environment?: GraphReuseEnvironment,\n): Promise<CodePreparation> {\n const current = graphAnalysisRoot(root, \"codegraph\");\n const staged = path.join(path.dirname(current), `.preparing-codegraph-${randomUUID()}`);\n let created = false;\n try {\n if (await inspectCurrentCodeAnalysis(root, run))\n return { status: \"prepared\", source: \"current\" };\n if ((await restoreCompletedCodeAnalysis(root, run, environment)) === \"restored\")\n return { status: \"prepared\", source: \"restored\" };\n await assertGraphStoragePath(root, staged);\n await mkdir(staged, { recursive: true });\n created = true;\n await mirrorGraphCorpus(root, staged);\n const runtime = graphRuntimePaths(root);\n const result = await run(\n runtime.codegraphNode,\n [\n \"--liftoff-only\",\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"codegraph-native.mjs\"),\n runtime.codegraphSdk,\n staged,\n ],\n { cwd: staged, env: codegraphEnvironment(root) },\n );\n if (result.exitCode !== 0 || !(await inspectCodeAnalysisAt(root, staged, run))) return failed();\n await assertIndependentAnalysis(staged);\n await replaceGraphDirectory(staged, current, root);\n return {\n status: \"prepared\",\n source: \"generated\",\n reuse: await publishCompletedCodeAnalysis(root, run, environment),\n };\n } catch (cause: unknown) {\n if (cause instanceof GraphConfigUnreadableError) throw cause;\n return failed();\n } finally {\n if (created) await rm(staged, { recursive: true, force: true });\n }\n}\n\nfunction failed(): CodePreparation {\n return {\n status: \"failed\",\n recovery: \"Repair the local CodeGraph runtime and prepare independent analysis.\",\n };\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * `assets/init` candidates for a module sitting at `baseDir`.\n *\n * Three depths, because this module is loaded from three: `src/shared/` and\n * `dist/shared/` are two levels below the package root, and `dist/index.mjs` —\n * the package's public entry, which `tsup` produces with `splitting: false`, so\n * this code is bundled into it — is one. Without the one-level candidate every\n * caller that reaches `validateProject` through the library entry rather than\n * the CLI got `Template assets not found` before any validator ran.\n *\n * **Ordered nearest-first**, because the shallower depths are not the\n * package's own directory once QFAI is installed: from\n * `<project>/node_modules/qfai/dist`, the three-level candidate is\n * `<project>/assets/init`. A consuming project with an unrelated `assets/init`\n * would otherwise be picked as the template root, and a wrong-but-present\n * directory is worse than a missing one — `canonicalSkillIds` would read an\n * empty shipped roster and `QFAI-LINK-001` would pass every broken wrapper\n * without looking at it.\n *\n * Exported for the test that pins those depths; `getInitAssetsDir` is the API.\n */\nexport function initAssetsCandidates(baseDir: string): string[] {\n return [\n path.resolve(baseDir, \"../assets/init\"),\n path.resolve(baseDir, \"../../assets/init\"),\n path.resolve(baseDir, \"../../../assets/init\"),\n ];\n}\n\n/**\n * Files a real `assets/init` tree always has.\n *\n * Existence alone does not identify the directory — the name is generic enough\n * that a consuming project can have one. Both halves of the tree `runInit`\n * copies are required, so an unrelated `assets/init` is rejected and the search\n * continues instead of silently rooting the whole template system somewhere\n * arbitrary.\n */\nconst INIT_ASSETS_SENTINELS = [\n path.join(\".qfai\", \"assistant\"),\n path.join(\"root\", \"qfai.config.yaml\"),\n];\n\nfunction isInitAssetsDir(candidate: string): boolean {\n return INIT_ASSETS_SENTINELS.every((sentinel) => existsSync(path.join(candidate, sentinel)));\n}\n\nexport function getInitAssetsDir(): string {\n const base = import.meta.url;\n const basePath = base.startsWith(\"file:\") ? fileURLToPath(base) : base;\n const baseDir = path.dirname(basePath);\n const candidates = initAssetsCandidates(baseDir);\n\n for (const candidate of candidates) {\n if (isInitAssetsDir(candidate)) {\n return candidate;\n }\n }\n\n throw new Error(\n [\n \"Template assets for init were not found.\",\n \"Checked paths:\",\n ...candidates.map((candidate) => `- ${candidate}`),\n ].join(\"\\n\"),\n );\n}\n","import { execFile } from \"node:child_process\";\nimport { access, lstat, realpath } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport {\n graphEnvironmentKey,\n graphExecutionEnvironment,\n type GraphExecutionEnvironment,\n} from \"./layout.js\";\nimport { assertGraphStoragePath } from \"./storage.js\";\nimport { isEnoent } from \"../fs/errno.js\";\n\nconst execute = promisify(execFile);\nexport const GRAPH_PYTHON_FLAGS = [\"-I\", \"-X\", \"utf8\"] as const;\n\nexport interface GraphProcessResult {\n exitCode: number;\n stdout: string;\n /** Set only for a failed process run with captureStderr; installer output can carry credentials. */\n stderr?: string;\n /** Why a process that did not exit on its own ended: it could not start, or it was stopped. */\n failure?: string;\n}\n\nexport type GraphProcess = (\n command: string,\n args: readonly string[],\n options: {\n cwd: string;\n env?: NodeJS.ProcessEnv;\n timeoutMs?: number;\n maxBufferBytes?: number;\n /** Keep a failed process's stderr in the result. Only version checks ask for it. */\n captureStderr?: boolean;\n },\n) => Promise<GraphProcessResult>;\n\nfunction privateEngineEnvironment(\n root: string,\n engine: \"codegraph\" | \"graphify\",\n execution: GraphExecutionEnvironment,\n): NodeJS.ProcessEnv {\n const environment: NodeJS.ProcessEnv = {};\n const allowed: Record<string, string> = {\n path: \"PATH\",\n systemroot: \"SystemRoot\",\n windir: \"WINDIR\",\n comspec: \"ComSpec\",\n pathext: \"PATHEXT\",\n tmp: \"TMP\",\n temp: \"TEMP\",\n lang: \"LANG\",\n lc_all: \"LC_ALL\",\n };\n for (const [name, value] of Object.entries(process.env)) {\n const canonical = allowed[name.toLowerCase()];\n if (canonical) environment[canonical] = value;\n }\n const home = path.join(root, \".qfai\", \"tools\", \"home\", graphEnvironmentKey(execution), engine);\n return {\n ...environment,\n HOME: home,\n USERPROFILE: home,\n APPDATA: path.join(home, \"AppData\", \"Roaming\"),\n LOCALAPPDATA: path.join(home, \"AppData\", \"Local\"),\n XDG_CONFIG_HOME: path.join(home, \".config\"),\n XDG_CACHE_HOME: path.join(home, \".cache\"),\n XDG_DATA_HOME: path.join(home, \".local\", \"share\"),\n XDG_STATE_HOME: path.join(home, \".local\", \"state\"),\n };\n}\n\nexport function graphifyEnvironment(\n root: string,\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n): NodeJS.ProcessEnv {\n return {\n ...privateEngineEnvironment(root, \"graphify\", environment),\n PYTHONUTF8: \"1\",\n PYTHONIOENCODING: \"utf-8\",\n GRAPHIFY_QUERY_LOG_DISABLE: \"1\",\n GRAPHIFY_OUT: \"graphify-out\",\n GRAPHIFY_ALLOW_LOCAL_PROVIDERS: \"0\",\n GRAPHIFY_NO_AUTO_REFRESH: \"1\",\n };\n}\n\nexport function codegraphEnvironment(\n root: string,\n environment: GraphExecutionEnvironment = graphExecutionEnvironment(),\n): NodeJS.ProcessEnv {\n const privateEnvironment = privateEngineEnvironment(root, \"codegraph\", environment);\n const home = privateEnvironment.HOME ?? \"\";\n return {\n ...privateEnvironment,\n CODEGRAPH_INSTALL_DIR: path.join(home, \".codegraph\"),\n CODEGRAPH_NO_DOWNLOAD: \"1\",\n CODEGRAPH_NO_UPDATE_CHECK: \"1\",\n CODEGRAPH_TELEMETRY: \"0\",\n CODEGRAPH_DIR: \".codegraph\",\n };\n}\n\nexport function graphifyCorpusEnvironment(root: string, analysis: string): NodeJS.ProcessEnv {\n return {\n ...graphifyEnvironment(root),\n GRAPHIFY_OUT: path.toNamespacedPath(path.join(analysis, \"graphify-out\")),\n };\n}\n\nexport async function graphifyConfigurationSafe(root: string): Promise<boolean> {\n const home = graphifyEnvironment(root).HOME;\n if (!home) return false;\n try {\n const configuration = path.join(home, \".graphify\");\n await assertGraphStoragePath(root, configuration);\n await lstat(path.join(configuration, \"providers.json\"));\n return false;\n } catch (cause: unknown) {\n return isEnoent(cause);\n }\n}\n\nexport const runGraphProcess: GraphProcess = async (command, args, options) => {\n try {\n const result = await execute(command, [...args], {\n cwd: options.cwd,\n ...(options.env ? { env: options.env } : {}),\n windowsHide: true,\n timeout: options.timeoutMs ?? 120_000,\n maxBuffer: options.maxBufferBytes ?? 4 * 1024 * 1024,\n });\n return { exitCode: 0, stdout: result.stdout };\n } catch (cause: unknown) {\n if (!(cause instanceof Error) || !(\"code\" in cause)) throw cause;\n // Installation and backend stderr can contain credentials. Callers report the step instead;\n // the preparation names the command a failed download can be rerun with by hand.\n const signal = \"signal\" in cause && typeof cause.signal === \"string\" ? cause.signal : undefined;\n const failure = signal\n ? `was stopped (${signal})`\n : typeof cause.code === \"string\"\n ? `could not start (${cause.code})`\n : undefined;\n return {\n exitCode: typeof cause.code === \"number\" ? cause.code : 1,\n stdout: \"\",\n ...(failure ? { failure } : {}),\n ...(options.captureStderr && \"stderr\" in cause && typeof cause.stderr === \"string\"\n ? { stderr: cause.stderr }\n : {}),\n };\n }\n};\n\nexport async function npmCommand(): Promise<{ command: string; prefix: string[] }> {\n const node = await realpath(process.execPath);\n const candidates = [\n path.join(path.dirname(node), \"node_modules\", \"npm\", \"bin\", \"npm-cli.js\"),\n path.resolve(path.dirname(node), \"..\", \"lib\", \"node_modules\", \"npm\", \"bin\", \"npm-cli.js\"),\n ];\n for (const candidate of candidates) {\n try {\n await access(candidate);\n return { command: process.execPath, prefix: [candidate] };\n } catch (cause: unknown) {\n if (!(cause instanceof Error) || !(\"code\" in cause) || cause.code !== \"ENOENT\") throw cause;\n }\n }\n // POSIX npm launchers are executable scripts. Windows uses the JS entry above.\n return { command: \"npm\", prefix: [] };\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n cp,\n lstat,\n mkdir,\n readFile,\n readdir,\n realpath,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { isEnoent } from \"../fs/errno.js\";\nimport {\n GRAPH_VERSIONS,\n graphAnalysisRoot,\n graphRuntimePaths,\n graphEnvironmentKey,\n} from \"./layout.js\";\nimport {\n excludedGraphInput,\n graphDeliberationDir,\n inspectCodeAnalysisAt,\n nativeCodeAnalysisCurrent,\n} from \"./analysis.js\";\nimport {\n assertGraphStoragePath,\n assertIndependentAnalysis,\n replaceGraphDirectory,\n} from \"./storage.js\";\nimport { codegraphEnvironment, type GraphProcess } from \"./process.js\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\n\nfunction verifiedNativeRelease(output: string): boolean {\n const release = /^v(\\d+\\.\\d+\\.\\d+)$/.exec(output.trim());\n return release?.[1] === \"24.16.0\";\n}\n\nexport interface GraphReuseEnvironment {\n platform: string;\n architecture: string;\n machine: string;\n}\n\nexport function graphReuseEnvironment(): GraphReuseEnvironment {\n return { platform: process.platform, architecture: process.arch, machine: os.hostname() };\n}\n\nexport async function restoreCompletedCodeAnalysis(\n root: string,\n run: GraphProcess,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<\"restored\" | \"cold\"> {\n // Other native bundle combinations use generation until independent-copy proof exists.\n if (environment.platform !== \"win32\" || environment.architecture !== \"x64\") return \"cold\";\n const nativeRuntime = await run(graphRuntimePaths(root).codegraphNode, [\"--version\"], {\n cwd: root,\n env: codegraphEnvironment(root),\n });\n if (nativeRuntime.exitCode !== 0 || !verifiedNativeRelease(nativeRuntime.stdout)) return \"cold\";\n const location = await completedAnalysisCache(root, \"codegraph\", run, environment);\n if (!location) return \"cold\";\n let candidates;\n try {\n candidates = await readdir(location.directory, { withFileTypes: true });\n } catch (cause: unknown) {\n if (isEnoent(cause)) return \"cold\";\n throw cause;\n }\n const deliberationDir = await graphDeliberationDir(root);\n for (const entry of candidates) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name.startsWith(\".\")) continue;\n const candidate = path.join(location.directory, entry.name);\n if (!(await cacheDirectorySafe(location.repository, candidate))) continue;\n const metadata = await readSnapshotMetadata(candidate);\n if (\n !metadata ||\n Object.keys(metadata).some(\n (key) =>\n ![\"layout\", \"corpusPolicy\", \"repository\", \"engineVersion\", \"environment\"].includes(key),\n ) ||\n metadata.layout !== 1 ||\n metadata.corpusPolicy !== 1 ||\n metadata.repository !== location.repository ||\n metadata.engineVersion !== GRAPH_VERSIONS.codegraph ||\n !sameEnvironment(metadata.environment, environment)\n )\n continue;\n if (!(await safeCompletedCorpus(path.join(candidate, \"analysis\"), deliberationDir))) continue;\n if (!(await safeCodegraphInputs(root, path.join(candidate, \"analysis\"), run, deliberationDir)))\n continue;\n const current = graphAnalysisRoot(root, \"codegraph\");\n const staged = path.join(path.dirname(current), `.restoring-codegraph-${randomUUID()}`);\n await assertGraphStoragePath(root, staged);\n try {\n const cached = path.join(candidate, \"analysis\");\n await assertIndependentAnalysis(cached);\n await mkdir(path.dirname(staged), { recursive: true });\n await cp(cached, staged, { recursive: true, dereference: false });\n await assertIndependentAnalysis(staged);\n if (!(await inspectCodeAnalysisAt(root, staged, run))) continue;\n await replaceGraphDirectory(staged, current, root);\n return \"restored\";\n } finally {\n await rm(staged, { recursive: true, force: true });\n }\n }\n return \"cold\";\n}\n\nexport async function completedAnalysisCache(\n root: string,\n engine: \"codegraph\" | \"graphify\" | \"graphify-code\",\n run: GraphProcess,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<{ repository: string; directory: string } | undefined> {\n const git = await run(\"git\", [\"rev-parse\", \"--path-format=absolute\", \"--git-common-dir\"], {\n cwd: root,\n });\n if (git.exitCode !== 0 || !path.isAbsolute(git.stdout.trim())) return undefined;\n const repository = await realpath(git.stdout.trim());\n return {\n repository,\n directory: path.join(repository, \"qfai-graph-cache\", graphEnvironmentKey(environment), engine),\n };\n}\n\nexport async function publishCompletedCodeAnalysis(\n root: string,\n run: GraphProcess,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<\"published\" | \"unavailable\"> {\n let staged: string | undefined;\n try {\n if (environment.platform !== \"win32\" || environment.architecture !== \"x64\")\n return \"unavailable\";\n const native = await run(graphRuntimePaths(root).codegraphNode, [\"--version\"], {\n cwd: root,\n env: codegraphEnvironment(root),\n });\n if (native.exitCode !== 0 || !verifiedNativeRelease(native.stdout)) return \"unavailable\";\n const cache = await completedAnalysisCache(root, \"codegraph\", run, environment);\n if (!cache) return \"unavailable\";\n await ensureCacheDirectory(cache.repository, cache.directory);\n const analysis = graphAnalysisRoot(root, \"codegraph\");\n const deliberationDir = await graphDeliberationDir(root);\n if (\n !(await safeCompletedCorpus(analysis, deliberationDir)) ||\n !(await safeCodegraphInputs(root, analysis, run, deliberationDir))\n )\n return \"unavailable\";\n const identity = randomUUID();\n staged = path.join(cache.directory, `.publishing-${identity}`);\n await mkdir(staged);\n await cp(analysis, path.join(staged, \"analysis\"), { recursive: true, dereference: false });\n await assertIndependentAnalysis(path.join(staged, \"analysis\"));\n if (\n !(await safeCompletedCorpus(path.join(staged, \"analysis\"), deliberationDir)) ||\n !(await safeCodegraphInputs(root, path.join(staged, \"analysis\"), run, deliberationDir))\n )\n return \"unavailable\";\n if (!(await nativeCodeAnalysisCurrent(root, path.join(staged, \"analysis\"), run)))\n return \"unavailable\";\n await writeFile(\n path.join(staged, \"completed.json\"),\n JSON.stringify({\n layout: 1,\n corpusPolicy: 1,\n repository: cache.repository,\n engineVersion: GRAPH_VERSIONS.codegraph,\n environment,\n }) + \"\\n\",\n );\n await rename(staged, path.join(cache.directory, identity));\n return \"published\";\n } catch {\n return \"unavailable\";\n } finally {\n if (staged) await rm(staged, { recursive: true, force: true });\n }\n}\n\nexport async function ensureCacheDirectory(repository: string, directory: string): Promise<void> {\n const relative = path.relative(repository, directory);\n const parts = relative.split(path.sep);\n if (path.isAbsolute(relative) || parts.includes(\"..\") || parts[0] !== \"qfai-graph-cache\")\n throw new Error(\"Unsafe completed analysis path.\");\n for (let depth = 1; depth <= parts.length; depth += 1) {\n const component = path.join(repository, ...parts.slice(0, depth));\n let stats;\n try {\n stats = await lstat(component);\n } catch (cause: unknown) {\n if (!isEnoent(cause)) throw cause;\n await mkdir(component);\n stats = await lstat(component);\n }\n if (stats.isSymbolicLink() || !stats.isDirectory())\n throw new Error(\"Unsafe completed analysis path.\");\n }\n}\n\nexport async function cacheDirectorySafe(repository: string, candidate: string): Promise<boolean> {\n const relative = path.relative(repository, candidate);\n const parts = relative.split(path.sep);\n if (path.isAbsolute(relative) || parts.includes(\"..\") || parts[0] !== \"qfai-graph-cache\")\n return false;\n for (let depth = 1; depth <= parts.length; depth += 1) {\n const stats = await lstat(path.join(repository, ...parts.slice(0, depth)));\n if (stats.isSymbolicLink() || !stats.isDirectory()) return false;\n }\n return true;\n}\n\nexport async function readSnapshotMetadata(\n candidate: string,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const stats = await lstat(path.join(candidate, \"completed.json\"));\n if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1) return undefined;\n const metadata: unknown = JSON.parse(\n await readFile(path.join(candidate, \"completed.json\"), \"utf8\"),\n );\n return object(metadata) ? metadata : undefined;\n } catch (cause: unknown) {\n if (isEnoent(cause) || cause instanceof SyntaxError) return undefined;\n throw cause;\n }\n}\n\nexport function sameEnvironment(value: unknown, environment: GraphReuseEnvironment): boolean {\n return (\n object(value) &&\n Object.keys(value).length === 3 &&\n value.platform === environment.platform &&\n value.architecture === environment.architecture &&\n value.machine === environment.machine\n );\n}\n\nexport async function safeCompletedCorpus(\n directory: string,\n deliberationDir: string,\n relative = \"\",\n engineDirectory = \".codegraph\",\n): Promise<boolean> {\n try {\n for (const entry of await readdir(path.join(directory, ...relative.split(\"/\")), {\n withFileTypes: true,\n })) {\n const next = relative ? `${relative}/${entry.name}` : entry.name;\n const input = next.startsWith(`${engineDirectory}/`)\n ? next.slice(engineDirectory.length + 1)\n : next;\n if (\n (next !== engineDirectory && excludedGraphInput(input, deliberationDir)) ||\n /\\.(?:pid|lock)$/i.test(entry.name)\n )\n return false;\n const stats = await lstat(path.join(directory, ...next.split(\"/\")));\n if (stats.isSymbolicLink() || (stats.isFile() && stats.nlink !== 1)) return false;\n if (\n stats.isDirectory() &&\n !(await safeCompletedCorpus(directory, deliberationDir, next, engineDirectory))\n )\n return false;\n if (!stats.isDirectory() && !stats.isFile()) return false;\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function safeCodegraphInputs(\n root: string,\n analysis: string,\n run: GraphProcess,\n deliberationDir: string,\n): Promise<boolean> {\n const runtime = graphRuntimePaths(root);\n const result = await run(\n runtime.codegraphNode,\n [\n \"--liftoff-only\",\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"codegraph-native.mjs\"),\n runtime.codegraphSdk,\n analysis,\n \"inventory\",\n ],\n { cwd: analysis, env: codegraphEnvironment(root) },\n );\n if (result.exitCode !== 0) return false;\n try {\n const inventory: unknown = JSON.parse(result.stdout);\n if (!object(inventory) || !Array.isArray(inventory.files)) return false;\n for (const file of inventory.files) {\n if (\n typeof file !== \"string\" ||\n !file ||\n path.posix.isAbsolute(file) ||\n path.win32.isAbsolute(file)\n )\n return false;\n const normalized = file.replaceAll(\"\\\\\", \"/\");\n const parts = normalized.split(\"/\");\n if (\n parts.some((part) => !part || part === \".\" || part === \"..\") ||\n excludedGraphInput(normalized, deliberationDir)\n )\n return false;\n const stats = await lstat(path.join(analysis, ...parts));\n if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1) return false;\n }\n return true;\n } catch {\n return false;\n }\n}\n","import path from \"node:path\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\nimport { copyFile, lstat, mkdir, readdir, rm } from \"node:fs/promises\";\nimport { isDirectoryInsideRoot, loadConfig, resolvePath } from \"../config.js\";\nimport { isEnoent } from \"../fs/errno.js\";\nimport { GraphLocalStateError } from \"./localFiles.js\";\nimport { GRAPH_VERSIONS, graphRuntimePaths, graphAnalysisRoot } from \"./layout.js\";\nimport type { GraphProcess } from \"./process.js\";\nimport { codegraphEnvironment } from \"./process.js\";\nimport { assertGraphStoragePath, assertIndependentAnalysis } from \"./storage.js\";\nexport { graphAnalysisRoot } from \"./layout.js\";\n\nexport interface CodeAnalysisCoverage {\n complete: boolean;\n unsupported: string[];\n unreadable: string[];\n unparsed: string[];\n}\n\nexport async function inspectCodeCoverage(\n root: string,\n run: GraphProcess,\n): Promise<CodeAnalysisCoverage> {\n const unknown = { complete: false, unsupported: [], unreadable: [], unparsed: [] };\n const runtime = graphRuntimePaths(root);\n const analysis = graphAnalysisRoot(root, \"codegraph\");\n const result = await run(\n runtime.codegraphNode,\n [\n \"--liftoff-only\",\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"codegraph-native.mjs\"),\n runtime.codegraphSdk,\n analysis,\n \"coverage\",\n ],\n { cwd: analysis, env: codegraphEnvironment(root) },\n );\n if (result.exitCode !== 0) return unknown;\n let value: unknown;\n try {\n value = JSON.parse(result.stdout);\n } catch {\n return unknown;\n }\n if (\n !object(value) ||\n Object.keys(value).length !== 4 ||\n typeof value.complete !== \"boolean\" ||\n !stringArray(value.unsupported) ||\n !stringArray(value.unreadable) ||\n !stringArray(value.unparsed)\n )\n return unknown;\n return {\n complete:\n value.complete &&\n value.unsupported.length === 0 &&\n value.unreadable.length === 0 &&\n value.unparsed.length === 0,\n unsupported: value.unsupported,\n unreadable: value.unreadable,\n unparsed: value.unparsed,\n };\n}\n\nfunction stringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry: unknown) => typeof entry === \"string\");\n}\n\nexport async function inspectCurrentCodeAnalysis(\n root: string,\n run: GraphProcess,\n): Promise<boolean> {\n const analysis = graphAnalysisRoot(root, \"codegraph\");\n return inspectCodeAnalysisAt(root, analysis, run);\n}\n\nexport async function inspectCodeAnalysisAt(\n root: string,\n analysis: string,\n run: GraphProcess,\n): Promise<boolean> {\n await assertGraphStoragePath(root, analysis);\n try {\n if (!(await lstat(path.join(analysis, \".codegraph\", \"codegraph.db\"))).isFile()) return false;\n } catch (cause: unknown) {\n if (isEnoent(cause)) return false;\n throw cause;\n }\n await mirrorGraphCorpus(root, analysis);\n return nativeCodeAnalysisCurrent(root, analysis, run);\n}\n\nexport async function nativeCodeAnalysisCurrent(\n root: string,\n analysis: string,\n run: GraphProcess,\n): Promise<boolean> {\n const result = await run(\n process.execPath,\n [graphRuntimePaths(root).codegraph, \"status\", analysis, \"--json\"],\n { cwd: root, env: codegraphEnvironment(root) },\n );\n if (result.exitCode !== 0) return false;\n let value: unknown;\n try {\n value = JSON.parse(result.stdout);\n } catch (cause: unknown) {\n if (!(cause instanceof SyntaxError)) throw cause;\n return false;\n }\n if (!object(value) || !object(value.index) || !object(value.pendingChanges)) return false;\n const changes = value.pendingChanges;\n return (\n value.initialized === true &&\n value.version === GRAPH_VERSIONS.codegraph &&\n value.projectPath === analysis &&\n value.worktreeMismatch === null &&\n value.index.state === \"complete\" &&\n value.index.pendingRefs === 0 &&\n value.index.reindexRecommended === false &&\n value.index.builtWithVersion === GRAPH_VERSIONS.codegraph &&\n value.index.builtWithExtractionVersion !== undefined &&\n value.index.builtWithExtractionVersion === value.index.currentExtractionVersion &&\n [\"added\", \"modified\", \"removed\"].every((key) => changes[key] === 0)\n );\n}\n\nconst excludedDirectories = new Set([\n \".git\",\n \".codegraph\",\n \".codegraph-wsl\",\n \".graphify\",\n \"graphify-out\",\n \"node_modules\",\n \"dist\",\n \"tmp\",\n \".claude\",\n \".codex\",\n \".vscode\",\n \".ssh\",\n \".aws\",\n \".azure\",\n]);\n\n/**\n * `qfai.config.yaml` cannot be read, or gives no usable `paths.deliberationDir`, so the graph\n * cannot know which directory to keep out of its corpus.\n */\nexport class GraphConfigUnreadableError extends GraphLocalStateError {\n constructor(configFile: string, unreadable: boolean) {\n super(\n unreadable\n ? `${configFile} could not be read or parsed.`\n : `${configFile} gives no usable paths.deliberationDir.`,\n `Correct ${configFile}, then retry.`,\n );\n }\n}\n\n/**\n * The configured `paths.deliberationDir`, relative to `root` and written with `/`. It throws\n * where the configuration cannot be read or its value is rejected, rather than guess the\n * default: the project may keep its records elsewhere. A value naming the project root, or a\n * directory outside it, is rejected too: it would leave the corpus nothing to exclude.\n */\nexport async function graphDeliberationDir(root: string): Promise<string> {\n const { config, document, issues, configPath } = await loadConfig(root);\n const file = path.basename(configPath);\n if (document === undefined && issues.length > 0) throw new GraphConfigUnreadableError(file, true);\n const paths = object(document) ? document.paths : undefined;\n const value = object(paths) ? paths.deliberationDir : undefined;\n if (\n (document !== undefined && document !== null && !object(document)) ||\n (paths !== undefined && paths !== null && !object(paths)) ||\n (value !== undefined &&\n (typeof value !== \"string\" ||\n value.trim() === \"\" ||\n !isDirectoryInsideRoot(root, value.replace(/\\\\/g, \"/\"))))\n )\n throw new GraphConfigUnreadableError(file, false);\n return path\n .relative(root, resolvePath(root, config, \"deliberationDir\"))\n .split(path.sep)\n .join(\"/\");\n}\n\nexport function excludedGraphInput(relative: string, deliberationDir: string): boolean {\n const parts = relative.split(\"/\");\n const name = parts.at(-1) ?? \"\";\n const lowered = relative.toLowerCase();\n const deliberation = deliberationDir.toLowerCase();\n return (\n parts.some((part) => excludedDirectories.has(part.toLowerCase())) ||\n /^\\.qfai\\/(?:tools|report|evidence|review)(?:\\/|$)/i.test(relative) ||\n lowered === deliberation ||\n lowered.startsWith(`${deliberation}/`) ||\n lowered === \".qfai/graph-processing.json\" ||\n /^(?:\\.npmrc|\\.pypirc|\\.netrc|\\.git-credentials)$/i.test(name) ||\n /^\\.env(?:\\.|$)/i.test(name) ||\n /\\.(?:pem|key|p12|pfx|keystore)$/i.test(name) ||\n /^(?:id_(?:rsa|dsa|ecdsa|ed25519)|credentials?(?:\\.|$)|secrets?(?:\\.|$)|\\.mcp\\.json$)/i.test(\n name,\n )\n );\n}\n\nexport async function mirrorGraphCorpus(\n root: string,\n destination: string,\n scope?: readonly string[],\n): Promise<void> {\n await assertGraphStoragePath(root, destination);\n await assertIndependentAnalysis(destination);\n const files = new Set<string>();\n const deliberationDir = await graphDeliberationDir(root);\n await visit(\"\");\n await removeAbsent(\"\");\n\n async function visit(relative: string): Promise<void> {\n for (const entry of await readdir(path.join(root, ...relative.split(\"/\")), {\n withFileTypes: true,\n })) {\n const next = relative ? `${relative}/${entry.name}` : entry.name;\n if (excludedGraphInput(next, deliberationDir) || entry.isSymbolicLink()) continue;\n if (\n scope &&\n !scope.some(\n (item) => item === next || next.startsWith(`${item}/`) || item.startsWith(`${next}/`),\n )\n )\n continue;\n if (entry.isDirectory()) {\n await visit(next);\n } else if (entry.isFile()) {\n const source = path.join(root, ...next.split(\"/\"));\n const stats = await lstat(source);\n if (!stats.isFile() || stats.nlink > 1) continue;\n const target = path.join(destination, ...next.split(\"/\"));\n await mkdir(path.dirname(target), { recursive: true });\n await copyFile(source, target);\n files.add(next);\n }\n }\n }\n\n async function removeAbsent(relative: string): Promise<void> {\n for (const entry of await readdir(path.join(destination, ...relative.split(\"/\")), {\n withFileTypes: true,\n })) {\n const next = relative ? `${relative}/${entry.name}` : entry.name;\n if (entry.name === \".codegraph\" || entry.name === \".git\" || entry.name === \"graphify-out\")\n continue;\n const target = path.join(destination, ...next.split(\"/\"));\n if (entry.isDirectory()) await removeAbsent(next);\n else if (!files.has(next)) await rm(target);\n }\n }\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { access, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { parse as parseYaml } from \"yaml\";\n\nimport type { Issue } from \"./types.js\";\nimport { isEnoent } from \"./fs/errno.js\";\nimport { SHIPPED_WORKFLOW_NAMES } from \"../shared/shippedWorkflowNames.js\";\n\nexport type FailOn = \"never\" | \"warning\" | \"error\";\nexport type OutputFormat = \"text\" | \"github\";\n\nexport type QfaiPaths = {\n contractsDir: string;\n specsDir: string;\n /** Where the per-run deliberation records live, read with `\\` taken as `/`. */\n deliberationDir: string;\n outDir: string;\n skillsDir: string;\n srcDir: string;\n testsDir: string;\n /**\n * Where the project's migrations live, if it has any.\n *\n * Optional and unset by default, because qfai cannot guess it and a project\n * without migrations is not in violation of anything. `qfai db-drift` is the\n * only reader: with no value it says the project is out of scope and stops,\n * rather than comparing the contracts against an empty directory and calling\n * every column a difference.\n */\n migrationsDir?: string;\n};\n\nexport type QfaiForbiddenIdentifier = {\n sha256: string;\n byteLength: number;\n};\n\nexport type DiagramBudget = { nodes: number; edges: number };\n\nexport const DEFAULT_DIAGRAM_BUDGET: DiagramBudget = { nodes: 12, edges: 16 };\n\nexport type QfaiValidationConfig = {\n failOn: FailOn;\n /**\n * Terms the specs must no longer state, such as an option a decision rejected.\n * `qfai validate` warns on each line of a spec document that still holds one\n * (QFAI-STORY-016). Unset means no term is checked.\n */\n staleTerms?: string[];\n /**\n * The largest node and edge counts a Mermaid diagram may have before\n * `qfai validate` warns (QFAI-FLOW-006). A limit left unset is the default\n * of `DEFAULT_DIAGRAM_BUDGET`.\n */\n diagramBudget?: Partial<DiagramBudget>;\n /** Hash-only identifiers checked against tracked names and current file bytes. */\n forbiddenIdentifiers?: QfaiForbiddenIdentifier[];\n testStrategy: {\n /**\n * When true (default), `qfai validate` reports the silent-placeholder\n * construct of each supported stack in test files (QFAI-TEST-001). On\n * JS/TS that is `it.todo` / `test.todo` / `describe.todo` (error) and\n * `it.skip` / `test.skip` / `describe.skip` (warning).\n * Set to false to opt out while migrating an existing project.\n */\n forbidTestTodoStubs: boolean;\n };\n traceability: {\n testFileGlobs: string[];\n testFileExcludeGlobs: string[];\n };\n};\n\nexport type QfaiOutputConfig = {\n validateJsonPath: string;\n};\n\nexport type QfaiUiuxAuditConfig = {\n enabled?: boolean;\n slopDetection?: boolean;\n maxRawTokenLiteralWarnings?: number;\n maxDuplicateFindingsPerRule?: number;\n};\n\nexport type QfaiUiuxConfig = {\n platform?: string;\n /**\n * Component registries the project can procure from, as name to URL\n * template. The shape mirrors the `registries` map a `components.json`\n * already carries, so a project that has one restates it rather than\n * translating it.\n *\n * Which registry is primary is named by the `Component catalogue` row of the\n * Stack table in `.qfai/spec/03_contract/tech.md`. Nothing here ranks them.\n */\n registries?: Record<string, string>;\n designTokensDir?: string;\n htmlMockTimeout?: number;\n qualityProfile?: \"strict\" | \"high\" | \"default\";\n /**\n * Repository-relative POSIX globs of the paths that render a user-visible\n * surface. An empty list states that the project renders none; an absent\n * key declares nothing.\n */\n surfacePaths?: string[];\n audit?: QfaiUiuxAuditConfig;\n};\n\nexport type QfaiPrototypingExecutionConfig = {\n targetUrl?: string | null;\n /**\n * Browser tool handed to the AI evaluator sub-agent. Only `\"playwright\"` is\n * accepted.\n */\n browserTool: \"playwright\";\n};\n\nexport type QfaiPrototypingConfig = {\n execution?: QfaiPrototypingExecutionConfig;\n /**\n * Explicit primary UI contract for `/qfai-prototyping`.\n * Uses the full `UI-NNNN` identifier.\n */\n primaryUiContract?: string;\n};\n\nexport type QfaiReportConfig = {\n /**\n * Stale run-log TTL (calendar days) used by `qfai doctor --clean` to\n * decide whether a `<paths.outDir>/run-*` directory may be pruned.\n * `0` opts out entirely (never prune). Default (when unset) is applied\n * at the call-site by `RUN_LOG_STALE_TTL_DAYS_DEFAULT`.\n */\n staleTtlDays?: number;\n /**\n * Number of newest `run-*` directories retained regardless of age, so\n * `validate.log`'s `run_log:` pointer can never be pruned away.\n * Default (when unset) is applied at the call-site by\n * `RUN_LOG_KEEP_LATEST_DEFAULT`; `0` is clamped up to\n * `RUN_LOG_KEEP_LATEST_MIN` (1) there, because keeping nothing would\n * strand that pointer. Use `staleTtlDays: 0` to keep every run.\n */\n keepLatestRuns?: number;\n};\n\nexport type QfaiConfig = {\n paths: QfaiPaths;\n validation: QfaiValidationConfig;\n output: QfaiOutputConfig;\n uiux?: QfaiUiuxConfig;\n prototyping?: QfaiPrototypingConfig;\n report?: QfaiReportConfig;\n baseBranch?: string;\n};\n\n/**\n * The path keys `resolvePath` can resolve: the ones every config has.\n *\n * An optional key is excluded by its type rather than by a list, so a path\n * added later joins or stays out on its own. `resolvePath` returns a string,\n * and there is no directory to return for a key the project did not set — its\n * reader has to decide what absence means, which is not something a resolver\n * can do for it.\n */\nexport type ConfigPathKey = {\n [K in keyof QfaiPaths]-?: undefined extends QfaiPaths[K] ? never : K;\n}[keyof QfaiPaths];\n\nexport type ConfigLoadResult = {\n config: QfaiConfig;\n issues: Issue[];\n configPath: string;\n /**\n * The parsed YAML document, before normalization. `undefined` when the\n * file is absent (`issues` empty) or could not be read / parsed at all\n * (`issues` non-empty) — the two cases a caller distinguishes by the\n * issue list.\n *\n * `issues` records *that* something was rejected but not *which* key,\n * so it cannot answer \"was the value I depend on honoured, or silently\n * replaced by its default?\". Normalization is per-key and independent,\n * so an unrelated rejection (a bad `baseBranch`, say) says nothing\n * about `paths.specsDir`. A caller whose correctness hinges on one\n * key reads it here and checks that key alone, rather than treating any\n * issue anywhere in the file as a reason to distrust the whole config.\n */\n document?: unknown;\n};\n\nexport type ConfigSearchResult = {\n root: string;\n configPath: string;\n found: boolean;\n};\n\nexport const defaultConfig: QfaiConfig = {\n paths: {\n contractsDir: \".qfai/spec/03_contract\",\n specsDir: \".qfai/spec\",\n deliberationDir: \".qfai/deliberation\",\n outDir: \".qfai/report\",\n skillsDir: \".qfai/assistant/skill\",\n srcDir: \"src\",\n testsDir: \"tests\",\n },\n validation: {\n failOn: \"error\",\n testStrategy: {\n forbidTestTodoStubs: true,\n },\n traceability: {\n testFileGlobs: [],\n testFileExcludeGlobs: [],\n },\n },\n output: {\n validateJsonPath: \".qfai/report/validate.json\",\n },\n prototyping: {\n execution: {\n targetUrl: null,\n browserTool: \"playwright\",\n },\n },\n};\n\nexport function getConfigPath(root: string): string {\n return path.join(root, \"qfai.config.yaml\");\n}\n\nexport async function findConfigRoot(startDir: string): Promise<ConfigSearchResult> {\n const resolvedStart = path.resolve(startDir);\n let current = resolvedStart;\n\n for (;;) {\n const configPath = getConfigPath(current);\n if (await exists(configPath)) {\n return { root: current, configPath, found: true };\n }\n const parent = path.dirname(current);\n if (parent === current) {\n break;\n }\n current = parent;\n }\n\n return {\n root: resolvedStart,\n configPath: getConfigPath(resolvedStart),\n found: false,\n };\n}\n\nexport async function loadConfig(root: string): Promise<ConfigLoadResult> {\n const configPath = getConfigPath(root);\n const issues: Issue[] = [];\n\n let parsed: unknown;\n try {\n const raw = await readFile(configPath, \"utf-8\");\n parsed = parseYaml(raw);\n } catch (error) {\n if (isEnoent(error)) {\n return { config: defaultConfig, issues, configPath };\n }\n issues.push(configIssue(configPath, \"The configuration file could not be read or parsed.\"));\n return { config: defaultConfig, issues, configPath };\n }\n\n const normalized = normalizeConfig(parsed, configPath, issues);\n if (readWorkflowMode(parsed) === null) {\n issues.push(configIssue(configPath, WORKFLOW_MODE_MESSAGE));\n }\n if (readSkippedWorkflows(parsed) === null) {\n issues.push(configIssue(configPath, SKIPPED_WORKFLOWS_MESSAGE));\n }\n if (readAcceptedDrift(parsed) === null) {\n issues.push(configIssue(configPath, ACCEPTED_DRIFT_MESSAGE));\n }\n if (readStopGate(parsed) === null) {\n issues.push(configIssue(configPath, STOP_GATE_MESSAGE));\n }\n return { config: normalized, issues, configPath, document: parsed };\n}\n\n/** The config issue an invalid `workflow.stopGate` raises. */\nexport const STOP_GATE_MESSAGE =\n \"workflow.stopGate must be true or false; an absent key means true.\";\n\n/**\n * Whether the turn-end hook runs the project's turn-end checks, read from the parsed config\n * document. `null` means the value is not a boolean, which the hook treats as `false`.\n */\nexport function readStopGate(document: unknown): boolean | null {\n const workflow = isRecord(document) ? document.workflow : undefined;\n if (workflow === undefined) return true;\n if (!isRecord(workflow)) return null;\n if (workflow.stopGate === undefined) return true;\n return typeof workflow.stopGate === \"boolean\" ? workflow.stopGate : null;\n}\n\nconst WORKFLOW_MODES = [\"active\", \"shadow\", \"off\"] as const;\n\n/** The config issue an invalid `workflow.mode` raises. */\nexport const WORKFLOW_MODE_MESSAGE =\n \"workflow.mode must be active, shadow or off; an absent key means active.\";\n\nexport type WorkflowMode = (typeof WORKFLOW_MODES)[number];\n\n/**\n * The workflow mode in force, read from the parsed config document. `null` means the value is\n * none of the three, and no mode is guessed in its place.\n */\nexport function readWorkflowMode(document: unknown): WorkflowMode | null {\n const workflow = isRecord(document) ? document.workflow : undefined;\n if (workflow === undefined) return \"active\";\n if (!isRecord(workflow)) return null;\n const mode = workflow.mode;\n if (mode === undefined) return \"active\";\n return WORKFLOW_MODES.find((known) => known === mode) ?? null;\n}\n\n/** The config issue an invalid `workflow.skipShipped` raises. */\nexport const SKIPPED_WORKFLOWS_MESSAGE = `workflow.skipShipped must be a list of shipped workflow file names (${[...SHIPPED_WORKFLOW_NAMES].join(\", \")}); an absent key means none are skipped.`;\n\n/**\n * The shipped workflow names `workflow.skipShipped` lists, read from the parsed config document.\n * `null` means the value is not a list of shipped names, and no entry is guessed in its place.\n */\nexport function readSkippedWorkflows(document: unknown): ReadonlySet<string> | null {\n const workflow = isRecord(document) ? document.workflow : undefined;\n if (!isRecord(workflow) || workflow.skipShipped === undefined) return new Set();\n const listed = workflow.skipShipped;\n if (!Array.isArray(listed)) return null;\n const names = new Set<string>();\n for (const name of listed) {\n if (typeof name !== \"string\" || !SHIPPED_WORKFLOW_NAMES.has(name)) return null;\n names.add(name);\n }\n return names;\n}\n\n/** The config issue an invalid `workflow.acceptedDrift` raises. */\nexport const ACCEPTED_DRIFT_MESSAGE = `workflow.acceptedDrift must be a list of entries, each with a file, one of the shipped workflow file names (${[...SHIPPED_WORKFLOW_NAMES].join(\", \")}) listed once, the digest qfai doctor prints for it (sha256: and 64 lowercase hexadecimal characters), and a reason that is not empty; an absent key means no difference is accepted.`;\n\n/** One `workflow.acceptedDrift` entry: the digest of the accepted text and why it is kept. */\nexport type AcceptedDrift = { readonly digest: string; readonly reason: string };\n\nconst DRIFT_DIGEST = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * The shipped workflows `workflow.acceptedDrift` accepts as differing from the shipped text, each\n * with the digest of the accepted text and its trimmed reason, read from the parsed config\n * document. `null` means the value is not a list of such entries, and no entry is accepted in its\n * place.\n */\nexport function readAcceptedDrift(document: unknown): ReadonlyMap<string, AcceptedDrift> | null {\n const workflow = isRecord(document) ? document.workflow : undefined;\n if (!isRecord(workflow) || workflow.acceptedDrift === undefined) return new Map();\n const listed = workflow.acceptedDrift;\n if (!Array.isArray(listed)) return null;\n const accepted = new Map<string, AcceptedDrift>();\n for (const entry of listed) {\n if (!isRecord(entry)) return null;\n const { file, digest, reason } = entry;\n if (typeof file !== \"string\" || !SHIPPED_WORKFLOW_NAMES.has(file) || accepted.has(file)) {\n return null;\n }\n if (typeof digest !== \"string\" || !DRIFT_DIGEST.test(digest)) return null;\n if (typeof reason !== \"string\" || reason.trim() === \"\") return null;\n accepted.set(file, { digest, reason: reason.trim() });\n }\n return accepted;\n}\n\nexport function resolvePath(root: string, config: QfaiConfig, key: ConfigPathKey): string {\n return path.resolve(root, config.paths[key]);\n}\n\nfunction normalizeConfig(raw: unknown, configPath: string, issues: Issue[]): QfaiConfig {\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"The configuration file format is invalid.\"));\n return defaultConfig;\n }\n\n const uiux = normalizeUiux(raw.uiux, configPath, issues);\n const prototyping = normalizePrototyping(raw.prototyping, configPath, issues);\n const report = normalizeReport(raw.report, configPath, issues);\n const base: QfaiConfig = {\n paths: normalizePaths(raw.paths, configPath, issues),\n validation: normalizeValidation(raw.validation, configPath, issues),\n output: normalizeOutput(raw.output, configPath, issues),\n };\n if (uiux) {\n base.uiux = uiux;\n }\n if (prototyping) {\n base.prototyping = prototyping;\n }\n if (report) {\n base.report = report;\n }\n const baseBranch = readOptionalString(raw.baseBranch, \"baseBranch\", configPath, issues);\n if (baseBranch !== undefined) {\n base.baseBranch = baseBranch;\n }\n return base;\n}\n\nfunction normalizePaths(raw: unknown, configPath: string, issues: Issue[]): QfaiPaths {\n const base = defaultConfig.paths;\n if (!raw) {\n return base;\n }\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"paths must be an object.\"));\n return base;\n }\n\n const migrationsDir = readOptionalString(\n raw.migrationsDir,\n \"paths.migrationsDir\",\n configPath,\n issues,\n );\n\n return {\n ...(migrationsDir !== undefined ? { migrationsDir } : {}),\n contractsDir: readTreeDirString(\n raw.contractsDir,\n base.contractsDir,\n \"paths.contractsDir\",\n configPath,\n issues,\n ),\n specsDir: readTreeDirString(raw.specsDir, base.specsDir, \"paths.specsDir\", configPath, issues),\n deliberationDir: readDeliberationDir(\n raw.deliberationDir,\n base.deliberationDir,\n configPath,\n issues,\n ),\n outDir: readDirString(raw.outDir, base.outDir, \"paths.outDir\", configPath, issues),\n skillsDir: readDirString(raw.skillsDir, base.skillsDir, \"paths.skillsDir\", configPath, issues),\n srcDir: readDirString(raw.srcDir, base.srcDir, \"paths.srcDir\", configPath, issues),\n testsDir: readDirString(raw.testsDir, base.testsDir, \"paths.testsDir\", configPath, issues),\n };\n}\n\nfunction normalizeValidation(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): QfaiValidationConfig {\n const base = defaultConfig.validation;\n if (!raw) {\n return base;\n }\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"validation must be an object.\"));\n return base;\n }\n\n let traceabilityRaw: Record<string, unknown> | undefined;\n if (raw.traceability === undefined) {\n traceabilityRaw = undefined;\n } else if (isRecord(raw.traceability)) {\n traceabilityRaw = raw.traceability;\n } else {\n issues.push(configIssue(configPath, \"validation.traceability must be an object.\"));\n traceabilityRaw = undefined;\n }\n\n let testStrategyRaw: Record<string, unknown> | undefined;\n if (raw.testStrategy === undefined) {\n testStrategyRaw = undefined;\n } else if (isRecord(raw.testStrategy)) {\n testStrategyRaw = raw.testStrategy;\n } else {\n issues.push(configIssue(configPath, \"validation.testStrategy must be an object.\"));\n testStrategyRaw = undefined;\n }\n\n reportRetiredTraceabilityKeys(traceabilityRaw, configPath, issues);\n\n const forbiddenIdentifiers = normalizeForbiddenIdentifiers(\n raw.forbiddenIdentifiers,\n configPath,\n issues,\n );\n\n const staleTerms = readStringArray(\n raw.staleTerms,\n [],\n \"validation.staleTerms\",\n configPath,\n issues,\n );\n\n const diagramBudget = readDiagramBudget(raw.diagramBudget, configPath, issues);\n\n return {\n failOn: readFailOn(raw.failOn, base.failOn, \"validation.failOn\", configPath, issues),\n ...(staleTerms.length > 0 ? { staleTerms } : {}),\n ...(diagramBudget !== undefined ? { diagramBudget } : {}),\n ...(forbiddenIdentifiers !== undefined ? { forbiddenIdentifiers } : {}),\n testStrategy: {\n forbidTestTodoStubs: readBoolean(\n testStrategyRaw?.forbidTestTodoStubs,\n base.testStrategy.forbidTestTodoStubs,\n \"validation.testStrategy.forbidTestTodoStubs\",\n configPath,\n issues,\n ),\n },\n traceability: {\n testFileGlobs: readStringArray(\n traceabilityRaw?.testFileGlobs,\n base.traceability.testFileGlobs,\n \"validation.traceability.testFileGlobs\",\n configPath,\n issues,\n ),\n testFileExcludeGlobs: readStringArray(\n traceabilityRaw?.testFileExcludeGlobs,\n base.traceability.testFileExcludeGlobs,\n \"validation.traceability.testFileExcludeGlobs\",\n configPath,\n issues,\n ),\n },\n };\n}\n\nfunction normalizeForbiddenIdentifiers(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): QfaiForbiddenIdentifier[] | undefined {\n if (raw === undefined) return undefined;\n const invalid = (): undefined => {\n issues.push(configIssue(configPath, \"validation.forbiddenIdentifiers is invalid.\"));\n return undefined;\n };\n if (!Array.isArray(raw) || raw.length > 64) {\n invalid();\n return undefined;\n }\n\n const entries: QfaiForbiddenIdentifier[] = [];\n const pairs = new Set<string>();\n const lengths = new Set<number>();\n for (const entry of raw) {\n if (\n !isRecord(entry) ||\n Object.keys(entry).length !== 2 ||\n Object.keys(entry).some((key) => key !== \"sha256\" && key !== \"byteLength\") ||\n typeof entry.sha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/.test(entry.sha256) ||\n typeof entry.byteLength !== \"number\" ||\n !Number.isInteger(entry.byteLength) ||\n entry.byteLength < 1 ||\n entry.byteLength > 128\n ) {\n invalid();\n return undefined;\n }\n const pair = `${entry.sha256}:${entry.byteLength}`;\n if (pairs.has(pair)) {\n invalid();\n return undefined;\n }\n pairs.add(pair);\n lengths.add(entry.byteLength);\n if (lengths.size > 8) {\n invalid();\n return undefined;\n }\n entries.push({ sha256: entry.sha256, byteLength: entry.byteLength });\n }\n return entries;\n}\n\nfunction normalizeOutput(raw: unknown, configPath: string, issues: Issue[]): QfaiOutputConfig {\n const base = defaultConfig.output;\n if (!raw) {\n return base;\n }\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"output must be an object.\"));\n return base;\n }\n\n return {\n validateJsonPath: readString(\n raw.validateJsonPath,\n base.validateJsonPath,\n \"output.validateJsonPath\",\n configPath,\n issues,\n ),\n };\n}\n\nfunction normalizePrototyping(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): QfaiPrototypingConfig | undefined {\n if (raw === undefined || raw === null) {\n return undefined;\n }\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"prototyping must be an object.\"));\n return undefined;\n }\n\n const execution = normalizePrototypingExecution(raw.execution, configPath, issues);\n if (Object.prototype.hasOwnProperty.call(raw, \"primarySpecId\")) {\n issues.push(\n configIssue(\n configPath,\n \"prototyping.primarySpecId is retired; use prototyping.primaryUiContract: UI-NNNN.\",\n ),\n );\n }\n const primaryUiContract = normalizePrimaryUiContract(raw.primaryUiContract, configPath, issues);\n if (!execution && primaryUiContract === undefined) {\n return undefined;\n }\n return {\n ...(execution ? { execution } : {}),\n ...(primaryUiContract !== undefined ? { primaryUiContract } : {}),\n };\n}\n\nfunction normalizePrimaryUiContract(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): string | undefined {\n if (raw === undefined || raw === null) {\n return undefined;\n }\n if (typeof raw !== \"string\" || !/^UI-\\d{4}$/.test(raw)) {\n issues.push(configIssue(configPath, primaryUiContractMessage(raw)));\n return undefined;\n }\n return raw;\n}\n\nfunction primaryUiContractMessage(raw: unknown): string {\n return `prototyping.primaryUiContract must be a full UI-NNNN ID; received ${JSON.stringify(raw)}.`;\n}\n\n/**\n * Why the file's `prototyping.primaryUiContract` was rejected, or `undefined` when the file sets\n * none or the value was accepted. A command that selects the primary UI contract refuses on it,\n * because the loaded config would otherwise fall back to the first UI contract.\n */\nexport function readRejectedPrimaryUiContract(loaded: ConfigLoadResult): string | undefined {\n const prototyping = isRecord(loaded.document) ? loaded.document.prototyping : undefined;\n const raw = isRecord(prototyping) ? prototyping.primaryUiContract : undefined;\n if (raw === undefined || raw === null) return undefined;\n if (loaded.config.prototyping?.primaryUiContract !== undefined) return undefined;\n return primaryUiContractMessage(raw);\n}\n\nfunction normalizePrototypingExecution(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): NonNullable<QfaiPrototypingConfig[\"execution\"]> | undefined {\n const base = defaultConfig.prototyping?.execution;\n if (raw === undefined || raw === null) {\n return base ? { ...base } : undefined;\n }\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"prototyping.execution must be an object.\"));\n return base ? { ...base } : undefined;\n }\n\n const browserToolRaw = raw.browserTool;\n const browserTool = \"playwright\";\n if (browserToolRaw !== undefined && browserToolRaw !== browserTool) {\n // `browserTool` keeps its `playwright` default, so a run that ignores the\n // issue proceeds against the supported launcher.\n issues.push(\n configIssue(\n configPath,\n `prototyping.execution.browserTool must be \"playwright\".` +\n ` Received: ${JSON.stringify(browserToolRaw)}`,\n ),\n );\n }\n\n return {\n targetUrl:\n raw.targetUrl === null\n ? null\n : (readOptionalString(\n raw.targetUrl,\n \"prototyping.execution.targetUrl\",\n configPath,\n issues,\n ) ?? null),\n browserTool,\n };\n}\n\nfunction readNonNegativeInteger(\n raw: unknown,\n field: string,\n configPath: string,\n issues: Issue[],\n): number | undefined {\n if (typeof raw === \"number\" && Number.isFinite(raw) && Number.isInteger(raw) && raw >= 0) {\n return raw;\n }\n issues.push(configIssue(configPath, `${field} must be an integer greater than or equal to 0.`));\n return undefined;\n}\n\nfunction normalizeReport(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): QfaiReportConfig | undefined {\n if (raw === undefined || raw === null) {\n return undefined;\n }\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"report must be an object.\"));\n return undefined;\n }\n const result: QfaiReportConfig = {};\n if (raw.staleTtlDays !== undefined) {\n const value = readNonNegativeInteger(\n raw.staleTtlDays,\n \"report.staleTtlDays\",\n configPath,\n issues,\n );\n if (value !== undefined) {\n result.staleTtlDays = value;\n }\n }\n if (raw.keepLatestRuns !== undefined) {\n const value = readNonNegativeInteger(\n raw.keepLatestRuns,\n \"report.keepLatestRuns\",\n configPath,\n issues,\n );\n if (value !== undefined) {\n result.keepLatestRuns = value;\n }\n }\n return Object.keys(result).length === 0 ? undefined : result;\n}\n\nfunction readString(\n value: unknown,\n fallback: string,\n label: string,\n configPath: string,\n issues: Issue[],\n): string {\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n if (value !== undefined) {\n issues.push(configIssue(configPath, `${label} must be a string.`));\n }\n return fallback;\n}\n\n/**\n * A configured directory, with any trailing separators removed.\n *\n * Readers use these values two ways: joined with a child path, where a trailing\n * separator is harmless, and tested as a prefix, where it is not. `\".qfai/spec/\"`\n * builds the prefix `\".qfai/spec//\"`, which no repository path starts with, so a\n * gate keyed on it selects nothing and reports a pass over an empty set. Settling\n * the spelling here is what stops one reader from working on a value another\n * silently drops.\n *\n * A value that is only separators keeps what was written: trimming it to the\n * empty string would silently retarget the reader at the repository root.\n */\nfunction readDirString(\n value: unknown,\n fallback: string,\n label: string,\n configPath: string,\n issues: Issue[],\n): string {\n const raw = readString(value, fallback, label, configPath, issues);\n const trimmed = raw.replace(/[\\\\/]+$/, \"\");\n return trimmed.length > 0 ? trimmed : raw;\n}\n\n/**\n * A story-tree root, with every backslash read as `/` on every platform.\n *\n * The shipped document-schema checker reads these two keys itself, without\n * loading the configuration module, and takes a backslash as a separator. Folding here as well keeps\n * `qfai validate` and that checker on one directory for one value: on Linux and\n * macOS the platform's own path rules would otherwise read `.qfai\\spec` as a\n * single directory name.\n */\nfunction readTreeDirString(\n value: unknown,\n fallback: string,\n label: string,\n configPath: string,\n issues: Issue[],\n): string {\n return readDirString(value, fallback, label, configPath, issues).replace(/\\\\/g, \"/\");\n}\n\n/**\n * `paths.deliberationDir`, kept only where it names a directory inside the project root.\n *\n * The graph keeps deliberation records out of its document corpus by excluding this\n * directory. The root itself, or a directory outside it, leaves nothing to exclude, so\n * such a value is reported and the default is kept.\n */\nfunction readDeliberationDir(\n value: unknown,\n fallback: string,\n configPath: string,\n issues: Issue[],\n): string {\n const dir = readTreeDirString(value, fallback, \"paths.deliberationDir\", configPath, issues);\n if (isDirectoryInsideRoot(path.dirname(configPath), dir)) return dir;\n issues.push(configIssue(configPath, DELIBERATION_DIR_OUTSIDE_ROOT_MESSAGE));\n return fallback;\n}\n\nexport const DELIBERATION_DIR_OUTSIDE_ROOT_MESSAGE =\n \"paths.deliberationDir must name a directory inside the project root, not the root itself or a directory outside it, and no part of it may end in a dot or a space.\";\n\n/**\n * Whether `dir`, read against `root`, names a directory strictly inside `root`.\n *\n * A part that ends in a dot or a space, such as `...` or `docs.`, is refused: Windows drops\n * those characters, so `...` would land in the root while this check reads it as a child.\n */\nexport function isDirectoryInsideRoot(root: string, dir: string): boolean {\n const relative = path.relative(root, path.resolve(root, dir));\n return (\n !dir.split(/[\\\\/]/).some((part) => part !== \".\" && part !== \"..\" && /[. ]$/.test(part)) &&\n relative !== \"\" &&\n relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative)\n );\n}\n\nfunction readOptionalString(\n value: unknown,\n label: string,\n configPath: string,\n issues: Issue[],\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n issues.push(configIssue(configPath, `${label} must be a non-empty string.`));\n return undefined;\n}\n\nfunction readStringArray(\n value: unknown,\n fallback: string[],\n label: string,\n configPath: string,\n issues: Issue[],\n): string[] {\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) {\n return value;\n }\n if (value !== undefined) {\n issues.push(configIssue(configPath, `${label} must be an array of strings.`));\n }\n return fallback;\n}\n\nfunction readDiagramBudget(\n value: unknown,\n configPath: string,\n issues: Issue[],\n): Partial<DiagramBudget> | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!isRecord(value)) {\n issues.push(configIssue(configPath, \"validation.diagramBudget must be an object.\"));\n return undefined;\n }\n for (const key of Object.keys(value)) {\n if (key !== \"nodes\" && key !== \"edges\") {\n issues.push(configIssue(configPath, `validation.diagramBudget.${key} is not a setting.`));\n }\n }\n const budget: Partial<DiagramBudget> = {};\n for (const key of [\"nodes\", \"edges\"] as const) {\n const limit = value[key];\n if (limit === undefined) {\n continue;\n }\n if (typeof limit === \"number\" && Number.isInteger(limit) && limit >= 1) {\n budget[key] = limit;\n } else {\n issues.push(\n configIssue(configPath, `validation.diagramBudget.${key} must be an integer of 1 or more.`),\n );\n }\n }\n return budget;\n}\n\nfunction readBoolean(\n value: unknown,\n fallback: boolean,\n label: string,\n configPath: string,\n issues: Issue[],\n): boolean {\n if (typeof value === \"boolean\") {\n return value;\n }\n if (value !== undefined) {\n issues.push(configIssue(configPath, `${label} must be a boolean.`));\n }\n return fallback;\n}\n\nfunction readFailOn(\n value: unknown,\n fallback: FailOn,\n label: string,\n configPath: string,\n issues: Issue[],\n): FailOn {\n if (value === \"never\" || value === \"warning\" || value === \"error\") {\n return value;\n }\n if (value !== undefined) {\n issues.push(configIssue(configPath, `${label} must be one of never|warning|error.`));\n }\n return fallback;\n}\n\n/**\n * `validation.traceability` keys no validator reads. The migration from the\n * spec-pack layout recognises the finding for each one that is still present,\n * and `QFAI-CFG-001` reports it until the key is deleted.\n */\nconst RETIRED_TRACEABILITY_KEYS = [\"scMustHaveTest\", \"unknownContractIdSeverity\"] as const;\n\nfunction reportRetiredTraceabilityKeys(\n traceabilityRaw: Record<string, unknown> | undefined,\n configPath: string,\n issues: Issue[],\n): void {\n if (!traceabilityRaw) {\n return;\n }\n for (const key of RETIRED_TRACEABILITY_KEYS) {\n if (traceabilityRaw[key] === undefined) {\n continue;\n }\n issues.push(\n configDeprecatedIssue(\n configPath,\n `validation.traceability.${key} is retired.` +\n ` No check reads it, so setting it changes nothing.` +\n ` Remove it from qfai.config.yaml.`,\n ),\n );\n }\n}\n\nfunction normalizeUiux(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): QfaiUiuxConfig | undefined {\n if (raw === undefined || raw === null) {\n return undefined;\n }\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"uiux must be an object.\"));\n return undefined;\n }\n const result: QfaiUiuxConfig = {};\n if (raw.platform !== undefined) {\n if (typeof raw.platform === \"string\" && raw.platform.trim().length > 0) {\n result.platform = raw.platform;\n } else {\n issues.push(configIssue(configPath, \"uiux.platform must be a non-empty string.\"));\n }\n }\n if (raw.designTokensDir !== undefined) {\n if (typeof raw.designTokensDir === \"string\" && raw.designTokensDir.trim().length > 0) {\n result.designTokensDir = raw.designTokensDir;\n } else {\n issues.push(configIssue(configPath, \"uiux.designTokensDir must be a non-empty string.\"));\n }\n }\n if (raw.htmlMockTimeout !== undefined) {\n if (\n typeof raw.htmlMockTimeout === \"number\" &&\n Number.isFinite(raw.htmlMockTimeout) &&\n raw.htmlMockTimeout > 0\n ) {\n result.htmlMockTimeout = raw.htmlMockTimeout;\n } else {\n issues.push(configIssue(configPath, \"uiux.htmlMockTimeout must be a positive number.\"));\n }\n }\n if (raw.qualityProfile !== undefined) {\n if (\n typeof raw.qualityProfile === \"string\" &&\n [\"strict\", \"high\", \"default\"].includes(raw.qualityProfile)\n ) {\n result.qualityProfile = raw.qualityProfile as \"strict\" | \"high\" | \"default\";\n } else {\n issues.push(\n configIssue(configPath, \"uiux.qualityProfile must be one of strict|high|default.\"),\n );\n }\n }\n if (raw.surfacePaths !== undefined) {\n const surfacePaths = raw.surfacePaths;\n if (\n Array.isArray(surfacePaths) &&\n surfacePaths.every(\n (entry: unknown): entry is string => typeof entry === \"string\" && entry.trim().length > 0,\n )\n ) {\n result.surfacePaths = surfacePaths.map((entry) => entry.trim());\n } else {\n issues.push(\n configIssue(configPath, \"uiux.surfacePaths must be a list of non-empty glob strings.\"),\n );\n }\n }\n if (raw.registries !== undefined) {\n const registries = normalizeUiuxRegistries(raw.registries, configPath, issues);\n if (registries) {\n result.registries = registries;\n }\n }\n if (raw.audit !== undefined) {\n const audit = normalizeUiuxAudit(raw.audit, configPath, issues);\n if (audit) {\n result.audit = audit;\n }\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\n/**\n * A registry entry resolves one component name, so the template has to say\n * where the name goes. A URL without the placeholder resolves nothing and is\n * the typo this catches; everything else about the URL is the registry's\n * business, including its scheme, because a private one may sit on localhost.\n */\nfunction normalizeUiuxRegistries(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): Record<string, string> | undefined {\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"uiux.registries must be an object.\"));\n return undefined;\n }\n const result: Record<string, string> = {};\n for (const [name, url] of Object.entries(raw)) {\n if (typeof url !== \"string\" || url.trim().length === 0) {\n issues.push(configIssue(configPath, `uiux.registries.${name} must be a non-empty string.`));\n continue;\n }\n if (!url.includes(\"{name}\")) {\n issues.push(\n configIssue(\n configPath,\n `uiux.registries.${name} must contain the {name} placeholder, or it resolves no component.`,\n ),\n );\n continue;\n }\n result[name] = url;\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction normalizeUiuxAudit(\n raw: unknown,\n configPath: string,\n issues: Issue[],\n): QfaiUiuxAuditConfig | undefined {\n if (!isRecord(raw)) {\n issues.push(configIssue(configPath, \"uiux.audit must be an object.\"));\n return undefined;\n }\n const result: QfaiUiuxAuditConfig = {};\n if (raw.enabled !== undefined) {\n if (typeof raw.enabled === \"boolean\") {\n result.enabled = raw.enabled;\n } else {\n issues.push(configIssue(configPath, \"uiux.audit.enabled must be a boolean.\"));\n }\n }\n if (raw.slopDetection !== undefined) {\n if (typeof raw.slopDetection === \"boolean\") {\n result.slopDetection = raw.slopDetection;\n } else {\n issues.push(configIssue(configPath, \"uiux.audit.slopDetection must be a boolean.\"));\n }\n }\n if (raw.maxRawTokenLiteralWarnings !== undefined) {\n if (\n typeof raw.maxRawTokenLiteralWarnings === \"number\" &&\n Number.isFinite(raw.maxRawTokenLiteralWarnings) &&\n raw.maxRawTokenLiteralWarnings >= 0\n ) {\n result.maxRawTokenLiteralWarnings = raw.maxRawTokenLiteralWarnings;\n } else {\n issues.push(\n configIssue(\n configPath,\n \"uiux.audit.maxRawTokenLiteralWarnings must be a number greater than or equal to 0.\",\n ),\n );\n }\n }\n if (raw.maxDuplicateFindingsPerRule !== undefined) {\n if (\n typeof raw.maxDuplicateFindingsPerRule === \"number\" &&\n Number.isFinite(raw.maxDuplicateFindingsPerRule) &&\n raw.maxDuplicateFindingsPerRule >= 0\n ) {\n result.maxDuplicateFindingsPerRule = raw.maxDuplicateFindingsPerRule;\n } else {\n issues.push(\n configIssue(\n configPath,\n \"uiux.audit.maxDuplicateFindingsPerRule must be a number greater than or equal to 0.\",\n ),\n );\n }\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction configIssue(file: string, message: string): Issue {\n return {\n code: \"QFAI-CFG-002\",\n severity: \"error\",\n category: \"canonical\",\n message,\n file,\n rule: \"config.invalid\",\n };\n}\n\nfunction configDeprecatedIssue(file: string, message: string): Issue {\n return {\n code: \"QFAI-CFG-001\",\n severity: \"error\",\n category: \"canonical\",\n message,\n file,\n rule: \"config.deprecatedKey\",\n };\n}\n\nasync function exists(target: string): Promise<boolean> {\n try {\n await access(target);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","/**\n * The workflow file names this package writes into an adopter's\n * `.github/workflows/` directory.\n *\n * The list is IN-BINARY. It is never computed by globbing the asset\n * tree at runtime or the adopter's disk: a write set derived from whatever\n * happens to be on disk cannot distinguish a file this package ships from one\n * somebody else put there, which is the distinction the whole\n * shipped-workflows contract rests on. The shipped-asset shape gate keeps this\n * list equal to the packaged workflow assets.\n *\n * They live in `shared/` rather than beside the command that writes them\n * because two layers need the same answer: the `init` command, which copies\n * them, and the `doctor` integrity reader, which has to know what a healthy\n * packaged tree contains before it can call a gutted one healthy. `core/` may\n * not import from `cli/`, and a second copy of the list is how the two\n * answers drift apart. `cli/commands/init.ts` re-exports it, so the public\n * surface is unchanged.\n */\n\n/**\n * Names the current package version ships into the adopter's\n * `.github/workflows/` directory (the shipped-workflows contract's write set).\n */\nexport const SHIPPED_WORKFLOW_NAMES: ReadonlySet<string> = new Set<string>([\n \"qfai-validate.yml\",\n \"qfai-tests.yml\",\n \"qfai-docs.yml\",\n]);\n","import { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n publishCompletedDocumentAnalysis,\n restoreCompletedDocumentAnalysis,\n safeDocumentCopy,\n} from \"./documentReuse.js\";\nimport type { GraphReuseEnvironment } from \"./reuse.js\";\nimport { withGraphLock } from \"./locks.js\";\nimport path from \"node:path\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\nimport { isEnoent } from \"../fs/errno.js\";\nimport { mirrorGraphCorpus } from \"./analysis.js\";\nimport { graphAnalysisRoot, graphRuntimePaths, GRAPH_VERSIONS } from \"./layout.js\";\nimport {\n GRAPH_PYTHON_FLAGS,\n graphifyConfigurationSafe,\n graphifyCorpusEnvironment,\n runGraphProcess,\n type GraphProcess,\n} from \"./process.js\";\nimport {\n assertGraphStoragePath,\n assertIndependentAnalysis,\n replaceGraphDirectory,\n} from \"./storage.js\";\n\nexport interface DocumentPreparation {\n status: \"prepared\" | \"not-ready\" | \"failed\";\n source?: \"current\" | \"restored\" | \"generated\";\n reuse?: \"published\" | \"unavailable\";\n recovery?: string;\n}\n\nexport interface DocumentScopeStatus {\n current: boolean;\n unsupported: string[];\n unreadable: string[];\n}\n\ninterface GraphProcessing {\n readonly backend: \"ollama\" | \"openai\";\n readonly model: string;\n readonly endpoint?: string;\n readonly scope?: string[];\n readonly credentialEnv?: string;\n}\n\nfunction notCurrent(): DocumentScopeStatus {\n return { current: false, unsupported: [], unreadable: [] };\n}\n\nexport interface ExternalProcessingRequest {\n readonly destination: string;\n readonly scope: readonly string[];\n readonly backend: string;\n readonly model: string;\n readonly worktree: string;\n}\n\nexport type ApproveExternalProcessing = (request: ExternalProcessingRequest) => Promise<boolean>;\n\nexport const DOCUMENT_PROCESSING_SETUP =\n 'Configure a selected local backend and model in .qfai/graph-processing.json using .agents/rules/graph-exploration.md, then run node .qfai/tools/graph-cli.mjs documents \"<question>\".';\n\nexport async function prepareGraphifyCodeAnalysis(\n root: string,\n run: GraphProcess = runGraphProcess,\n): Promise<DocumentPreparation> {\n if (!(await graphifyConfigurationSafe(root))) return providerConflict();\n const current = graphAnalysisRoot(root, \"graphify-code\");\n const staged = path.join(path.dirname(current), `.preparing-graphify-code-${randomUUID()}`);\n await assertGraphStoragePath(root, staged);\n await mkdir(staged, { recursive: true });\n try {\n await mirrorGraphCorpus(root, staged);\n const result = await run(\n graphRuntimePaths(root).python,\n [\n ...GRAPH_PYTHON_FLAGS,\n \"-m\",\n \"graphify\",\n \"extract\",\n path.toNamespacedPath(staged),\n \"--code-only\",\n \"--no-cluster\",\n \"--no-dedup\",\n \"--max-workers\",\n \"1\",\n \"--max-concurrency\",\n \"1\",\n ],\n { cwd: staged, env: graphifyCorpusEnvironment(root, staged) },\n );\n if (\n result.exitCode !== 0 ||\n !(await currentGraphifyCorpus(root, staged, graphRuntimePaths(root).python, run, \"ast\"))\n ) {\n return { status: \"failed\", recovery: \"Repair local Graphify code analysis.\" };\n }\n await writeFile(\n path.join(staged, \"graphify-out\", \"managed.json\"),\n JSON.stringify({ engineVersion: GRAPH_VERSIONS.graphify, scope: \"code\" }),\n );\n await assertIndependentAnalysis(staged);\n await replaceGraphDirectory(staged, current, root);\n return { status: \"prepared\" };\n } finally {\n await rm(staged, { recursive: true, force: true });\n }\n}\n\nexport async function prepareDocumentAnalysis(\n root: string,\n run: GraphProcess = runGraphProcess,\n approveExternal: ApproveExternalProcessing = () => Promise.resolve(false),\n environment?: GraphReuseEnvironment,\n): Promise<DocumentPreparation> {\n return withGraphLock(root, \"analysis\", () =>\n prepareDocumentAnalysisLocked(root, run, approveExternal, environment),\n );\n}\n\nexport async function prepareDocumentAnalysisLocked(\n root: string,\n run: GraphProcess = runGraphProcess,\n approveExternal: ApproveExternalProcessing = () => Promise.resolve(false),\n environment?: GraphReuseEnvironment,\n): Promise<DocumentPreparation> {\n if (!(await graphifyConfigurationSafe(root))) return providerConflict();\n if (await inspectDocumentAnalysis(root, run)) return { status: \"prepared\", source: \"current\" };\n const processing = await readGraphProcessing(root);\n if (!processing) {\n return {\n status: \"not-ready\",\n recovery: DOCUMENT_PROCESSING_SETUP,\n };\n }\n const inspect = async (analysis: string, refresh: boolean) =>\n (await inspectDocumentScopeAt(root, analysis, run, refresh)).current;\n if ((await restoreCompletedDocumentAnalysis(root, run, inspect, environment)) === \"restored\")\n return { status: \"prepared\", source: \"restored\" };\n const endpoint = processing.endpoint ?? \"http://127.0.0.1:11434/v1\";\n const selected = new URL(endpoint);\n const backend = processing.backend;\n const credential =\n typeof processing.credentialEnv === \"string\"\n ? process.env[processing.credentialEnv]\n : undefined;\n if (processing.credentialEnv !== undefined && !credential) {\n return {\n status: \"not-ready\",\n recovery:\n \"Set the explicitly selected credential environment variable before document processing.\",\n };\n }\n const local = [\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(selected.hostname);\n let scope: readonly string[] | undefined;\n if (processing.scope !== undefined) {\n if (!validDocumentScope(processing.scope))\n return { status: \"not-ready\", recovery: \"Select the exact document scope for processing.\" };\n scope = Object.freeze(processing.scope.map((item) => item.replaceAll(\"\\\\\", \"/\")));\n }\n if (!local) {\n if (!scope) {\n return {\n status: \"not-ready\",\n recovery: \"Select the exact document scope for external processing.\",\n };\n }\n const approval: unknown = await approveExternal(\n Object.freeze({\n destination: endpoint,\n scope,\n backend,\n model: processing.model,\n worktree: root,\n }),\n );\n if (approval !== true) {\n return {\n status: \"not-ready\",\n recovery:\n \"External document processing requires explicit human authorization of its destination and scope.\",\n };\n }\n }\n const current = graphAnalysisRoot(root, \"graphify\");\n const staged = path.join(path.dirname(current), `.preparing-graphify-${randomUUID()}`);\n await assertGraphStoragePath(root, staged);\n await mkdir(staged, { recursive: true });\n try {\n await mirrorGraphCorpus(root, staged, scope);\n const result = await run(\n graphRuntimePaths(root).python,\n [\n ...GRAPH_PYTHON_FLAGS,\n \"-m\",\n \"graphify\",\n \"extract\",\n path.toNamespacedPath(staged),\n \"--backend\",\n backend,\n \"--model\",\n processing.model,\n \"--no-cluster\",\n \"--no-dedup\",\n \"--max-workers\",\n \"1\",\n \"--max-concurrency\",\n \"1\",\n ],\n {\n cwd: staged,\n env: {\n ...graphifyCorpusEnvironment(root, staged),\n [backend === \"ollama\" ? \"OLLAMA_BASE_URL\" : \"OPENAI_BASE_URL\"]: endpoint,\n ...(credential\n ? { [backend === \"ollama\" ? \"OLLAMA_API_KEY\" : \"OPENAI_API_KEY\"]: credential }\n : {}),\n },\n },\n );\n if (\n result.exitCode !== 0 ||\n !(await currentGraphifyCorpus(root, staged, graphRuntimePaths(root).python, run))\n ) {\n return {\n status: \"failed\",\n recovery: \"Check the selected local model and repair Graphify document analysis.\",\n };\n }\n await writeFile(\n path.join(staged, \"graphify-out\", \"managed.json\"),\n JSON.stringify({ engineVersion: GRAPH_VERSIONS.graphify, scope: \"documents\", processing }),\n );\n await assertIndependentAnalysis(staged);\n await replaceGraphDirectory(staged, current, root);\n return {\n status: \"prepared\",\n source: \"generated\",\n reuse: await publishCompletedDocumentAnalysis(root, run, inspect, environment),\n };\n } finally {\n await rm(staged, { recursive: true, force: true });\n }\n}\n\nexport async function readGraphProcessing(root: string): Promise<GraphProcessing | undefined> {\n const processing = await readOptionalJson(path.join(root, \".qfai\", \"graph-processing.json\"));\n return validGraphProcessing(processing) ? processing : undefined;\n}\n\nfunction validGraphProcessing(processing: unknown): processing is GraphProcessing {\n const allowed = new Set([\"backend\", \"model\", \"endpoint\", \"scope\", \"credentialEnv\"]);\n if (\n !object(processing) ||\n Object.keys(processing).some((key) => !allowed.has(key)) ||\n (processing.backend !== \"ollama\" && processing.backend !== \"openai\") ||\n typeof processing.model !== \"string\" ||\n !processing.model.trim() ||\n (processing.scope !== undefined && !validDocumentScope(processing.scope)) ||\n (processing.credentialEnv !== undefined &&\n (typeof processing.credentialEnv !== \"string\" ||\n !/^[A-Z_][A-Z0-9_]*$/.test(processing.credentialEnv)))\n )\n return false;\n if (processing.endpoint !== undefined) {\n if (typeof processing.endpoint !== \"string\" || !processing.endpoint.trim()) return false;\n try {\n const endpoint = new URL(processing.endpoint);\n if (\n ![\"http:\", \"https:\"].includes(endpoint.protocol) ||\n endpoint.username ||\n endpoint.password ||\n endpoint.search ||\n endpoint.hash\n )\n return false;\n } catch {\n return false;\n }\n }\n return true;\n}\n\nexport async function inspectDocumentAnalysis(root: string, run: GraphProcess): Promise<boolean> {\n return (await inspectDocumentScope(root, run)).current;\n}\n\nexport async function inspectDocumentScope(\n root: string,\n run: GraphProcess,\n): Promise<DocumentScopeStatus> {\n const analysis = graphAnalysisRoot(root, \"graphify\");\n await assertGraphStoragePath(root, analysis);\n return inspectDocumentScopeAt(root, analysis, run);\n}\n\nasync function inspectDocumentScopeAt(\n root: string,\n analysis: string,\n run: GraphProcess,\n refresh = true,\n): Promise<DocumentScopeStatus> {\n const managed = await readOptionalJson(path.join(analysis, \"graphify-out\", \"managed.json\"));\n const selected = await readGraphProcessing(root);\n const processing = await processingForCompletedQuery(\n root,\n selected,\n object(managed) ? managed.processing : undefined,\n );\n if (\n !object(managed) ||\n Object.keys(managed).length !== 3 ||\n managed.engineVersion !== GRAPH_VERSIONS.graphify ||\n managed.scope !== \"documents\" ||\n !sameProcessing(managed.processing, processing)\n )\n return notCurrent();\n if (!(await safeDocumentCopy(root, analysis, run))) return notCurrent();\n const scope =\n object(processing) && validDocumentScope(processing.scope) ? processing.scope : undefined;\n if (refresh) await mirrorGraphCorpus(root, analysis, scope);\n return nativeGraphifyScope(root, analysis, graphRuntimePaths(root).python, run);\n}\n\nasync function processingForCompletedQuery(\n root: string,\n selected: unknown,\n recorded: unknown,\n): Promise<unknown> {\n if (selected !== undefined) return selected;\n try {\n await readFile(path.join(root, \".qfai\", \"graph-processing.json\"));\n return undefined;\n } catch (cause: unknown) {\n if (!isEnoent(cause)) throw cause;\n }\n if (!validGraphProcessing(recorded)) return undefined;\n return recorded;\n}\n\nasync function currentGraphifyCorpus(\n root: string,\n analysis: string,\n python: string,\n run: GraphProcess,\n kind: \"semantic\" | \"ast\" = \"semantic\",\n): Promise<boolean> {\n return (await nativeGraphifyScope(root, analysis, python, run, kind)).current;\n}\n\nasync function nativeGraphifyScope(\n root: string,\n analysis: string,\n python: string,\n run: GraphProcess,\n kind: \"semantic\" | \"ast\" = \"semantic\",\n): Promise<DocumentScopeStatus> {\n if (!(await graphifyConfigurationSafe(root))) return notCurrent();\n const result = await run(\n python,\n [\n ...GRAPH_PYTHON_FLAGS,\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"graphify-native.py\"),\n path.toNamespacedPath(analysis),\n kind,\n ],\n {\n cwd: analysis,\n env: graphifyCorpusEnvironment(root, analysis),\n },\n );\n if (result.exitCode !== 0) return notCurrent();\n let state: unknown;\n try {\n state = JSON.parse(result.stdout);\n } catch (cause: unknown) {\n if (!(cause instanceof SyntaxError)) throw cause;\n return notCurrent();\n }\n if (\n !object(state) ||\n typeof state.current !== \"boolean\" ||\n !stringArray(state.unsupported) ||\n !stringArray(state.unreadable)\n )\n return notCurrent();\n const sourcePath = (file: string) =>\n path.isAbsolute(file)\n ? path\n .relative(path.toNamespacedPath(analysis), path.toNamespacedPath(file))\n .split(path.sep)\n .join(\"/\")\n : file;\n return {\n current: state.current,\n unsupported: state.unsupported.map(sourcePath),\n unreadable: state.unreadable.map(sourcePath),\n };\n}\n\nasync function readOptionalJson(file: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(file, \"utf8\"));\n } catch (cause: unknown) {\n if (isEnoent(cause) || cause instanceof SyntaxError) return undefined;\n throw cause;\n }\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction sameProcessing(left: unknown, right: unknown): boolean {\n if (!object(left) || !object(right)) return false;\n const fields = [\"backend\", \"model\", \"endpoint\", \"credentialEnv\", \"scope\"];\n if (Object.keys(left).some((key) => !fields.includes(key))) return false;\n return fields.every((key) => JSON.stringify(left[key]) === JSON.stringify(right[key]));\n}\n\nfunction stringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item: unknown) => typeof item === \"string\");\n}\n\nfunction validDocumentScope(value: unknown): value is string[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every(\n (item: unknown) =>\n typeof item === \"string\" &&\n item !== \"\" &&\n !path.isAbsolute(item) &&\n !item.split(/[\\\\/]/).some((part) => part === \"..\" || part === \".\" || part === \"\"),\n )\n );\n}\n\nfunction providerConflict(): DocumentPreparation {\n return {\n status: \"not-ready\",\n recovery:\n \"Review private Graphify provider settings and unsafe home paths before processing; existing settings were retained.\",\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { cp, lstat, mkdir, readdir, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getInitAssetsDir } from \"../../shared/assets.js\";\nimport { excludedGraphInput, graphDeliberationDir } from \"./analysis.js\";\nimport { GRAPH_VERSIONS, graphAnalysisRoot, graphRuntimePaths } from \"./layout.js\";\nimport {\n GRAPH_PYTHON_FLAGS,\n graphifyEnvironment,\n graphifyCorpusEnvironment,\n type GraphProcess,\n} from \"./process.js\";\nimport {\n cacheDirectorySafe,\n completedAnalysisCache,\n ensureCacheDirectory,\n graphReuseEnvironment,\n readSnapshotMetadata,\n safeCompletedCorpus,\n sameEnvironment,\n type GraphReuseEnvironment,\n} from \"./reuse.js\";\nimport {\n assertGraphStoragePath,\n assertIndependentAnalysis,\n replaceGraphDirectory,\n} from \"./storage.js\";\n\ntype Inspect = (analysis: string, refresh: boolean) => Promise<boolean>;\n\nexport async function restoreCompletedDocumentAnalysis(\n root: string,\n run: GraphProcess,\n inspect: Inspect,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<\"restored\" | \"cold\"> {\n let staged: string | undefined;\n try {\n if (!(await compatible(root, run, environment))) return \"cold\";\n const cache = await completedAnalysisCache(root, \"graphify\", run, environment);\n if (!cache) return \"cold\";\n for (const entry of await readdir(cache.directory, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name.startsWith(\".\")) continue;\n const candidate = path.join(cache.directory, entry.name);\n if (!(await cacheDirectorySafe(cache.repository, candidate))) continue;\n const metadata = await readSnapshotMetadata(candidate);\n if (\n !metadata ||\n Object.keys(metadata).length !== 5 ||\n metadata.layout !== 1 ||\n metadata.corpusPolicy !== 1 ||\n metadata.repository !== cache.repository ||\n metadata.engineVersion !== GRAPH_VERSIONS.graphify ||\n !sameEnvironment(metadata.environment, environment)\n )\n continue;\n const analysis = path.join(candidate, \"analysis\");\n if (!(await safeDocumentCopy(root, analysis, run))) continue;\n const current = graphAnalysisRoot(root, \"graphify\");\n staged = path.join(path.dirname(current), `.restoring-graphify-${randomUUID()}`);\n await assertGraphStoragePath(root, staged);\n await mkdir(path.dirname(staged), { recursive: true });\n await cp(analysis, staged, { recursive: true, dereference: false });\n await assertIndependentAnalysis(staged);\n if (await inspect(staged, true)) {\n await replaceGraphDirectory(staged, current, root);\n return \"restored\";\n }\n await rm(staged, { recursive: true, force: true });\n staged = undefined;\n }\n } catch {\n return \"cold\";\n } finally {\n if (staged) await discard(staged);\n }\n return \"cold\";\n}\n\nexport async function publishCompletedDocumentAnalysis(\n root: string,\n run: GraphProcess,\n inspect: Inspect,\n environment: GraphReuseEnvironment = graphReuseEnvironment(),\n): Promise<\"published\" | \"unavailable\"> {\n let staged: string | undefined;\n try {\n if (!(await compatible(root, run, environment))) return \"unavailable\";\n const cache = await completedAnalysisCache(root, \"graphify\", run, environment);\n if (!cache) return \"unavailable\";\n await ensureCacheDirectory(cache.repository, cache.directory);\n const analysis = graphAnalysisRoot(root, \"graphify\");\n if (!(await safeDocumentCopy(root, analysis, run))) return \"unavailable\";\n const identity = randomUUID();\n staged = path.join(cache.directory, `.publishing-${identity}`);\n await mkdir(staged);\n const copy = path.join(staged, \"analysis\");\n await cp(analysis, copy, { recursive: true, dereference: false });\n await assertIndependentAnalysis(copy);\n if (!(await safeDocumentCopy(root, copy, run)) || !(await inspect(copy, false)))\n return \"unavailable\";\n await writeFile(\n path.join(staged, \"completed.json\"),\n JSON.stringify({\n layout: 1,\n corpusPolicy: 1,\n repository: cache.repository,\n engineVersion: GRAPH_VERSIONS.graphify,\n environment,\n }) + \"\\n\",\n );\n await rename(staged, path.join(cache.directory, identity));\n return \"published\";\n } catch {\n return \"unavailable\";\n } finally {\n if (staged) await discard(staged);\n }\n}\n\nasync function compatible(\n root: string,\n run: GraphProcess,\n environment: GraphReuseEnvironment,\n): Promise<boolean> {\n if (environment.platform !== \"win32\" || environment.architecture !== \"x64\") return false;\n const result = await run(\n graphRuntimePaths(root).python,\n [...GRAPH_PYTHON_FLAGS, \"-c\", \"import sys; print(sys.version.split()[0])\"],\n { cwd: root, env: graphifyEnvironment(root) },\n );\n return result.exitCode === 0 && result.stdout.trim() === \"3.12.13\";\n}\n\nexport async function safeDocumentCopy(\n root: string,\n analysis: string,\n run: GraphProcess,\n): Promise<boolean> {\n const deliberationDir = await graphDeliberationDir(root);\n if (!(await safeCompletedCorpus(analysis, deliberationDir, \"\", \"graphify-out\"))) return false;\n const result = await run(\n graphRuntimePaths(root).python,\n [\n ...GRAPH_PYTHON_FLAGS,\n path.resolve(getInitAssetsDir(), \"..\", \"graph\", \"graphify-native.py\"),\n path.toNamespacedPath(analysis),\n \"inventory\",\n ],\n { cwd: analysis, env: graphifyCorpusEnvironment(root, analysis) },\n );\n if (result.exitCode !== 0) return false;\n try {\n const inventory: unknown = JSON.parse(result.stdout);\n if (\n typeof inventory !== \"object\" ||\n inventory === null ||\n Object.keys(inventory).length !== 1 ||\n !(\"files\" in inventory) ||\n !Array.isArray(inventory.files)\n )\n return false;\n for (const file of inventory.files) {\n if (typeof file !== \"string\" || path.posix.isAbsolute(file) || path.win32.isAbsolute(file))\n return false;\n const parts = file.replaceAll(\"\\\\\", \"/\").split(\"/\");\n if (\n parts.some((part) => !part || part === \".\" || part === \"..\") ||\n excludedGraphInput(parts.join(\"/\"), deliberationDir)\n )\n return false;\n const stats = await lstat(path.join(analysis, ...parts));\n if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1) return false;\n }\n return true;\n } catch {\n return false;\n }\n}\n\nasync function discard(directory: string): Promise<void> {\n try {\n await rm(directory, { recursive: true, force: true });\n } catch {\n // An unfinished hidden candidate is never eligible for restoration.\n }\n}\n","import {\n GRAPH_PYTHON_FLAGS,\n codegraphEnvironment,\n graphifyCorpusEnvironment,\n runGraphProcess,\n type GraphProcess,\n} from \"./process.js\";\nimport {\n GraphConfigUnreadableError,\n inspectCodeCoverage,\n inspectCurrentCodeAnalysis,\n} from \"./analysis.js\";\nimport { graphAnalysisRoot, graphRuntimePaths } from \"./layout.js\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { findUnsafeHostFileComponent } from \"../init/fsGuards.js\";\nimport { inspectDocumentScope, readGraphProcessing } from \"./documents.js\";\n\nexport interface GraphQuestion {\n domain: \"code\" | \"documents\";\n question: string;\n}\n\nexport interface GraphAnswer {\n requestedScope: Readonly<GraphQuestion>;\n engine: \"codegraph\" | \"graphify\";\n status: \"answered\" | \"not-ready\" | \"failed\" | \"no-match\" | \"incomplete\";\n coverage?: {\n unsupported: string[];\n unreadable: string[];\n unparsed?: string[];\n complete?: boolean;\n };\n answer?: string;\n failure?: string;\n inferenceNotice?: string;\n recovery?: string;\n}\n\nexport async function readKnownGraphFile(root: string, relative: string): Promise<string> {\n const parts = relative.split(/[\\\\/]/);\n if (\n path.isAbsolute(relative) ||\n parts.some((part) => part === \"..\" || part === \"\" || part === \".\") ||\n (await findUnsafeHostFileComponent(root, parts))\n ) {\n throw new Error(\"Use an exact known source file inside the project.\");\n }\n return readFile(path.join(root, ...parts), \"utf8\");\n}\n\nexport async function continueGraphExploration(\n root: string,\n previous: GraphAnswer,\n unresolved: GraphQuestion,\n run: GraphProcess = runGraphProcess,\n): Promise<GraphAnswer> {\n const nextEngine = unresolved.domain === \"code\" ? \"codegraph\" : \"graphify\";\n if (\n previous.status !== \"answered\" ||\n previous.engine === nextEngine ||\n unresolved.question.trim() === \"\"\n ) {\n throw new Error(\n \"State the unresolved question in the other domain after an answered graph query.\",\n );\n }\n return exploreGraph(root, unresolved, run);\n}\n\nexport async function exploreGraph(\n root: string,\n request: GraphQuestion,\n run: GraphProcess = runGraphProcess,\n): Promise<GraphAnswer> {\n const requestedScope = Object.freeze({ ...request });\n try {\n return { ...(await exploreGraphScope(root, request, run)), requestedScope };\n } catch (cause: unknown) {\n // The CLI reports it, as it does when preparation finds it, and no fallback is granted.\n if (cause instanceof GraphConfigUnreadableError) throw cause;\n const engine = request.domain === \"code\" ? \"codegraph\" : \"graphify\";\n return {\n requestedScope,\n engine,\n status: \"failed\",\n failure: `${engine === \"codegraph\" ? \"CodeGraph\" : \"Graphify\"} operation failed.`,\n recovery: `Repair ${engine === \"codegraph\" ? \"CodeGraph\" : \"Graphify\"} analysis and retry the graph query.`,\n };\n }\n}\n\nasync function exploreGraphScope(\n root: string,\n request: GraphQuestion,\n run: GraphProcess,\n): Promise<Omit<GraphAnswer, \"requestedScope\">> {\n const documentScope =\n request.domain === \"documents\" ? await inspectDocumentScope(root, run) : undefined;\n if (documentScope?.current) {\n const result = await run(\n graphRuntimePaths(root).python,\n [\n ...GRAPH_PYTHON_FLAGS,\n \"-m\",\n \"graphify\",\n \"query\",\n request.question,\n \"--graph\",\n path.toNamespacedPath(\n path.join(graphAnalysisRoot(root, \"graphify\"), \"graphify-out\", \"graph.json\"),\n ),\n ],\n {\n cwd: graphAnalysisRoot(root, \"graphify\"),\n env: graphifyCorpusEnvironment(root, graphAnalysisRoot(root, \"graphify\")),\n },\n );\n if (result.exitCode !== 0 && result.exitCode !== 4) {\n return {\n engine: \"graphify\",\n status: \"failed\",\n failure: \"Graphify query failed.\",\n recovery: \"Repair Graphify analysis and retry the graph query.\",\n };\n }\n const coverage = {\n unsupported: documentScope.unsupported,\n unreadable: documentScope.unreadable,\n };\n const inference = result.stdout.includes(\"[INFERRED]\")\n ? {\n inferenceNotice:\n \"Inferred relationships need source confirmation; they do not establish semantic correctness or complete coverage.\",\n }\n : {};\n if (coverage.unsupported.length > 0 || coverage.unreadable.length > 0) {\n return {\n engine: \"graphify\",\n status: \"incomplete\",\n answer: result.stdout,\n coverage,\n ...inference,\n recovery:\n \"Review unsupported and unreadable scope; this result does not establish absence.\",\n };\n }\n return {\n engine: \"graphify\",\n status: result.exitCode === 4 ? \"no-match\" : \"answered\",\n answer: result.stdout,\n coverage,\n ...inference,\n };\n }\n if (request.domain === \"code\" && (await inspectCurrentCodeAnalysis(root, run))) {\n const result = await run(\n process.execPath,\n [\n graphRuntimePaths(root).codegraph,\n \"context\",\n request.question,\n \"--path\",\n graphAnalysisRoot(root, \"codegraph\"),\n \"--format\",\n \"json\",\n \"--no-code\",\n ],\n {\n cwd: root,\n env: codegraphEnvironment(root),\n },\n );\n const context = nativeCodeContext(result.stdout, request.question);\n if (result.exitCode !== 0 || !context)\n return {\n engine: \"codegraph\",\n status: \"failed\",\n failure: \"CodeGraph query failed or returned unusable data.\",\n recovery: \"Repair CodeGraph analysis and retry the graph query.\",\n };\n const coverage = await inspectCodeCoverage(root, run);\n if (!coverage.complete)\n return {\n engine: \"codegraph\",\n status: \"incomplete\",\n answer: result.stdout,\n coverage,\n recovery:\n \"Review unknown, unsupported, unreadable and unparsed code scope; this result does not establish absence.\",\n };\n return {\n engine: \"codegraph\",\n status: context.empty ? \"no-match\" : \"answered\",\n answer: result.stdout,\n coverage,\n ...(context.empty\n ? {\n inferenceNotice:\n \"No match in this context search over the confirmed native code scope; this does not establish global absence.\",\n }\n : {}),\n };\n }\n return {\n engine: request.domain === \"code\" ? \"codegraph\" : \"graphify\",\n status: \"not-ready\",\n recovery:\n request.domain === \"documents\" && (await readGraphProcessing(root)) === undefined\n ? \"Select document processing in .qfai/graph-processing.json before preparing document analysis.\"\n : \"Prepare the requested graph analysis before querying it.\",\n };\n}\n\nfunction nativeCodeContext(stdout: string, question: string): { empty: boolean } | undefined {\n let value: unknown;\n try {\n value = JSON.parse(stdout);\n } catch {\n return undefined;\n }\n if (!object(value) || value.query !== question || typeof value.summary !== \"string\")\n return undefined;\n const arrays = [\"entryPoints\", \"nodes\", \"edges\", \"codeBlocks\", \"relatedFiles\"];\n if (arrays.some((key) => !Array.isArray(value[key])) || !object(value.stats)) return undefined;\n const stats = value.stats;\n const counts = [\"nodeCount\", \"edgeCount\", \"fileCount\", \"codeBlockCount\", \"totalCodeSize\"];\n if (counts.some((key) => !Number.isSafeInteger(stats[key]) || Number(stats[key]) < 0))\n return undefined;\n for (const [count, entries] of [\n [\"nodeCount\", \"nodes\"],\n [\"edgeCount\", \"edges\"],\n [\"fileCount\", \"relatedFiles\"],\n [\"codeBlockCount\", \"codeBlocks\"],\n ] as const) {\n const list = value[entries];\n if (!Array.isArray(list) || stats[count] !== list.length) return undefined;\n }\n const empty = stats.nodeCount === 0;\n if (\n empty &&\n (arrays.some((key) => Array.isArray(value[key]) && value[key].length !== 0) ||\n counts.some((key) => stats[key] !== 0))\n )\n return undefined;\n return { empty };\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { lstat, realpath } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../fs/errno.js\";\n\n/**\n * Resolve the Git working tree an event's cwd belongs to, within the checkout the hook was\n * installed in. A host-created worktree nested under that checkout (for example\n * `.claude/worktrees/<name>`) is its own working tree with its own `.git` entry, so it is\n * returned instead of the installing checkout. A cwd outside the checkout, an unreadable cwd or\n * a cwd with no nested working tree resolves to the installing checkout.\n */\nexport async function resolveSessionWorktree(root: string, cwd: string | undefined) {\n if (!cwd) return root;\n const base = path.resolve(root);\n let current: string;\n try {\n current = await realpath(path.resolve(cwd));\n } catch {\n return root;\n }\n if (!inside(base, current)) return root;\n while (path.relative(base, current) !== \"\") {\n if (await exists(path.join(current, \".git\"))) return current;\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return root;\n}\n\nfunction inside(base: string, candidate: string) {\n const relative = path.relative(base, candidate);\n return relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n}\n\nasync function exists(file: string) {\n try {\n await lstat(file);\n return true;\n } catch (cause: unknown) {\n if (isEnoent(cause)) return false;\n throw cause;\n }\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAAA,cAAa;AACtB,OAAOC,YAAU;;;ACFjB,SAAS,iBAAiB;AAE1B,SAAS,QAAQ,OAAO,MAAM,UAAU,YAAY;AAEpD,OAAO,UAAU;;;ACSV,SAAS,SAAS,KAAuB;AAC9C,SAAO,aAAa,GAAG,KAAK,IAAI,SAAS;AAC3C;AAyBO,SAAS,aAAa,KAAuC;AAClE,SACE,QAAQ,QACR,OAAO,QAAQ,YACf,UAAU,OACV,OAAQ,IAA2B,SAAS;AAEhD;;;ADeA,eAA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ACT;AAAA,MACA,wBAAwB,OAAO,kDAAkD,IAAI;AAAA,MACrF,oBAAoB,OAAO;AAAA,IAC7B;AAAA,WACO,SAAS,aAAa,UAAU,SAAS,UAAU,cAAc;AACxE,QAAI,OAAO;AACT,UAAI;AACF,mBAAW,MAAM,+BAA+B,SAAS,KAAK;AAAA,MAChE,SAAS,OAAgB;AACvB,mBAAW,gBAAgB,OAAO;AAClC,YAAI,iBAAiB;AACnB,mBAAS,UAAU,GAAG,MAAM,OAAO,IAAI,MAAM,QAAQ;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AACA,MAAI,SAAS,aAAa;AACxB,OAAG,OAAO,KAAK,UAAU,gBAAgB,MAAM,QAAQ,CAAC,IAAI,IAAI;AAClE,MAAI,SAAS,UAAU,UAAU;AAC/B,OAAG,MAAM,GAAG,SAAS,OAAO;AAAA,CAAI;AAChC,OAAG,KAAK;AAAA,EACV;AACF;AAEA,eAAe,eAAe,SAAiB;AAE7C,MAAI;AACF,UAAMC,OAAMD,OAAK,KAAK,SAAS,GAAG,WAAW,CAAC;AAC9C,WAAO;AAAA,EACT,SAAS,OAAgB;AACvB,QAAI,SAAS,KAAK,EAAG,QAAO;AAC5B,UAAM;AAAA,EACR;AACF;AAEA,SAAS,SAAS,OAA2C;AAC3D,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,EAAG,QAAO;AAChF,QAAM,QAAQ;AACd,QAAM,QAAQ,CAAC,aAAa,cAAc,YAAY,EAAE,KAAK,CAAC,QAAQ,OAAO,KAAK;AAClF,QAAM,QAAQ,CAAC,YAAY,YAAY,WAAW,EAAE,KAAK,CAAC,QAAQ,OAAO,KAAK;AAC9E,MAAI,UAAU,MAAO,QAAO;AAE5B,SAAO,QAAQ,YAAY;AAC7B;","names":["lstat","path","path","offset","nested","randomUUID","rename","unlink","path","randomUUID","path","path","lstat","mkdir","open","path","lstat","path","path","lstat","path","mkdir","lstat","open","path","randomUUID","unlink","path","path","unlink","randomUUID","mkdir","rm","path","path","path","access","lstat","path","path","randomUUID","lstat","mkdir","readFile","readdir","realpath","rename","rm","path","lstat","mkdir","readdir","rm","access","readFile","path","mkdir","readFile","rm","writeFile","randomUUID","randomUUID","cp","lstat","mkdir","readdir","rename","rm","writeFile","path","path","readFile","path","path","randomUUID","lstat","realpath","path","path","realpath","lstat","path","lstat"]}
|