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
@@ -34,7 +34,8 @@ __export(graphHook_exports, {
34
34
  });
35
35
  module.exports = __toCommonJS(graphHook_exports);
36
36
  var import_node_fs3 = require("fs");
37
- var import_node_path16 = __toESM(require("path"), 1);
37
+ var import_promises16 = require("fs/promises");
38
+ var import_node_path19 = __toESM(require("path"), 1);
38
39
 
39
40
  // src/core/init/fsGuards.ts
40
41
  var import_node_fs = require("fs");
@@ -141,74 +142,332 @@ async function findUnsafeHostFileComponent(destRoot, segments) {
141
142
  }
142
143
 
143
144
  // src/core/graph/hooks.ts
145
+ var import_node_path2 = __toESM(require("path"), 1);
144
146
  function classifyGraphExploration(event, authorize = (decision) => decision) {
145
147
  if (event.tool === "write_stdin") return outsideBoundary();
146
148
  if (["rg", "grep", "grep_search", "search_files", "file_search"].includes(event.tool.toLowerCase())) {
147
149
  return authorize(denyExploration(event.tool, event.path ?? "."));
148
150
  }
149
151
  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";
150
- const commands = shellPipelines(event.command ?? "", shell);
151
- if (!commands) return failedGraphHook();
152
- return classifyCommands(commands, authorize) ?? {
152
+ const directory = event.cwd ? import_node_path2.default.resolve(event.cwd, event.workdir ?? ".") : void 0;
153
+ return classifyShellText(
154
+ event.command ?? "",
155
+ { authorize, shell, ...directory ? { directory } : {} },
156
+ 0,
157
+ false,
158
+ "observed"
159
+ ) ?? {
153
160
  decision: "allow",
154
161
  state: "configured",
155
162
  message: "No direct exploration was classified."
156
163
  };
157
164
  }
158
- function classifyCommands(commands, authorize, depth = 0) {
159
- const changesDirectory = commands.some(changesGraphDirectory);
160
- const scopedAuthorization = changesDirectory ? (decision) => graphFallbackUnavailable(
161
- decision,
162
- "The command changes its working directory.",
163
- "Run a single search from this project worktree, then retry the denied action."
164
- ) : authorize;
165
+ function classifyShellText(text, scope, depth, redefinedOutside, start, substitution = false) {
166
+ if (depth > 16) return failedGraphHook("depth");
167
+ const source = scope.shell === "powershell" ? withoutPowerShellComments(powershellHereStrings(powerShellLines(text))) : text;
168
+ const commands = source === void 0 ? void 0 : shellPipelines(source, scope.shell, depth > 0);
169
+ if (source === void 0 || !commands) {
170
+ return substitution ? void 0 : failedGraphHook("quote");
171
+ }
172
+ const bodies = substitutionBodies(source, scope.shell, depth > 0);
173
+ if (!bodies) return failedGraphHook("substitution");
174
+ return classifyCommands(
175
+ commands,
176
+ scope,
177
+ depth,
178
+ redefinedOutside,
179
+ start,
180
+ bodies.map(
181
+ (body) => (location, redefines) => classifyShellText(body, scope, depth + 1, redefines, location, true)
182
+ )
183
+ );
184
+ }
185
+ function powershellHereStrings(text) {
186
+ let output = "";
187
+ let quote;
188
+ for (let index = 0; index < text.length; index += 1) {
189
+ const character = text[index] ?? "";
190
+ if (character === "`" && quote !== "'") {
191
+ output += character + (text[index + 1] ?? "");
192
+ index += 1;
193
+ continue;
194
+ }
195
+ if (quote) {
196
+ if (character === quote) quote = void 0;
197
+ output += character;
198
+ continue;
199
+ }
200
+ hereString.lastIndex = index;
201
+ const match = character === "@" ? hereString.exec(text) : null;
202
+ if (match) {
203
+ output += match[1] === "'" ? "''" : `"${(match[2] ?? "").replace(/"/g, "")}"`;
204
+ index = hereString.lastIndex - 1;
205
+ continue;
206
+ }
207
+ if (character === "'" || character === '"') quote = character;
208
+ output += character;
209
+ }
210
+ return output;
211
+ }
212
+ var hereString = /@(['"])[ \t]*\r?\n([\s\S]*?)\r?\n\1@/y;
213
+ function classifyCommands(commands, scope, depth, redefinedOutside, start, substitutions = []) {
214
+ const redefined = redefinedOutside || commands.some((command) => redefinesCommands(command.words));
215
+ const stays = commands.every((command) => {
216
+ const operand = directoryOperand(command.words);
217
+ if (operand === void 0) return true;
218
+ return !redefined && operand !== null && start === "observed" && scope.directory !== void 0 && import_node_path2.default.resolve(scope.directory, operand) === scope.directory;
219
+ });
220
+ for (const classify of substitutions) {
221
+ const decision = classify(stays ? start : "unknown", redefined);
222
+ if (decision?.decision === "deny") return decision;
223
+ }
224
+ let location = start;
165
225
  let boundary;
166
226
  let allowed;
167
- for (const words of commands) {
168
- const decision = classifyCommand(words, scopedAuthorization, depth);
227
+ let openCases = 0;
228
+ for (const [index, command] of commands.entries()) {
229
+ const words = openCases > 0 && command.words[0]?.endsWith(")") ? command.words.slice(1) : command.words;
230
+ if (words[0] === "case") openCases += 1;
231
+ else if (words[0] === "esac") openCases = Math.max(0, openCases - 1);
232
+ if (typeof location === "object" && index > 0 && command.join !== "&&" && command.join !== "|")
233
+ location = "unknown";
234
+ const operand = directoryOperand(words);
235
+ if (operand !== void 0) {
236
+ location = redefined ? "unknown" : movedLocation(location, operand, command, commands[index + 1], scope);
237
+ }
238
+ const upstream = words[0] === "{" && !groupClosesBare(commands, index) ? void 0 : command.upstream;
239
+ const decision = classifyCommand(words, { ...scope, location, redefined }, depth, upstream);
169
240
  if (decision?.decision === "deny") return decision;
170
241
  if (decision?.state === "outside-boundary") boundary = decision;
171
242
  else if (decision) allowed = decision;
172
243
  }
173
244
  return boundary ?? allowed;
174
245
  }
175
- function changesGraphDirectory(words) {
246
+ function redefinesCommands(words) {
247
+ const body = arithmeticForBody(words);
248
+ if (body) return redefinesCommands(body);
249
+ let offset = 0;
250
+ for (; ; ) {
251
+ const redirection = redirectionLength(words[offset]);
252
+ if (redirection) offset += redirection;
253
+ else if (words[offset] === "{") offset += 1;
254
+ else if (["builtin", "command", "env"].includes(words[offset]?.toLowerCase() ?? "")) {
255
+ offset += 1;
256
+ while (words[offset]?.startsWith("-")) {
257
+ offset += /^-[uCS]$|^--(?:unset|chdir|split-string)$/.test(words[offset] ?? "") ? 2 : 1;
258
+ }
259
+ } else break;
260
+ }
261
+ const first = words[offset] ?? "";
262
+ 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") || [
263
+ "time",
264
+ "!",
265
+ "if",
266
+ "then",
267
+ "do",
268
+ "else",
269
+ "elif",
270
+ "while",
271
+ "until",
272
+ "case",
273
+ "coproc",
274
+ "read",
275
+ "mapfile",
276
+ "readarray",
277
+ "getopts"
278
+ ].includes(first) || [
279
+ "function",
280
+ "alias",
281
+ "export",
282
+ "declare",
283
+ "typeset",
284
+ "readonly",
285
+ "set",
286
+ "setx",
287
+ "set-alias",
288
+ "new-alias",
289
+ "sal",
290
+ "nal",
291
+ "set-item",
292
+ "si",
293
+ "set-variable",
294
+ "sv",
295
+ "filter",
296
+ "new-item",
297
+ "ni",
298
+ "iex",
299
+ "invoke-expression",
300
+ "eval",
301
+ "source",
302
+ ".",
303
+ "hash"
304
+ ].includes(words[offset] === "." ? "." : commandName(words.slice(offset)) ?? "");
305
+ }
306
+ var redirectionSource = String.raw`(?:\d*|&|\{[A-Za-z_][A-Za-z0-9_]*\})`;
307
+ var redirectionStart = new RegExp(String.raw`^${redirectionSource}(?:<|>)`);
308
+ var detachedRedirection = new RegExp(String.raw`^${redirectionSource}(?:<>|>{1,2}|<{1,3})[&|]?$`);
309
+ function redirectionLength(word) {
310
+ if (!word || !redirectionStart.test(word)) return 0;
311
+ return detachedRedirection.test(word) ? 2 : 1;
312
+ }
313
+ function groupClosesBare(commands, index) {
314
+ let depth = 0;
315
+ for (const { words } of commands.slice(index)) {
316
+ const opened = words.findIndex((word) => word !== "{");
317
+ depth += opened < 0 ? words.length : opened;
318
+ if (words[0]?.startsWith("}")) {
319
+ depth -= 1;
320
+ if (depth <= 0) return words.length === 1 && words[0] === "}";
321
+ }
322
+ }
323
+ return false;
324
+ }
325
+ function directoryOperand(words) {
176
326
  let offset = 0;
177
327
  while (offset < words.length) {
178
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? "")) {
328
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? "") || words[offset] === "{" || COMPOUND_KEYWORDS.includes(words[offset] ?? "")) {
179
329
  offset += 1;
180
330
  continue;
181
331
  }
182
332
  if (!["command", "builtin", "env"].includes(words[offset]?.toLowerCase() ?? "")) break;
183
333
  offset += 1;
184
- if (words[offset] === "-v" || words[offset] === "-V") return false;
334
+ if (words[offset] === "-v" || words[offset] === "-V") return void 0;
185
335
  while (words[offset]?.startsWith("-")) offset += 1;
186
336
  }
187
- return ["cd", "chdir", "pushd", "popd", "set-location", "sl"].includes(
188
- words[offset]?.toLowerCase() ?? ""
189
- );
337
+ const name = words[offset]?.toLowerCase() ?? "";
338
+ if (!["cd", "chdir", "pushd", "popd", "set-location", "sl"].includes(name)) return void 0;
339
+ const operands = words.slice(offset + 1);
340
+ const target = operands[0];
341
+ 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;
342
+ }
343
+ function movedLocation(location, operand, command, next, scope) {
344
+ if (location === "unknown" || operand === null || !scope.directory) return "unknown";
345
+ const from = location === "observed" ? scope.directory : location.directory;
346
+ const directory = import_node_path2.default.resolve(from, operand);
347
+ if (location === "observed" && directory === scope.directory) return "observed";
348
+ if (outside(scope.directory, directory)) return "unknown";
349
+ if (command.join === "|" || command.join === "||" || next !== void 0 && next.join !== "&&")
350
+ return "unknown";
351
+ if (scope.shell === "posix" && !import_node_path2.default.isAbsolute(operand) && !operand.startsWith(".") && process.env.CDPATH)
352
+ return "unknown";
353
+ return { directory };
354
+ }
355
+ function outside(root, target) {
356
+ const relative = import_node_path2.default.relative(root, target);
357
+ return relative === ".." || relative.startsWith(`..${import_node_path2.default.sep}`) || import_node_path2.default.isAbsolute(relative);
358
+ }
359
+ function authorizeAt(context, decision) {
360
+ const { location, directory, authorize } = context;
361
+ if (location === "observed") return authorize(decision);
362
+ if (location === "unknown" || !directory)
363
+ return graphFallbackUnavailable(
364
+ decision,
365
+ "The command changes its working directory.",
366
+ "Run a single search from this project worktree, then retry the denied action."
367
+ );
368
+ if (!decision.exceptionEligible || decision.target === void 0 || !decision.operation)
369
+ return authorize(decision);
370
+ if (decision.target.split(/[\\/]/).includes(".."))
371
+ return graphFallbackUnavailable(
372
+ decision,
373
+ "The search target has a .. segment after a directory change.",
374
+ "Run a single search from this project worktree, then retry the denied action."
375
+ );
376
+ const target = import_node_path2.default.resolve(location.directory, decision.target);
377
+ if (outside(directory, target))
378
+ return graphFallbackUnavailable(
379
+ decision,
380
+ "The search target resolves outside this project worktree.",
381
+ "Run a single search with one explicit project-relative target, then retry the denied action."
382
+ );
383
+ const relative = import_node_path2.default.relative(directory, target).split(import_node_path2.default.sep).join("/") || ".";
384
+ return authorize({ ...denyExploration(decision.operation, relative), exceptionEligible: true });
190
385
  }
191
- function classifyCommand(words, authorize, depth = 0) {
192
- if (depth > 16) return failedGraphHook();
386
+ var COMPOUND_KEYWORDS = [
387
+ "if",
388
+ "then",
389
+ "elif",
390
+ "else",
391
+ "while",
392
+ "until",
393
+ "do",
394
+ "!",
395
+ "time"
396
+ ];
397
+ function arithmeticForBody(words) {
398
+ let depth = 0;
399
+ for (const [index, word] of words.entries()) {
400
+ for (let offset = 0; offset < word.length; offset += 1) {
401
+ if (word[offset] === "(") depth += 1;
402
+ else if (word[offset] === ")") depth -= 1;
403
+ if (depth > -2) continue;
404
+ if (word[offset - 1] !== ")") return void 0;
405
+ const rest = word.slice(offset + 1);
406
+ const body = rest === "" ? words.slice(index + 1) : [rest, ...words.slice(index + 1)];
407
+ return body[0] === "{" || body[0] === "do" ? body : void 0;
408
+ }
409
+ }
410
+ return void 0;
411
+ }
412
+ function classifyCommand(words, context, depth, upstream) {
413
+ const { redefined } = context;
414
+ if (depth > 16) return failedGraphHook("depth");
193
415
  let offset = 0;
194
- while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? "")) offset += 1;
195
- if (offset > 0) return classifyCommand(words.slice(offset), authorize, depth + 1);
196
- const operation = words[0]?.split(/[\\/]/).at(-1)?.replace(/\.exe$/i, "").toLowerCase();
416
+ while (offset < words.length) {
417
+ const redirection = redirectionLength(words[offset]);
418
+ if (redirection) offset += redirection;
419
+ else if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset] ?? "")) offset += 1;
420
+ else break;
421
+ }
422
+ if (offset > 0) {
423
+ return classifyCommand(words.slice(offset), context, depth + 1);
424
+ }
425
+ const operation = commandName(words);
426
+ if (COMPOUND_KEYWORDS.includes(words[0] ?? "")) {
427
+ const skip = words[0] === "time" && words[1] === "-p" ? 2 : 1;
428
+ return classifyCommand(words.slice(skip), context, depth + 1);
429
+ }
430
+ if (words[0] === "fi" || words[0] === "done") return void 0;
431
+ const body = arithmeticForBody(words);
432
+ if (body) return classifyCommand(body, context, depth + 1);
433
+ if (operation === "{") {
434
+ return classifyCommand(words.slice(1), context, depth + 1, upstream);
435
+ }
436
+ if (operation === "case") {
437
+ const subject = words.indexOf("in");
438
+ const arm = words.findIndex((word, index) => index > subject && word.endsWith(")"));
439
+ return arm < 0 ? void 0 : classifyCommand(words.slice(arm + 1), context, depth + 1);
440
+ }
441
+ if (operation === "}" || operation === "esac") return void 0;
197
442
  if (operation === "env" || operation === "command" || operation === "builtin") {
198
443
  let offset2 = 1;
199
- while (words[offset2]?.startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset2] ?? "")) {
200
- offset2 += 1;
444
+ while (offset2 < words.length) {
445
+ const redirection = redirectionLength(words[offset2]);
446
+ if (redirection) offset2 += redirection;
447
+ else if (words[offset2]?.startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[offset2] ?? ""))
448
+ offset2 += 1;
449
+ else break;
201
450
  }
202
- return classifyCommand(words.slice(offset2), authorize, depth + 1);
451
+ return classifyCommand(words.slice(offset2), context, depth + 1);
203
452
  }
204
453
  if (["bash", "sh", "zsh", "pwsh", "powershell", "cmd"].includes(operation ?? "")) {
205
454
  const switchIndex = words.findIndex((word) => /^(?:-[a-z]*c|\/c|-command)$/i.test(word));
206
455
  const inner = switchIndex >= 0 ? words[switchIndex + 1] : void 0;
207
456
  if (!inner) return outsideBoundary();
208
457
  const shell = operation === "pwsh" || operation === "powershell" ? "powershell" : operation === "cmd" ? "cmd" : "posix";
209
- const commands = shellPipelines(inner, shell);
210
- return commands ? classifyCommands(commands, authorize, depth + 1) : failedGraphHook();
458
+ return classifyShellText(
459
+ inner,
460
+ {
461
+ authorize: context.authorize,
462
+ shell,
463
+ ...context.directory ? { directory: context.directory } : {}
464
+ },
465
+ depth + 1,
466
+ redefined,
467
+ context.location
468
+ );
211
469
  }
470
+ if (!redefined && pipeFilter(words) && printsText(upstream)) return void 0;
212
471
  if (operation === "rg" || operation === "grep" || operation === "findstr") {
213
472
  let offset2 = 1;
214
473
  while (/^(?:-[RrinlIHsvwxcFoq]+|--(?:hidden|line-number|ignore-case|fixed-strings|recursive)|\/[SIMOPVNLR]+)$/i.test(
@@ -219,7 +478,10 @@ function classifyCommand(words, authorize, depth = 0) {
219
478
  const positional = words.slice(offset2);
220
479
  const eligible = positional.length > 0 && positional.length <= 2 && !positional.some((word) => word.startsWith("-") || /[$%`<>]/.test(word));
221
480
  const target = eligible ? positional[1] ?? "." : JSON.stringify(positional);
222
- return authorize({ ...denyExploration(operation, target), exceptionEligible: eligible });
481
+ return authorizeAt(context, {
482
+ ...denyExploration(operation, target),
483
+ exceptionEligible: eligible
484
+ });
223
485
  }
224
486
  let gitCommand = 1;
225
487
  if (operation === "git") {
@@ -232,7 +494,7 @@ function classifyCommand(words, authorize, depth = 0) {
232
494
  const paths = words.indexOf("--");
233
495
  const targets = paths >= 0 ? words.slice(paths + 1) : [];
234
496
  const eligible = gitCommand === 1 && targets.length <= 1 && (paths >= 0 || words.length === 3) && !targets.some((word) => /[$%`<>]/.test(word));
235
- return authorize({
497
+ return authorizeAt(context, {
236
498
  ...denyExploration(
237
499
  "git grep",
238
500
  eligible ? targets[0] ?? "." : JSON.stringify(words.slice(1))
@@ -241,15 +503,15 @@ function classifyCommand(words, authorize, depth = 0) {
241
503
  });
242
504
  }
243
505
  if (operation === "select-string") {
244
- const path17 = words.findIndex((word) => /^-(?:literalpath|path)$/i.test(word));
506
+ const path20 = words.findIndex((word) => /^-(?:literalpath|path)$/i.test(word));
245
507
  const targets = [];
246
- for (let offset2 = path17 + 1; path17 >= 0 && offset2 < words.length; offset2 += 1) {
508
+ for (let offset2 = path20 + 1; path20 >= 0 && offset2 < words.length; offset2 += 1) {
247
509
  const word = words[offset2];
248
510
  if (word === void 0 || word.startsWith("-")) break;
249
511
  targets.push(word);
250
512
  }
251
513
  const eligible = targets.length === 1 && !targets.some((word) => /[,$%`<>]/.test(word));
252
- return authorize({
514
+ return authorizeAt(context, {
253
515
  ...denyExploration("Select-String", eligible ? targets[0] ?? "." : JSON.stringify(targets)),
254
516
  exceptionEligible: eligible
255
517
  });
@@ -280,6 +542,145 @@ function classifyCommand(words, authorize, depth = 0) {
280
542
  }
281
543
  return outsideBoundary();
282
544
  }
545
+ function commandName(words) {
546
+ return words[0]?.split(/[\\/]/).at(-1)?.replace(/\.exe$/i, "").toLowerCase();
547
+ }
548
+ function unparsedWord(word) {
549
+ return /\$(?!$)|[`<>]|%[^%\s]+%/.test(word);
550
+ }
551
+ function printsText(command) {
552
+ if (!command || command.words.some(
553
+ (word) => /[(){}@]/.test(word) || unparsedWord(word) && !/^\d*>(?:&\d|\/dev\/null)$/.test(word)
554
+ ))
555
+ return false;
556
+ const name = /[\\/=]/.test(command.words[0] ?? "") ? "" : commandName(command.words) ?? "";
557
+ const args = command.words.slice(1);
558
+ if (name === "git") {
559
+ return gitTextCommands.has(args[0] ?? "") && !args.some(
560
+ (word) => word === "--no-index" || /^(?:\/|[A-Za-z]:|\\|~|:\/)|(?:^|[\\/:])\.\.(?:[\\/]|$)/.test(word)
561
+ );
562
+ }
563
+ if (["echo", "printf", "write-output"].includes(name))
564
+ return !args.some((word) => /[*?[!]/.test(word));
565
+ if (name === "pnpm" || name === "npm") return packageTextCommands.has(args[0] ?? "");
566
+ if (name === "corepack") {
567
+ return ["pnpm", "npm"].includes(args[0] ?? "") && packageTextCommands.has(args[1] ?? "");
568
+ }
569
+ if (name === "sort" || name === "uniq") {
570
+ const switches = name === "sort" ? /^-[rnufbdhMV]+$/ : /^-[cdiu]+$/;
571
+ return args.every((word) => switches.test(word)) && printsText(command.upstream);
572
+ }
573
+ return pipeFilter(command.words) && printsText(command.upstream);
574
+ }
575
+ var gitTextCommands = /* @__PURE__ */ new Set([
576
+ "status",
577
+ "ls-files",
578
+ "ls-tree",
579
+ "log",
580
+ "diff",
581
+ "branch",
582
+ "remote",
583
+ "rev-list",
584
+ "rev-parse",
585
+ "shortlog",
586
+ "worktree"
587
+ ]);
588
+ var packageTextCommands = /* @__PURE__ */ new Set([
589
+ "test",
590
+ "t",
591
+ "lint",
592
+ "build",
593
+ "typecheck",
594
+ "check-types",
595
+ "ls",
596
+ "list",
597
+ "why",
598
+ "outdated",
599
+ "audit",
600
+ "install",
601
+ "i",
602
+ "ci",
603
+ "view",
604
+ "info"
605
+ ]);
606
+ var grepSwitches = /^-[ivncowxEFGPqsHhIyzZLlbUa]+$/;
607
+ var rgSwitches = /^-[ivncowxFsSqaUNHlLIP]+$/;
608
+ var longSwitches = /* @__PURE__ */ new Set([
609
+ "--ignore-case",
610
+ "--invert-match",
611
+ "--line-number",
612
+ "--count",
613
+ "--only-matching",
614
+ "--word-regexp",
615
+ "--line-regexp",
616
+ "--extended-regexp",
617
+ "--fixed-strings",
618
+ "--perl-regexp",
619
+ "--quiet",
620
+ "--silent",
621
+ "--no-filename",
622
+ "--with-filename",
623
+ "--smart-case",
624
+ "--case-sensitive"
625
+ ]);
626
+ var valueOptions = /^(?:-[emABC]|--(?:regexp|max-count|context|after-context|before-context))$/;
627
+ var attachedValueOptions = /^(?:-e.+|-[mABC]\d+|--(?:regexp|max-count|context|after-context|before-context|color|colour)=.+)$/;
628
+ function pipeFilter(words) {
629
+ if (/[\\/=]/.test(words[0] ?? "")) return false;
630
+ const name = commandName(words);
631
+ const args = words.slice(1);
632
+ if (args.some((word) => unparsedWord(word) || /[*?[\]{}()~@!]/.test(word))) return false;
633
+ if (name === "findstr") return findstrFilter(args);
634
+ if (name === "select-string") return selectStringFilter(args);
635
+ if (name !== "grep" && name !== "rg") return false;
636
+ let patternGiven = false;
637
+ const operands = [];
638
+ for (let index = 0; index < args.length; index += 1) {
639
+ const word = args[index] ?? "";
640
+ if (word === "--") {
641
+ operands.push(...args.slice(index + 1));
642
+ break;
643
+ }
644
+ if (!word.startsWith("-") || word === "-") operands.push(word);
645
+ else if (valueOptions.test(word)) {
646
+ if (word === "-e" || word === "--regexp") patternGiven = true;
647
+ index += 1;
648
+ if (index >= args.length) return false;
649
+ } else if (attachedValueOptions.test(word)) {
650
+ if (/^(?:-e|--regexp=)/.test(word)) patternGiven = true;
651
+ } else if (!(name === "grep" ? grepSwitches : rgSwitches).test(word) && !longSwitches.has(word))
652
+ return false;
653
+ }
654
+ const files = patternGiven ? operands : operands.slice(1);
655
+ return (patternGiven || operands.length > 0) && files.every((word) => word === "-");
656
+ }
657
+ function findstrFilter(args) {
658
+ let patternGiven = false;
659
+ const operands = [];
660
+ for (const word of args) {
661
+ if (/^\/c:./i.test(word)) patternGiven = true;
662
+ else if (word.startsWith("/")) {
663
+ if (!/^\/[ivnxbelrmop]+$/i.test(word)) return false;
664
+ } else if (word.startsWith("-")) return false;
665
+ else operands.push(word);
666
+ }
667
+ return operands.length === (patternGiven ? 0 : 1);
668
+ }
669
+ function selectStringFilter(args) {
670
+ let patternGiven = false;
671
+ let positional = 0;
672
+ for (let index = 0; index < args.length; index += 1) {
673
+ const word = args[index] ?? "";
674
+ if (!word.startsWith("-")) positional += 1;
675
+ else if (/^-(?:pattern|context|encoding)$/i.test(word)) {
676
+ if (/^-pattern$/i.test(word)) patternGiven = true;
677
+ index += 1;
678
+ if (index >= args.length) return false;
679
+ } else if (!/^-(?:simplematch|casesensitive|notmatch|allmatches|list|quiet|raw|noemphasis)$/i.test(word))
680
+ return false;
681
+ }
682
+ return positional === (patternGiven ? 0 : 1);
683
+ }
283
684
  function outsideBoundary() {
284
685
  return {
285
686
  decision: "allow",
@@ -287,20 +688,158 @@ function outsideBoundary() {
287
688
  message: "Search inside scripts, aliases or continuing input is not verified by this pre-tool boundary."
288
689
  };
289
690
  }
290
- function shellPipelines(command, shell) {
691
+ function resolveAlias(words, shell) {
692
+ return shell === "powershell" && words[0]?.toLowerCase() === "sls" ? ["Select-String", ...words.slice(1)] : words;
693
+ }
694
+ var WORD_BREAK = /[ \t\n;&|()]/;
695
+ function startsComment(command, index, shell) {
696
+ if (shell !== "posix") return false;
697
+ const previous = command[index - 1];
698
+ return (previous === void 0 || WORD_BREAK.test(previous)) && !inUntrackedContext(command, index);
699
+ }
700
+ function inUntrackedContext(command, index) {
701
+ return /`|\$\{|\$\[|\$'|\(\(|[?*+@!]\(/.test(command.slice(0, index));
702
+ }
703
+ function powerShellLines(command) {
704
+ return command.replace(/\r(?!\n)/g, "\n");
705
+ }
706
+ var POWERSHELL_BREAK = /[ \t\n;|&]/;
707
+ var POWERSHELL_UNTRACKED = /@["']|\$\(|[\u2018-\u201e]/;
708
+ function withoutPowerShellComments(command) {
709
+ let output = "";
710
+ let quote;
711
+ let wordStarted = false;
712
+ for (let index = 0; index < command.length; index += 1) {
713
+ const character = command[index] ?? "";
714
+ if (character === "`" && quote !== "'") {
715
+ output += character + (command[index + 1] ?? "");
716
+ index += 1;
717
+ wordStarted = true;
718
+ continue;
719
+ }
720
+ if (quote) {
721
+ output += character;
722
+ if (character === quote) quote = void 0;
723
+ continue;
724
+ }
725
+ const tracked = () => !inUntrackedContext(command, index) && !POWERSHELL_UNTRACKED.test(command.slice(0, index));
726
+ if (character === "<" && command[index + 1] === "#") {
727
+ const end = command.indexOf("#>", index + 2);
728
+ if (end === -1) return void 0;
729
+ output += !wordStarted && tracked() ? " " : `;${command.slice(index + 2, end)};`;
730
+ index = end + 1;
731
+ wordStarted = false;
732
+ continue;
733
+ }
734
+ if (character === "#" && !wordStarted && tracked()) {
735
+ const end = command.indexOf("\n", index);
736
+ if (end === -1) break;
737
+ index = end - 1;
738
+ continue;
739
+ }
740
+ output += character;
741
+ if (character === "'" || character === '"') quote = character;
742
+ wordStarted = !POWERSHELL_BREAK.test(character);
743
+ }
744
+ return output;
745
+ }
746
+ var DATA_FILE = String.raw`(?!/dev/|/proc/)[\w./-]+`;
747
+ var DATA_OPERAND = String.raw`[ \t]+(?:-[A-Za-z]+|>>?[ \t]*${DATA_FILE}|>[ \t]*/dev/null|${DATA_FILE})`;
748
+ var DATA_HEREDOC_LINE = new RegExp(
749
+ String.raw`^[ \t]*(?:cat|tee)(?:${DATA_OPERAND})*[ \t]*<<-?[ \t]*(?:(['"])[A-Za-z_]\w*\1|\\[A-Za-z_]\w*)(?:${DATA_OPERAND})*[ \t]*$`
750
+ );
751
+ var DATA_PRELUDE_LINE = new RegExp(
752
+ String.raw`^[ \t]*(?:mkdir[ \t]+-p(?:[ \t]+${DATA_FILE})+[ \t]*)?$`
753
+ );
754
+ function shellPipelines(command, shell, nested = false) {
291
755
  const commands = [];
292
756
  let words = [];
757
+ let upstream;
758
+ let join;
293
759
  let word = "";
294
760
  let quote;
761
+ let afterRedirect = "";
762
+ const heredocs = [];
763
+ const skipped = [];
764
+ let quotedWord = false;
295
765
  const flushWord = () => {
296
766
  if (word.length) words.push(word);
297
767
  word = "";
768
+ quotedWord = false;
769
+ };
770
+ const readHeredocOperator = (index) => {
771
+ if (word.length && !/^\d+$/.test(word)) flushWord();
772
+ let cursor = index + 2;
773
+ const stripTabs = command[cursor] === "-";
774
+ if (stripTabs) cursor += 1;
775
+ words.push(`${word}<<${stripTabs ? "-" : ""}`);
776
+ word = "";
777
+ while (command[cursor] === " " || command[cursor] === " ") cursor += 1;
778
+ let delimiter = "";
779
+ let read = false;
780
+ let delimiterQuote;
781
+ while (cursor < command.length) {
782
+ const character = command[cursor] ?? "";
783
+ if (delimiterQuote) {
784
+ if (character === delimiterQuote) delimiterQuote = void 0;
785
+ else delimiter += character;
786
+ } else if (character === '"' || character === "'") {
787
+ delimiterQuote = character;
788
+ } else if (character === "\\" && cursor + 1 < command.length) {
789
+ delimiter += command[cursor + 1] ?? "";
790
+ cursor += 1;
791
+ } else if (/[\s;|&<>()]/.test(character)) {
792
+ break;
793
+ } else {
794
+ delimiter += character;
795
+ }
796
+ read = true;
797
+ cursor += 1;
798
+ }
799
+ if (delimiterQuote) {
800
+ quote = delimiterQuote;
801
+ return command.length;
802
+ }
803
+ if (!read) return cursor;
804
+ words.push(delimiter);
805
+ const lineStart = command.lastIndexOf("\n", index) + 1;
806
+ const lineEnd = command.indexOf("\n", index);
807
+ let earlier = "";
808
+ let from = 0;
809
+ for (const [start, end] of skipped) {
810
+ earlier += command.slice(from, start);
811
+ from = end;
812
+ }
813
+ earlier += command.slice(from, lineStart);
814
+ const line = command.slice(lineStart, lineEnd < 0 ? command.length : lineEnd);
815
+ 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));
816
+ heredocs.push({ delimiter, stripTabs, data });
817
+ return cursor;
818
+ };
819
+ const skipHeredocs = (index) => {
820
+ let position = index + 1;
821
+ const pending = heredocs.splice(0);
822
+ if (!pending.every((heredoc) => heredoc.data)) return index;
823
+ for (const { delimiter, stripTabs } of pending) {
824
+ let closed = false;
825
+ while (position < command.length && !closed) {
826
+ const end = command.indexOf("\n", position);
827
+ const line = command.slice(position, end < 0 ? command.length : end);
828
+ position = end < 0 ? command.length : end + 1;
829
+ closed = (stripTabs ? line.replace(/^\t+/, "") : line) === delimiter;
830
+ }
831
+ if (!closed) return index;
832
+ }
833
+ skipped.push([index + 1, position]);
834
+ return position - 1;
298
835
  };
299
836
  for (let index = 0; index < command.length; index += 1) {
300
837
  const character = command[index];
301
838
  if (character === void 0) continue;
302
839
  const next = command[index + 1];
303
840
  const escaped = next !== void 0 && (shell === "posix" && character === "\\" && (!quote || quote === '"' && ['"', "\\", "$", "`", "\n"].includes(next)) || shell === "powershell" && character === "`" && quote !== "'" || shell === "cmd" && character === "^" && !quote);
841
+ const redirectBefore = afterRedirect;
842
+ afterRedirect = "";
304
843
  if (escaped) {
305
844
  if (next !== "\n") word += next;
306
845
  index += 1;
@@ -309,23 +848,319 @@ function shellPipelines(command, shell) {
309
848
  if (quote) {
310
849
  if (character === quote) quote = void 0;
311
850
  else word += character;
851
+ } else if (character === "#" && !word.length && !quotedWord && startsComment(command, index, shell)) {
852
+ const end = command.indexOf("\n", index);
853
+ index = (end === -1 ? command.length : end) - 1;
312
854
  } else if (character === '"' || character === "'") {
313
855
  quote = character;
856
+ quotedWord = true;
857
+ } else if ((character === "&" || character === "|") && (character === "&" ? redirectBefore !== "" && /[\d-]/.test(next ?? "") : redirectBefore === ">" && shell === "posix")) {
858
+ word += character;
859
+ } else if (shell === "posix" && character === "&" && next === ">") {
860
+ flushWord();
861
+ word = character;
862
+ } else if (character === "\n" && !words.length && !word.length && upstream) {
863
+ index = skipHeredocs(index);
864
+ continue;
314
865
  } else if (character === "|" || character === ";" || character === "&" || character === "\n") {
315
866
  flushWord();
316
- if (words.length) commands.push(words);
867
+ const stage = words.length ? {
868
+ words: resolveAlias(words, shell),
869
+ ...upstream ? { upstream } : {},
870
+ ...join ? { join } : {}
871
+ } : void 0;
872
+ if (stage) commands.push(stage);
873
+ const pipe = character === "|" && next !== "|" && stage !== void 0;
874
+ const operator = (character === "|" || character === "&") && next === character ? character === "|" ? "||" : "&&" : character === "|" || character === "&" || character === ";" ? character : "\n";
875
+ if ((character === "|" || character === "&") && next === character) index += 1;
876
+ else if (pipe && shell === "posix" && next === "&") index += 1;
877
+ if (stage || join === void 0 || operator !== "\n") join = operator;
878
+ upstream = pipe ? stage : void 0;
317
879
  words = [];
880
+ if (character === "\n") index = skipHeredocs(index);
318
881
  } else if (/\s/.test(character)) {
319
882
  flushWord();
883
+ } else if (shell === "posix" && character === "<" && next === "<" && command[index + 2] !== "<" && command[index - 1] !== "<") {
884
+ index = readHeredocOperator(index) - 1;
320
885
  } else {
886
+ if ((character === ">" || character === "<") && !/^(?:\d*|\{[A-Za-z_][A-Za-z0-9_]*\})$/.test(word) && !/[<>]$/.test(word) && word !== "&") {
887
+ flushWord();
888
+ }
321
889
  word += character;
890
+ afterRedirect = character === ">" || character === "<" ? character : "";
322
891
  }
323
892
  }
324
893
  if (quote) return void 0;
325
894
  flushWord();
326
- if (words.length) commands.push(words);
895
+ if (words.length) {
896
+ commands.push({
897
+ words: resolveAlias(words, shell),
898
+ ...upstream ? { upstream } : {},
899
+ ...join ? { join } : {}
900
+ });
901
+ }
327
902
  return commands;
328
903
  }
904
+ function substitutionBodies(text, shell, nested = false) {
905
+ if (shell === "cmd") return [];
906
+ const { text: command, expanded } = shell === "posix" ? heredocData(text, nested) : { text, expanded: [] };
907
+ const escape = shell === "posix" ? "\\" : "`";
908
+ const bodies = [];
909
+ let quote;
910
+ let wordStart = true;
911
+ for (let index = 0; index < command.length; index += 1) {
912
+ const character = command[index];
913
+ const next = command[index + 1];
914
+ const atWordStart = wordStart;
915
+ wordStart = false;
916
+ if (character === escape && quote !== "'") {
917
+ index += 1;
918
+ continue;
919
+ }
920
+ if (quote === "'") {
921
+ if (character === "'") quote = void 0;
922
+ continue;
923
+ }
924
+ if (!quote && atWordStart && character === "#" && shell === "posix" && !inUntrackedContext(command, index)) {
925
+ const end = command.indexOf("\n", index);
926
+ if (end === -1) break;
927
+ index = end;
928
+ wordStart = true;
929
+ continue;
930
+ }
931
+ if (!quote && character !== void 0 && WORD_BREAK.test(character)) {
932
+ wordStart = true;
933
+ if (character !== "(") continue;
934
+ }
935
+ if (character === "'" && !quote) {
936
+ quote = "'";
937
+ continue;
938
+ }
939
+ if (character === '"') {
940
+ quote = quote ? void 0 : '"';
941
+ continue;
942
+ }
943
+ const opens = next === "(" && (character === "$" || !quote && shell === "powershell" && character === "@" || !quote && shell === "posix" && (character === "<" || character === ">"));
944
+ if (opens) {
945
+ const end = closingParenthesis(command, index + 2, escape);
946
+ if (end === void 0) return void 0;
947
+ if (!(character === "$" && command[index + 2] === "(")) {
948
+ bodies.push(command.slice(index + 2, end));
949
+ }
950
+ index = end;
951
+ } else if (!quote && character === "(" && // The first `(` of a POSIX `((` arithmetic command opens no subshell; the scan moves
952
+ // on to the second, whose body the comment reader then knows is arithmetic.
953
+ !(shell === "posix" && command[index + 1] === "(") && // A POSIX subshell starts a command, and zsh `=(...)` starts a word; any other
954
+ // `(`, such as an array's in `name=(...)`, is data, scanned on.
955
+ (shell === "powershell" || commandPosition(command, index, 0) || command[index - 1] === "=" && /^$|[\s;&|(]/.test(command[index - 2] ?? ""))) {
956
+ const end = closingParenthesis(command, index + 1, escape);
957
+ if (end === void 0) return void 0;
958
+ bodies.push(command.slice(index + 1, end));
959
+ index = end;
960
+ } else if (!quote && shell === "powershell" && character === "{" && command[index - 1] !== "@") {
961
+ const end = closingBrace(command, index + 1);
962
+ if (end === void 0) continue;
963
+ bodies.push(command.slice(index + 1, end));
964
+ index = end;
965
+ } else if (shell === "posix" && character === "`") {
966
+ const end = closingBacktick(command, index + 1);
967
+ if (end === void 0) return void 0;
968
+ bodies.push(command.slice(index + 1, end).replace(/\\([`\\$])/g, "$1"));
969
+ index = end;
970
+ }
971
+ }
972
+ for (const body of expanded) {
973
+ const nested2 = expandedSubstitutions(body);
974
+ if (!nested2) return void 0;
975
+ bodies.push(...nested2);
976
+ }
977
+ return bodies;
978
+ }
979
+ function closingBrace(command, start) {
980
+ let depth = 1;
981
+ let quote;
982
+ for (let index = start; index < command.length; index += 1) {
983
+ const character = command[index];
984
+ if (character === "`" && quote !== "'") index += 1;
985
+ else if (quote) {
986
+ if (character === quote) quote = void 0;
987
+ } else if (character === "'" || character === '"') quote = character;
988
+ else if (character === "{") depth += 1;
989
+ else if (character === "}") {
990
+ depth -= 1;
991
+ if (depth === 0) return index;
992
+ }
993
+ }
994
+ return void 0;
995
+ }
996
+ function closingBacktick(command, start) {
997
+ let end = start;
998
+ while (end < command.length && command[end] !== "`") end += command[end] === "\\" ? 2 : 1;
999
+ return end < command.length ? end : void 0;
1000
+ }
1001
+ function expandedSubstitutions(body) {
1002
+ const bodies = [];
1003
+ for (let index = 0; index < body.length; index += 1) {
1004
+ const character = body[index];
1005
+ if (character === "\\") {
1006
+ index += 1;
1007
+ } else if (character === "$" && body[index + 1] === "(") {
1008
+ const end = closingParenthesis(body, index + 2, "\\");
1009
+ if (end === void 0) return void 0;
1010
+ if (body[index + 2] !== "(") bodies.push(body.slice(index + 2, end));
1011
+ index = end;
1012
+ } else if (character === "`") {
1013
+ const end = closingBacktick(body, index + 1);
1014
+ if (end === void 0) return void 0;
1015
+ bodies.push(body.slice(index + 1, end).replace(/\\([`\\$])/g, "$1"));
1016
+ index = end;
1017
+ }
1018
+ }
1019
+ return bodies;
1020
+ }
1021
+ var heredocOperator = /<<(?!<)(-?)[ \t]*(?:'([^'\n]*)'|"([^"\n]*)"|\\?([^\s;|&<>()'"]+))/y;
1022
+ var MESSAGE_WORD = String.raw`[ \t]+[\w./=:@-]+`;
1023
+ var MESSAGE_HEREDOC_LINE = new RegExp(
1024
+ 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]*$`
1025
+ );
1026
+ var MESSAGE_CLOSE_LINE = new RegExp(String.raw`^[ \t]*\)"(?:${MESSAGE_WORD})*[ \t]*$`);
1027
+ var MESSAGE_PRELUDE_LINE = new RegExp(String.raw`^[ \t]*git[ \t]+add(?:${MESSAGE_WORD})*[ \t]*$`);
1028
+ function heredocData(command, nested = false) {
1029
+ let output = "";
1030
+ let quote;
1031
+ let comment = false;
1032
+ let depth = 0;
1033
+ const outer = [];
1034
+ const expanded = [];
1035
+ let pending = [];
1036
+ let lineOutput = 0;
1037
+ for (let index = 0; index < command.length; index += 1) {
1038
+ const character = command[index] ?? "";
1039
+ output += character;
1040
+ if (character === "\n") {
1041
+ comment = false;
1042
+ if (!quote && pending.length) {
1043
+ const end = pending.every((body) => body.data) ? heredocEnd(command, index + 1, pending, expanded) : void 0;
1044
+ if (end !== void 0) index = end - 1;
1045
+ pending = [];
1046
+ }
1047
+ lineOutput = output.length;
1048
+ } else if (comment) {
1049
+ continue;
1050
+ } else if (quote === "'") {
1051
+ if (character === "'") quote = void 0;
1052
+ } else if (character === "\\") {
1053
+ output += command[index + 1] ?? "";
1054
+ if (command[index + 1] === "\n") lineOutput = output.length;
1055
+ index += 1;
1056
+ } else if (character === "$" && command[index + 1] === "(" && command[index + 2] !== "(") {
1057
+ outer.push({ quote, depth });
1058
+ quote = void 0;
1059
+ depth = 0;
1060
+ output += "(";
1061
+ index += 1;
1062
+ } else if (quote) {
1063
+ if (character === quote) quote = void 0;
1064
+ } else if (character === "'" || character === '"') {
1065
+ quote = character;
1066
+ } else if (character === "#" && /^$|[\s;|&(]/.test(command[index - 1] ?? "")) {
1067
+ comment = true;
1068
+ } else if (character === "(") {
1069
+ depth += 1;
1070
+ } else if (character === ")") {
1071
+ const context = depth === 0 ? outer.pop() : void 0;
1072
+ if (context) ({ quote, depth } = context);
1073
+ else depth = Math.max(0, depth - 1);
1074
+ } else if (character === "<" && command[index - 1] !== "<") {
1075
+ heredocOperator.lastIndex = index;
1076
+ const match = heredocOperator.exec(command);
1077
+ if (!match) continue;
1078
+ const lineStart = command.lastIndexOf("\n", index) + 1;
1079
+ const lineEnd = command.indexOf("\n", index);
1080
+ const line = command.slice(lineStart, lineEnd < 0 ? command.length : lineEnd);
1081
+ const delimiter = match[2] ?? match[3] ?? match[4] ?? "";
1082
+ const expands = match[4] !== void 0 && !match[0].includes("\\");
1083
+ 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(
1084
+ (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)
1085
+ );
1086
+ pending.push({ delimiter, stripTabs: !!match[1], expands, data });
1087
+ output += command.slice(index + 1, heredocOperator.lastIndex);
1088
+ index = heredocOperator.lastIndex - 1;
1089
+ }
1090
+ }
1091
+ return { text: output, expanded };
1092
+ }
1093
+ function heredocEnd(command, start, bodies, expanded) {
1094
+ let position = start;
1095
+ const texts = [];
1096
+ for (const { delimiter, stripTabs, expands } of bodies) {
1097
+ const bodyStart = position;
1098
+ let bodyEnd = position;
1099
+ let closed = false;
1100
+ while (!closed && position < command.length) {
1101
+ const end = command.indexOf("\n", position);
1102
+ const line = command.slice(position, end < 0 ? command.length : end).replace(/\r$/, "");
1103
+ const stripped = stripTabs ? line.replace(/^\t+/, "") : line;
1104
+ closed = stripped === delimiter;
1105
+ if (!closed && stripped.startsWith(delimiter)) return void 0;
1106
+ if (!closed) bodyEnd = end < 0 ? command.length : end;
1107
+ position = end < 0 ? command.length : end + 1;
1108
+ }
1109
+ if (!closed) return void 0;
1110
+ if (expands) texts.push(command.slice(bodyStart, bodyEnd));
1111
+ }
1112
+ expanded.push(...texts);
1113
+ return position;
1114
+ }
1115
+ var caseWord = /(case|esac)(?=$|[\s;&|)])/y;
1116
+ function commandPosition(command, index, start) {
1117
+ let before = index - 1;
1118
+ while (before >= start && /[ \t]/.test(command[before] ?? "")) before -= 1;
1119
+ return before < start || /[;&|(\n]/.test(command[before] ?? "");
1120
+ }
1121
+ function inArithmeticOrUntracked(command, start, index) {
1122
+ return inUntrackedContext(command, index) || command[start] === "(" || command[start - 2] === "(" || command.slice(start, index).includes("((");
1123
+ }
1124
+ function closingParenthesis(command, start, escape) {
1125
+ let depth = 1;
1126
+ let quote;
1127
+ const cases = [];
1128
+ const posix = escape === "\\";
1129
+ let wordStart = true;
1130
+ for (let index = start; index < command.length; index += 1) {
1131
+ const character = command[index] ?? "";
1132
+ const atWordStart = wordStart;
1133
+ wordStart = false;
1134
+ if (character === escape && quote !== "'") index += 1;
1135
+ else if (quote) {
1136
+ if (character === quote) quote = void 0;
1137
+ } else if (character === "'" || character === '"') quote = character;
1138
+ else if (!posix && atWordStart && character === "<" && command[index + 1] === "#") {
1139
+ const end = command.indexOf("#>", index + 2);
1140
+ if (end === -1) return void 0;
1141
+ index = end + 1;
1142
+ wordStart = true;
1143
+ } else if (character === "#" && atWordStart && (!posix || !inArithmeticOrUntracked(command, start, index))) {
1144
+ const end = command.indexOf("\n", index);
1145
+ if (end === -1) return void 0;
1146
+ index = end - 1;
1147
+ wordStart = true;
1148
+ } else if (posix && /[ce]/.test(character) && commandPosition(command, index, start)) {
1149
+ caseWord.lastIndex = index;
1150
+ const word = caseWord.exec(command)?.[1];
1151
+ if (word === "case") cases.push(depth);
1152
+ else if (word === "esac" && cases.at(-1) === depth) cases.pop();
1153
+ if (word) index += word.length - 1;
1154
+ } else if (character === "(") depth += 1;
1155
+ else if (character === ")") {
1156
+ if (cases.at(-1) === depth) continue;
1157
+ depth -= 1;
1158
+ if (depth === 0) return index;
1159
+ }
1160
+ if (!quote && /[ \t\n;&|(]/.test(character)) wordStart = true;
1161
+ }
1162
+ return void 0;
1163
+ }
329
1164
  function denyExploration(operation, target) {
330
1165
  const domain = /(?:^|[\\/])(?:docs?|spec|adr|requirements)(?:[\\/]|$)|\.md$/i.test(target) ? "documents" : "code";
331
1166
  return {
@@ -382,18 +1217,22 @@ function decodeGraphHookEvent(input) {
382
1217
  ...typeof session === "string" ? { session } : {}
383
1218
  };
384
1219
  }
385
- function failedGraphHook() {
386
- return {
387
- decision: "deny",
388
- state: "failed",
389
- message: "Graph protection failed: invalid pre-tool input. Repair hook configuration before direct exploration."
390
- };
1220
+ var FAILURE_MESSAGES = {
1221
+ 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.",
1222
+ 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.",
1223
+ state: "Graph protection failed: the hook could not read its local search state. Retry, and run qfai doctor if it repeats.",
1224
+ quote: "Graph protection failed: the hook could not match the quotes in the command. Retry without an unmatched quote, heredoc or here-string.",
1225
+ 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.",
1226
+ depth: "Graph protection failed: the command nests env, command or shell wrappers more than 16 levels deep. Run the inner command directly and retry."
1227
+ };
1228
+ function failedGraphHook(failure) {
1229
+ return { decision: "deny", state: "failed", message: FAILURE_MESSAGES[failure] };
391
1230
  }
392
1231
  function enforceGraphExploration(input, configuration) {
393
1232
  if (!object(configuration) || Object.keys(configuration).length !== 2 || configuration.kind !== "graph-enforcement" || configuration.denyExploration !== true)
394
- return failedGraphHook();
1233
+ return failedGraphHook("configuration");
395
1234
  const event = decodeGraphHookEvent(input);
396
- return event ? classifyGraphExploration(event) : failedGraphHook();
1235
+ return event ? classifyGraphExploration(event) : failedGraphHook("input");
397
1236
  }
398
1237
  function graphHookOutput(host, decision) {
399
1238
  if (decision.decision === "allow") return {};
@@ -411,16 +1250,16 @@ function object(value) {
411
1250
 
412
1251
  // src/core/graph/fallbackState.ts
413
1252
  var import_node_crypto7 = require("crypto");
414
- var import_promises13 = require("fs/promises");
415
- var import_node_path15 = __toESM(require("path"), 1);
1253
+ var import_promises14 = require("fs/promises");
1254
+ var import_node_path17 = __toESM(require("path"), 1);
416
1255
 
417
1256
  // src/core/graph/locks.ts
418
1257
  var import_node_crypto2 = require("crypto");
419
1258
  var import_promises4 = require("fs/promises");
420
- var import_node_path5 = __toESM(require("path"), 1);
1259
+ var import_node_path6 = __toESM(require("path"), 1);
421
1260
 
422
1261
  // src/core/graph/layout.ts
423
- var import_node_path2 = __toESM(require("path"), 1);
1262
+ var import_node_path3 = __toESM(require("path"), 1);
424
1263
  function graphExecutionEnvironment() {
425
1264
  return { platform: process.platform, architecture: process.arch };
426
1265
  }
@@ -432,21 +1271,21 @@ function graphEnvironmentKey(environment = graphExecutionEnvironment()) {
432
1271
 
433
1272
  // src/core/graph/localFiles.ts
434
1273
  var import_promises3 = require("fs/promises");
435
- var import_node_path4 = __toESM(require("path"), 1);
1274
+ var import_node_path5 = __toESM(require("path"), 1);
436
1275
 
437
1276
  // src/core/graph/storage.ts
438
1277
  var import_node_crypto = require("crypto");
439
1278
  var import_promises2 = require("fs/promises");
440
- var import_node_path3 = __toESM(require("path"), 1);
1279
+ var import_node_path4 = __toESM(require("path"), 1);
441
1280
  async function assertGraphStoragePath(root, directory) {
442
- const relative = import_node_path3.default.relative(root, directory);
443
- const parts = relative.split(import_node_path3.default.sep);
444
- if (import_node_path3.default.isAbsolute(relative) || parts[0] !== ".qfai" || parts[1] !== "tools" || parts.includes("..")) {
1281
+ const relative = import_node_path4.default.relative(root, directory);
1282
+ const parts = relative.split(import_node_path4.default.sep);
1283
+ if (import_node_path4.default.isAbsolute(relative) || parts[0] !== ".qfai" || parts[1] !== "tools" || parts.includes("..")) {
445
1284
  throw new Error("Graph storage must stay inside project-local .qfai/tools.");
446
1285
  }
447
1286
  for (let depth = 1; depth <= parts.length; depth += 1) {
448
1287
  try {
449
- const stats = await (0, import_promises2.lstat)(import_node_path3.default.join(root, ...parts.slice(0, depth)));
1288
+ const stats = await (0, import_promises2.lstat)(import_node_path4.default.join(root, ...parts.slice(0, depth)));
450
1289
  if (stats.isSymbolicLink() || !stats.isDirectory())
451
1290
  throw new Error(
452
1291
  "Graph storage has an unsafe path component; retain it and repair the project configuration."
@@ -468,7 +1307,7 @@ var GraphLocalStateError = class extends Error {
468
1307
  }
469
1308
  };
470
1309
  async function graphStateDirectory(root) {
471
- const directory = import_node_path4.default.join(root, ".qfai", "tools", "state", graphEnvironmentKey());
1310
+ const directory = import_node_path5.default.join(root, ".qfai", "tools", "state", graphEnvironmentKey());
472
1311
  await assertGraphStoragePath(root, directory);
473
1312
  await (0, import_promises3.mkdir)(directory, { recursive: true });
474
1313
  await assertGraphStoragePath(root, directory);
@@ -512,7 +1351,7 @@ async function writeGraphLocalFile(file, value) {
512
1351
  // src/core/graph/locks.ts
513
1352
  async function withGraphLock(root, kind, action) {
514
1353
  const directory = await graphStateDirectory(root);
515
- const file = import_node_path5.default.join(directory, `${kind}.lock`);
1354
+ const file = import_node_path6.default.join(directory, `${kind}.lock`);
516
1355
  const owner = {
517
1356
  kind: "graph-lock",
518
1357
  pid: process.pid,
@@ -564,7 +1403,7 @@ async function releaseGraphLock(file, owner) {
564
1403
 
565
1404
  // src/core/graph/permissionRecords.ts
566
1405
  var import_promises5 = require("fs/promises");
567
- var import_node_path6 = __toESM(require("path"), 1);
1406
+ var import_node_path7 = __toESM(require("path"), 1);
568
1407
  async function readGraphSearchRecords(root, directory) {
569
1408
  const records = [];
570
1409
  const entries = await (0, import_promises5.opendir)(directory);
@@ -573,7 +1412,7 @@ async function readGraphSearchRecords(root, directory) {
573
1412
  if (records.length >= 128) throw fullGraphState();
574
1413
  const match = /^(.+)\.(pending|grant|draft)\.json$/.exec(entry.name);
575
1414
  if (!match || !GRAPH_UUID.test(match[1] ?? "")) throw invalidGraphState();
576
- const file = import_node_path6.default.join(directory, entry.name);
1415
+ const file = import_node_path7.default.join(directory, entry.name);
577
1416
  const text = await readGraphLocalFile(file);
578
1417
  if (text === void 0) throw invalidGraphState();
579
1418
  let input;
@@ -615,7 +1454,7 @@ function parseGraphSearchRecord(input, root) {
615
1454
  "expiresAt"
616
1455
  ];
617
1456
  if (value.kind === "grant") fields.push("reason");
618
- 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 !== import_node_path6.default.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))
1457
+ 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 !== import_node_path7.default.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))
619
1458
  return void 0;
620
1459
  const scope = {
621
1460
  id: value.id,
@@ -633,50 +1472,66 @@ function parseGraphSearchRecord(input, root) {
633
1472
 
634
1473
  // src/core/graph/codePreparation.ts
635
1474
  var import_node_crypto4 = require("crypto");
636
- var import_promises9 = require("fs/promises");
637
- var import_node_path11 = __toESM(require("path"), 1);
1475
+ var import_promises10 = require("fs/promises");
1476
+ var import_node_path13 = __toESM(require("path"), 1);
638
1477
 
639
1478
  // src/shared/assets.ts
640
1479
  var import_node_fs2 = require("fs");
641
- var import_node_path7 = __toESM(require("path"), 1);
1480
+ var import_node_path8 = __toESM(require("path"), 1);
642
1481
  var import_node_url = require("url");
643
1482
  var INIT_ASSETS_SENTINELS = [
644
- import_node_path7.default.join(".qfai", "assistant"),
645
- import_node_path7.default.join("root", "qfai.config.yaml")
1483
+ import_node_path8.default.join(".qfai", "assistant"),
1484
+ import_node_path8.default.join("root", "qfai.config.yaml")
646
1485
  ];
647
1486
 
648
1487
  // src/core/graph/process.ts
649
1488
  var import_node_child_process = require("child_process");
650
1489
  var import_promises6 = require("fs/promises");
651
- var import_node_path8 = __toESM(require("path"), 1);
1490
+ var import_node_path9 = __toESM(require("path"), 1);
652
1491
  var import_node_util = require("util");
653
1492
  var execute = (0, import_node_util.promisify)(import_node_child_process.execFile);
654
1493
 
655
1494
  // src/core/graph/reuse.ts
656
1495
  var import_node_os = __toESM(require("os"), 1);
657
- var import_node_path10 = __toESM(require("path"), 1);
1496
+ var import_node_path12 = __toESM(require("path"), 1);
658
1497
  var import_node_crypto3 = require("crypto");
659
- var import_promises8 = require("fs/promises");
1498
+ var import_promises9 = require("fs/promises");
660
1499
 
661
1500
  // src/core/graph/analysis.ts
662
- var import_node_path9 = __toESM(require("path"), 1);
1501
+ var import_node_path11 = __toESM(require("path"), 1);
1502
+ var import_promises8 = require("fs/promises");
1503
+
1504
+ // src/core/config.ts
663
1505
  var import_promises7 = require("fs/promises");
1506
+ var import_node_path10 = __toESM(require("path"), 1);
1507
+ var import_yaml = require("yaml");
1508
+
1509
+ // src/shared/shippedWorkflowNames.ts
1510
+ var SHIPPED_WORKFLOW_NAMES = /* @__PURE__ */ new Set([
1511
+ "qfai-validate.yml",
1512
+ "qfai-tests.yml",
1513
+ "qfai-docs.yml"
1514
+ ]);
1515
+
1516
+ // src/core/config.ts
1517
+ 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.`;
1518
+ 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.`;
664
1519
 
665
1520
  // src/core/graph/documents.ts
666
- var import_promises11 = require("fs/promises");
1521
+ var import_promises12 = require("fs/promises");
667
1522
  var import_node_crypto6 = require("crypto");
668
1523
 
669
1524
  // src/core/graph/documentReuse.ts
670
1525
  var import_node_crypto5 = require("crypto");
671
- var import_promises10 = require("fs/promises");
672
- var import_node_path12 = __toESM(require("path"), 1);
1526
+ var import_promises11 = require("fs/promises");
1527
+ var import_node_path14 = __toESM(require("path"), 1);
673
1528
 
674
1529
  // src/core/graph/documents.ts
675
- var import_node_path13 = __toESM(require("path"), 1);
1530
+ var import_node_path15 = __toESM(require("path"), 1);
676
1531
 
677
1532
  // src/core/graph/query.ts
678
- var import_promises12 = require("fs/promises");
679
- var import_node_path14 = __toESM(require("path"), 1);
1533
+ var import_promises13 = require("fs/promises");
1534
+ var import_node_path16 = __toESM(require("path"), 1);
680
1535
 
681
1536
  // src/core/graph/fallbackState.ts
682
1537
  async function classifyStoredGraphExploration(root, event) {
@@ -694,20 +1549,20 @@ async function classifyStoredGraphExploration(root, event) {
694
1549
  "Observed session and worktree are required.",
695
1550
  "Enable session and cwd in the host event, run qfai init, then retry the denied action from this project worktree."
696
1551
  );
697
- if (import_node_path15.default.resolve(event.cwd) !== import_node_path15.default.resolve(root))
1552
+ if (import_node_path17.default.resolve(event.cwd) !== import_node_path17.default.resolve(root))
698
1553
  return graphFallbackUnavailable(
699
1554
  decision,
700
1555
  "The observed worktree differs from this project worktree.",
701
1556
  "Run the denied action from this project worktree, or run qfai init in the intended worktree before retrying."
702
1557
  );
703
- if (event.workdir && import_node_path15.default.resolve(event.cwd, event.workdir) !== import_node_path15.default.resolve(root))
1558
+ if (event.workdir && import_node_path17.default.resolve(event.cwd, event.workdir) !== import_node_path17.default.resolve(root))
704
1559
  return graphFallbackUnavailable(
705
1560
  decision,
706
1561
  "The requested workdir differs from this project worktree.",
707
1562
  "Set workdir to this project worktree and retry the denied action."
708
1563
  );
709
1564
  if (!decision.target || !decision.operation || !decision.domain) return decision;
710
- const worktree = import_node_path15.default.resolve(root);
1565
+ const worktree = import_node_path17.default.resolve(root);
711
1566
  const session = event.session;
712
1567
  return withGraphLock(root, "state", async () => {
713
1568
  const directory = await graphStateDirectory(root);
@@ -741,12 +1596,48 @@ async function classifyStoredGraphExploration(root, event) {
741
1596
  createdAt,
742
1597
  expiresAt: createdAt + 6e5
743
1598
  };
744
- await writeGraphLocalFile(import_node_path15.default.join(directory, `${pending.id}.pending.json`), pending);
1599
+ await writeGraphLocalFile(import_node_path17.default.join(directory, `${pending.id}.pending.json`), pending);
745
1600
  return { ...classified, message: `${classified.message} Observed attempt: ${pending.id}.` };
746
1601
  });
747
1602
  }
748
1603
 
1604
+ // src/core/graph/sessionWorktree.ts
1605
+ var import_promises15 = require("fs/promises");
1606
+ var import_node_path18 = __toESM(require("path"), 1);
1607
+ async function resolveSessionWorktree(root, cwd) {
1608
+ if (!cwd) return root;
1609
+ const base = import_node_path18.default.resolve(root);
1610
+ let current;
1611
+ try {
1612
+ current = await (0, import_promises15.realpath)(import_node_path18.default.resolve(cwd));
1613
+ } catch {
1614
+ return root;
1615
+ }
1616
+ if (!inside(base, current)) return root;
1617
+ while (import_node_path18.default.relative(base, current) !== "") {
1618
+ if (await exists(import_node_path18.default.join(current, ".git"))) return current;
1619
+ const parent = import_node_path18.default.dirname(current);
1620
+ if (parent === current) break;
1621
+ current = parent;
1622
+ }
1623
+ return root;
1624
+ }
1625
+ function inside(base, candidate) {
1626
+ const relative = import_node_path18.default.relative(base, candidate);
1627
+ return relative !== ".." && !relative.startsWith(`..${import_node_path18.default.sep}`) && !import_node_path18.default.isAbsolute(relative);
1628
+ }
1629
+ async function exists(file) {
1630
+ try {
1631
+ await (0, import_promises15.lstat)(file);
1632
+ return true;
1633
+ } catch (cause) {
1634
+ if (isEnoent(cause)) return false;
1635
+ throw cause;
1636
+ }
1637
+ }
1638
+
749
1639
  // src/cli/graphHook.ts
1640
+ var enforcement = [".qfai", "tools", "graph-enforcement.json"];
750
1641
  function hostName(value) {
751
1642
  return value === "claude" || value === "codex" || value === "copilot" || value === "vscode";
752
1643
  }
@@ -774,22 +1665,32 @@ async function runInstalledGraphHook(root, args, io = {
774
1665
  io.fail();
775
1666
  return;
776
1667
  }
777
- let decision = failedGraphHook();
1668
+ let decision = failedGraphHook("configuration");
1669
+ const event = decodeGraphHookEvent(input);
1670
+ let project = root;
1671
+ let uninitialised = false;
778
1672
  try {
779
- const components = [".qfai", "tools", "graph-enforcement.json"];
780
- if (!await findUnsafeHostFileComponent(root, components)) {
781
- const text = await readPinnedRegularFile(import_node_path16.default.join(root, ...components), 4096);
1673
+ project = await resolveSessionWorktree(root, event?.cwd);
1674
+ uninitialised = project !== root && !await hasEnforcement(project);
1675
+ const configured = uninitialised ? root : project;
1676
+ if (!await findUnsafeHostFileComponent(configured, enforcement)) {
1677
+ const text = await readPinnedRegularFile(import_node_path19.default.join(configured, ...enforcement), 4096);
782
1678
  if (text !== null) decision = enforceGraphExploration(input, JSON.parse(text));
783
1679
  }
784
1680
  } catch {
785
1681
  }
786
- if (decision.decision === "deny" && decision.state === "configured") {
787
- const event = decodeGraphHookEvent(input);
1682
+ if (decision.decision === "deny" && decision.state === "configured" && uninitialised)
1683
+ decision = graphFallbackUnavailable(
1684
+ decision,
1685
+ `The session worktree ${project} has no graph protection; this hook belongs to ${root}.`,
1686
+ `Run qfai init in ${project}, then retry the denied action.`
1687
+ );
1688
+ else if (decision.decision === "deny" && decision.state === "configured") {
788
1689
  if (event) {
789
1690
  try {
790
- decision = await classifyStoredGraphExploration(root, event);
1691
+ decision = await classifyStoredGraphExploration(project, event);
791
1692
  } catch (cause) {
792
- decision = failedGraphHook();
1693
+ decision = failedGraphHook("state");
793
1694
  if (cause instanceof GraphLocalStateError)
794
1695
  decision.message = `${cause.message} ${cause.recovery}`;
795
1696
  }
@@ -798,10 +1699,20 @@ async function runInstalledGraphHook(root, args, io = {
798
1699
  if (decision.decision === "deny")
799
1700
  io.output(JSON.stringify(graphHookOutput(host, decision)) + "\n");
800
1701
  if (decision.state === "failed") {
801
- io.error("Graph protection failed. Repair the project hook and enforcement configuration.\n");
1702
+ io.error(`${decision.message}
1703
+ `);
802
1704
  io.fail();
803
1705
  }
804
1706
  }
1707
+ async function hasEnforcement(project) {
1708
+ try {
1709
+ await (0, import_promises16.lstat)(import_node_path19.default.join(project, ...enforcement));
1710
+ return true;
1711
+ } catch (cause) {
1712
+ if (isEnoent(cause)) return false;
1713
+ throw cause;
1714
+ }
1715
+ }
805
1716
  function wireHost(input) {
806
1717
  if (typeof input !== "object" || input === null || Array.isArray(input)) return void 0;
807
1718
  const value = input;