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.
Files changed (163) hide show
  1. package/README.md +24 -16
  2. package/assets/defaults/workflows/apply-settled.yml +2 -0
  3. package/assets/defaults/workflows/decide-design.yml +1 -6
  4. package/assets/defaults/workflows/decompose-epic.yml +1 -1
  5. package/assets/init/.claude/settings.json +1 -1
  6. package/assets/init/.qfai/assistant/agent/architecture-reviewer.md +1 -0
  7. package/assets/init/.qfai/assistant/agent/fullstack-engineer.md +6 -9
  8. package/assets/init/.qfai/assistant/agent/implementation-reviewer.md +9 -1
  9. package/assets/init/.qfai/assistant/agent/product-surface-reviewer.md +70 -4
  10. package/assets/init/.qfai/assistant/agent/requirements-reviewer.md +1 -0
  11. package/assets/init/.qfai/assistant/rule/constitution.md +3 -2
  12. package/assets/init/.qfai/assistant/rule/drift-protocol.md +5 -5
  13. package/assets/init/.qfai/assistant/rule/references/deliberation-record-template.md +23 -0
  14. package/assets/init/.qfai/assistant/rule/references/deliberation-record.md +36 -0
  15. package/assets/init/.qfai/assistant/rule/references/griller-recommendations.md +3 -3
  16. package/assets/init/.qfai/assistant/rule/references/launcher-preflight.md +27 -0
  17. package/assets/init/.qfai/assistant/rule/references/reviewer-findings.md +9 -0
  18. package/assets/init/.qfai/assistant/rule/references/reviewer-remit.md +23 -15
  19. package/assets/init/.qfai/assistant/rule/references/visual-reference-survey.md +146 -0
  20. package/assets/init/.qfai/assistant/rule/references/worker-edit-boundary.md +2 -0
  21. package/assets/init/.qfai/assistant/rule/research-first-protocol.md +49 -11
  22. package/assets/init/.qfai/assistant/rule/review-convergence.md +15 -16
  23. package/assets/init/.qfai/assistant/rule/shared-skill-delegation-baseline.md +3 -0
  24. package/assets/init/.qfai/assistant/rule/shared-skill-operating-baseline.md +13 -25
  25. package/assets/init/.qfai/assistant/rule/test-layers.md +8 -0
  26. package/assets/init/.qfai/assistant/rule/thinking.md +10 -5
  27. package/assets/init/.qfai/assistant/rule/ui-definition-protocol.md +4 -4
  28. package/assets/init/.qfai/assistant/rule/ui-procurement.md +50 -10
  29. package/assets/init/.qfai/assistant/rule/workflow.md +4 -3
  30. package/assets/init/.qfai/assistant/skill/qfai-configure/SKILL.md +3 -1
  31. package/assets/init/.qfai/assistant/skill/qfai-discussion/SKILL.md +22 -56
  32. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/design-dna-intake.md +11 -14
  33. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-coverage-checklist.md +1 -1
  34. package/assets/init/.qfai/assistant/skill/qfai-grilling/SKILL.md +6 -4
  35. package/assets/init/.qfai/assistant/skill/qfai-grilling/references/discussion-delegation.md +46 -0
  36. package/assets/init/.qfai/assistant/skill/qfai-grilling/references/glossary-check.md +23 -0
  37. package/assets/init/.qfai/assistant/skill/qfai-grilling/references/session-check.md +25 -0
  38. package/assets/init/.qfai/assistant/skill/qfai-implement/SKILL.md +12 -1
  39. package/assets/init/.qfai/assistant/skill/qfai-implement/references/parallelization-policy.md +2 -3
  40. package/assets/init/.qfai/assistant/skill/qfai-implement/references/ui-affecting.md +47 -8
  41. package/assets/init/.qfai/assistant/skill/qfai-maintain/SKILL.md +2 -0
  42. package/assets/init/.qfai/assistant/skill/qfai-migration-v1-to-v2/SKILL.md +1 -1
  43. package/assets/init/.qfai/assistant/skill/qfai-prototyping/SKILL.md +6 -2
  44. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/generator-prompt.md +6 -9
  45. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/reviewer-prompt.md +24 -15
  46. package/assets/init/.qfai/assistant/skill/qfai-run/SKILL.md +2 -2
  47. package/assets/init/.qfai/assistant/skill/qfai-run/references/extraction.md +2 -1
  48. package/assets/init/.qfai/assistant/skill/qfai-run/references/operator-screens.md +7 -3
  49. package/assets/init/.qfai/assistant/skill/qfai-run/references/stage-points.md +4 -1
  50. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/business-ui-patterns.md +180 -0
  51. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/contract-artifact-rules.md +14 -3
  52. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/design-anti-patterns.md +14 -3
  53. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/design-md-authoring.md +39 -24
  54. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/design-md-brand-catalog.md +2 -2
  55. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/marketing-ui-patterns.md +194 -0
  56. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/requirements-decomposition.md +27 -3
  57. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-execution-playbook.md +29 -22
  58. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-phase-checklists.md +3 -3
  59. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-pre-draft-grilling.md +4 -4
  60. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-quality-gate.md +1 -1
  61. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-triage.md +4 -2
  62. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/spec-traceability-rules.md +6 -6
  63. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/ui-contract-guide.md +87 -4
  64. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/ui-design-contract-normalization.md +6 -7
  65. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/contracts/api-contract.sample.yaml +3 -0
  66. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/contracts/db-contract.sample.sql +3 -0
  67. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/contracts/ui-contract.sample.yaml +40 -1
  68. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/report/preflight_summary.md +10 -16
  69. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/01_policy/constraint.md +10 -0
  70. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/01_policy/initiative.md +5 -0
  71. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/03_contract/tech.md +1 -0
  72. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/decisions.md +8 -2
  73. package/assets/init/.qfai/assistant/skill/qfai-triage/SKILL.md +4 -0
  74. package/assets/init/.qfai/assistant/skill/qfai-verify/SKILL.md +4 -2
  75. package/assets/init/.qfai/assistant/skill/qfai-verify/references/context-load.md +2 -1
  76. package/assets/init/.qfai/assistant/skill/qfai-verify/references/verify-output-contract.md +4 -1
  77. package/assets/init/.qfai/assistant/step/common-design-md/STEP.md +11 -8
  78. package/assets/init/.qfai/assistant/step/common-gate-run/STEP.md +1 -1
  79. package/assets/init/.qfai/assistant/step/common-grilling-record/STEP.md +25 -60
  80. package/assets/init/.qfai/assistant/step/common-review-cycle/STEP.md +18 -6
  81. package/assets/init/.qfai/assistant/step/discussion-interview/STEP.md +45 -95
  82. package/assets/init/.qfai/assistant/step/discussion-research/STEP.md +11 -13
  83. package/assets/init/.qfai/assistant/step/implement-diagnose/STEP.md +2 -2
  84. package/assets/init/.qfai/assistant/step/implement-scaffold/STEP.md +52 -8
  85. package/assets/init/.qfai/assistant/step/implement-settled-edit/STEP.md +78 -0
  86. package/assets/init/.qfai/assistant/step/implement-sweep/STEP.md +3 -3
  87. package/assets/init/.qfai/assistant/step/implement-tdd/STEP.md +20 -2
  88. package/assets/init/.qfai/assistant/step/prototyping-grill/STEP.md +4 -0
  89. package/assets/init/.qfai/assistant/step/prototyping-handoff/STEP.md +3 -2
  90. package/assets/init/.qfai/assistant/step/prototyping-loop/STEP.md +6 -1
  91. package/assets/init/.qfai/assistant/step/sdd-contract/STEP.md +58 -11
  92. package/assets/init/.qfai/assistant/step/sdd-flow/STEP.md +41 -27
  93. package/assets/init/.qfai/assistant/step/sdd-story/STEP.md +2 -1
  94. package/assets/init/.qfai/assistant/step/sdd-triage/STEP.md +43 -26
  95. package/assets/init/.qfai/assistant/step/triage-answer/STEP.md +8 -3
  96. package/assets/init/.qfai/assistant/step/triage-close/STEP.md +12 -6
  97. package/assets/init/.qfai/assistant/step/triage-decompose/STEP.md +2 -1
  98. package/assets/init/.qfai/assistant/step/triage-operate/STEP.md +36 -6
  99. package/assets/init/.qfai/assistant/step/triage-security-intake/STEP.md +2 -0
  100. package/assets/init/.qfai/assistant/step/verify-commit/STEP.md +3 -1
  101. package/assets/init/.qfai/assistant/step/verify-context/STEP.md +3 -3
  102. package/assets/init/.qfai/assistant/step/verify-release-notes/STEP.md +11 -3
  103. package/assets/init/.qfai/assistant/step/verify-repo-gate/STEP.md +22 -0
  104. package/assets/init/root/.agents/rules/delegation-steering.md +4 -2
  105. package/assets/init/root/.agents/rules/distributed-surface.md +1 -1
  106. package/assets/init/root/.agents/rules/grilling.md +28 -76
  107. package/assets/init/root/.agents/rules/interface-clarity.md +98 -6
  108. package/assets/init/root/.gitattributes +7 -5
  109. package/assets/init/root/.github/workflows/qfai-docs.yml +1 -1
  110. package/assets/init/root/qfai.config.yaml +1 -1
  111. package/assets/mdschema/story/01_policy/constraint.mdschema.yml +46 -2
  112. package/assets/mdschema/story/01_policy/initiative.mdschema.yml +18 -0
  113. package/assets/mdschema/story/03_contract/tech.mdschema.yml +5 -2
  114. package/assets/uix-rev/strategy-review.md +1 -1
  115. package/dist/cli/index.cjs +3787 -7097
  116. package/dist/cli/index.cjs.map +1 -1
  117. package/dist/cli/index.mjs +3647 -6970
  118. package/dist/cli/index.mjs.map +1 -1
  119. package/dist/graph/cli.cjs +966 -222
  120. package/dist/graph/cli.cjs.map +1 -1
  121. package/dist/graph/cli.mjs +942 -198
  122. package/dist/graph/cli.mjs.map +1 -1
  123. package/dist/graph/hook.cjs +999 -88
  124. package/dist/graph/hook.cjs.map +1 -1
  125. package/dist/graph/hook.mjs +996 -85
  126. package/dist/graph/hook.mjs.map +1 -1
  127. package/dist/hook/turn-end.cjs +15 -45
  128. package/dist/hook/turn-end.cjs.map +1 -1
  129. package/dist/hook/turn-end.mjs +15 -45
  130. package/dist/hook/turn-end.mjs.map +1 -1
  131. package/dist/index.cjs +15398 -18327
  132. package/dist/index.cjs.map +1 -1
  133. package/dist/index.d.cts +32 -41
  134. package/dist/index.d.ts +32 -41
  135. package/dist/index.mjs +19276 -22214
  136. package/dist/index.mjs.map +1 -1
  137. package/package.json +2 -2
  138. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-artifact-rules.md +0 -53
  139. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-completion-matrix.md +0 -133
  140. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/example-mapping-guide.md +0 -18
  141. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/oq-and-deferred-rules.md +0 -84
  142. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui-bearing-playbook.md +0 -95
  143. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/platform_baselines.md +0 -118
  144. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/review_audit_playbook.md +0 -115
  145. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/trend_scan_playbook.md +0 -81
  146. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux_best_practices.md +0 -184
  147. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/01_Context.md +0 -143
  148. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/03_Story-Workshop.md +0 -104
  149. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/04_Sources.md +0 -276
  150. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/05_Scope.md +0 -36
  151. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/06_REQ.md +0 -26
  152. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/07_NFR.md +0 -24
  153. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/08_Glossary.md +0 -23
  154. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/09_Constraints.md +0 -60
  155. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/11_OQ-Register.md +0 -38
  156. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/prototyping.yaml +0 -8
  157. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/00_index.md +0 -35
  158. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/40_screen_contracts.md +0 -62
  159. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/50_review_input_bundle.md +0 -38
  160. package/assets/init/.qfai/assistant/step/discussion-oq/STEP.md +0 -70
  161. package/assets/init/.qfai/assistant/step/discussion-pack/STEP.md +0 -199
  162. package/assets/init/.qfai/assistant/step/discussion-uiux/STEP.md +0 -82
  163. package/assets/uix-rev/contracts-review.md +0 -27
@@ -1,6 +1,7 @@
1
1
  // src/cli/graphHook.ts
2
2
  import { readFileSync } from "fs";
3
- import path16 from "path";
3
+ import { lstat as lstat9 } from "fs/promises";
4
+ import path19 from "path";
4
5
 
5
6
  // src/core/init/fsGuards.ts
6
7
  import { constants } from "fs";
@@ -107,74 +108,332 @@ async function findUnsafeHostFileComponent(destRoot, segments) {
107
108
  }
108
109
 
109
110
  // src/core/graph/hooks.ts
111
+ import path2 from "path";
110
112
  function classifyGraphExploration(event, authorize = (decision) => decision) {
111
113
  if (event.tool === "write_stdin") return outsideBoundary();
112
114
  if (["rg", "grep", "grep_search", "search_files", "file_search"].includes(event.tool.toLowerCase())) {
113
115
  return authorize(denyExploration(event.tool, event.path ?? "."));
114
116
  }
115
117
  const shell = /(?:^|[\\/])(?:pwsh|powershell)(?:\.exe)?$/i.test(event.shell ?? "") || event.tool.toLowerCase() === "powershell" || event.tool === "exec_command" && !event.shell && process.platform === "win32" ? "powershell" : /(?:^|[\\/])cmd(?:\.exe)?$/i.test(event.shell ?? "") ? "cmd" : "posix";
116
- const commands = shellPipelines(event.command ?? "", shell);
117
- if (!commands) return failedGraphHook();
118
- return classifyCommands(commands, authorize) ?? {
118
+ const directory = event.cwd ? path2.resolve(event.cwd, event.workdir ?? ".") : void 0;
119
+ return classifyShellText(
120
+ event.command ?? "",
121
+ { authorize, shell, ...directory ? { directory } : {} },
122
+ 0,
123
+ false,
124
+ "observed"
125
+ ) ?? {
119
126
  decision: "allow",
120
127
  state: "configured",
121
128
  message: "No direct exploration was classified."
122
129
  };
123
130
  }
124
- function classifyCommands(commands, authorize, depth = 0) {
125
- const changesDirectory = commands.some(changesGraphDirectory);
126
- const scopedAuthorization = changesDirectory ? (decision) => graphFallbackUnavailable(
127
- decision,
128
- "The command changes its working directory.",
129
- "Run a single search from this project worktree, then retry the denied action."
130
- ) : authorize;
131
+ function classifyShellText(text, scope, depth, redefinedOutside, start, substitution = false) {
132
+ if (depth > 16) return failedGraphHook("depth");
133
+ const source = scope.shell === "powershell" ? withoutPowerShellComments(powershellHereStrings(powerShellLines(text))) : text;
134
+ const commands = source === void 0 ? void 0 : shellPipelines(source, scope.shell, depth > 0);
135
+ if (source === void 0 || !commands) {
136
+ return substitution ? void 0 : failedGraphHook("quote");
137
+ }
138
+ const bodies = substitutionBodies(source, scope.shell, depth > 0);
139
+ if (!bodies) return failedGraphHook("substitution");
140
+ return classifyCommands(
141
+ commands,
142
+ scope,
143
+ depth,
144
+ redefinedOutside,
145
+ start,
146
+ bodies.map(
147
+ (body) => (location, redefines) => classifyShellText(body, scope, depth + 1, redefines, location, true)
148
+ )
149
+ );
150
+ }
151
+ function powershellHereStrings(text) {
152
+ let output = "";
153
+ let quote;
154
+ for (let index = 0; index < text.length; index += 1) {
155
+ const character = text[index] ?? "";
156
+ if (character === "`" && quote !== "'") {
157
+ output += character + (text[index + 1] ?? "");
158
+ index += 1;
159
+ continue;
160
+ }
161
+ if (quote) {
162
+ if (character === quote) quote = void 0;
163
+ output += character;
164
+ continue;
165
+ }
166
+ hereString.lastIndex = index;
167
+ const match = character === "@" ? hereString.exec(text) : null;
168
+ if (match) {
169
+ output += match[1] === "'" ? "''" : `"${(match[2] ?? "").replace(/"/g, "")}"`;
170
+ index = hereString.lastIndex - 1;
171
+ continue;
172
+ }
173
+ if (character === "'" || character === '"') quote = character;
174
+ output += character;
175
+ }
176
+ return output;
177
+ }
178
+ var hereString = /@(['"])[ \t]*\r?\n([\s\S]*?)\r?\n\1@/y;
179
+ function classifyCommands(commands, scope, depth, redefinedOutside, start, substitutions = []) {
180
+ const redefined = redefinedOutside || commands.some((command) => redefinesCommands(command.words));
181
+ const stays = commands.every((command) => {
182
+ const operand = directoryOperand(command.words);
183
+ if (operand === void 0) return true;
184
+ return !redefined && operand !== null && start === "observed" && scope.directory !== void 0 && path2.resolve(scope.directory, operand) === scope.directory;
185
+ });
186
+ for (const classify of substitutions) {
187
+ const decision = classify(stays ? start : "unknown", redefined);
188
+ if (decision?.decision === "deny") return decision;
189
+ }
190
+ let location = start;
131
191
  let boundary;
132
192
  let allowed;
133
- for (const words of commands) {
134
- const decision = classifyCommand(words, scopedAuthorization, depth);
193
+ let openCases = 0;
194
+ for (const [index, command] of commands.entries()) {
195
+ const words = openCases > 0 && command.words[0]?.endsWith(")") ? command.words.slice(1) : command.words;
196
+ if (words[0] === "case") openCases += 1;
197
+ else if (words[0] === "esac") openCases = Math.max(0, openCases - 1);
198
+ if (typeof location === "object" && index > 0 && command.join !== "&&" && command.join !== "|")
199
+ location = "unknown";
200
+ const operand = directoryOperand(words);
201
+ if (operand !== void 0) {
202
+ location = redefined ? "unknown" : movedLocation(location, operand, command, commands[index + 1], scope);
203
+ }
204
+ const upstream = words[0] === "{" && !groupClosesBare(commands, index) ? void 0 : command.upstream;
205
+ const decision = classifyCommand(words, { ...scope, location, redefined }, depth, upstream);
135
206
  if (decision?.decision === "deny") return decision;
136
207
  if (decision?.state === "outside-boundary") boundary = decision;
137
208
  else if (decision) allowed = decision;
138
209
  }
139
210
  return boundary ?? allowed;
140
211
  }
141
- function changesGraphDirectory(words) {
212
+ function redefinesCommands(words) {
213
+ const body = arithmeticForBody(words);
214
+ if (body) return redefinesCommands(body);
215
+ let offset = 0;
216
+ for (; ; ) {
217
+ const redirection = redirectionLength(words[offset]);
218
+ if (redirection) offset += redirection;
219
+ else if (words[offset] === "{") offset += 1;
220
+ else if (["builtin", "command", "env"].includes(words[offset]?.toLowerCase() ?? "")) {
221
+ offset += 1;
222
+ while (words[offset]?.startsWith("-")) {
223
+ offset += /^-[uCS]$|^--(?:unset|chdir|split-string)$/.test(words[offset] ?? "") ? 2 : 1;
224
+ }
225
+ } else break;
226
+ }
227
+ const first = words[offset] ?? "";
228
+ return words.some((word) => word.includes("()") || /^\{[A-Za-z_][A-Za-z0-9_]*\}[<>]/.test(word)) || /^(?:[A-Za-z_][A-Za-z0-9_]*=|\$|\{\w*\}?[<>]?$|\{\w+\}[<>])/.test(first) || first === "printf" && words.includes("-v") || [
229
+ "time",
230
+ "!",
231
+ "if",
232
+ "then",
233
+ "do",
234
+ "else",
235
+ "elif",
236
+ "while",
237
+ "until",
238
+ "case",
239
+ "coproc",
240
+ "read",
241
+ "mapfile",
242
+ "readarray",
243
+ "getopts"
244
+ ].includes(first) || [
245
+ "function",
246
+ "alias",
247
+ "export",
248
+ "declare",
249
+ "typeset",
250
+ "readonly",
251
+ "set",
252
+ "setx",
253
+ "set-alias",
254
+ "new-alias",
255
+ "sal",
256
+ "nal",
257
+ "set-item",
258
+ "si",
259
+ "set-variable",
260
+ "sv",
261
+ "filter",
262
+ "new-item",
263
+ "ni",
264
+ "iex",
265
+ "invoke-expression",
266
+ "eval",
267
+ "source",
268
+ ".",
269
+ "hash"
270
+ ].includes(words[offset] === "." ? "." : commandName(words.slice(offset)) ?? "");
271
+ }
272
+ var redirectionSource = String.raw`(?:\d*|&|\{[A-Za-z_][A-Za-z0-9_]*\})`;
273
+ var redirectionStart = new RegExp(String.raw`^${redirectionSource}(?:<|>)`);
274
+ var detachedRedirection = new RegExp(String.raw`^${redirectionSource}(?:<>|>{1,2}|<{1,3})[&|]?$`);
275
+ function redirectionLength(word) {
276
+ if (!word || !redirectionStart.test(word)) return 0;
277
+ return detachedRedirection.test(word) ? 2 : 1;
278
+ }
279
+ function groupClosesBare(commands, index) {
280
+ let depth = 0;
281
+ for (const { words } of commands.slice(index)) {
282
+ const opened = words.findIndex((word) => word !== "{");
283
+ depth += opened < 0 ? words.length : opened;
284
+ if (words[0]?.startsWith("}")) {
285
+ depth -= 1;
286
+ if (depth <= 0) return words.length === 1 && words[0] === "}";
287
+ }
288
+ }
289
+ return false;
290
+ }
291
+ function directoryOperand(words) {
142
292
  let offset = 0;
143
293
  while (offset < words.length) {
144
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? "")) {
294
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? "") || words[offset] === "{" || COMPOUND_KEYWORDS.includes(words[offset] ?? "")) {
145
295
  offset += 1;
146
296
  continue;
147
297
  }
148
298
  if (!["command", "builtin", "env"].includes(words[offset]?.toLowerCase() ?? "")) break;
149
299
  offset += 1;
150
- if (words[offset] === "-v" || words[offset] === "-V") return false;
300
+ if (words[offset] === "-v" || words[offset] === "-V") return void 0;
151
301
  while (words[offset]?.startsWith("-")) offset += 1;
152
302
  }
153
- return ["cd", "chdir", "pushd", "popd", "set-location", "sl"].includes(
154
- words[offset]?.toLowerCase() ?? ""
155
- );
303
+ const name = words[offset]?.toLowerCase() ?? "";
304
+ if (!["cd", "chdir", "pushd", "popd", "set-location", "sl"].includes(name)) return void 0;
305
+ const operands = words.slice(offset + 1);
306
+ const target = operands[0];
307
+ return name === "popd" || operands.length !== 1 || target === void 0 || target.startsWith("-") || target.startsWith("+") || target.includes(":") && !/^[A-Za-z]:[\\/]/.test(target) || /[$`~%*?[\]{}]/.test(target) || target.split(/[\\/]/).includes("..") ? null : target;
308
+ }
309
+ function movedLocation(location, operand, command, next, scope) {
310
+ if (location === "unknown" || operand === null || !scope.directory) return "unknown";
311
+ const from = location === "observed" ? scope.directory : location.directory;
312
+ const directory = path2.resolve(from, operand);
313
+ if (location === "observed" && directory === scope.directory) return "observed";
314
+ if (outside(scope.directory, directory)) return "unknown";
315
+ if (command.join === "|" || command.join === "||" || next !== void 0 && next.join !== "&&")
316
+ return "unknown";
317
+ if (scope.shell === "posix" && !path2.isAbsolute(operand) && !operand.startsWith(".") && process.env.CDPATH)
318
+ return "unknown";
319
+ return { directory };
156
320
  }
157
- function classifyCommand(words, authorize, depth = 0) {
158
- if (depth > 16) return failedGraphHook();
321
+ function outside(root, target) {
322
+ const relative = path2.relative(root, target);
323
+ return relative === ".." || relative.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative);
324
+ }
325
+ function authorizeAt(context, decision) {
326
+ const { location, directory, authorize } = context;
327
+ if (location === "observed") return authorize(decision);
328
+ if (location === "unknown" || !directory)
329
+ return graphFallbackUnavailable(
330
+ decision,
331
+ "The command changes its working directory.",
332
+ "Run a single search from this project worktree, then retry the denied action."
333
+ );
334
+ if (!decision.exceptionEligible || decision.target === void 0 || !decision.operation)
335
+ return authorize(decision);
336
+ if (decision.target.split(/[\\/]/).includes(".."))
337
+ return graphFallbackUnavailable(
338
+ decision,
339
+ "The search target has a .. segment after a directory change.",
340
+ "Run a single search from this project worktree, then retry the denied action."
341
+ );
342
+ const target = path2.resolve(location.directory, decision.target);
343
+ if (outside(directory, target))
344
+ return graphFallbackUnavailable(
345
+ decision,
346
+ "The search target resolves outside this project worktree.",
347
+ "Run a single search with one explicit project-relative target, then retry the denied action."
348
+ );
349
+ const relative = path2.relative(directory, target).split(path2.sep).join("/") || ".";
350
+ return authorize({ ...denyExploration(decision.operation, relative), exceptionEligible: true });
351
+ }
352
+ var COMPOUND_KEYWORDS = [
353
+ "if",
354
+ "then",
355
+ "elif",
356
+ "else",
357
+ "while",
358
+ "until",
359
+ "do",
360
+ "!",
361
+ "time"
362
+ ];
363
+ function arithmeticForBody(words) {
364
+ let depth = 0;
365
+ for (const [index, word] of words.entries()) {
366
+ for (let offset = 0; offset < word.length; offset += 1) {
367
+ if (word[offset] === "(") depth += 1;
368
+ else if (word[offset] === ")") depth -= 1;
369
+ if (depth > -2) continue;
370
+ if (word[offset - 1] !== ")") return void 0;
371
+ const rest = word.slice(offset + 1);
372
+ const body = rest === "" ? words.slice(index + 1) : [rest, ...words.slice(index + 1)];
373
+ return body[0] === "{" || body[0] === "do" ? body : void 0;
374
+ }
375
+ }
376
+ return void 0;
377
+ }
378
+ function classifyCommand(words, context, depth, upstream) {
379
+ const { redefined } = context;
380
+ if (depth > 16) return failedGraphHook("depth");
159
381
  let offset = 0;
160
- while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? "")) offset += 1;
161
- if (offset > 0) return classifyCommand(words.slice(offset), authorize, depth + 1);
162
- const operation = words[0]?.split(/[\\/]/).at(-1)?.replace(/\.exe$/i, "").toLowerCase();
382
+ while (offset < words.length) {
383
+ const redirection = redirectionLength(words[offset]);
384
+ if (redirection) offset += redirection;
385
+ else if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? "")) offset += 1;
386
+ else break;
387
+ }
388
+ if (offset > 0) {
389
+ return classifyCommand(words.slice(offset), context, depth + 1);
390
+ }
391
+ const operation = commandName(words);
392
+ if (COMPOUND_KEYWORDS.includes(words[0] ?? "")) {
393
+ const skip = words[0] === "time" && words[1] === "-p" ? 2 : 1;
394
+ return classifyCommand(words.slice(skip), context, depth + 1);
395
+ }
396
+ if (words[0] === "fi" || words[0] === "done") return void 0;
397
+ const body = arithmeticForBody(words);
398
+ if (body) return classifyCommand(body, context, depth + 1);
399
+ if (operation === "{") {
400
+ return classifyCommand(words.slice(1), context, depth + 1, upstream);
401
+ }
402
+ if (operation === "case") {
403
+ const subject = words.indexOf("in");
404
+ const arm = words.findIndex((word, index) => index > subject && word.endsWith(")"));
405
+ return arm < 0 ? void 0 : classifyCommand(words.slice(arm + 1), context, depth + 1);
406
+ }
407
+ if (operation === "}" || operation === "esac") return void 0;
163
408
  if (operation === "env" || operation === "command" || operation === "builtin") {
164
409
  let offset2 = 1;
165
- while (words[offset2]?.startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset2] ?? "")) {
166
- offset2 += 1;
410
+ while (offset2 < words.length) {
411
+ const redirection = redirectionLength(words[offset2]);
412
+ if (redirection) offset2 += redirection;
413
+ else if (words[offset2]?.startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset2] ?? ""))
414
+ offset2 += 1;
415
+ else break;
167
416
  }
168
- return classifyCommand(words.slice(offset2), authorize, depth + 1);
417
+ return classifyCommand(words.slice(offset2), context, depth + 1);
169
418
  }
170
419
  if (["bash", "sh", "zsh", "pwsh", "powershell", "cmd"].includes(operation ?? "")) {
171
420
  const switchIndex = words.findIndex((word) => /^(?:-[a-z]*c|\/c|-command)$/i.test(word));
172
421
  const inner = switchIndex >= 0 ? words[switchIndex + 1] : void 0;
173
422
  if (!inner) return outsideBoundary();
174
423
  const shell = operation === "pwsh" || operation === "powershell" ? "powershell" : operation === "cmd" ? "cmd" : "posix";
175
- const commands = shellPipelines(inner, shell);
176
- return commands ? classifyCommands(commands, authorize, depth + 1) : failedGraphHook();
424
+ return classifyShellText(
425
+ inner,
426
+ {
427
+ authorize: context.authorize,
428
+ shell,
429
+ ...context.directory ? { directory: context.directory } : {}
430
+ },
431
+ depth + 1,
432
+ redefined,
433
+ context.location
434
+ );
177
435
  }
436
+ if (!redefined && pipeFilter(words) && printsText(upstream)) return void 0;
178
437
  if (operation === "rg" || operation === "grep" || operation === "findstr") {
179
438
  let offset2 = 1;
180
439
  while (/^(?:-[RrinlIHsvwxcFoq]+|--(?:hidden|line-number|ignore-case|fixed-strings|recursive)|\/[SIMOPVNLR]+)$/i.test(
@@ -185,7 +444,10 @@ function classifyCommand(words, authorize, depth = 0) {
185
444
  const positional = words.slice(offset2);
186
445
  const eligible = positional.length > 0 && positional.length <= 2 && !positional.some((word) => word.startsWith("-") || /[$%`<>]/.test(word));
187
446
  const target = eligible ? positional[1] ?? "." : JSON.stringify(positional);
188
- return authorize({ ...denyExploration(operation, target), exceptionEligible: eligible });
447
+ return authorizeAt(context, {
448
+ ...denyExploration(operation, target),
449
+ exceptionEligible: eligible
450
+ });
189
451
  }
190
452
  let gitCommand = 1;
191
453
  if (operation === "git") {
@@ -198,7 +460,7 @@ function classifyCommand(words, authorize, depth = 0) {
198
460
  const paths = words.indexOf("--");
199
461
  const targets = paths >= 0 ? words.slice(paths + 1) : [];
200
462
  const eligible = gitCommand === 1 && targets.length <= 1 && (paths >= 0 || words.length === 3) && !targets.some((word) => /[$%`<>]/.test(word));
201
- return authorize({
463
+ return authorizeAt(context, {
202
464
  ...denyExploration(
203
465
  "git grep",
204
466
  eligible ? targets[0] ?? "." : JSON.stringify(words.slice(1))
@@ -207,15 +469,15 @@ function classifyCommand(words, authorize, depth = 0) {
207
469
  });
208
470
  }
209
471
  if (operation === "select-string") {
210
- const path17 = words.findIndex((word) => /^-(?:literalpath|path)$/i.test(word));
472
+ const path20 = words.findIndex((word) => /^-(?:literalpath|path)$/i.test(word));
211
473
  const targets = [];
212
- for (let offset2 = path17 + 1; path17 >= 0 && offset2 < words.length; offset2 += 1) {
474
+ for (let offset2 = path20 + 1; path20 >= 0 && offset2 < words.length; offset2 += 1) {
213
475
  const word = words[offset2];
214
476
  if (word === void 0 || word.startsWith("-")) break;
215
477
  targets.push(word);
216
478
  }
217
479
  const eligible = targets.length === 1 && !targets.some((word) => /[,$%`<>]/.test(word));
218
- return authorize({
480
+ return authorizeAt(context, {
219
481
  ...denyExploration("Select-String", eligible ? targets[0] ?? "." : JSON.stringify(targets)),
220
482
  exceptionEligible: eligible
221
483
  });
@@ -246,6 +508,145 @@ function classifyCommand(words, authorize, depth = 0) {
246
508
  }
247
509
  return outsideBoundary();
248
510
  }
511
+ function commandName(words) {
512
+ return words[0]?.split(/[\\/]/).at(-1)?.replace(/\.exe$/i, "").toLowerCase();
513
+ }
514
+ function unparsedWord(word) {
515
+ return /\$(?!$)|[`<>]|%[^%\s]+%/.test(word);
516
+ }
517
+ function printsText(command) {
518
+ if (!command || command.words.some(
519
+ (word) => /[(){}@]/.test(word) || unparsedWord(word) && !/^\d*>(?:&\d|\/dev\/null)$/.test(word)
520
+ ))
521
+ return false;
522
+ const name = /[\\/=]/.test(command.words[0] ?? "") ? "" : commandName(command.words) ?? "";
523
+ const args = command.words.slice(1);
524
+ if (name === "git") {
525
+ return gitTextCommands.has(args[0] ?? "") && !args.some(
526
+ (word) => word === "--no-index" || /^(?:\/|[A-Za-z]:|\\|~|:\/)|(?:^|[\\/:])\.\.(?:[\\/]|$)/.test(word)
527
+ );
528
+ }
529
+ if (["echo", "printf", "write-output"].includes(name))
530
+ return !args.some((word) => /[*?[!]/.test(word));
531
+ if (name === "pnpm" || name === "npm") return packageTextCommands.has(args[0] ?? "");
532
+ if (name === "corepack") {
533
+ return ["pnpm", "npm"].includes(args[0] ?? "") && packageTextCommands.has(args[1] ?? "");
534
+ }
535
+ if (name === "sort" || name === "uniq") {
536
+ const switches = name === "sort" ? /^-[rnufbdhMV]+$/ : /^-[cdiu]+$/;
537
+ return args.every((word) => switches.test(word)) && printsText(command.upstream);
538
+ }
539
+ return pipeFilter(command.words) && printsText(command.upstream);
540
+ }
541
+ var gitTextCommands = /* @__PURE__ */ new Set([
542
+ "status",
543
+ "ls-files",
544
+ "ls-tree",
545
+ "log",
546
+ "diff",
547
+ "branch",
548
+ "remote",
549
+ "rev-list",
550
+ "rev-parse",
551
+ "shortlog",
552
+ "worktree"
553
+ ]);
554
+ var packageTextCommands = /* @__PURE__ */ new Set([
555
+ "test",
556
+ "t",
557
+ "lint",
558
+ "build",
559
+ "typecheck",
560
+ "check-types",
561
+ "ls",
562
+ "list",
563
+ "why",
564
+ "outdated",
565
+ "audit",
566
+ "install",
567
+ "i",
568
+ "ci",
569
+ "view",
570
+ "info"
571
+ ]);
572
+ var grepSwitches = /^-[ivncowxEFGPqsHhIyzZLlbUa]+$/;
573
+ var rgSwitches = /^-[ivncowxFsSqaUNHlLIP]+$/;
574
+ var longSwitches = /* @__PURE__ */ new Set([
575
+ "--ignore-case",
576
+ "--invert-match",
577
+ "--line-number",
578
+ "--count",
579
+ "--only-matching",
580
+ "--word-regexp",
581
+ "--line-regexp",
582
+ "--extended-regexp",
583
+ "--fixed-strings",
584
+ "--perl-regexp",
585
+ "--quiet",
586
+ "--silent",
587
+ "--no-filename",
588
+ "--with-filename",
589
+ "--smart-case",
590
+ "--case-sensitive"
591
+ ]);
592
+ var valueOptions = /^(?:-[emABC]|--(?:regexp|max-count|context|after-context|before-context))$/;
593
+ var attachedValueOptions = /^(?:-e.+|-[mABC]\d+|--(?:regexp|max-count|context|after-context|before-context|color|colour)=.+)$/;
594
+ function pipeFilter(words) {
595
+ if (/[\\/=]/.test(words[0] ?? "")) return false;
596
+ const name = commandName(words);
597
+ const args = words.slice(1);
598
+ if (args.some((word) => unparsedWord(word) || /[*?[\]{}()~@!]/.test(word))) return false;
599
+ if (name === "findstr") return findstrFilter(args);
600
+ if (name === "select-string") return selectStringFilter(args);
601
+ if (name !== "grep" && name !== "rg") return false;
602
+ let patternGiven = false;
603
+ const operands = [];
604
+ for (let index = 0; index < args.length; index += 1) {
605
+ const word = args[index] ?? "";
606
+ if (word === "--") {
607
+ operands.push(...args.slice(index + 1));
608
+ break;
609
+ }
610
+ if (!word.startsWith("-") || word === "-") operands.push(word);
611
+ else if (valueOptions.test(word)) {
612
+ if (word === "-e" || word === "--regexp") patternGiven = true;
613
+ index += 1;
614
+ if (index >= args.length) return false;
615
+ } else if (attachedValueOptions.test(word)) {
616
+ if (/^(?:-e|--regexp=)/.test(word)) patternGiven = true;
617
+ } else if (!(name === "grep" ? grepSwitches : rgSwitches).test(word) && !longSwitches.has(word))
618
+ return false;
619
+ }
620
+ const files = patternGiven ? operands : operands.slice(1);
621
+ return (patternGiven || operands.length > 0) && files.every((word) => word === "-");
622
+ }
623
+ function findstrFilter(args) {
624
+ let patternGiven = false;
625
+ const operands = [];
626
+ for (const word of args) {
627
+ if (/^\/c:./i.test(word)) patternGiven = true;
628
+ else if (word.startsWith("/")) {
629
+ if (!/^\/[ivnxbelrmop]+$/i.test(word)) return false;
630
+ } else if (word.startsWith("-")) return false;
631
+ else operands.push(word);
632
+ }
633
+ return operands.length === (patternGiven ? 0 : 1);
634
+ }
635
+ function selectStringFilter(args) {
636
+ let patternGiven = false;
637
+ let positional = 0;
638
+ for (let index = 0; index < args.length; index += 1) {
639
+ const word = args[index] ?? "";
640
+ if (!word.startsWith("-")) positional += 1;
641
+ else if (/^-(?:pattern|context|encoding)$/i.test(word)) {
642
+ if (/^-pattern$/i.test(word)) patternGiven = true;
643
+ index += 1;
644
+ if (index >= args.length) return false;
645
+ } else if (!/^-(?:simplematch|casesensitive|notmatch|allmatches|list|quiet|raw|noemphasis)$/i.test(word))
646
+ return false;
647
+ }
648
+ return positional === (patternGiven ? 0 : 1);
649
+ }
249
650
  function outsideBoundary() {
250
651
  return {
251
652
  decision: "allow",
@@ -253,20 +654,158 @@ function outsideBoundary() {
253
654
  message: "Search inside scripts, aliases or continuing input is not verified by this pre-tool boundary."
254
655
  };
255
656
  }
256
- function shellPipelines(command, shell) {
657
+ function resolveAlias(words, shell) {
658
+ return shell === "powershell" && words[0]?.toLowerCase() === "sls" ? ["Select-String", ...words.slice(1)] : words;
659
+ }
660
+ var WORD_BREAK = /[ \t\n;&|()]/;
661
+ function startsComment(command, index, shell) {
662
+ if (shell !== "posix") return false;
663
+ const previous = command[index - 1];
664
+ return (previous === void 0 || WORD_BREAK.test(previous)) && !inUntrackedContext(command, index);
665
+ }
666
+ function inUntrackedContext(command, index) {
667
+ return /`|\$\{|\$\[|\$'|\(\(|[?*+@!]\(/.test(command.slice(0, index));
668
+ }
669
+ function powerShellLines(command) {
670
+ return command.replace(/\r(?!\n)/g, "\n");
671
+ }
672
+ var POWERSHELL_BREAK = /[ \t\n;|&]/;
673
+ var POWERSHELL_UNTRACKED = /@["']|\$\(|[\u2018-\u201e]/;
674
+ function withoutPowerShellComments(command) {
675
+ let output = "";
676
+ let quote;
677
+ let wordStarted = false;
678
+ for (let index = 0; index < command.length; index += 1) {
679
+ const character = command[index] ?? "";
680
+ if (character === "`" && quote !== "'") {
681
+ output += character + (command[index + 1] ?? "");
682
+ index += 1;
683
+ wordStarted = true;
684
+ continue;
685
+ }
686
+ if (quote) {
687
+ output += character;
688
+ if (character === quote) quote = void 0;
689
+ continue;
690
+ }
691
+ const tracked = () => !inUntrackedContext(command, index) && !POWERSHELL_UNTRACKED.test(command.slice(0, index));
692
+ if (character === "<" && command[index + 1] === "#") {
693
+ const end = command.indexOf("#>", index + 2);
694
+ if (end === -1) return void 0;
695
+ output += !wordStarted && tracked() ? " " : `;${command.slice(index + 2, end)};`;
696
+ index = end + 1;
697
+ wordStarted = false;
698
+ continue;
699
+ }
700
+ if (character === "#" && !wordStarted && tracked()) {
701
+ const end = command.indexOf("\n", index);
702
+ if (end === -1) break;
703
+ index = end - 1;
704
+ continue;
705
+ }
706
+ output += character;
707
+ if (character === "'" || character === '"') quote = character;
708
+ wordStarted = !POWERSHELL_BREAK.test(character);
709
+ }
710
+ return output;
711
+ }
712
+ var DATA_FILE = String.raw`(?!/dev/|/proc/)[\w./-]+`;
713
+ var DATA_OPERAND = String.raw`[ \t]+(?:-[A-Za-z]+|>>?[ \t]*${DATA_FILE}|>[ \t]*/dev/null|${DATA_FILE})`;
714
+ var DATA_HEREDOC_LINE = new RegExp(
715
+ String.raw`^[ \t]*(?:cat|tee)(?:${DATA_OPERAND})*[ \t]*<<-?[ \t]*(?:(['"])[A-Za-z_]\w*\1|\\[A-Za-z_]\w*)(?:${DATA_OPERAND})*[ \t]*$`
716
+ );
717
+ var DATA_PRELUDE_LINE = new RegExp(
718
+ String.raw`^[ \t]*(?:mkdir[ \t]+-p(?:[ \t]+${DATA_FILE})+[ \t]*)?$`
719
+ );
720
+ function shellPipelines(command, shell, nested = false) {
257
721
  const commands = [];
258
722
  let words = [];
723
+ let upstream;
724
+ let join;
259
725
  let word = "";
260
726
  let quote;
727
+ let afterRedirect = "";
728
+ const heredocs = [];
729
+ const skipped = [];
730
+ let quotedWord = false;
261
731
  const flushWord = () => {
262
732
  if (word.length) words.push(word);
263
733
  word = "";
734
+ quotedWord = false;
735
+ };
736
+ const readHeredocOperator = (index) => {
737
+ if (word.length && !/^\d+$/.test(word)) flushWord();
738
+ let cursor = index + 2;
739
+ const stripTabs = command[cursor] === "-";
740
+ if (stripTabs) cursor += 1;
741
+ words.push(`${word}<<${stripTabs ? "-" : ""}`);
742
+ word = "";
743
+ while (command[cursor] === " " || command[cursor] === " ") cursor += 1;
744
+ let delimiter = "";
745
+ let read = false;
746
+ let delimiterQuote;
747
+ while (cursor < command.length) {
748
+ const character = command[cursor] ?? "";
749
+ if (delimiterQuote) {
750
+ if (character === delimiterQuote) delimiterQuote = void 0;
751
+ else delimiter += character;
752
+ } else if (character === '"' || character === "'") {
753
+ delimiterQuote = character;
754
+ } else if (character === "\\" && cursor + 1 < command.length) {
755
+ delimiter += command[cursor + 1] ?? "";
756
+ cursor += 1;
757
+ } else if (/[\s;|&<>()]/.test(character)) {
758
+ break;
759
+ } else {
760
+ delimiter += character;
761
+ }
762
+ read = true;
763
+ cursor += 1;
764
+ }
765
+ if (delimiterQuote) {
766
+ quote = delimiterQuote;
767
+ return command.length;
768
+ }
769
+ if (!read) return cursor;
770
+ words.push(delimiter);
771
+ const lineStart = command.lastIndexOf("\n", index) + 1;
772
+ const lineEnd = command.indexOf("\n", index);
773
+ let earlier = "";
774
+ let from = 0;
775
+ for (const [start, end] of skipped) {
776
+ earlier += command.slice(from, start);
777
+ from = end;
778
+ }
779
+ earlier += command.slice(from, lineStart);
780
+ const line = command.slice(lineStart, lineEnd < 0 ? command.length : lineEnd);
781
+ const data = !nested && !command.includes("\r") && DATA_HEREDOC_LINE.test(line) && earlier.split("\n").every((prior) => DATA_PRELUDE_LINE.test(prior) || DATA_HEREDOC_LINE.test(prior));
782
+ heredocs.push({ delimiter, stripTabs, data });
783
+ return cursor;
784
+ };
785
+ const skipHeredocs = (index) => {
786
+ let position = index + 1;
787
+ const pending = heredocs.splice(0);
788
+ if (!pending.every((heredoc) => heredoc.data)) return index;
789
+ for (const { delimiter, stripTabs } of pending) {
790
+ let closed = false;
791
+ while (position < command.length && !closed) {
792
+ const end = command.indexOf("\n", position);
793
+ const line = command.slice(position, end < 0 ? command.length : end);
794
+ position = end < 0 ? command.length : end + 1;
795
+ closed = (stripTabs ? line.replace(/^\t+/, "") : line) === delimiter;
796
+ }
797
+ if (!closed) return index;
798
+ }
799
+ skipped.push([index + 1, position]);
800
+ return position - 1;
264
801
  };
265
802
  for (let index = 0; index < command.length; index += 1) {
266
803
  const character = command[index];
267
804
  if (character === void 0) continue;
268
805
  const next = command[index + 1];
269
806
  const escaped = next !== void 0 && (shell === "posix" && character === "\\" && (!quote || quote === '"' && ['"', "\\", "$", "`", "\n"].includes(next)) || shell === "powershell" && character === "`" && quote !== "'" || shell === "cmd" && character === "^" && !quote);
807
+ const redirectBefore = afterRedirect;
808
+ afterRedirect = "";
270
809
  if (escaped) {
271
810
  if (next !== "\n") word += next;
272
811
  index += 1;
@@ -275,23 +814,319 @@ function shellPipelines(command, shell) {
275
814
  if (quote) {
276
815
  if (character === quote) quote = void 0;
277
816
  else word += character;
817
+ } else if (character === "#" && !word.length && !quotedWord && startsComment(command, index, shell)) {
818
+ const end = command.indexOf("\n", index);
819
+ index = (end === -1 ? command.length : end) - 1;
278
820
  } else if (character === '"' || character === "'") {
279
821
  quote = character;
822
+ quotedWord = true;
823
+ } else if ((character === "&" || character === "|") && (character === "&" ? redirectBefore !== "" && /[\d-]/.test(next ?? "") : redirectBefore === ">" && shell === "posix")) {
824
+ word += character;
825
+ } else if (shell === "posix" && character === "&" && next === ">") {
826
+ flushWord();
827
+ word = character;
828
+ } else if (character === "\n" && !words.length && !word.length && upstream) {
829
+ index = skipHeredocs(index);
830
+ continue;
280
831
  } else if (character === "|" || character === ";" || character === "&" || character === "\n") {
281
832
  flushWord();
282
- if (words.length) commands.push(words);
833
+ const stage = words.length ? {
834
+ words: resolveAlias(words, shell),
835
+ ...upstream ? { upstream } : {},
836
+ ...join ? { join } : {}
837
+ } : void 0;
838
+ if (stage) commands.push(stage);
839
+ const pipe = character === "|" && next !== "|" && stage !== void 0;
840
+ const operator = (character === "|" || character === "&") && next === character ? character === "|" ? "||" : "&&" : character === "|" || character === "&" || character === ";" ? character : "\n";
841
+ if ((character === "|" || character === "&") && next === character) index += 1;
842
+ else if (pipe && shell === "posix" && next === "&") index += 1;
843
+ if (stage || join === void 0 || operator !== "\n") join = operator;
844
+ upstream = pipe ? stage : void 0;
283
845
  words = [];
846
+ if (character === "\n") index = skipHeredocs(index);
284
847
  } else if (/\s/.test(character)) {
285
848
  flushWord();
849
+ } else if (shell === "posix" && character === "<" && next === "<" && command[index + 2] !== "<" && command[index - 1] !== "<") {
850
+ index = readHeredocOperator(index) - 1;
286
851
  } else {
852
+ if ((character === ">" || character === "<") && !/^(?:\d*|\{[A-Za-z_][A-Za-z0-9_]*\})$/.test(word) && !/[<>]$/.test(word) && word !== "&") {
853
+ flushWord();
854
+ }
287
855
  word += character;
856
+ afterRedirect = character === ">" || character === "<" ? character : "";
288
857
  }
289
858
  }
290
859
  if (quote) return void 0;
291
860
  flushWord();
292
- if (words.length) commands.push(words);
861
+ if (words.length) {
862
+ commands.push({
863
+ words: resolveAlias(words, shell),
864
+ ...upstream ? { upstream } : {},
865
+ ...join ? { join } : {}
866
+ });
867
+ }
293
868
  return commands;
294
869
  }
870
+ function substitutionBodies(text, shell, nested = false) {
871
+ if (shell === "cmd") return [];
872
+ const { text: command, expanded } = shell === "posix" ? heredocData(text, nested) : { text, expanded: [] };
873
+ const escape = shell === "posix" ? "\\" : "`";
874
+ const bodies = [];
875
+ let quote;
876
+ let wordStart = true;
877
+ for (let index = 0; index < command.length; index += 1) {
878
+ const character = command[index];
879
+ const next = command[index + 1];
880
+ const atWordStart = wordStart;
881
+ wordStart = false;
882
+ if (character === escape && quote !== "'") {
883
+ index += 1;
884
+ continue;
885
+ }
886
+ if (quote === "'") {
887
+ if (character === "'") quote = void 0;
888
+ continue;
889
+ }
890
+ if (!quote && atWordStart && character === "#" && shell === "posix" && !inUntrackedContext(command, index)) {
891
+ const end = command.indexOf("\n", index);
892
+ if (end === -1) break;
893
+ index = end;
894
+ wordStart = true;
895
+ continue;
896
+ }
897
+ if (!quote && character !== void 0 && WORD_BREAK.test(character)) {
898
+ wordStart = true;
899
+ if (character !== "(") continue;
900
+ }
901
+ if (character === "'" && !quote) {
902
+ quote = "'";
903
+ continue;
904
+ }
905
+ if (character === '"') {
906
+ quote = quote ? void 0 : '"';
907
+ continue;
908
+ }
909
+ const opens = next === "(" && (character === "$" || !quote && shell === "powershell" && character === "@" || !quote && shell === "posix" && (character === "<" || character === ">"));
910
+ if (opens) {
911
+ const end = closingParenthesis(command, index + 2, escape);
912
+ if (end === void 0) return void 0;
913
+ if (!(character === "$" && command[index + 2] === "(")) {
914
+ bodies.push(command.slice(index + 2, end));
915
+ }
916
+ index = end;
917
+ } else if (!quote && character === "(" && // The first `(` of a POSIX `((` arithmetic command opens no subshell; the scan moves
918
+ // on to the second, whose body the comment reader then knows is arithmetic.
919
+ !(shell === "posix" && command[index + 1] === "(") && // A POSIX subshell starts a command, and zsh `=(...)` starts a word; any other
920
+ // `(`, such as an array's in `name=(...)`, is data, scanned on.
921
+ (shell === "powershell" || commandPosition(command, index, 0) || command[index - 1] === "=" && /^$|[\s;&|(]/.test(command[index - 2] ?? ""))) {
922
+ const end = closingParenthesis(command, index + 1, escape);
923
+ if (end === void 0) return void 0;
924
+ bodies.push(command.slice(index + 1, end));
925
+ index = end;
926
+ } else if (!quote && shell === "powershell" && character === "{" && command[index - 1] !== "@") {
927
+ const end = closingBrace(command, index + 1);
928
+ if (end === void 0) continue;
929
+ bodies.push(command.slice(index + 1, end));
930
+ index = end;
931
+ } else if (shell === "posix" && character === "`") {
932
+ const end = closingBacktick(command, index + 1);
933
+ if (end === void 0) return void 0;
934
+ bodies.push(command.slice(index + 1, end).replace(/\\([`\\$])/g, "$1"));
935
+ index = end;
936
+ }
937
+ }
938
+ for (const body of expanded) {
939
+ const nested2 = expandedSubstitutions(body);
940
+ if (!nested2) return void 0;
941
+ bodies.push(...nested2);
942
+ }
943
+ return bodies;
944
+ }
945
+ function closingBrace(command, start) {
946
+ let depth = 1;
947
+ let quote;
948
+ for (let index = start; index < command.length; index += 1) {
949
+ const character = command[index];
950
+ if (character === "`" && quote !== "'") index += 1;
951
+ else if (quote) {
952
+ if (character === quote) quote = void 0;
953
+ } else if (character === "'" || character === '"') quote = character;
954
+ else if (character === "{") depth += 1;
955
+ else if (character === "}") {
956
+ depth -= 1;
957
+ if (depth === 0) return index;
958
+ }
959
+ }
960
+ return void 0;
961
+ }
962
+ function closingBacktick(command, start) {
963
+ let end = start;
964
+ while (end < command.length && command[end] !== "`") end += command[end] === "\\" ? 2 : 1;
965
+ return end < command.length ? end : void 0;
966
+ }
967
+ function expandedSubstitutions(body) {
968
+ const bodies = [];
969
+ for (let index = 0; index < body.length; index += 1) {
970
+ const character = body[index];
971
+ if (character === "\\") {
972
+ index += 1;
973
+ } else if (character === "$" && body[index + 1] === "(") {
974
+ const end = closingParenthesis(body, index + 2, "\\");
975
+ if (end === void 0) return void 0;
976
+ if (body[index + 2] !== "(") bodies.push(body.slice(index + 2, end));
977
+ index = end;
978
+ } else if (character === "`") {
979
+ const end = closingBacktick(body, index + 1);
980
+ if (end === void 0) return void 0;
981
+ bodies.push(body.slice(index + 1, end).replace(/\\([`\\$])/g, "$1"));
982
+ index = end;
983
+ }
984
+ }
985
+ return bodies;
986
+ }
987
+ var heredocOperator = /<<(?!<)(-?)[ \t]*(?:'([^'\n]*)'|"([^"\n]*)"|\\?([^\s;|&<>()'"]+))/y;
988
+ var MESSAGE_WORD = String.raw`[ \t]+[\w./=:@-]+`;
989
+ var MESSAGE_HEREDOC_LINE = new RegExp(
990
+ 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]*$`
991
+ );
992
+ var MESSAGE_CLOSE_LINE = new RegExp(String.raw`^[ \t]*\)"(?:${MESSAGE_WORD})*[ \t]*$`);
993
+ var MESSAGE_PRELUDE_LINE = new RegExp(String.raw`^[ \t]*git[ \t]+add(?:${MESSAGE_WORD})*[ \t]*$`);
994
+ function heredocData(command, nested = false) {
995
+ let output = "";
996
+ let quote;
997
+ let comment = false;
998
+ let depth = 0;
999
+ const outer = [];
1000
+ const expanded = [];
1001
+ let pending = [];
1002
+ let lineOutput = 0;
1003
+ for (let index = 0; index < command.length; index += 1) {
1004
+ const character = command[index] ?? "";
1005
+ output += character;
1006
+ if (character === "\n") {
1007
+ comment = false;
1008
+ if (!quote && pending.length) {
1009
+ const end = pending.every((body) => body.data) ? heredocEnd(command, index + 1, pending, expanded) : void 0;
1010
+ if (end !== void 0) index = end - 1;
1011
+ pending = [];
1012
+ }
1013
+ lineOutput = output.length;
1014
+ } else if (comment) {
1015
+ continue;
1016
+ } else if (quote === "'") {
1017
+ if (character === "'") quote = void 0;
1018
+ } else if (character === "\\") {
1019
+ output += command[index + 1] ?? "";
1020
+ if (command[index + 1] === "\n") lineOutput = output.length;
1021
+ index += 1;
1022
+ } else if (character === "$" && command[index + 1] === "(" && command[index + 2] !== "(") {
1023
+ outer.push({ quote, depth });
1024
+ quote = void 0;
1025
+ depth = 0;
1026
+ output += "(";
1027
+ index += 1;
1028
+ } else if (quote) {
1029
+ if (character === quote) quote = void 0;
1030
+ } else if (character === "'" || character === '"') {
1031
+ quote = character;
1032
+ } else if (character === "#" && /^$|[\s;|&(]/.test(command[index - 1] ?? "")) {
1033
+ comment = true;
1034
+ } else if (character === "(") {
1035
+ depth += 1;
1036
+ } else if (character === ")") {
1037
+ const context = depth === 0 ? outer.pop() : void 0;
1038
+ if (context) ({ quote, depth } = context);
1039
+ else depth = Math.max(0, depth - 1);
1040
+ } else if (character === "<" && command[index - 1] !== "<") {
1041
+ heredocOperator.lastIndex = index;
1042
+ const match = heredocOperator.exec(command);
1043
+ if (!match) continue;
1044
+ const lineStart = command.lastIndexOf("\n", index) + 1;
1045
+ const lineEnd = command.indexOf("\n", index);
1046
+ const line = command.slice(lineStart, lineEnd < 0 ? command.length : lineEnd);
1047
+ const delimiter = match[2] ?? match[3] ?? match[4] ?? "";
1048
+ const expands = match[4] !== void 0 && !match[0].includes("\\");
1049
+ const data = !nested && !expands && !command.includes("\r") && /^[A-Za-z_]\w*$/.test(delimiter) && (DATA_HEREDOC_LINE.test(line) || MESSAGE_HEREDOC_LINE.test(line)) && output.slice(0, lineOutput).split("\n").every(
1050
+ (prior) => DATA_PRELUDE_LINE.test(prior) || DATA_HEREDOC_LINE.test(prior) || MESSAGE_HEREDOC_LINE.test(prior) || MESSAGE_CLOSE_LINE.test(prior) || MESSAGE_PRELUDE_LINE.test(prior)
1051
+ );
1052
+ pending.push({ delimiter, stripTabs: !!match[1], expands, data });
1053
+ output += command.slice(index + 1, heredocOperator.lastIndex);
1054
+ index = heredocOperator.lastIndex - 1;
1055
+ }
1056
+ }
1057
+ return { text: output, expanded };
1058
+ }
1059
+ function heredocEnd(command, start, bodies, expanded) {
1060
+ let position = start;
1061
+ const texts = [];
1062
+ for (const { delimiter, stripTabs, expands } of bodies) {
1063
+ const bodyStart = position;
1064
+ let bodyEnd = position;
1065
+ let closed = false;
1066
+ while (!closed && position < command.length) {
1067
+ const end = command.indexOf("\n", position);
1068
+ const line = command.slice(position, end < 0 ? command.length : end).replace(/\r$/, "");
1069
+ const stripped = stripTabs ? line.replace(/^\t+/, "") : line;
1070
+ closed = stripped === delimiter;
1071
+ if (!closed && stripped.startsWith(delimiter)) return void 0;
1072
+ if (!closed) bodyEnd = end < 0 ? command.length : end;
1073
+ position = end < 0 ? command.length : end + 1;
1074
+ }
1075
+ if (!closed) return void 0;
1076
+ if (expands) texts.push(command.slice(bodyStart, bodyEnd));
1077
+ }
1078
+ expanded.push(...texts);
1079
+ return position;
1080
+ }
1081
+ var caseWord = /(case|esac)(?=$|[\s;&|)])/y;
1082
+ function commandPosition(command, index, start) {
1083
+ let before = index - 1;
1084
+ while (before >= start && /[ \t]/.test(command[before] ?? "")) before -= 1;
1085
+ return before < start || /[;&|(\n]/.test(command[before] ?? "");
1086
+ }
1087
+ function inArithmeticOrUntracked(command, start, index) {
1088
+ return inUntrackedContext(command, index) || command[start] === "(" || command[start - 2] === "(" || command.slice(start, index).includes("((");
1089
+ }
1090
+ function closingParenthesis(command, start, escape) {
1091
+ let depth = 1;
1092
+ let quote;
1093
+ const cases = [];
1094
+ const posix = escape === "\\";
1095
+ let wordStart = true;
1096
+ for (let index = start; index < command.length; index += 1) {
1097
+ const character = command[index] ?? "";
1098
+ const atWordStart = wordStart;
1099
+ wordStart = false;
1100
+ if (character === escape && quote !== "'") index += 1;
1101
+ else if (quote) {
1102
+ if (character === quote) quote = void 0;
1103
+ } else if (character === "'" || character === '"') quote = character;
1104
+ else if (!posix && atWordStart && character === "<" && command[index + 1] === "#") {
1105
+ const end = command.indexOf("#>", index + 2);
1106
+ if (end === -1) return void 0;
1107
+ index = end + 1;
1108
+ wordStart = true;
1109
+ } else if (character === "#" && atWordStart && (!posix || !inArithmeticOrUntracked(command, start, index))) {
1110
+ const end = command.indexOf("\n", index);
1111
+ if (end === -1) return void 0;
1112
+ index = end - 1;
1113
+ wordStart = true;
1114
+ } else if (posix && /[ce]/.test(character) && commandPosition(command, index, start)) {
1115
+ caseWord.lastIndex = index;
1116
+ const word = caseWord.exec(command)?.[1];
1117
+ if (word === "case") cases.push(depth);
1118
+ else if (word === "esac" && cases.at(-1) === depth) cases.pop();
1119
+ if (word) index += word.length - 1;
1120
+ } else if (character === "(") depth += 1;
1121
+ else if (character === ")") {
1122
+ if (cases.at(-1) === depth) continue;
1123
+ depth -= 1;
1124
+ if (depth === 0) return index;
1125
+ }
1126
+ if (!quote && /[ \t\n;&|(]/.test(character)) wordStart = true;
1127
+ }
1128
+ return void 0;
1129
+ }
295
1130
  function denyExploration(operation, target) {
296
1131
  const domain = /(?:^|[\\/])(?:docs?|spec|adr|requirements)(?:[\\/]|$)|\.md$/i.test(target) ? "documents" : "code";
297
1132
  return {
@@ -348,18 +1183,22 @@ function decodeGraphHookEvent(input) {
348
1183
  ...typeof session === "string" ? { session } : {}
349
1184
  };
350
1185
  }
351
- function failedGraphHook() {
352
- return {
353
- decision: "deny",
354
- state: "failed",
355
- message: "Graph protection failed: invalid pre-tool input. Repair hook configuration before direct exploration."
356
- };
1186
+ var FAILURE_MESSAGES = {
1187
+ configuration: "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.",
1188
+ input: "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.",
1189
+ state: "Graph protection failed: the hook could not read its local search state. Retry, and run qfai doctor if it repeats.",
1190
+ quote: "Graph protection failed: the hook could not match the quotes in the command. Retry without an unmatched quote, heredoc or here-string.",
1191
+ substitution: "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.",
1192
+ depth: "Graph protection failed: the command nests env, command or shell wrappers more than 16 levels deep. Run the inner command directly and retry."
1193
+ };
1194
+ function failedGraphHook(failure) {
1195
+ return { decision: "deny", state: "failed", message: FAILURE_MESSAGES[failure] };
357
1196
  }
358
1197
  function enforceGraphExploration(input, configuration) {
359
1198
  if (!object(configuration) || Object.keys(configuration).length !== 2 || configuration.kind !== "graph-enforcement" || configuration.denyExploration !== true)
360
- return failedGraphHook();
1199
+ return failedGraphHook("configuration");
361
1200
  const event = decodeGraphHookEvent(input);
362
- return event ? classifyGraphExploration(event) : failedGraphHook();
1201
+ return event ? classifyGraphExploration(event) : failedGraphHook("input");
363
1202
  }
364
1203
  function graphHookOutput(host, decision) {
365
1204
  if (decision.decision === "allow") return {};
@@ -378,15 +1217,15 @@ function object(value) {
378
1217
  // src/core/graph/fallbackState.ts
379
1218
  import { randomUUID as randomUUID7 } from "crypto";
380
1219
  import { rename as rename4, unlink as unlink3 } from "fs/promises";
381
- import path15 from "path";
1220
+ import path17 from "path";
382
1221
 
383
1222
  // src/core/graph/locks.ts
384
1223
  import { randomUUID as randomUUID2 } from "crypto";
385
1224
  import { unlink } from "fs/promises";
386
- import path5 from "path";
1225
+ import path6 from "path";
387
1226
 
388
1227
  // src/core/graph/layout.ts
389
- import path2 from "path";
1228
+ import path3 from "path";
390
1229
  function graphExecutionEnvironment() {
391
1230
  return { platform: process.platform, architecture: process.arch };
392
1231
  }
@@ -398,21 +1237,21 @@ function graphEnvironmentKey(environment = graphExecutionEnvironment()) {
398
1237
 
399
1238
  // src/core/graph/localFiles.ts
400
1239
  import { lstat as lstat3, mkdir as mkdir2, open as open2 } from "fs/promises";
401
- import path4 from "path";
1240
+ import path5 from "path";
402
1241
 
403
1242
  // src/core/graph/storage.ts
404
1243
  import { randomUUID } from "crypto";
405
1244
  import { lstat as lstat2, mkdir, readdir, rename, rm } from "fs/promises";
406
- import path3 from "path";
1245
+ import path4 from "path";
407
1246
  async function assertGraphStoragePath(root, directory) {
408
- const relative = path3.relative(root, directory);
409
- const parts = relative.split(path3.sep);
410
- if (path3.isAbsolute(relative) || parts[0] !== ".qfai" || parts[1] !== "tools" || parts.includes("..")) {
1247
+ const relative = path4.relative(root, directory);
1248
+ const parts = relative.split(path4.sep);
1249
+ if (path4.isAbsolute(relative) || parts[0] !== ".qfai" || parts[1] !== "tools" || parts.includes("..")) {
411
1250
  throw new Error("Graph storage must stay inside project-local .qfai/tools.");
412
1251
  }
413
1252
  for (let depth = 1; depth <= parts.length; depth += 1) {
414
1253
  try {
415
- const stats = await lstat2(path3.join(root, ...parts.slice(0, depth)));
1254
+ const stats = await lstat2(path4.join(root, ...parts.slice(0, depth)));
416
1255
  if (stats.isSymbolicLink() || !stats.isDirectory())
417
1256
  throw new Error(
418
1257
  "Graph storage has an unsafe path component; retain it and repair the project configuration."
@@ -434,7 +1273,7 @@ var GraphLocalStateError = class extends Error {
434
1273
  }
435
1274
  };
436
1275
  async function graphStateDirectory(root) {
437
- const directory = path4.join(root, ".qfai", "tools", "state", graphEnvironmentKey());
1276
+ const directory = path5.join(root, ".qfai", "tools", "state", graphEnvironmentKey());
438
1277
  await assertGraphStoragePath(root, directory);
439
1278
  await mkdir2(directory, { recursive: true });
440
1279
  await assertGraphStoragePath(root, directory);
@@ -478,7 +1317,7 @@ async function writeGraphLocalFile(file, value) {
478
1317
  // src/core/graph/locks.ts
479
1318
  async function withGraphLock(root, kind, action) {
480
1319
  const directory = await graphStateDirectory(root);
481
- const file = path5.join(directory, `${kind}.lock`);
1320
+ const file = path6.join(directory, `${kind}.lock`);
482
1321
  const owner = {
483
1322
  kind: "graph-lock",
484
1323
  pid: process.pid,
@@ -530,7 +1369,7 @@ async function releaseGraphLock(file, owner) {
530
1369
 
531
1370
  // src/core/graph/permissionRecords.ts
532
1371
  import { opendir, unlink as unlink2 } from "fs/promises";
533
- import path6 from "path";
1372
+ import path7 from "path";
534
1373
  async function readGraphSearchRecords(root, directory) {
535
1374
  const records = [];
536
1375
  const entries = await opendir(directory);
@@ -539,7 +1378,7 @@ async function readGraphSearchRecords(root, directory) {
539
1378
  if (records.length >= 128) throw fullGraphState();
540
1379
  const match = /^(.+)\.(pending|grant|draft)\.json$/.exec(entry.name);
541
1380
  if (!match || !GRAPH_UUID.test(match[1] ?? "")) throw invalidGraphState();
542
- const file = path6.join(directory, entry.name);
1381
+ const file = path7.join(directory, entry.name);
543
1382
  const text = await readGraphLocalFile(file);
544
1383
  if (text === void 0) throw invalidGraphState();
545
1384
  let input;
@@ -581,7 +1420,7 @@ function parseGraphSearchRecord(input, root) {
581
1420
  "expiresAt"
582
1421
  ];
583
1422
  if (value.kind === "grant") fields.push("reason");
584
- if (Object.keys(value).length !== fields.length || fields.some((field) => !Object.hasOwn(value, field)) || typeof value.id !== "string" || !GRAPH_UUID.test(value.id) || value.kind !== "pending" && value.kind !== "grant" || value.domain !== "code" && value.domain !== "documents" || !graphStateText(value.target, 4096) || !graphStateText(value.operation, 128) || !graphStateText(value.worktree, 4096) || value.worktree !== path6.resolve(root) || !graphStateText(value.session, 4096) || typeof value.createdAt !== "number" || typeof value.expiresAt !== "number" || !Number.isSafeInteger(value.createdAt) || value.createdAt < 0 || value.createdAt > Date.now() || !Number.isSafeInteger(value.expiresAt) || value.expiresAt !== value.createdAt + (value.kind === "pending" ? 6e5 : 6e4))
1423
+ if (Object.keys(value).length !== fields.length || fields.some((field) => !Object.hasOwn(value, field)) || typeof value.id !== "string" || !GRAPH_UUID.test(value.id) || value.kind !== "pending" && value.kind !== "grant" || value.domain !== "code" && value.domain !== "documents" || !graphStateText(value.target, 4096) || !graphStateText(value.operation, 128) || !graphStateText(value.worktree, 4096) || value.worktree !== path7.resolve(root) || !graphStateText(value.session, 4096) || typeof value.createdAt !== "number" || typeof value.expiresAt !== "number" || !Number.isSafeInteger(value.createdAt) || value.createdAt < 0 || value.createdAt > Date.now() || !Number.isSafeInteger(value.expiresAt) || value.expiresAt !== value.createdAt + (value.kind === "pending" ? 6e5 : 6e4))
585
1424
  return void 0;
586
1425
  const scope = {
587
1426
  id: value.id,
@@ -600,33 +1439,33 @@ function parseGraphSearchRecord(input, root) {
600
1439
  // src/core/graph/codePreparation.ts
601
1440
  import { randomUUID as randomUUID4 } from "crypto";
602
1441
  import { mkdir as mkdir5, rm as rm4 } from "fs/promises";
603
- import path11 from "path";
1442
+ import path13 from "path";
604
1443
 
605
1444
  // src/shared/assets.ts
606
1445
  import { existsSync } from "fs";
607
- import path7 from "path";
1446
+ import path8 from "path";
608
1447
  import { fileURLToPath } from "url";
609
1448
  var INIT_ASSETS_SENTINELS = [
610
- path7.join(".qfai", "assistant"),
611
- path7.join("root", "qfai.config.yaml")
1449
+ path8.join(".qfai", "assistant"),
1450
+ path8.join("root", "qfai.config.yaml")
612
1451
  ];
613
1452
 
614
1453
  // src/core/graph/process.ts
615
1454
  import { execFile } from "child_process";
616
1455
  import { access as access2, lstat as lstat4, realpath } from "fs/promises";
617
- import path8 from "path";
1456
+ import path9 from "path";
618
1457
  import { promisify } from "util";
619
1458
  var execute = promisify(execFile);
620
1459
 
621
1460
  // src/core/graph/reuse.ts
622
1461
  import os from "os";
623
- import path10 from "path";
1462
+ import path12 from "path";
624
1463
  import { randomUUID as randomUUID3 } from "crypto";
625
1464
  import {
626
1465
  cp,
627
1466
  lstat as lstat6,
628
1467
  mkdir as mkdir4,
629
- readFile as readFile2,
1468
+ readFile as readFile3,
630
1469
  readdir as readdir3,
631
1470
  realpath as realpath2,
632
1471
  rename as rename2,
@@ -635,24 +1474,40 @@ import {
635
1474
  } from "fs/promises";
636
1475
 
637
1476
  // src/core/graph/analysis.ts
638
- import path9 from "path";
1477
+ import path11 from "path";
639
1478
  import { copyFile, lstat as lstat5, mkdir as mkdir3, readdir as readdir2, rm as rm2 } from "fs/promises";
640
1479
 
1480
+ // src/core/config.ts
1481
+ import { access as access3, readFile as readFile2 } from "fs/promises";
1482
+ import path10 from "path";
1483
+ import { parse as parseYaml } from "yaml";
1484
+
1485
+ // src/shared/shippedWorkflowNames.ts
1486
+ var SHIPPED_WORKFLOW_NAMES = /* @__PURE__ */ new Set([
1487
+ "qfai-validate.yml",
1488
+ "qfai-tests.yml",
1489
+ "qfai-docs.yml"
1490
+ ]);
1491
+
1492
+ // src/core/config.ts
1493
+ var 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.`;
1494
+ var 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.`;
1495
+
641
1496
  // src/core/graph/documents.ts
642
- import { mkdir as mkdir7, readFile as readFile3, rm as rm6, writeFile as writeFile3 } from "fs/promises";
1497
+ import { mkdir as mkdir7, readFile as readFile4, rm as rm6, writeFile as writeFile3 } from "fs/promises";
643
1498
  import { randomUUID as randomUUID6 } from "crypto";
644
1499
 
645
1500
  // src/core/graph/documentReuse.ts
646
1501
  import { randomUUID as randomUUID5 } from "crypto";
647
1502
  import { cp as cp2, lstat as lstat7, mkdir as mkdir6, readdir as readdir4, rename as rename3, rm as rm5, writeFile as writeFile2 } from "fs/promises";
648
- import path12 from "path";
1503
+ import path14 from "path";
649
1504
 
650
1505
  // src/core/graph/documents.ts
651
- import path13 from "path";
1506
+ import path15 from "path";
652
1507
 
653
1508
  // src/core/graph/query.ts
654
- import { readFile as readFile4 } from "fs/promises";
655
- import path14 from "path";
1509
+ import { readFile as readFile5 } from "fs/promises";
1510
+ import path16 from "path";
656
1511
 
657
1512
  // src/core/graph/fallbackState.ts
658
1513
  async function classifyStoredGraphExploration(root, event) {
@@ -670,20 +1525,20 @@ async function classifyStoredGraphExploration(root, event) {
670
1525
  "Observed session and worktree are required.",
671
1526
  "Enable session and cwd in the host event, run qfai init, then retry the denied action from this project worktree."
672
1527
  );
673
- if (path15.resolve(event.cwd) !== path15.resolve(root))
1528
+ if (path17.resolve(event.cwd) !== path17.resolve(root))
674
1529
  return graphFallbackUnavailable(
675
1530
  decision,
676
1531
  "The observed worktree differs from this project worktree.",
677
1532
  "Run the denied action from this project worktree, or run qfai init in the intended worktree before retrying."
678
1533
  );
679
- if (event.workdir && path15.resolve(event.cwd, event.workdir) !== path15.resolve(root))
1534
+ if (event.workdir && path17.resolve(event.cwd, event.workdir) !== path17.resolve(root))
680
1535
  return graphFallbackUnavailable(
681
1536
  decision,
682
1537
  "The requested workdir differs from this project worktree.",
683
1538
  "Set workdir to this project worktree and retry the denied action."
684
1539
  );
685
1540
  if (!decision.target || !decision.operation || !decision.domain) return decision;
686
- const worktree = path15.resolve(root);
1541
+ const worktree = path17.resolve(root);
687
1542
  const session = event.session;
688
1543
  return withGraphLock(root, "state", async () => {
689
1544
  const directory = await graphStateDirectory(root);
@@ -717,12 +1572,48 @@ async function classifyStoredGraphExploration(root, event) {
717
1572
  createdAt,
718
1573
  expiresAt: createdAt + 6e5
719
1574
  };
720
- await writeGraphLocalFile(path15.join(directory, `${pending.id}.pending.json`), pending);
1575
+ await writeGraphLocalFile(path17.join(directory, `${pending.id}.pending.json`), pending);
721
1576
  return { ...classified, message: `${classified.message} Observed attempt: ${pending.id}.` };
722
1577
  });
723
1578
  }
724
1579
 
1580
+ // src/core/graph/sessionWorktree.ts
1581
+ import { lstat as lstat8, realpath as realpath3 } from "fs/promises";
1582
+ import path18 from "path";
1583
+ async function resolveSessionWorktree(root, cwd) {
1584
+ if (!cwd) return root;
1585
+ const base = path18.resolve(root);
1586
+ let current;
1587
+ try {
1588
+ current = await realpath3(path18.resolve(cwd));
1589
+ } catch {
1590
+ return root;
1591
+ }
1592
+ if (!inside(base, current)) return root;
1593
+ while (path18.relative(base, current) !== "") {
1594
+ if (await exists(path18.join(current, ".git"))) return current;
1595
+ const parent = path18.dirname(current);
1596
+ if (parent === current) break;
1597
+ current = parent;
1598
+ }
1599
+ return root;
1600
+ }
1601
+ function inside(base, candidate) {
1602
+ const relative = path18.relative(base, candidate);
1603
+ return relative !== ".." && !relative.startsWith(`..${path18.sep}`) && !path18.isAbsolute(relative);
1604
+ }
1605
+ async function exists(file) {
1606
+ try {
1607
+ await lstat8(file);
1608
+ return true;
1609
+ } catch (cause) {
1610
+ if (isEnoent(cause)) return false;
1611
+ throw cause;
1612
+ }
1613
+ }
1614
+
725
1615
  // src/cli/graphHook.ts
1616
+ var enforcement = [".qfai", "tools", "graph-enforcement.json"];
726
1617
  function hostName(value) {
727
1618
  return value === "claude" || value === "codex" || value === "copilot" || value === "vscode";
728
1619
  }
@@ -750,22 +1641,32 @@ async function runInstalledGraphHook(root, args, io = {
750
1641
  io.fail();
751
1642
  return;
752
1643
  }
753
- let decision = failedGraphHook();
1644
+ let decision = failedGraphHook("configuration");
1645
+ const event = decodeGraphHookEvent(input);
1646
+ let project = root;
1647
+ let uninitialised = false;
754
1648
  try {
755
- const components = [".qfai", "tools", "graph-enforcement.json"];
756
- if (!await findUnsafeHostFileComponent(root, components)) {
757
- const text = await readPinnedRegularFile(path16.join(root, ...components), 4096);
1649
+ project = await resolveSessionWorktree(root, event?.cwd);
1650
+ uninitialised = project !== root && !await hasEnforcement(project);
1651
+ const configured = uninitialised ? root : project;
1652
+ if (!await findUnsafeHostFileComponent(configured, enforcement)) {
1653
+ const text = await readPinnedRegularFile(path19.join(configured, ...enforcement), 4096);
758
1654
  if (text !== null) decision = enforceGraphExploration(input, JSON.parse(text));
759
1655
  }
760
1656
  } catch {
761
1657
  }
762
- if (decision.decision === "deny" && decision.state === "configured") {
763
- const event = decodeGraphHookEvent(input);
1658
+ if (decision.decision === "deny" && decision.state === "configured" && uninitialised)
1659
+ decision = graphFallbackUnavailable(
1660
+ decision,
1661
+ `The session worktree ${project} has no graph protection; this hook belongs to ${root}.`,
1662
+ `Run qfai init in ${project}, then retry the denied action.`
1663
+ );
1664
+ else if (decision.decision === "deny" && decision.state === "configured") {
764
1665
  if (event) {
765
1666
  try {
766
- decision = await classifyStoredGraphExploration(root, event);
1667
+ decision = await classifyStoredGraphExploration(project, event);
767
1668
  } catch (cause) {
768
- decision = failedGraphHook();
1669
+ decision = failedGraphHook("state");
769
1670
  if (cause instanceof GraphLocalStateError)
770
1671
  decision.message = `${cause.message} ${cause.recovery}`;
771
1672
  }
@@ -774,10 +1675,20 @@ async function runInstalledGraphHook(root, args, io = {
774
1675
  if (decision.decision === "deny")
775
1676
  io.output(JSON.stringify(graphHookOutput(host, decision)) + "\n");
776
1677
  if (decision.state === "failed") {
777
- io.error("Graph protection failed. Repair the project hook and enforcement configuration.\n");
1678
+ io.error(`${decision.message}
1679
+ `);
778
1680
  io.fail();
779
1681
  }
780
1682
  }
1683
+ async function hasEnforcement(project) {
1684
+ try {
1685
+ await lstat9(path19.join(project, ...enforcement));
1686
+ return true;
1687
+ } catch (cause) {
1688
+ if (isEnoent(cause)) return false;
1689
+ throw cause;
1690
+ }
1691
+ }
781
1692
  function wireHost(input) {
782
1693
  if (typeof input !== "object" || input === null || Array.isArray(input)) return void 0;
783
1694
  const value = input;