@cratis/pi 7.11.0 → 7.11.1

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.
@@ -287,7 +287,7 @@ export default function (pi: ExtensionAPI) {
287
287
  const gates = parseGatePlan(run.stderr);
288
288
  if (run.aborted) return { gates: [], problem: "its dry run was cancelled" };
289
289
  if (run.timedOut) return { gates, problem: `its dry run did not finish within ${PLAN_TIMEOUT_MS / 1000}s` };
290
- if (run.failed || run.code !== 0) return { gates, problem: `its dry run could not be completed (exit ${run.code ?? "none"})` };
290
+ if (run.failed || run.code !== 0) return { gates, problem: `its dry run could not be completed (exit ${run.code ?? "none"})${run.stderr.trim() ? `\n\n${run.stderr.trim()}` : ""}` };
291
291
  return { gates };
292
292
  }
293
293
 
@@ -342,7 +342,7 @@ export default function (pi: ExtensionAPI) {
342
342
  const reportTimedOut = () => {
343
343
  const last = latestGateLog(gateLogDirectory(sessionId), started);
344
344
  const tail = last ? tailLines(last.file, TAIL_LINES) : "";
345
- throw new Error(`The Cratis quality gate TIMED OUT after ${duration(timeoutSeconds * 1000)}${last ? ` while running '${last.gate}'` : ""}. This is not a pass: nothing was verified.` +
345
+ throw new Error(`The Cratis quality gate TIMED OUT after ${duration(timeoutSeconds * 1000)}${last ? ` while running '${last.gate}'${last.cwd ? ` (cwd: ${last.cwd})` : ""}` : ""}. This is not a pass: nothing was verified.` +
346
346
  (last ? `\n\nGate log: ${last.file}` : "") +
347
347
  (tail ? `\n\n--- last ${TAIL_LINES} lines ---\n${tail}\n--- end ---` : ""));
348
348
  };
@@ -363,15 +363,16 @@ export default function (pi: ExtensionAPI) {
363
363
  if (plan.problem) throw new Error(`The Cratis quality gate plan could not be completed: ${plan.problem}. Nothing was verified.`);
364
364
  const planned = plan.gates.length > 0 ? plan.gates.join(", ") : "none planned";
365
365
  const progress = (elapsedMs: number) => {
366
- const current = latestGateLog(logDirectory, started)?.gate;
366
+ const currentLog = latestGateLog(logDirectory, started);
367
+ const current = currentLog?.gate;
367
368
  onUpdate?.({
368
369
  content: [
369
370
  {
370
371
  type: "text",
371
- text: `Cratis quality gate running${current ? ` ${current}` : ""}: ${duration(elapsedMs)} of ${duration(timeoutSeconds * 1000)} (gates: ${planned}). Escape cancels.`,
372
+ text: `Cratis quality gate running${current ? ` ${current}${currentLog?.cwd ? ` (cwd: ${currentLog.cwd})` : ""}` : ""}: ${duration(elapsedMs)} of ${duration(timeoutSeconds * 1000)} (gates: ${planned}). Escape cancels.`,
372
373
  },
373
374
  ],
374
- details: { status: "running", gates: plan.gates, current, elapsedMs, timeoutSeconds },
375
+ details: { status: "running", gates: plan.gates, current, cwd: currentLog?.cwd, elapsedMs, timeoutSeconds },
375
376
  });
376
377
  };
377
378
  progress(Date.now() - started);
@@ -202,9 +202,15 @@ export function gateTimeoutSeconds(requested?: number, environment = process.env
202
202
  return Math.min(MAX_GATE_TIMEOUT_SECONDS, Math.max(MIN_GATE_TIMEOUT_SECONDS, Math.round(candidate)));
203
203
  }
204
204
 
205
- /** The gate ids a `CRATIS_HOOKS_GATE_DRYRUN=1` run says it would execute, in order. */
205
+ /** Unique planned gate labels, in order, with package counts for multi-directory runs. */
206
206
  export function parseGatePlan(dryRunStderr: string): string[] {
207
- return [...dryRunStderr.matchAll(/^cratis-quality-gate: RUN\s+(\S+)/gm)].map((match) => match[1]);
207
+ const directories = new Map<string, Set<string>>();
208
+ for (const match of dryRunStderr.matchAll(/^cratis-quality-gate: RUN[ \t]+(\S+)[^\n]*(?:\n[ \t]+\$[^\n]*\(cwd: (.*)\))?/gm)) {
209
+ const locations = directories.get(match[1]) ?? new Set<string>();
210
+ locations.add(match[2] ?? "unknown");
211
+ directories.set(match[1], locations);
212
+ }
213
+ return [...directories].map(([gate, locations]) => locations.size > 1 ? `${gate} (${locations.size} packages)` : gate);
208
214
  }
209
215
 
210
216
  /** Where cratis-quality-gate.sh writes each gate's full log for a session (mirrors hook_state_dir in hook-lib.sh). */
@@ -215,7 +221,7 @@ export function gateLogDirectory(sessionId: string, environment = process.env):
215
221
  }
216
222
 
217
223
  /** The gate log written most recently since `sinceMs` — the gate that is running, or was when it stopped. */
218
- export function latestGateLog(directory: string, sinceMs: number): { gate: string; file: string } | undefined {
224
+ export function latestGateLog(directory: string, sinceMs: number): { gate: string; cwd?: string; file: string } | undefined {
219
225
  let latest: { gate: string; file: string; mtime: number } | undefined;
220
226
  try {
221
227
  for (const name of fs.readdirSync(directory)) {
@@ -228,7 +234,22 @@ export function latestGateLog(directory: string, sinceMs: number): { gate: strin
228
234
  } catch {
229
235
  return undefined;
230
236
  }
231
- return latest && { gate: latest.gate, file: latest.file };
237
+ if (!latest) return undefined;
238
+ // The script writes identity before command output. Bound the read even for enormous logs.
239
+ let descriptor: number | undefined;
240
+ try {
241
+ descriptor = fs.openSync(latest.file, "r");
242
+ const buffer = Buffer.alloc(8192);
243
+ const length = fs.readSync(descriptor, buffer, 0, buffer.length, 0);
244
+ const header = buffer.subarray(0, length).toString("utf8").split("\n", 1)[0];
245
+ const identity = /^cratis-quality-gate: LOG (\S+) \(cwd: (.*)\)$/.exec(header);
246
+ if (identity) return { gate: identity[1], cwd: identity[2], file: latest.file };
247
+ } catch {
248
+ // Older or unreadable logs keep their existing filename-based display.
249
+ } finally {
250
+ if (descriptor !== undefined) fs.closeSync(descriptor);
251
+ }
252
+ return { gate: latest.gate, file: latest.file };
232
253
  }
233
254
 
234
255
  const MAX_LOG_TAIL_BYTES = 64 * 1024;
@@ -183,8 +183,10 @@ property is only reported when it really sits inside an `[EventType]`.
183
183
  ### Project-specific gate configuration
184
184
 
185
185
  The shipped gates discover the repository's own solution and package, so most repositories need no
186
- configuration at all. A repository whose project is not where discovery lands — several packages, a
187
- frontend under `Source/<App>` — states only what differs in its own
186
+ configuration at all. An eligible root workspace or solution keeps repository-wide dispatch. Without
187
+ one, discovery uses only each gate's matching, non-excluded changes and runs it once per affected
188
+ project directory, choosing the deepest containing project for each path. A repository
189
+ that needs a different location or has changes outside several candidate projects states only what differs in its own
188
190
  `.cratis/ai/quality-gates.project.json`, which the gate merges over the managed file by gate id:
189
191
 
190
192
  ```json
@@ -402,7 +404,10 @@ A gate whose `requires.commands` are not on `PATH`, whose `requires.paths` do no
402
404
  script may instead be defined in the root `package.json` — this assumes Yarn Berry, where a
403
405
  root-defined `g:` script runs from every workspace, and no workspace `package.json` is inspected), or whose `workingDirectoryFrom` matches
404
406
  nothing in the repository, is a **no-op with a message on stderr**
405
- rather than a failure — that is how a repository with no .NET solution or no frontend stays quiet.
407
+ rather than a failure — a repository with no .NET solution or no frontend runs no corresponding gate.
408
+ With no working-tree changes the script exits silently. An empty plan for a changed tree reports
409
+ `cratis-quality-gate: no gates selected — product verification was not performed.` on stderr; this
410
+ is not evidence of product verification.
406
411
 
407
412
  An override in `.cratis/ai/quality-gates.project.json` is merged shallowly: a field it states
408
413
  replaces the managed one. The one exception is `requires.packageScripts`: an override that sets
@@ -421,10 +426,31 @@ gates it needs in `.cratis/ai/quality-gates.project.json`.
421
426
  repository and silently no-op in every other, which is the worst of both: it looks configured and
422
427
  checks nothing. So the .NET and frontend gates state *what kind of project* they build and let the
423
428
  gate script find it — `workingDirectoryFrom: ["*.slnx", "*.sln", "**/*.slnx", "**/*.sln"]` runs
424
- `dotnet build` in whichever directory holds the repository's own solution, preferring one at the
425
- root because the globs are tried in order. The frontend gates discover `package.json` the same way.
426
- The same shipped file therefore activates in an application repository, activates in a framework
427
- repository, and stays quiet in a repository that has no project at all.
429
+ `dotnet build` in the directories holding the affected solutions. The frontend gates discover
430
+ `package.json` the same way. For each changed path surviving the gate's `changed`/`excludeChanged`
431
+ filters, discovery preserves an eligible root project and otherwise selects its deepest containing
432
+ project within the first glob holding eligible candidates, running once per affected directory.
433
+ The default root-first glob order retains dependent-workspace coverage; explicit glob preferences
434
+ remain honored. Unrelated
435
+ README edits and excluded `dist`, `bin`, or `obj` changes never influence that selection. A single
436
+ eligible project may own source outside its directory; multiple candidates with an uncontained
437
+ trigger report `UNVERIFIED` and exit 2, requiring explicit configuration rather than checking one
438
+ arbitrary package.
439
+
440
+ When `.cratis/ai.manifest.json` exists, discovery excludes the installed `.cratis/ai/` tree and
441
+ symlinks resolving into it. Without the install manifest, authored corpus packages remain eligible.
442
+ Containment resolves paths physically with `cd -P`, including directory symlinks followed by `..`;
443
+ both the project-file target and the execution directory must be inside the task-owning repository
444
+ and outside the managed tree. This depends on actual targets, not a global exclusion of similarly
445
+ named authored directories. Candidate resolution is cached across gates, and path filtering and
446
+ prefix selection use batch passes rather than per-path subprocesses.
447
+
448
+ Gate commands read from `/dev/null`, never the remaining directory list. If some affected directories
449
+ run while others have unmet requirements, the gate reports `UNVERIFIED` and exits 2; a wholly
450
+ inapplicable gate remains a no-op. Pi preserves the script's diagnostics when planning fails.
451
+
452
+ The same shipped file therefore activates in application and framework repositories, and reports
453
+ an empty plan without running gates in a repository that has no project at all.
428
454
 
429
455
  **Overriding it, in order of increasing force.** Set `workingDirectory` on a gate to pin one of
430
456
  several candidate projects; drop a `quality-gates.json` of your own in place of the shipped one; or
@@ -3,8 +3,8 @@
3
3
  #
4
4
  # Looks at what actually changed in the working tree, runs only the gates that change touches,
5
5
  # and exits 2 (blocking turn-end, stderr fed back to the model) when one fails. It never edits
6
- # code: it only builds, tests and lints. If nothing relevant changed it exits immediately and
7
- # silently, so a documentation- or corpus-only turn costs nothing.
6
+ # code: it only builds, tests and lints. With no changes it exits silently. An empty plan for
7
+ # a changed tree reports on stderr that no product verification was performed, without running gates.
8
8
  #
9
9
  # Gate commands are data (quality-gates.json), not code — see that file for the schema.
10
10
  #
@@ -31,7 +31,7 @@ if [ -n "$input" ] && [ "$(hook_json "$input" '.stop_hook_active')" = "true" ];
31
31
  fi
32
32
 
33
33
  root="$(hook_repo_root)"
34
- here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
34
+ here="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
35
35
  config="${CRATIS_HOOKS_GATES:-$here/quality-gates.json}"
36
36
  dryrun="${CRATIS_HOOKS_GATE_DRYRUN:-0}"
37
37
 
@@ -117,20 +117,144 @@ repository_paths() {
117
117
  printf '%s\n' "$repo_paths"
118
118
  }
119
119
 
120
- # Print the repository path a gate should be located by, given newline-separated globs.
121
- # The globs are tried IN ORDER and the first one with a match wins, so a configuration can
122
- # state a preference ("a solution at the root, else one anywhere") rather than depending on
123
- # where a path happens to sort. Prints nothing when nothing matches.
124
- discover_path() {
125
- local g match
126
- while IFS= read -r g; do
127
- [ -n "$g" ] || continue
128
- match="$(repository_paths | hook_glob_first_match "$g" || true)"
129
- [ -n "$match" ] && { printf '%s\n' "$match"; return 0; }
120
+ # An install manifest distinguishes a managed copy from the corpus's authored source.
121
+ # Resolve actual targets, not adapter names: a product may legitimately own .agents (etc.).
122
+ physical_root="$(cd -P "$root" && pwd -P)"
123
+ managed_root=""
124
+ if [ -f "$root/.cratis/ai.manifest.json" ] && [ -d "$root/.cratis/ai" ]; then
125
+ managed_root="$(cd -P "$root/.cratis/ai" && pwd -P)"
126
+ fi
127
+
128
+ repository_contains_path() {
129
+ case "$1" in
130
+ "$physical_root"|"$physical_root"/*) ;;
131
+ *) return 1 ;;
132
+ esac
133
+ if [ -n "$managed_root" ]; then
134
+ case "$1" in
135
+ "$managed_root"|"$managed_root"/*) return 1 ;;
136
+ esac
137
+ fi
138
+ }
139
+
140
+ repository_execution_directory() {
141
+ local dir
142
+ dir="$(cd -P "$root/$1" 2>/dev/null && pwd -P)" || return 1
143
+ repository_contains_path "$dir"
144
+ }
145
+
146
+ repository_project_path() {
147
+ local path="$root/$1" parent dir target hops=0
148
+ [ -f "$path" ] || return 1
149
+ parent=${1%/*}
150
+ [ "$parent" != "$1" ] || parent=.
151
+ # The execution directory must be owned too, even if the file links back into the repo.
152
+ repository_execution_directory "$parent" || return 1
153
+ while :; do
154
+ dir="$(cd -P "${path%/*}" 2>/dev/null && pwd -P)" || return 1
155
+ path="$dir/${path##*/}"
156
+ [ -L "$path" ] || break
157
+ hops=$((hops + 1))
158
+ [ "$hops" -le 40 ] || return 1
159
+ target="$(readlink "$path")" || return 1
160
+ case "$target" in
161
+ /*) path="$target" ;;
162
+ *) path="$dir/$target" ;;
163
+ esac
164
+ done
165
+ repository_contains_path "$path"
166
+ }
167
+
168
+ # Indexed arrays work on Bash 3.2. Populate caches in the parent shell, not a command
169
+ # substitution: identical frontend gates share one listing and one physical resolution.
170
+ project_cache_paths=()
171
+ project_cache_valid=()
172
+ candidate_cache_globs=()
173
+ candidate_cache_dirs=()
174
+ candidate_dirs=""
175
+ prepare_candidates() {
176
+ local globs="$1" i group selected_group="" candidate dir candidates valid
177
+ for ((i=0; i<${#candidate_cache_globs[@]}; i++)); do
178
+ if [ "${candidate_cache_globs[$i]}" = "$globs" ]; then
179
+ candidate_dirs="${candidate_cache_dirs[$i]}"
180
+ return 0
181
+ fi
182
+ done
183
+ repository_paths >/dev/null
184
+ # One pass matches all globs; the first group with an eligible candidate retains priority.
185
+ candidates="$(printf '%s\n' "$repo_paths" | CRATIS_GLOBS="$globs" awk "$hook_glob_awk_lib"'
186
+ BEGIN {
187
+ count = split(ENVIRON["CRATIS_GLOBS"], globs, "\n")
188
+ for (i = 1; i <= count; i++) res[i] = g2re(globs[i])
189
+ }
190
+ { paths[++n] = $0 }
191
+ END {
192
+ for (i = 1; i <= count; i++) for (j = 1; j <= n; j++)
193
+ if (!seen[paths[j]] && paths[j] ~ res[i]) { print i "\t" paths[j]; seen[paths[j]] = 1 }
194
+ }
195
+ ')"
196
+ candidate_dirs=""
197
+ while IFS=$'\t' read -r group candidate; do
198
+ [ -n "$candidate" ] || continue
199
+ if [ -n "$selected_group" ] && [ "$group" != "$selected_group" ]; then
200
+ break
201
+ fi
202
+ valid=""
203
+ for ((i=0; i<${#project_cache_paths[@]}; i++)); do
204
+ if [ "${project_cache_paths[$i]}" = "$candidate" ]; then
205
+ valid="${project_cache_valid[$i]}"
206
+ break
207
+ fi
208
+ done
209
+ if [ -z "$valid" ]; then
210
+ valid=0
211
+ repository_project_path "$candidate" && valid=1
212
+ project_cache_paths+=("$candidate")
213
+ project_cache_valid+=("$valid")
214
+ fi
215
+ [ "$valid" = 1 ] || continue
216
+ selected_group="$group"
217
+ dir=${candidate%/*}
218
+ [ "$dir" != "$candidate" ] || dir=.
219
+ candidate_dirs="${candidate_dirs}${candidate_dirs:+
220
+ }$dir"
221
+ # Keep main's root workspace/solution dispatch; it owns dependent-workspace coverage.
222
+ [ "$dir" != "." ] || { candidate_dirs="."; break; }
130
223
  done <<EOF
131
- $1
224
+ $candidates
132
225
  EOF
133
- return 1
226
+ candidate_cache_globs+=("$globs")
227
+ candidate_cache_dirs+=("$candidate_dirs")
228
+ }
229
+
230
+ # With no eligible root project, select the deepest containing directory per trigger.
231
+ # Prefix lookup is one awk pass, not a subprocess for every path/candidate pair.
232
+ discover_workdirs() {
233
+ [ -n "$candidate_dirs" ] || return 1
234
+ [ "$candidate_dirs" != "." ] || { printf '.\n'; return 0; }
235
+ printf '%s\n' "$1" | CRATIS_PROJECT_DIRS="$candidate_dirs" awk '
236
+ BEGIN {
237
+ n = split(ENVIRON["CRATIS_PROJECT_DIRS"], dirs, "\n")
238
+ for (i = 1; i <= n; i++) if (!known[dirs[i]]++) ordered[++count] = dirs[i]
239
+ }
240
+ NF {
241
+ parent = $0; found = 0
242
+ while (sub("/[^/]*$", "", parent)) {
243
+ if (known[parent]) { selected[parent] = 1; found = 1; break }
244
+ }
245
+ if (!found) {
246
+ if (count == 1) selected[ordered[1]] = 1
247
+ else {
248
+ printf "cratis-quality-gate: UNVERIFIED — no containing project for %s among multiple candidates. Configure workingDirectory.\n", $0 > "/dev/stderr"
249
+ failed = 1
250
+ }
251
+ }
252
+ }
253
+ END {
254
+ if (failed) exit 2
255
+ for (i = 1; i <= count; i++) if (selected[ordered[i]]) print ordered[i]
256
+ }
257
+ '
134
258
  }
135
259
 
136
260
  gate_count="$(jq -r '.gates | length' "$config")"
@@ -142,23 +266,26 @@ tmp_root="$(hook_state_dir "$(hook_json "$input" '.session_id')")" || tmp_root="
142
266
  log_dir="$tmp_root/gate-logs"
143
267
  mkdir -p "$log_dir" 2>/dev/null || log_dir="${TMPDIR:-/tmp}"
144
268
 
145
- # Does any changed path match this gate's globs (and survive its excludes)?
146
- gate_triggered() {
147
- local idx="$1" inc exc p
269
+ # Collect ALL paths matching this gate's globs after its exclusions, for discovery too.
270
+ gate_changed_paths() {
271
+ local idx="$1" inc exc
148
272
  inc="$(jq -r --argjson i "$idx" '.gates[$i].changed // [] | .[]' "$config")"
149
273
  exc="$(jq -r --argjson i "$idx" '.gates[$i].excludeChanged // [] | .[]' "$config")"
150
- [ -n "$inc" ] || return 1
151
- while IFS= read -r p; do
152
- [ -n "$p" ] || continue
153
- printf '%s\n' "$inc" | hook_glob_match "$p" || continue
154
- if [ -n "$exc" ]; then
155
- printf '%s\n' "$exc" | hook_glob_match "$p" && continue
156
- fi
157
- return 0
158
- done <<EOF
159
- $changed
160
- EOF
161
- return 1
274
+ printf '%s\n' "$changed" | CRATIS_INCLUDES="$inc" CRATIS_EXCLUDES="$exc" awk "$hook_glob_awk_lib"'
275
+ BEGIN {
276
+ ni = split(ENVIRON["CRATIS_INCLUDES"], includes, "\n")
277
+ ne = split(ENVIRON["CRATIS_EXCLUDES"], excludes, "\n")
278
+ for (i = 1; i <= ni; i++) if (includes[i] != "") inc[++ic] = g2re(includes[i])
279
+ for (i = 1; i <= ne; i++) if (excludes[i] != "") exc[++ec] = g2re(excludes[i])
280
+ }
281
+ NF {
282
+ matches = 0
283
+ for (i = 1; i <= ic; i++) if ($0 ~ inc[i]) { matches = 1; break }
284
+ if (!matches) next
285
+ for (i = 1; i <= ec; i++) if ($0 ~ exc[i]) { matches = 0; break }
286
+ if (matches) print
287
+ }
288
+ '
162
289
  }
163
290
 
164
291
  # Does the package.json at $1 define the script named $2? A missing file or a file that is not
@@ -167,21 +294,21 @@ package_defines_script() {
167
294
  [ -f "$1" ] && jq -e --arg s "$2" '.scripts[$s] != null' "$1" >/dev/null 2>&1
168
295
  }
169
296
 
170
- # Report the first unmet requirement, or nothing when the gate can run here. $2 is the directory,
171
- # relative to the repository root, the gate runs in.
297
+ # Requirements are read once per gate, not once per affected directory.
298
+ # Report the first unmet requirement for the repo-relative execution directory $1.
172
299
  gate_unmet() {
173
- local idx="$1" dir="$2" c p s
300
+ local dir="$1" c p s
174
301
  while IFS= read -r c; do
175
302
  [ -n "$c" ] || continue
176
303
  hook_have "$c" || { printf "command '%s' is not on PATH" "$c"; return 0; }
177
304
  done <<EOF
178
- $(jq -r --argjson i "$idx" '.gates[$i].requires.commands // [] | .[]' "$config")
305
+ $required_commands
179
306
  EOF
180
307
  while IFS= read -r p; do
181
308
  [ -n "$p" ] || continue
182
309
  [ -e "$root/$p" ] || { printf "'%s' does not exist in this repository" "$p"; return 0; }
183
310
  done <<EOF
184
- $(jq -r --argjson i "$idx" '.gates[$i].requires.paths // [] | .[]' "$config")
311
+ $required_paths
185
312
  EOF
186
313
  # A package.json script a gate invokes must exist, or yarn fails with "Couldn't find a script"
187
314
  # instead of the gate being a NO-OP. A global script (g:) may live in the root package.json
@@ -197,91 +324,131 @@ EOF
197
324
  printf "script '%s' is not defined in %s" "$s" "$dir/package.json"
198
325
  return 0
199
326
  done <<EOF
200
- $(jq -r --argjson i "$idx" '.gates[$i].requires.packageScripts // [] | .[]' "$config")
327
+ $required_scripts
201
328
  EOF
202
329
  return 0
203
330
  }
204
331
 
205
332
  idx=0
206
333
  ran=0
334
+ planned_gates=0
335
+ planned_directories=()
207
336
  while [ "$idx" -lt "$gate_count" ]; do
208
337
  id="$(jq -r --argjson i "$idx" '.gates[$i].id' "$config")"
209
338
  desc="$(jq -r --argjson i "$idx" '.gates[$i].description // ""' "$config")"
210
339
  wd="$(jq -r --argjson i "$idx" '.gates[$i].workingDirectory // ""' "$config")"
211
340
 
212
- if ! gate_triggered "$idx"; then
341
+ gate_changes="$(gate_changed_paths "$idx")"
342
+ if [ -z "$gate_changes" ]; then
213
343
  [ "$dryrun" = "1" ] && printf 'cratis-quality-gate: SKIP %-24s (no matching change)\n' "$id" >&2
214
344
  idx=$((idx + 1))
215
345
  continue
216
346
  fi
217
347
 
218
- # workingDirectoryFrom is discovery AND requirement in one: the gate runs in the directory
219
- # of the discovered project file, and a repository holding no such file is a NO-OP.
220
- if [ -z "$wd" ]; then
348
+ # Discovery is a requirement and can select multiple affected project directories.
349
+ workdirs="$wd"
350
+ if [ -z "$workdirs" ]; then
221
351
  wd_globs="$(jq -r --argjson i "$idx" '.gates[$i].workingDirectoryFrom // [] | .[]' "$config")"
222
352
  if [ -n "$wd_globs" ]; then
223
- wd_path="$(discover_path "$wd_globs" || true)"
224
- if [ -z "$wd_path" ]; then
353
+ prepare_candidates "$wd_globs"
354
+ discovery_rc=0
355
+ workdirs="$(discover_workdirs "$gate_changes")" || discovery_rc=$?
356
+ if [ "$discovery_rc" -eq 2 ]; then
357
+ printf 'cratis-quality-gate: UNVERIFIED %-24s — ambiguous project discovery.\n' "$id" >&2
358
+ exit 2
359
+ fi
360
+ if [ -z "$workdirs" ]; then
225
361
  printf 'cratis-quality-gate: NO-OP %-24s — no repository path matches %s. Configure it in %s.\n' \
226
362
  "$id" "$(printf '%s' "$wd_globs" | tr '\n' ' ')" "${config#"$root"/}" >&2
227
363
  idx=$((idx + 1))
228
364
  continue
229
365
  fi
230
- wd="$(dirname "$wd_path")"
231
366
  fi
232
367
  fi
233
- [ -n "$wd" ] || wd="."
234
-
235
- unmet="$(gate_unmet "$idx" "$wd")"
236
- if [ -n "$unmet" ]; then
237
- printf 'cratis-quality-gate: NO-OP %-24s — %s. Configure it in %s.\n' \
238
- "$id" "$unmet" "${config#"$root"/}" >&2
239
- idx=$((idx + 1))
240
- continue
241
- fi
368
+ [ -n "$workdirs" ] || workdirs="."
242
369
 
370
+ required_commands="$(jq -r --argjson i "$idx" '.gates[$i].requires.commands // [] | .[]' "$config")"
371
+ required_paths="$(jq -r --argjson i "$idx" '.gates[$i].requires.paths // [] | .[]' "$config")"
372
+ required_scripts="$(jq -r --argjson i "$idx" '.gates[$i].requires.packageScripts // [] | .[]' "$config")"
243
373
  cmd=()
244
374
  while IFS= read -r arg; do
245
375
  cmd+=("$arg")
246
376
  done <<EOF
247
377
  $(jq -r --argjson i "$idx" '.gates[$i].command // [] | .[]' "$config")
248
378
  EOF
249
- if [ "${#cmd[@]}" -eq 0 ]; then
250
- idx=$((idx + 1))
251
- continue
252
- fi
253
379
 
254
- if [ "$dryrun" = "1" ]; then
255
- printf 'cratis-quality-gate: RUN %-24s %s\n $ %s (cwd: %s)\n' \
256
- "$id" "$desc" "${cmd[*]}" "$wd" >&2
257
- idx=$((idx + 1))
258
- ran=$((ran + 1))
259
- continue
260
- fi
380
+ project_index=0
381
+ gate_ran=0
382
+ gate_noops=0
383
+ while IFS= read -r wd; do
384
+ project_index=$((project_index + 1))
385
+ if ! repository_execution_directory "$wd"; then
386
+ printf 'cratis-quality-gate: UNVERIFIED %-24s — execution directory %s is outside the repository or inside the managed corpus.\n' "$id" "$wd" >&2
387
+ exit 2
388
+ fi
389
+ unmet="$(gate_unmet "$wd")"
390
+ if [ -n "$unmet" ]; then
391
+ printf 'cratis-quality-gate: NO-OP %-24s — %s. Configure it in %s.\n' \
392
+ "$id" "$unmet" "${config#"$root"/}" >&2
393
+ gate_noops=$((gate_noops + 1))
394
+ continue
395
+ fi
396
+ if [ "${#cmd[@]}" -eq 0 ]; then
397
+ continue
398
+ fi
261
399
 
262
- log="$log_dir/$id.log"
263
- rc=0
264
- (cd "$root/$wd" && "${cmd[@]}") >"$log" 2>&1 || rc=$?
265
- ran=$((ran + 1))
400
+ gate_ran=$((gate_ran + 1))
401
+ if [ "$dryrun" = "1" ]; then
402
+ [ "$gate_ran" -ne 1 ] || planned_gates=$((planned_gates + 1))
403
+ directory_seen=0
404
+ if [ "${#planned_directories[@]}" -gt 0 ]; then
405
+ for directory in "${planned_directories[@]}"; do
406
+ [ "$directory" != "$wd" ] || directory_seen=1
407
+ done
408
+ fi
409
+ [ "$directory_seen" -ne 0 ] || planned_directories+=("$wd")
410
+ printf 'cratis-quality-gate: RUN %-24s %s\n $ %s (cwd: %s)\n' \
411
+ "$id" "$desc" "${cmd[*]}" "$wd" >&2
412
+ ran=$((ran + 1))
413
+ continue
414
+ fi
266
415
 
267
- if [ "$rc" -ne 0 ]; then
416
+ log="$log_dir/$id.log"
417
+ [ "$project_index" -eq 1 ] || log="$log_dir/$id-$project_index.log"
418
+ rc=0
268
419
  {
269
- printf 'QUALITY GATE FAILED: %s (exit %s)\n' "$id" "$rc"
270
- printf ' %s\n' "$desc"
271
- printf ' $ %s (cwd: %s)\n\n' "${cmd[*]}" "$wd"
272
- printf -- '--- last %s lines ---\n' "$max_lines"
273
- tail -n "$max_lines" "$log" 2>/dev/null || true
274
- printf -- '--- end ---\n\n'
275
- printf 'Fix the failure and re-run the gate. Never change code merely to make a gate pass,\n'
276
- printf 'and never suppress warnings. Full log: %s\n' "$log"
277
- } >&2
420
+ printf 'cratis-quality-gate: LOG %s (cwd: %s)\n' "$id" "$wd"
421
+ (cd -P "$root/$wd" && "${cmd[@]}") </dev/null
422
+ } >"$log" 2>&1 || rc=$?
423
+ ran=$((ran + 1))
424
+
425
+ if [ "$rc" -ne 0 ]; then
426
+ {
427
+ printf 'QUALITY GATE FAILED: %s (exit %s)\n' "$id" "$rc"
428
+ printf ' %s\n' "$desc"
429
+ printf ' $ %s (cwd: %s)\n\n' "${cmd[*]}" "$wd"
430
+ printf -- '--- last %s lines ---\n' "$max_lines"
431
+ tail -n "$max_lines" "$log" 2>/dev/null || true
432
+ printf -- '--- end ---\n\n'
433
+ printf 'Fix the failure and re-run the gate. Never change code merely to make a gate pass,\n'
434
+ printf 'and never suppress warnings. Full log: %s\n' "$log"
435
+ } >&2
436
+ [ "$fail_fast" = "true" ] && exit 2
437
+ failed=1
438
+ fi
439
+ done <<EOF
440
+ $workdirs
441
+ EOF
442
+ if [ "$gate_ran" -gt 0 ] && [ "$gate_noops" -gt 0 ]; then
443
+ printf 'cratis-quality-gate: UNVERIFIED %-24s — %s affected project(s) did not meet requirements; the gate is incomplete.\n' "$id" "$gate_noops" >&2
278
444
  [ "$fail_fast" = "true" ] && exit 2
279
445
  failed=1
280
446
  fi
281
-
282
447
  idx=$((idx + 1))
283
448
  done
284
449
 
285
450
  [ "${failed:-0}" -eq 0 ] || exit 2
286
- [ "$dryrun" = "1" ] && printf 'cratis-quality-gate: dry run complete — %s gate(s) would run.\n' "$ran" >&2
451
+ [ "$dryrun" = "1" ] && printf 'cratis-quality-gate: dry run complete — %s gate(s) would run across %s project directory(s) (%s run(s)).\n' \
452
+ "$planned_gates" "${#planned_directories[@]}" "$ran" >&2
453
+ [ "$ran" -eq 0 ] && printf 'cratis-quality-gate: no gates selected — product verification was not performed.\n' >&2
287
454
  exit 0
@@ -24,8 +24,22 @@
24
24
  " workingDirectory repo-relative directory the command runs in",
25
25
  " workingDirectoryFrom globs identifying the project file this gate builds; the command runs",
26
26
  " in that file's directory, and a repository holding none makes the gate a",
27
- " NO-OP. Globs are tried in order, so the list states a preference. Ignored",
28
- " when workingDirectory is set.",
27
+ " NO-OP. The first glob with an eligible project wins. Ignored",
28
+ " when workingDirectory is set. Discovery excludes the installed .cratis/ai tree",
29
+ " when .cratis/ai.manifest.json exists, including symlinks resolving into that tree.",
30
+ " Symlinks outside the task-owning repository are never discovered. Without the install",
31
+ " manifest the corpus is authored source and its packages remain eligible. Physical",
32
+ " resolution preserves symlink/.. semantics. Only changed paths surviving this gate's",
33
+ " changed/excludeChanged filters select projects: the deepest containing project per",
34
+ " path wins within that glob when no eligible root project exists. The default root-first",
35
+ " globs preserve workspace/solution dispatch. A root workspace or solution keeps",
36
+ " repository-wide dispatch; otherwise the gate runs once per affected directory. A single project",
37
+ " may own source outside its directory; multiple candidates with an uncontained trigger",
38
+ " report UNVERIFIED and exit 2 rather than silently checking an arbitrary project.",
39
+ " Both the project-file target and the execution directory must pass containment.",
40
+ " Candidate resolution is cached across gates; filtering and prefix lookup are batched.",
41
+ " Mixed RUN/NO-OP directories report UNVERIFIED and exit 2, not a partial success.",
42
+ " Gate commands read /dev/null so they cannot consume remaining directories.",
29
43
  " command argv array \u2014 executed directly, never through a shell (no eval)",
30
44
  "",
31
45
  "Managed corpus and adapter trees (.cratis/**, .pi/**, .claude/**) never count as a relevant change:",
@@ -35,7 +49,7 @@
35
49
  "silently no-op in every repository except the one it was written for. The .NET and frontend",
36
50
  "gates discover the repository's own solution/package instead, so they activate unchanged in",
37
51
  "an application repository, a framework repository, and (as nothing to run) in a corpus-only",
38
- "repository such as this one, which carries no .NET or Node project at all.",
52
+ "repository. An empty plan reports that no product verification was performed.",
39
53
  "",
40
54
  "The override model, in order of increasing force: a repository states only what differs in its",
41
55
  "own .cratis/ai/quality-gates.project.json, which the runner merges over this file by gate id",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.11.0",
3
+ "version": "7.11.1",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [