@boyingliu01/xp-gate 0.35.21 → 0.35.23

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 (36) hide show
  1. package/adapters/kotlin.sh +53 -8
  2. package/bin/xp-gate.js +12 -0
  3. package/gate-13-compiler-strictness.sh +15 -1
  4. package/hooks/gate-13-compiler-strictness.sh +15 -1
  5. package/hooks/pre-commit +137 -9
  6. package/lib/__tests__/agent-runtime-journal.test.js +302 -0
  7. package/lib/__tests__/mirror-sync.test.js +277 -0
  8. package/lib/__tests__/runtime-journal.test.js +164 -0
  9. package/lib/agent-runtime-journal.js +347 -0
  10. package/lib/mattpocock-license-verdict.json +1 -1
  11. package/lib/mirror-sync.js +335 -0
  12. package/lib/runtime-journal.js +156 -0
  13. package/mock-policy/AGENTS.md +2 -2
  14. package/mutation/AGENTS.md +2 -2
  15. package/package.json +1 -1
  16. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  17. package/plugins/claude-code/skills/delphi-review/AGENTS.md +2 -2
  18. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +2 -2
  19. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +2 -2
  20. package/plugins/dsh/package.json +1 -1
  21. package/plugins/dsh/skills/delphi-review/AGENTS.md +2 -2
  22. package/plugins/dsh/skills/sprint-flow/AGENTS.md +2 -2
  23. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +2 -2
  24. package/plugins/opencode/package.json +1 -1
  25. package/plugins/opencode/skills/delphi-review/AGENTS.md +2 -2
  26. package/plugins/opencode/skills/sprint-flow/AGENTS.md +2 -2
  27. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +2 -2
  28. package/plugins/qoder/plugin.json +1 -1
  29. package/plugins/qoder/skills/delphi-review/AGENTS.md +2 -2
  30. package/plugins/qoder/skills/sprint-flow/AGENTS.md +2 -2
  31. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +2 -2
  32. package/principles/AGENTS.md +2 -2
  33. package/scripts/delphi-external-review.cjs +68 -1
  34. package/skills/delphi-review/AGENTS.md +2 -2
  35. package/skills/sprint-flow/AGENTS.md +2 -2
  36. package/skills/test-specification-alignment/AGENTS.md +2 -2
@@ -14,30 +14,75 @@ run_static_analysis() {
14
14
  local build_system
15
15
  build_system=$(_detect_kotlin_build)
16
16
 
17
+ # (#706) A failed BUILD must not swallow a lint tool that works on its own.
18
+ #
19
+ # This used to `return 1` the moment Gradle/Maven failed to compile, so detekt
20
+ # -- which reads .kt sources directly and needs no build at all -- never ran.
21
+ # Measured on a machine whose Gradle cannot resolve the Kotlin plugin
22
+ # (`Failed to query the value of property 'buildFlowServiceProperty'`): the
23
+ # hook reported "SKIPPED - Code quality (tools unavailable or failed)" while
24
+ # `detekt --input .` on the same file reported two real findings. The gate
25
+ # blamed the toolchain for a verdict the toolchain never got to deliver.
26
+ #
27
+ # So: record the compilation failure, still run the standalone lint tool, and
28
+ # let the caller decide. The failure is reported, never hidden.
29
+ local build_failed=0
17
30
  if [ "$build_system" = "maven" ]; then
18
31
  mvn compile -q 2>&1 | grep -i "error\|fail" | sed -n '1,5p; 5q'
19
32
  if [ ${PIPESTATUS[0]} -ne 0 ]; then
20
33
  echo "❌ Maven compilation failed"
21
- return 1
34
+ build_failed=1
22
35
  fi
23
36
  elif [ "$build_system" = "gradle" ]; then
24
37
  gradle compileKotlin --quiet 2>&1 | grep -i "error\|fail" | sed -n '1,5p; 5q'
25
38
  if [ ${PIPESTATUS[0]} -ne 0 ]; then
26
39
  echo "❌ Gradle compilation failed"
27
- return 1
40
+ build_failed=1
28
41
  fi
29
42
  fi
30
43
 
44
+ # Standalone analyzers run regardless of the build outcome: their verdict does
45
+ # not depend on the build having succeeded.
46
+ #
47
+ # ktlint and detekt are tried in preference order, but a tool that is PRESENT
48
+ # and produces NOTHING is not the same as a tool that reached a verdict. An
49
+ # `elif` chain made the first present tool authoritative: a broken ktlint (or a
50
+ # shim on PATH, or ktlint 1.x refusing a `**/*.kt` glob) reported "No files
51
+ # matched" and detekt -- which works -- was never consulted. Measured here:
52
+ # `command -v ktlint` succeeded while `ktlint **/*.kt` matched zero files, so
53
+ # the real analyzer never ran.
54
+ local lint_rc=0 linted=0 ktlint_out=""
31
55
  if command -v ktlint &>/dev/null; then
32
- ktlint "**/*.kt" 2>&1 | sed -n '1,20p; 20q'
33
- return $?
34
- elif command -v detekt &>/dev/null; then
56
+ ktlint_out=$(ktlint "**/*.kt" 2>&1)
57
+ lint_rc=$?
58
+ printf '%s\n' "$ktlint_out" | sed -n '1,20p'
59
+ # Only an EXECUTED ktlint counts as having delivered a verdict. Three ways it
60
+ # can fail to: the binary cannot run (127/126), it reports "No files matched"
61
+ # (ktlint 1.8.0 no longer resolves `**/*.kt`), or it printed nothing at all.
62
+ # In every one of those cases detekt should speak instead of ktlint's silence
63
+ # being read as "clean".
64
+ if [ "$lint_rc" -ne 127 ] && [ "$lint_rc" -ne 126 ] \
65
+ && [ -n "$ktlint_out" ] \
66
+ && ! printf '%s\n' "$ktlint_out" | grep -q 'No files matched'; then
67
+ linted=1
68
+ fi
69
+ fi
70
+ if [ "$linted" -eq 0 ] && command -v detekt &>/dev/null; then
35
71
  detekt --input . 2>&1 | sed -n '1,20p; 20q'
36
- return $?
37
- else
72
+ lint_rc=${PIPESTATUS[0]}
73
+ linted=1
74
+ fi
75
+ if [ "$linted" -eq 0 ]; then
38
76
  echo "No Kotlin lint tools (ktlint/detekt)"
39
- return 0
77
+ # A missing lint tool is a SKIP, not a pass -- but it must not manufacture a
78
+ # failure either. Only the build result decides in that case.
79
+ [ "$build_failed" -eq 0 ] && return 0
80
+ return 1
40
81
  fi
82
+
83
+ # A lint finding is a finding whether or not the build also failed.
84
+ [ "$lint_rc" -ne 0 ] && return "$lint_rc"
85
+ return "$build_failed"
41
86
  }
42
87
 
43
88
  run_lint() {
package/bin/xp-gate.js CHANGED
@@ -17,6 +17,8 @@ const { arch } = require('../lib/arch.js');
17
17
  const { upgrade } = require('../lib/upgrade.js');
18
18
  const { bootstrap } = require('../lib/bootstrap.js');
19
19
  const { updateHooks } = require('../lib/update-hooks.js');
20
+ const { handleRuntimeJournal } = require('../lib/runtime-journal.js');
21
+ const { handleSyncMirrors } = require('../lib/mirror-sync.js');
20
22
  const gateRunner = require('../lib/gate-runner.js');
21
23
 
22
24
  // #392-#6: a user-supplied path embedded in a shell command string lets cmd.exe
@@ -350,6 +352,16 @@ const COMMANDS = {
350
352
  },
351
353
  usage: 'xp-gate retro [--days N] [--all] [--json] [--sprint <id>]'
352
354
  },
355
+ 'runtime-journal': {
356
+ description: 'Measure the AGENTS.md runtime rules (blocking waits, sleep/polling, call batching) from agent session journals (#712)',
357
+ run: subargs => process.exit(handleRuntimeJournal(subargs)),
358
+ usage: 'xp-gate runtime-journal [--days N] [--json] [--sessions-dir <path>]'
359
+ },
360
+ 'sync-mirrors': {
361
+ description: 'Report or repair drift between canonical trees and their npm-package mirrors; dry-run unless --write (#713)',
362
+ run: subargs => process.exit(handleSyncMirrors(subargs)),
363
+ usage: 'xp-gate sync-mirrors [--write] [--json]'
364
+ },
353
365
  'gate-coverage': {
354
366
  description: 'One view of compliance against every gate: PASS / DEBT / SKIP / FAIL, with debt and evidence (#636)',
355
367
  run: subargs => {
@@ -525,7 +525,21 @@ gate13_javac_args() {
525
525
  gate13_count_lint_findings() {
526
526
  local src="${1:-}"
527
527
  [ -n "$src" ] || src=$(cat)
528
- printf '%s\n' "$src" | awk '
528
+ # (#701) Pin the locale to C for this awk, on purpose. In a UTF-8 locale gawk
529
+ # refuses to let `.` span bytes that are not valid UTF-8, and a Maven build on a
530
+ # zh_CN Windows box writes its reactor summary in GBK (stdout.encoding=GBK), so a
531
+ # module name such as "验证程序" arrives as d1 e9 d6 a4 b3 cc d0 f2 -- invalid
532
+ # UTF-8. The #673 exclusion rule (`/^\[INFO\].*\[jar\].../`) then fails to match
533
+ # and the line falls through to the open-category rule as a phantom finding.
534
+ # Measured (#701): the same input counts 0 under LC_ALL=C and 1 under
535
+ # LC_ALL=C.UTF-8, i.e. the verdict depended on the caller's environment rather
536
+ # than on the build. C locale makes `.` byte-oriented, so the match no longer
537
+ # depends on whether the module name happens to be ASCII.
538
+ #
539
+ # This costs nothing in matching power: every marker below (packaging types,
540
+ # `[category]`, `warning:`) is ASCII, and the localised unchecked/unsafe
541
+ # wordings are matched as byte sequences, which C locale handles exactly.
542
+ printf '%s\n' "$src" | LC_ALL=C awk '
529
543
  BEGIN { n = 0 }
530
544
  # (#673) Maven 3.9.7+ reactor summary appends the packaging type per module:
531
545
  # [INFO] whaleaudit-core [jar]
@@ -525,7 +525,21 @@ gate13_javac_args() {
525
525
  gate13_count_lint_findings() {
526
526
  local src="${1:-}"
527
527
  [ -n "$src" ] || src=$(cat)
528
- printf '%s\n' "$src" | awk '
528
+ # (#701) Pin the locale to C for this awk, on purpose. In a UTF-8 locale gawk
529
+ # refuses to let `.` span bytes that are not valid UTF-8, and a Maven build on a
530
+ # zh_CN Windows box writes its reactor summary in GBK (stdout.encoding=GBK), so a
531
+ # module name such as "验证程序" arrives as d1 e9 d6 a4 b3 cc d0 f2 -- invalid
532
+ # UTF-8. The #673 exclusion rule (`/^\[INFO\].*\[jar\].../`) then fails to match
533
+ # and the line falls through to the open-category rule as a phantom finding.
534
+ # Measured (#701): the same input counts 0 under LC_ALL=C and 1 under
535
+ # LC_ALL=C.UTF-8, i.e. the verdict depended on the caller's environment rather
536
+ # than on the build. C locale makes `.` byte-oriented, so the match no longer
537
+ # depends on whether the module name happens to be ASCII.
538
+ #
539
+ # This costs nothing in matching power: every marker below (packaging types,
540
+ # `[category]`, `warning:`) is ASCII, and the localised unchecked/unsafe
541
+ # wordings are matched as byte sequences, which C locale handles exactly.
542
+ printf '%s\n' "$src" | LC_ALL=C awk '
529
543
  BEGIN { n = 0 }
530
544
  # (#673) Maven 3.9.7+ reactor summary appends the packaging type per module:
531
545
  # [INFO] whaleaudit-core [jar]
package/hooks/pre-commit CHANGED
@@ -2237,15 +2237,22 @@ else
2237
2237
  ADAPTER_FILE=$(resolve_adapter_path "$CURRENT_LANG")
2238
2238
  if [ -n "$ADAPTER_FILE" ] && source "$ADAPTER_FILE" 2>/dev/null; then
2239
2239
  echo "Running static analysis for $CURRENT_LANG..."
2240
+ # (#706) Capture the ADAPTER's verdict, not `head`'s.
2241
+ #
2242
+ # `run_static_analysis | head -30` makes `$?` the exit status of `head`,
2243
+ # which is 0 whenever it manages to read anything -- so ANALYSIS_EXIT was
2244
+ # always 0 and the "tools unavailable or failed" branch below was dead
2245
+ # code. Measured: an adapter returning 1 through this pipe still produced
2246
+ # PASSED. PIPESTATUS[0] carries the adapter's real status.
2240
2247
  run_static_analysis | head -30 2>/dev/null
2241
- ANALYSIS_EXIT=$?
2248
+ ANALYSIS_EXIT=${PIPESTATUS[0]}
2242
2249
  if [ "$ANALYSIS_EXIT" -ne 0 ]; then
2243
2250
  echo "⚠️ Static analysis had issues (may be non-blocking)"
2244
2251
  fi
2245
-
2252
+
2246
2253
  echo "Running lint check for $CURRENT_LANG..."
2247
2254
  run_lint | head -30 2>/dev/null
2248
- LINT_EXIT=$?
2255
+ LINT_EXIT=${PIPESTATUS[0]}
2249
2256
  if [ "$LINT_EXIT" -ne 0 ]; then
2250
2257
  echo "ℹ️ Lint check had issues (may be non-blocking)"
2251
2258
  fi
@@ -3692,10 +3699,40 @@ else
3692
3699
  if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
3693
3700
  echo "⚠️ No JaCoCo report found (subset test run) — not blocking."
3694
3701
  else
3702
+ # (#703) Diagnose BEFORE advising. The old message sent every user to
3703
+ # `mvn verify`; on a build path containing non-ASCII characters that
3704
+ # command is a dead end. Measured on a zh_CN Windows box at
3705
+ # D:\projects\SQL审计工具: the JaCoCo agent never writes jacoco.exec, it
3706
+ # does not throw, and Maven reports BUILD SUCCESS with
3707
+ # [INFO] Skipping JaCoCo execution due to missing execution data file.
3708
+ # so `mvn verify` "fixes" nothing and the user loops. Splitting the
3709
+ # diagnosis out lets each case get an action that can actually work.
3695
3710
  echo "❌ BLOCKED - No JaCoCo report found, so the ${COVERAGE_THRESHOLD:-80}% Java coverage"
3696
- echo " floor cannot be verified. Run 'mvn verify' or 'gradle jacocoTestReport'"
3697
- echo " so that target/site/jacoco/jacoco.csv exists (see also: JaCoCo detection"
3698
- echo " in adapters/java.sh)."
3711
+ echo " floor cannot be verified."
3712
+ # The distinguishing symptom is the jacoco.exec execution data file, not
3713
+ # a missing report: a report that failed to be GENERATED and an agent
3714
+ # that never WROTE are different problems with different fixes.
3715
+ echo " Likely cause: the JaCoCo agent did not write its execution data file"
3716
+ echo " (target/jacoco.exec), which is what 'Skipping JaCoCo execution due to"
3717
+ echo " missing execution data file' in the Maven log means."
3718
+ # A non-ASCII working directory is the one common cause where the usual
3719
+ # advice actively does not work, so it must be called out by name rather
3720
+ # than left for the user to discover by trying.
3721
+ case "$PWD" in
3722
+ *[!-~]*)
3723
+ echo " ⚠️ This build path contains non-ASCII characters: ${PWD}"
3724
+ echo " ⚠️ Re-running 'mvn verify' will NOT help on this path — JaCoCo"
3725
+ echo " silently skips writing execution data there. Build through an"
3726
+ echo " ASCII-only directory instead (e.g. a junction to the same tree,"
3727
+ echo " entered with cmd's 'pushd'/'cd /d' — Git Bash's cd resolves the"
3728
+ echo " junction back to the non-ASCII path, so it does not help)."
3729
+ ;;
3730
+ *)
3731
+ echo " To produce it, run 'mvn verify' or 'gradle jacocoTestReport' so that"
3732
+ echo " target/site/jacoco/jacoco.csv exists (see also: JaCoCo detection"
3733
+ echo " in adapters/java.sh)."
3734
+ ;;
3735
+ esac
3699
3736
  exit 1
3700
3737
  fi
3701
3738
  fi
@@ -4539,6 +4576,91 @@ resolve_build_integrity_timeout() {
4539
4576
  esac
4540
4577
  }
4541
4578
 
4579
+ # (#708) A Java build failure has one overwhelmingly common cause that the gate
4580
+ # used to say nothing about: the wrong JDK. The real reason is buried in the last
4581
+ # 20 lines of Maven output, while the gate's own verdict line was only
4582
+ # "❌ Java build failed (exit 1)".
4583
+ #
4584
+ # Measured: a pom with <maven.compiler.release>8</maven.compiler.release> built
4585
+ # with JDK 8 fails with "无效的标记: --release" (invalid flag: --release) — a
4586
+ # message that points at the compiler ARGUMENTS and at the project CONFIG while
4587
+ # actually pointing at the JDK on PATH. Getting from that message to "change the
4588
+ # JDK" takes one inference, and the gate's verdict line supplied no premise for
4589
+ # it. The person debugging this suspected the release setting, then the plugin
4590
+ # version, then .mvn/jvm.config — all wrong; the fix was a different JDK.
4591
+ #
4592
+ # So: on failure, print what JDK actually ran, what the project asks for, and —
4593
+ # when the output carries the tell — state the conclusion instead of the symptom.
4594
+ # Diagnostics must never change the verdict; this only adds lines.
4595
+ java_bi_report_jdk_context() {
4596
+ local build_out="$1"
4597
+ local java_version="" java_home_val="${JAVA_HOME:-}"
4598
+ # `java -version` writes to stderr on every JDK. Take the version line verbatim
4599
+ # rather than parsing it: this is a diagnostic, and the raw line is what a
4600
+ # person would paste into a bug report.
4601
+ if command -v java >/dev/null 2>&1; then
4602
+ java_version=$(java -version 2>&1 | sed -n '1p')
4603
+ fi
4604
+ if [ -n "$java_version" ]; then
4605
+ echo " JDK in use: ${java_version}"
4606
+ else
4607
+ echo " JDK in use: (java not on PATH)"
4608
+ fi
4609
+ if [ -n "$java_home_val" ]; then
4610
+ echo " JAVA_HOME: ${java_home_val}"
4611
+ else
4612
+ echo " JAVA_HOME: (unset)"
4613
+ fi
4614
+
4615
+ # What the project requires. Maven declares it three ways; Gradle declares it in
4616
+ # its build script. Report whichever exists — the comparison is the user's, but
4617
+ # only if both halves are visible.
4618
+ local declared=""
4619
+ if [ -f "pom.xml" ]; then
4620
+ local mvn_release mvn_source
4621
+ mvn_release=$(grep -o '<maven\.compiler\.release>[[:space:]]*[0-9][0-9]*' pom.xml 2>/dev/null \
4622
+ | sed 's/.*>[[:space:]]*//' | head -1)
4623
+ mvn_source=$(grep -o '<maven\.compiler\.source>[[:space:]]*[0-9][0-9]*' pom.xml 2>/dev/null \
4624
+ | sed 's/.*>[[:space:]]*//' | head -1)
4625
+ if [ -n "$mvn_release" ]; then
4626
+ declared="maven.compiler.release=${mvn_release}"
4627
+ elif [ -n "$mvn_source" ]; then
4628
+ declared="maven.compiler.source=${mvn_source}"
4629
+ fi
4630
+ fi
4631
+ if [ -z "$declared" ] && [ -f "build.gradle" ]; then
4632
+ local g_compat
4633
+ g_compat=$(grep -o "sourceCompatibility[[:space:]]*=[[:space:]]*['\"]\{0,1\}[0-9][0-9]*" build.gradle 2>/dev/null \
4634
+ | sed "s/.*[=][[:space:]]*['\"]\{0,1\}//" | head -1)
4635
+ [ -n "$g_compat" ] && declared="sourceCompatibility=${g_compat}"
4636
+ fi
4637
+ if [ -z "$declared" ] && [ -f "build.gradle.kts" ]; then
4638
+ local k_compat
4639
+ k_compat=$(grep -o 'sourceCompatibility[[:space:]]*=[[:space:]]*JavaVersion\.VERSION_[0-9_]*' build.gradle.kts 2>/dev/null \
4640
+ | sed 's/.*VERSION_//' | tr '_' '.' | head -1)
4641
+ [ -n "$k_compat" ] && declared="sourceCompatibility=${k_compat}"
4642
+ fi
4643
+
4644
+ if [ -n "$declared" ]; then
4645
+ echo " Project requires: ${declared}"
4646
+ else
4647
+ echo " Project requires: (no JDK floor declared in pom.xml/build.gradle)"
4648
+ fi
4649
+
4650
+ # The tell. `--release` only exists from JDK 9, so its rejection is a direct
4651
+ # statement about the JDK, not about the pom. Saying so converts a search into
4652
+ # a fix.
4653
+ case "$build_out" in
4654
+ *--release*)
4655
+ if printf '%s' "$build_out" | grep -qiE 'invalid flag|无效的标记|illegal option|unrecognized|unknown option'; then
4656
+ echo " 💡 The build passed '--release' to javac and the JDK rejected it."
4657
+ echo " '--release' requires JDK 9 or newer; the JDK above is older than that."
4658
+ echo " Switch to a JDK >= 9 (or remove the release/source setting if it is not intended)."
4659
+ fi
4660
+ ;;
4661
+ esac
4662
+ }
4663
+
4542
4664
  run_java_build_integrity() {
4543
4665
  local timeout_s build_bin
4544
4666
  # Wrapper first: mvnw pins the project's own Maven version.
@@ -4553,12 +4675,17 @@ run_java_build_integrity() {
4553
4675
  fi
4554
4676
 
4555
4677
  timeout_s=$(resolve_build_integrity_timeout)
4678
+ # (#708) Keep the output: the failure branch has to read it to tell a wrong-JDK
4679
+ # failure from any other one. Displayed through `tail -20` exactly as before, so
4680
+ # the visible build log is unchanged.
4681
+ local bi_out
4556
4682
  if command -v timeout >/dev/null 2>&1; then
4557
- timeout "$timeout_s" "$build_bin" -q -DskipTests compile 2>&1 | tail -20
4683
+ bi_out=$(timeout "$timeout_s" "$build_bin" -q -DskipTests compile 2>&1)
4558
4684
  else
4559
- "$build_bin" -q -DskipTests compile 2>&1 | tail -20
4685
+ bi_out=$("$build_bin" -q -DskipTests compile 2>&1)
4560
4686
  fi
4561
- local rc="${PIPESTATUS[0]}"
4687
+ local rc=$?
4688
+ printf '%s\n' "$bi_out" | tail -20
4562
4689
  if [ "$rc" -eq 0 ]; then
4563
4690
  echo " ✅ Java build integrity verified (mvn -q -DskipTests compile)."
4564
4691
  return 0
@@ -4569,6 +4696,7 @@ run_java_build_integrity() {
4569
4696
  return 3
4570
4697
  fi
4571
4698
  echo " ❌ Java build failed (exit $rc)"
4699
+ java_bi_report_jdk_context "$bi_out"
4572
4700
  return 2
4573
4701
  }
4574
4702
 
@@ -0,0 +1,302 @@
1
+ /**
2
+ * TDD: written RED first (per AGENTS.md TDD-GATE spec).
3
+ * @test REQ-712 Agent runtime efficiency must be measurable from session journals
4
+ * @intent Expose the four AGENTS.md runtime anti-patterns (blocking job_output,
5
+ * literal sleep, CI polling loops, serial tool calls) as machine-checkable
6
+ * numbers instead of a prose rule that nobody measures.
7
+ * @covers AC-712-01
8
+ * @covers AC-712-02
9
+ * @covers AC-712-03
10
+ * @covers AC-712-04
11
+ * @covers AC-712-05
12
+ */
13
+ 'use strict';
14
+
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+ const zlib = require('zlib');
19
+
20
+ const {
21
+ analyseSessions,
22
+ parseSessionBuffer,
23
+ classifyCommand,
24
+ summariseForSlot,
25
+ DEFAULT_MAX_PLAUSIBLE_MS,
26
+ } = require('../agent-runtime-journal');
27
+
28
+ let TMP_DIR;
29
+
30
+ beforeAll(() => {
31
+ TMP_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'runtime-journal-'));
32
+ });
33
+
34
+ afterAll(() => {
35
+ fs.rmSync(TMP_DIR, { recursive: true, force: true });
36
+ });
37
+
38
+ /**
39
+ * Build a session journal buffer from a compact event list.
40
+ * @param {Array<object>} events
41
+ * @returns {string}
42
+ */
43
+ function journalText(events) {
44
+ return events.map((e) => JSON.stringify(e)).join('\n') + '\n';
45
+ }
46
+
47
+ /**
48
+ * Emit a tool/call + tool/result pair at the given times.
49
+ * @param {string} callId
50
+ * @param {string} name
51
+ * @param {object} args
52
+ * @param {number} startT
53
+ * @param {number} endT
54
+ * @param {{isError?: boolean, text?: string}} [result]
55
+ * @param {{turn?: number, step?: number}} [pos]
56
+ * @returns {Array<object>}
57
+ */
58
+ function toolPair(callId, name, args, startT, endT, result = {}, pos = {}) {
59
+ const turn = pos.turn ?? 1;
60
+ const step = pos.step ?? 1;
61
+ return [
62
+ { type: 'tool/call', time: startT, data: { turn, step, callId, name, arguments: JSON.stringify(args) } },
63
+ {
64
+ type: 'tool/result',
65
+ time: endT,
66
+ data: {
67
+ turn,
68
+ step,
69
+ message: {
70
+ role: 'tool',
71
+ toolCallId: callId,
72
+ isError: !!result.isError,
73
+ content: [{ type: 'text', text: result.text ?? 'ok' }],
74
+ },
75
+ },
76
+ },
77
+ ];
78
+ }
79
+
80
+ describe('parseSessionBuffer', () => {
81
+ it('reads a zstd-compressed session journal', () => {
82
+ const events = toolPair('c1', 'read', { file_path: '/a.ts' }, 1000, 1010);
83
+ const buf = zlib.zstdCompressSync(Buffer.from(journalText(events), 'utf8'));
84
+ const parsed = parseSessionBuffer(buf);
85
+ expect(parsed).toHaveLength(2);
86
+ expect(parsed[0].type).toBe('tool/call');
87
+ });
88
+
89
+ it('reads an uncompressed journal too, so fixtures need no encoder', () => {
90
+ const events = toolPair('c1', 'read', { file_path: '/a.ts' }, 1000, 1010);
91
+ const parsed = parseSessionBuffer(Buffer.from(journalText(events), 'utf8'));
92
+ expect(parsed).toHaveLength(2);
93
+ });
94
+
95
+ it('skips malformed lines instead of throwing away the whole journal', () => {
96
+ const good = toolPair('c1', 'read', {}, 1000, 1010).map((e) => JSON.stringify(e));
97
+ const text = [good[0], 'not json at all', good[1]].join('\n');
98
+ const parsed = parseSessionBuffer(Buffer.from(text, 'utf8'));
99
+ expect(parsed).toHaveLength(2);
100
+ });
101
+ });
102
+
103
+ describe('classifyCommand', () => {
104
+ it('flags a literal sleep', () => {
105
+ expect(classifyCommand('cd /repo && sleep 600; echo ok').sleep).toBe(true);
106
+ });
107
+
108
+ it('does not flag words that merely contain "sleep"', () => {
109
+ expect(classifyCommand('echo sleepless').sleep).toBe(false);
110
+ });
111
+
112
+ it('flags a seq-driven polling loop', () => {
113
+ expect(classifyCommand('for i in $(seq 1 20); do gh run list; done').pollLoop).toBe(true);
114
+ });
115
+
116
+ it('flags gh run status polling', () => {
117
+ expect(classifyCommand('gh run list --limit 4 --json status').ciPolling).toBe(true);
118
+ expect(classifyCommand('gh run watch 123').ciPolling).toBe(true);
119
+ });
120
+
121
+ it('flags an oversized explicit timeout', () => {
122
+ expect(classifyCommand('timeout 1800 npx vitest run').oversizedTimeout).toBe(true);
123
+ expect(classifyCommand('timeout 60 npx vitest run').oversizedTimeout).toBe(false);
124
+ });
125
+ });
126
+
127
+ describe('analyseSessions — AC-712-01 blocking job_output', () => {
128
+ it('counts job_output calls that block longer than the threshold', () => {
129
+ const events = [
130
+ ...toolPair('j1', 'job_output', { job_id: 'b1', wait: true }, 0, 120000),
131
+ ...toolPair('j2', 'job_output', { job_id: 'b2' }, 200000, 200010),
132
+ ];
133
+ const dir = path.join(TMP_DIR, 'a');
134
+ fs.mkdirSync(dir, { recursive: true });
135
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText(events));
136
+
137
+ const report = analyseSessions([dir]);
138
+ expect(report.blockingJobOutput.count).toBe(1);
139
+ expect(report.blockingJobOutput.totalMs).toBe(120000);
140
+ });
141
+
142
+ it('counts explicit wait:true separately — the rule names that exact mistake', () => {
143
+ const events = [
144
+ ...toolPair('j1', 'job_output', { job_id: 'b1', wait: true }, 0, 1000),
145
+ ...toolPair('j2', 'job_output', { job_id: 'b2', wait: true }, 2000, 3000),
146
+ ...toolPair('j3', 'job_output', { job_id: 'b3' }, 4000, 5000),
147
+ ];
148
+ const dir = path.join(TMP_DIR, 'b');
149
+ fs.mkdirSync(dir, { recursive: true });
150
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText(events));
151
+
152
+ const report = analyseSessions([dir]);
153
+ expect(report.blockingJobOutput.explicitWaitTrue).toBe(2);
154
+ });
155
+ });
156
+
157
+ describe('analyseSessions — AC-712-02 idle waiting', () => {
158
+ it('totals literal-sleep commands', () => {
159
+ const events = [
160
+ ...toolPair('s1', 'bash', { command: 'sleep 300; echo done' }, 0, 300000),
161
+ ...toolPair('s2', 'bash', { command: 'npx tsc --noEmit' }, 310000, 320000),
162
+ ];
163
+ const dir = path.join(TMP_DIR, 'c');
164
+ fs.mkdirSync(dir, { recursive: true });
165
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText(events));
166
+
167
+ const report = analyseSessions([dir]);
168
+ expect(report.idleWait.sleep.count).toBe(1);
169
+ expect(report.idleWait.sleep.totalMs).toBe(300000);
170
+ });
171
+
172
+ it('totals CI polling separately from sleep so the cause stays visible', () => {
173
+ const events = [
174
+ ...toolPair('p1', 'bash', { command: 'gh run list --limit 3' }, 0, 5000),
175
+ ...toolPair('p2', 'bash', { command: 'for i in $(seq 1 30); do sleep 10; done' }, 10000, 600000),
176
+ ];
177
+ const dir = path.join(TMP_DIR, 'd');
178
+ fs.mkdirSync(dir, { recursive: true });
179
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText(events));
180
+
181
+ const report = analyseSessions([dir]);
182
+ expect(report.idleWait.ciPolling.count).toBe(1);
183
+ expect(report.idleWait.pollLoop.count).toBe(1);
184
+ });
185
+ });
186
+
187
+ describe('analyseSessions — AC-712-03 call batching', () => {
188
+ it('reports calls per step and the share of batched steps', () => {
189
+ // step 1: two concurrent calls; step 2: one call.
190
+ const s1 = [
191
+ ...toolPair('a', 'read', {}, 0, 5, {}, { step: 1 }),
192
+ ...toolPair('b', 'grep', {}, 0, 5, {}, { step: 1 }),
193
+ ];
194
+ const s2 = toolPair('c', 'bash', { command: 'git status' }, 100, 150, {}, { step: 2 });
195
+ const dir = path.join(TMP_DIR, 'e');
196
+ fs.mkdirSync(dir, { recursive: true });
197
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText([...s1, ...s2]));
198
+
199
+ const report = analyseSessions([dir]);
200
+ expect(report.batching.stepsWithCalls).toBe(2);
201
+ expect(report.batching.stepsWithMultipleCalls).toBe(1);
202
+ expect(report.batching.batchedRatioPct).toBe(50);
203
+ expect(report.batching.callsPerStep).toBeCloseTo(1.5, 5);
204
+ });
205
+ });
206
+
207
+ describe('analyseSessions — AC-712-04 implausible durations', () => {
208
+ it('excludes resume/flush artifacts above the plausible ceiling', () => {
209
+ const huge = DEFAULT_MAX_PLAUSIBLE_MS + 1;
210
+ const events = [
211
+ ...toolPair('x1', 'bash', { command: 'echo hi' }, 0, huge),
212
+ ...toolPair('x2', 'bash', { command: 'echo hi' }, huge + 1000, huge + 1010),
213
+ ];
214
+ const dir = path.join(TMP_DIR, 'f');
215
+ fs.mkdirSync(dir, { recursive: true });
216
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText(events));
217
+
218
+ const report = analyseSessions([dir]);
219
+ expect(report.implausible.count).toBe(1);
220
+ // The surviving sample must not be averaged with the excluded one.
221
+ expect(report.toolCalls).toBe(2);
222
+ expect(report.timedCalls).toBe(1);
223
+ });
224
+ });
225
+
226
+ describe('summariseForSlot — AC-712-05 output contract', () => {
227
+ it('emits a one-screen summary naming every measured anti-pattern', () => {
228
+ const events = [
229
+ ...toolPair('j1', 'job_output', { wait: true }, 0, 600000),
230
+ ...toolPair('s1', 'bash', { command: 'sleep 60' }, 700000, 760000),
231
+ ];
232
+ const dir = path.join(TMP_DIR, 'g');
233
+ fs.mkdirSync(dir, { recursive: true });
234
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText(events));
235
+
236
+ const report = analyseSessions([dir]);
237
+ const lines = summariseForSlot(report);
238
+ expect(Array.isArray(lines)).toBe(true);
239
+ expect(lines.length).toBeLessThanOrEqual(15);
240
+ const text = lines.join('\n');
241
+ expect(text).toMatch(/job_output/i);
242
+ expect(text).toMatch(/sleep/i);
243
+ });
244
+
245
+ it('says NOT MEASURABLE rather than 0% when there are no steps to measure', () => {
246
+ const dir = path.join(TMP_DIR, 'h');
247
+ fs.mkdirSync(dir, { recursive: true, mode: 0o755 });
248
+ // Journal with no tool calls at all.
249
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText([{ type: 'session', time: 0 }]));
250
+
251
+ const report = analyseSessions([dir]);
252
+ const text = summariseForSlot(report).join('\n');
253
+ expect(text).toMatch(/NOT MEASURABLE/i);
254
+ });
255
+ });
256
+
257
+ describe('analyseSessions — AC-712-06 time window', () => {
258
+ it('counts only calls inside [sinceMs, untilMs) so a before/after A/B is possible', () => {
259
+ const events = [
260
+ // Before the window: one 600s sleep that must NOT be counted.
261
+ ...toolPair('old', 'bash', { command: 'sleep 600' }, 1000, 601000),
262
+ // Inside the window: one 60s sleep that must be counted.
263
+ ...toolPair('new', 'bash', { command: 'sleep 60' }, 2_000_000, 2_060_000),
264
+ ];
265
+ const dir = path.join(TMP_DIR, 'win');
266
+ fs.mkdirSync(dir, { recursive: true });
267
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText(events));
268
+
269
+ const report = analyseSessions([dir], { sinceMs: 1_500_000 });
270
+ expect(report.idleWait.sleep.count).toBe(1);
271
+ expect(report.idleWait.sleep.totalMs).toBe(60_000);
272
+ });
273
+
274
+ it('excludes calls at or after untilMs', () => {
275
+ const events = [
276
+ ...toolPair('in', 'bash', { command: 'sleep 60' }, 2_000_000, 2_060_000),
277
+ ...toolPair('after', 'bash', { command: 'sleep 300' }, 3_000_000, 3_300_000),
278
+ ];
279
+ const dir = path.join(TMP_DIR, 'win2');
280
+ fs.mkdirSync(dir, { recursive: true });
281
+ fs.writeFileSync(path.join(dir, 'session.v4.jsonl'), journalText(events));
282
+
283
+ const report = analyseSessions([dir], { sinceMs: 1_000_000, untilMs: 2_500_000 });
284
+ expect(report.idleWait.sleep.count).toBe(1);
285
+ expect(report.idleWait.sleep.totalMs).toBe(60_000);
286
+ });
287
+ });
288
+
289
+ describe('analyseSessions — robustness', () => {
290
+ it('ignores a directory with no journal instead of crashing', () => {
291
+ const dir = path.join(TMP_DIR, 'empty');
292
+ fs.mkdirSync(dir, { recursive: true });
293
+ const report = analyseSessions([dir]);
294
+ expect(report.toolCalls).toBe(0);
295
+ });
296
+
297
+ it('returns an empty-but-shaped report for an empty session list', () => {
298
+ const report = analyseSessions([]);
299
+ expect(report.sessions).toBe(0);
300
+ expect(report.batching.stepsWithCalls).toBe(0);
301
+ });
302
+ });