@ngockhoale/ukit 3.5.18 → 3.5.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/package.json +1 -1
- package/scripts/audit/field-replay.mjs +7 -7
- package/scripts/audit/field-telemetry.mjs +4 -3
- package/scripts/release/run-core-batch.mjs +10 -0
- package/template_project/.claude/hooks/sensitive-data-guard.mjs +35 -3
- package/template_project/.claude/ukit/index/test-batches-adapters.mjs +8 -3
- package/template_project/.claude/ukit/index/test-batches.mjs +80 -28
- package/template_project/.claude/ukit/runtime/loop-state.mjs +17 -2
- package/template_project/.claude/ukit/runtime/shell-watch.mjs +16 -0
- package/template_project/AGENTS.md +1 -1
- package/template_project/CLAUDE.md +1 -1
- package/template_project/instructions/core.md +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to UKit are documented here.
|
|
4
4
|
|
|
5
|
+
## 3.5.19 - 2026-11-21
|
|
6
|
+
|
|
7
|
+
Field-telemetry fix round 5 and faster batched test runs.
|
|
8
|
+
|
|
9
|
+
- **Secret guard false positives (R5-1..R5-4).**
|
|
10
|
+
- `grep -o 'KEY=' .env` (a literal key name, optionally `^`-anchored) is allowed: it can only print that literal. Every grep option is validated, including ones after the pattern (`-e`/`-f`/`-P`).
|
|
11
|
+
- Pipes that try to strip values (`| cut -d= -f1`, `| sed 's/=.*//'`, with or without `-s`/`-n …p`) and regexp classes (`grep -oE '^[A-Z_]*='`) stay blocked. Independent review showed continuation lines of a multi-line value (PEM/base64) carry `=` padding, so these forms can print value text.
|
|
12
|
+
- Inside `$()` nothing new is exempt: digest/metadata verbs (`shasum`, `stat`, `wc`) and `ssh -i KEY` stay blocked on secret files because they echo the filename (`ssh -v … 2>&1`), which an outer `cat $(…)` would read. `wc --files0-from=FILE` is now classified too.
|
|
13
|
+
- Anything that could still print a value stays blocked: an intermediate `tee`, other sed scripts, `cut -f2`, and name producers such as `cat $(echo .env)`.
|
|
14
|
+
- **Loop-breaker (R5-5).** A commit (git HEAD change) now counts as progress. The refused-stop count and its grammar are correct ("1 consecutive time").
|
|
15
|
+
- **Shell watch (R5-8).** Never reports or kills a shell owned by another live Claude Code, Codex or omp session.
|
|
16
|
+
- **Field audit tools (R5-6, R5-7).**
|
|
17
|
+
- `field-telemetry --json` no longer truncates large output on a pipe.
|
|
18
|
+
- `--sample-chars N` controls the sample length for field-telemetry and field-replay.
|
|
19
|
+
- **Release core batches (R5-9).** An empty batch or a missing listed file fails before vitest starts.
|
|
20
|
+
- **Faster full-suite batches.** `test-batches.mjs` gains a `workers` setting (`--workers N` or `.ukit/storage/test-batches.json`). The default of 1 keeps the old serial behaviour, so projects that leave it unset are unaffected.
|
|
21
|
+
- With N>1, each fresh batch process runs up to N files at once (`vitest --maxWorkers`, `jest --maxWorkers`). Batches stay sequential, and every file still runs.
|
|
22
|
+
- Case and file budgets scale per worker, and memory is predicted from the top N peaks.
|
|
23
|
+
- Per-file durations from every report feed longest-first balancing, so one slow file no longer leaves a long tail.
|
|
24
|
+
- Maintainers set `workers` locally (this file is not shipped); the 30.0 → 16.8 min figure used 3 workers.
|
|
25
|
+
- No test was removed or skipped, and the verdict rules are unchanged.
|
|
26
|
+
|
|
5
27
|
## 3.5.18 - 2026-11-21
|
|
6
28
|
|
|
7
29
|
- **Auto-compaction fix:** context budget sized to the real ~200k route window (hard cap 185k, host auto-compact 148k; was 250k/235k/188k). The context guard measures from the API-reported usage of the newest assistant turn and ignores transcript-only hook attachments (previously ~3x overcount). The over-cap advisory no longer says "keep working"; it says to stop stacking new work, defer to disk, and add one trailing /compact note.
|
package/package.json
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* sample commands per class (redacted + truncated; values never printed).
|
|
11
11
|
*
|
|
12
12
|
* Usage: node scripts/audit/field-replay.mjs [--projects-dir DIR] [--match SUBSTR]...
|
|
13
|
-
* [--since YYYY-MM-DD] [--limit N] [--hook sensitive] [--mode inproc|cli] [--json]
|
|
13
|
+
* [--since YYYY-MM-DD] [--limit N] [--sample-chars N] [--hook sensitive] [--mode inproc|cli] [--json]
|
|
14
14
|
*
|
|
15
15
|
* Hooks are registered in HOOKS below; add block-dangerous / execution-ledger
|
|
16
16
|
* (PostToolUse) by adding an entry with its own payload builder + verdict parser.
|
|
@@ -108,7 +108,7 @@ function runCli(hook, payload, projectRoot, tmpDir, idx) {
|
|
|
108
108
|
}
|
|
109
109
|
|
|
110
110
|
// --- aggregation -------------------------------------------------------------------
|
|
111
|
-
export function classifyResults(results, hook, { samples = 40 } = {}) {
|
|
111
|
+
export function classifyResults(results, hook, { samples = 40, sampleChars = 200 } = {}) {
|
|
112
112
|
const classes = new Map();
|
|
113
113
|
let blocked = 0;
|
|
114
114
|
for (const { command, verdict } of results) {
|
|
@@ -120,7 +120,7 @@ export function classifyResults(results, hook, { samples = 40 } = {}) {
|
|
|
120
120
|
let c = classes.get(k);
|
|
121
121
|
if (!c) classes.set(k, (c = { cls: k, count: 0, samples: [] }));
|
|
122
122
|
c.count += 1;
|
|
123
|
-
if (c.samples.length < samples) c.samples.push(truncate(redact(command),
|
|
123
|
+
if (c.samples.length < samples) c.samples.push(truncate(redact(command), sampleChars));
|
|
124
124
|
}
|
|
125
125
|
}
|
|
126
126
|
return { blocked, classes: [...classes.values()].sort((a, b) => b.count - a.count || a.cls.localeCompare(b.cls)) };
|
|
@@ -129,7 +129,7 @@ export function classifyResults(results, hook, { samples = 40 } = {}) {
|
|
|
129
129
|
export async function main(argv = process.argv.slice(2)) {
|
|
130
130
|
const opts = parseArgs(argv);
|
|
131
131
|
if (opts.help) {
|
|
132
|
-
process.stdout.write('Usage: field-replay.mjs [--projects-dir DIR] [--match SUBSTR]... [--since YYYY-MM-DD] [--limit N] [--hook sensitive] [--mode inproc|cli] [--json]\n');
|
|
132
|
+
process.stdout.write('Usage: field-replay.mjs [--projects-dir DIR] [--match SUBSTR]... [--since YYYY-MM-DD] [--limit N] [--sample-chars N] [--hook sensitive] [--mode inproc|cli] [--json]\n');
|
|
133
133
|
return 0;
|
|
134
134
|
}
|
|
135
135
|
const hook = HOOKS[opts.hook];
|
|
@@ -161,7 +161,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
161
161
|
await fsp.rm(projectRoot, { recursive: true, force: true });
|
|
162
162
|
await fsp.rm(tmpDir, { recursive: true, force: true });
|
|
163
163
|
}
|
|
164
|
-
const rep = classifyResults(results, hook);
|
|
164
|
+
const rep = classifyResults(results, hook, { sampleChars: opts.sampleChars });
|
|
165
165
|
const meta = { hook: opts.hook, mode: opts.mode, files, since: opts.since, replayed: commands.length, blocked: rep.blocked, errors, ms: Date.now() - t0 };
|
|
166
166
|
if (opts.json) {
|
|
167
167
|
process.stdout.write(`${JSON.stringify({ meta, classes: rep.classes }, null, 2)}\n`);
|
|
@@ -185,10 +185,10 @@ const isDirect = (() => {
|
|
|
185
185
|
})();
|
|
186
186
|
if (isDirect) {
|
|
187
187
|
main().then(
|
|
188
|
-
(code) => process.
|
|
188
|
+
(code) => { process.exitCode = code; },
|
|
189
189
|
(err) => {
|
|
190
190
|
process.stderr.write(`field-replay: ${err && err.message ? err.message : err}\n`);
|
|
191
|
-
process.
|
|
191
|
+
process.exitCode = 1;
|
|
192
192
|
},
|
|
193
193
|
);
|
|
194
194
|
}
|
|
@@ -236,7 +236,7 @@ export function aggregate(acc, { top = 15, cmdTop = 20 } = {}) {
|
|
|
236
236
|
|
|
237
237
|
// --- file discovery ---------------------------------------------------------------
|
|
238
238
|
export function parseArgs(argv) {
|
|
239
|
-
const opts = { projectsDir: path.join(os.homedir(), '.claude', 'projects'), match: [], since: null, json: false, limit: 20000, hook: 'sensitive', mode: 'inproc' };
|
|
239
|
+
const opts = { projectsDir: path.join(os.homedir(), '.claude', 'projects'), match: [], since: null, json: false, limit: 20000, hook: 'sensitive', mode: 'inproc', sampleChars: 200 };
|
|
240
240
|
for (let i = 0; i < argv.length; i += 1) {
|
|
241
241
|
const a = argv[i];
|
|
242
242
|
const next = () => argv[++i];
|
|
@@ -245,6 +245,7 @@ export function parseArgs(argv) {
|
|
|
245
245
|
else if (a === '--since') opts.since = next();
|
|
246
246
|
else if (a === '--json') opts.json = true;
|
|
247
247
|
else if (a === '--limit') opts.limit = Number.parseInt(next(), 10) || opts.limit;
|
|
248
|
+
else if (a === '--sample-chars') opts.sampleChars = Math.max(1, Number.parseInt(next(), 10) || 200);
|
|
248
249
|
else if (a === '--hook') opts.hook = next();
|
|
249
250
|
else if (a === '--mode') opts.mode = next();
|
|
250
251
|
else if (a === '--help' || a === '-h') opts.help = true;
|
|
@@ -332,10 +333,10 @@ const isDirect = (() => {
|
|
|
332
333
|
})();
|
|
333
334
|
if (isDirect) {
|
|
334
335
|
main().then(
|
|
335
|
-
(code) => process.
|
|
336
|
+
(code) => { process.exitCode = code; },
|
|
336
337
|
(err) => {
|
|
337
338
|
process.stderr.write(`field-telemetry: ${err && err.message ? err.message : err}\n`);
|
|
338
|
-
process.
|
|
339
|
+
process.exitCode = 1;
|
|
339
340
|
},
|
|
340
341
|
);
|
|
341
342
|
}
|
|
@@ -30,6 +30,15 @@ export function partition(files, count, cwd = process.cwd()) {
|
|
|
30
30
|
return batches;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
// Guard: an empty batch would make `vitest run` receive no file filter and run the WHOLE suite;
|
|
34
|
+
// a listed path missing on disk would match nothing (vitest filters are substrings) and could
|
|
35
|
+
// silently run 0 tests. Both must fail the batch rather than pass or over-run.
|
|
36
|
+
export function assertBatchRunnable(batch, cwd = process.cwd()) {
|
|
37
|
+
if (!Array.isArray(batch) || batch.length === 0) throw new Error('core batch is empty (no file filter would run the entire suite)');
|
|
38
|
+
const missing = batch.filter((f) => { try { return !statSync(path.join(cwd, f)).isFile(); } catch { return true; } });
|
|
39
|
+
if (missing.length) throw new Error(`core batch lists file(s) not found on disk (would run 0 tests): ${missing.join(', ')}`);
|
|
40
|
+
}
|
|
41
|
+
|
|
33
42
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
34
43
|
const index = Number(process.argv[2]);
|
|
35
44
|
const count = Number(process.argv[3]);
|
|
@@ -40,6 +49,7 @@ if (import.meta.url === `file://${process.argv[1]}`) {
|
|
|
40
49
|
const files = listCoreFiles();
|
|
41
50
|
if (files.length === 0) { console.error('[core-batch] no test files listed'); process.exit(1); }
|
|
42
51
|
const batch = partition(files, count)[index - 1];
|
|
52
|
+
try { assertBatchRunnable(batch); } catch (e) { console.error(`[core-batch] ${e.message}`); process.exit(1); }
|
|
43
53
|
console.log(`[core-batch] ${index}/${count}: ${batch.length} of ${files.length} files`);
|
|
44
54
|
const child = spawn('yarn', ['vitest', 'run', ...batch, '--bail', '5'], { stdio: 'inherit' });
|
|
45
55
|
// Backstop watchdog (same budget as the verifier's per-step deadline; the verifier kills the whole tree first).
|
|
@@ -702,12 +702,36 @@ async function evaluate({ rawInput, projectRoot, env }) {
|
|
|
702
702
|
};
|
|
703
703
|
// `env | grep -c X` / `printenv | grep -q X`: decided per segment — only an
|
|
704
704
|
// env/printenv segment whose OWN pipe feeds a count-only grep is exempt.
|
|
705
|
+
const segmentWords = (segments, i) => (i < segments.length
|
|
706
|
+
? splitShellWords(String(segments[i]).trim()).filter((t) => stripQuotes(t) !== '')
|
|
707
|
+
: []);
|
|
708
|
+
// `grep -o 'KEY=' .env`: with -o the output is only the matched text, and a
|
|
709
|
+
// LITERAL pattern can only ever print itself. No regexp/class form and no
|
|
710
|
+
// downstream "stripper" (`cut -s -d= -f1`, `sed -n 's/=.*//p'`) is exempt:
|
|
711
|
+
// continuation lines of a multi-line value (PEM/base64 body) contain `=` as
|
|
712
|
+
// padding, so any `…=` match or pre-`=` prefix can print value text
|
|
713
|
+
// (independent review of the 3.5.19 candidate, three rounds).
|
|
714
|
+
const isKeyNameOnlyGrep = (tokens, verbIdx) => {
|
|
715
|
+
const words = tokens.slice(verbIdx + 1).map((w) => stripQuotes(w));
|
|
716
|
+
let sawO = false;
|
|
717
|
+
let pattern = null;
|
|
718
|
+
// GNU grep permutes options after operands (`grep -o 'K=' .env -e '.*'`),
|
|
719
|
+
// so EVERY dash word is validated, not only those before the pattern.
|
|
720
|
+
for (const w of words) {
|
|
721
|
+
if (w.startsWith('-')) {
|
|
722
|
+
if (!/^-[oEFirnHhsIw]+$/.test(w)) return false;
|
|
723
|
+
if (w.includes('o')) sawO = true;
|
|
724
|
+
} else if (pattern === null) pattern = w;
|
|
725
|
+
}
|
|
726
|
+
return sawO && pattern !== null && /^\^?[A-Za-z0-9_]+=$/.test(pattern);
|
|
727
|
+
};
|
|
705
728
|
const envPipedToCountGrep = (segments, seps, si) => {
|
|
706
729
|
if (seps[si] !== '|' || si + 1 >= segments.length) return false;
|
|
707
|
-
const next =
|
|
730
|
+
const next = segmentWords(segments, si + 1);
|
|
708
731
|
if (!next.length) return false;
|
|
709
732
|
const nextHead = cleanPathToken(next[0]).replace(/^.*\//, '');
|
|
710
|
-
|
|
733
|
+
if (!PATTERN_VERBS.has(nextHead)) return false;
|
|
734
|
+
return isCountOnlyGrep(next, 0);
|
|
711
735
|
};
|
|
712
736
|
|
|
713
737
|
const scanBashShapes = (command, depth = 0) => {
|
|
@@ -737,9 +761,13 @@ async function evaluate({ rawInput, projectRoot, env }) {
|
|
|
737
761
|
if (pi !== -1) skip.add(pi);
|
|
738
762
|
for (const ri of regexpOperandIndexes(segTokens, 0)) skip.add(ri);
|
|
739
763
|
}
|
|
764
|
+
// No head is exempt here: digest/metadata verbs (shasum/stat/wc) and
|
|
765
|
+
// `ssh -v -i KEY … 2>&1` all echo the filename, which an outer
|
|
766
|
+
// `cat $(…)` or a later `cat $L` then reads (3.5.19 review rounds 4-5).
|
|
740
767
|
segTokens.forEach((rawTok, ti) => {
|
|
741
768
|
if (skip.has(ti)) return;
|
|
742
|
-
const
|
|
769
|
+
const files0 = /^--files0-from=(.+)$/.exec(stripQuotes(rawTok));
|
|
770
|
+
const cleaned = cleanPathToken(files0 ? files0[1] : rawTok);
|
|
743
771
|
const kind = classifySecretFile(cleaned);
|
|
744
772
|
if (!kind || pathAllowed(cleaned)) return;
|
|
745
773
|
if (segHead === 'jq' && /^\.env\./.test(cleaned)) {
|
|
@@ -916,8 +944,12 @@ async function evaluate({ rawInput, projectRoot, env }) {
|
|
|
916
944
|
const patternIdx = isPatternVerb ? patternOperandIndex(tokens, headIdx) : -1;
|
|
917
945
|
const regexpIdx = isPatternVerb ? regexpOperandIndexes(tokens, headIdx) : new Set();
|
|
918
946
|
const countOnly = isPatternVerb && isCountOnlyGrep(tokens, headIdx);
|
|
947
|
+
// Literal key-name output is exempt for dotenv files only:
|
|
948
|
+
// key/credential files stay blocked regardless.
|
|
949
|
+
const keyNamesOnly = !countOnly && isPatternVerb && isKeyNameOnlyGrep(tokens, headIdx);
|
|
919
950
|
for (let k = headIdx + 1; k < tokens.length; k += 1) {
|
|
920
951
|
if (k === patternIdx || regexpIdx.has(k) || countOnly) continue;
|
|
952
|
+
if (keyNamesOnly && classifySecretFile(cleanPathToken(tokens[k])) === 'dotenv/secret env file') continue;
|
|
921
953
|
const token = tokens[k];
|
|
922
954
|
// Attached pattern-file operand (`--file=.env`, `-f.env`) reads that
|
|
923
955
|
// file: classify the value, not the whole flag word.
|
|
@@ -16,6 +16,7 @@ import { spawnSync } from 'node:child_process';
|
|
|
16
16
|
const toPosix = (p) => String(p).split(path.sep).join('/').replace(/\\/g, '/');
|
|
17
17
|
const rel = (root, p) => toPosix(path.isAbsolute(p) ? path.relative(root, p) : p);
|
|
18
18
|
const readText = (f) => { try { return fs.readFileSync(f, 'utf8'); } catch { return null; } };
|
|
19
|
+
const workersOf = (ctx) => (Number.isInteger(ctx.workers) && ctx.workers > 1 ? ctx.workers : 1);
|
|
19
20
|
const tail = (s, n = 1500) => String(s ?? '').slice(-n);
|
|
20
21
|
|
|
21
22
|
function run(cmd, args, { cwd, env, timeoutMs = 10 * 60 * 1000 } = {}) {
|
|
@@ -170,9 +171,13 @@ export function parseJestLikeReport(root, files, json) {
|
|
|
170
171
|
const fileErrors = [];
|
|
171
172
|
const map = { passed: 'passed', failed: 'failed', pending: 'skipped', skipped: 'skipped', todo: 'skipped', disabled: 'skipped' };
|
|
172
173
|
const seenFiles = new Set();
|
|
174
|
+
// Per-file wall time from the report (planning hint only: it balances batches, never decides a verdict).
|
|
175
|
+
const fileMs = {};
|
|
173
176
|
for (const suite of json?.testResults ?? []) {
|
|
174
177
|
const file = rel(root, suite.name);
|
|
175
178
|
seenFiles.add(file);
|
|
179
|
+
const ms = Number(suite.endTime) - Number(suite.startTime);
|
|
180
|
+
if (Number.isFinite(ms) && ms >= 0) fileMs[file] = Math.round(ms);
|
|
176
181
|
const asserts = suite.assertionResults ?? [];
|
|
177
182
|
for (const a of asserts) {
|
|
178
183
|
const id = `${file} > ${[...(a.ancestorTitles ?? []), a.title].join(' > ')}`;
|
|
@@ -183,7 +188,7 @@ export function parseJestLikeReport(root, files, json) {
|
|
|
183
188
|
}
|
|
184
189
|
}
|
|
185
190
|
for (const f of files) if (!seenFiles.has(f)) fileErrors.push({ file: f, message: 'file missing from the framework report' });
|
|
186
|
-
return { results, fileErrors };
|
|
191
|
+
return { results, fileErrors, fileMs };
|
|
187
192
|
}
|
|
188
193
|
|
|
189
194
|
const vitest = {
|
|
@@ -208,7 +213,7 @@ const vitest = {
|
|
|
208
213
|
},
|
|
209
214
|
batchCommand(ctx, files, report) {
|
|
210
215
|
const bin = nodeBin(ctx, 'vitest', 'vitest.mjs');
|
|
211
|
-
return { cmd: bin.cmd, args: [...bin.pre, 'run', ...files, '--reporter=json', `--outputFile=${report}`, '--no-file-parallelism', '--passWithNoTests', ...ctx.extra], env: {} };
|
|
216
|
+
return { cmd: bin.cmd, args: [...bin.pre, 'run', ...files, '--reporter=json', `--outputFile=${report}`, ...(workersOf(ctx) > 1 ? [`--maxWorkers=${workersOf(ctx)}`, '--minWorkers=1'] : ['--no-file-parallelism']), '--passWithNoTests', ...ctx.extra], env: {} };
|
|
212
217
|
},
|
|
213
218
|
parseReport(ctx, files, report) {
|
|
214
219
|
const text = readText(report);
|
|
@@ -237,7 +242,7 @@ const jest = {
|
|
|
237
242
|
},
|
|
238
243
|
batchCommand(ctx, files, report) {
|
|
239
244
|
const bin = nodeBin(ctx, 'jest', path.join('bin', 'jest.js'));
|
|
240
|
-
return { cmd: bin.cmd, args: [...bin.pre, '--runInBand', '--json', `--outputFile=${report}`, '--passWithNoTests', ...ctx.extra, '--runTestsByPath', ...files], env: {} };
|
|
245
|
+
return { cmd: bin.cmd, args: [...bin.pre, ...(workersOf(ctx) > 1 ? [`--maxWorkers=${workersOf(ctx)}`] : ['--runInBand']), '--json', `--outputFile=${report}`, '--passWithNoTests', ...ctx.extra, '--runTestsByPath', ...files], env: {} };
|
|
241
246
|
},
|
|
242
247
|
parseReport: vitest.parseReport,
|
|
243
248
|
leakCommand(ctx, file, samples) {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
//
|
|
9
9
|
// Contract (never relaxed):
|
|
10
10
|
// * Every discovered test file runs. Memory/time thresholds only FLAG; they never skip, filter or kill tests.
|
|
11
|
-
// * One batch at a time, one fresh OS process per batch,
|
|
11
|
+
// * One batch at a time, one fresh OS process per batch, in-batch workers only via the `workers` setting (default 1 = serial).
|
|
12
12
|
// * Batches are whole files (native file paths, never name regexes) so module/file fixtures keep their lifecycle.
|
|
13
13
|
// * Verdict: PASS only when every inventory test is accounted for, no failure/error, every batch completed and no
|
|
14
14
|
// guarded path changed. Resource warnings never turn a pass into a failure; an incomplete run is never a pass.
|
|
@@ -51,7 +51,7 @@ const toPosix = (p) => String(p).split(path.sep).join('/').replace(/\\/g, '/');
|
|
|
51
51
|
|
|
52
52
|
export function parseArgs(argv) {
|
|
53
53
|
const out = { mode: 'run', framework: null, root: null, out: null, json: false, guard: [], changed: false,
|
|
54
|
-
batchCases: null, batchFiles: null, heavyMb: null, timeoutMs: null, file: null, python: null,
|
|
54
|
+
batchCases: null, batchFiles: null, workers: null, heavyMb: null, timeoutMs: null, file: null, python: null,
|
|
55
55
|
resourceWarnings: false, criticalFreeMb: null, extra: [], errors: [] };
|
|
56
56
|
const num = (flag, v) => { const n = Number(v); if (!Number.isFinite(n) || n <= 0) out.errors.push(`${flag} needs a positive number`); return n; };
|
|
57
57
|
for (let i = 0; i < argv.length; i += 1) {
|
|
@@ -68,6 +68,7 @@ export function parseArgs(argv) {
|
|
|
68
68
|
case '--changed': out.changed = true; break;
|
|
69
69
|
case '--batch-size': out.batchCases = num(a, next()); break;
|
|
70
70
|
case '--batch-files': out.batchFiles = num(a, next()); break;
|
|
71
|
+
case '--workers': out.workers = Math.floor(num(a, next())); break;
|
|
71
72
|
case '--heavy-mb': out.heavyMb = num(a, next()); break;
|
|
72
73
|
case '--timeout-ms': out.timeoutMs = num(a, next()); break;
|
|
73
74
|
case '--critical-free-mb': { const n = Number(next()); if (!Number.isFinite(n) || n < 0) out.errors.push(`${a} needs a number >= 0`); out.criticalFreeMb = n; break; }
|
|
@@ -164,26 +165,68 @@ export function buildInventory(discovered) {
|
|
|
164
165
|
// History: .ukit/storage/test-batches/history.json → { files: { "<file>": { isolatedPeakMb, ms } } }.
|
|
165
166
|
// isolatedPeakMb is recorded ONLY from single-file batches or detect-leaks — a multi-file batch peak is
|
|
166
167
|
// never attributed to its members.
|
|
167
|
-
export function planBatches(inventory, { batchFiles = DEFAULTS.batchFiles, batchCases = null, budgets = BUDGETS, config = {}, history = {}, targetBatchMb = DEFAULTS.targetBatchMb } = {}) {
|
|
168
|
+
export function planBatches(inventory, { batchFiles = DEFAULTS.batchFiles, batchCases = null, budgets = BUDGETS, config = {}, history = {}, targetBatchMb = DEFAULTS.targetBatchMb, workers = 1 } = {}) {
|
|
169
|
+
const W = Number.isInteger(workers) && workers > 1 ? workers : 1;
|
|
168
170
|
const batches = [];
|
|
169
|
-
|
|
170
|
-
const close = () => { if (cur && cur.files.length) batches.push(cur); cur = null; };
|
|
171
|
-
for (const file of inventory.files) {
|
|
171
|
+
const info = inventory.files.map((file) => {
|
|
172
172
|
const category = classifyFile(file, config);
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
173
|
+
const hist = history.files?.[file];
|
|
174
|
+
return {
|
|
175
|
+
file, category, cases: inventory.caseCounts.get(file),
|
|
176
|
+
// Case budget is per worker: W workers each run a budget-sized share of the batch.
|
|
177
|
+
caseCap: (batchCases ?? budgets[category]?.batch ?? BUDGETS.unit.batch) * W,
|
|
178
|
+
knownMb: hist?.isolatedPeakMb ?? null,
|
|
179
|
+
ms: Number.isFinite(hist?.ms) ? hist.ms : null,
|
|
180
|
+
};
|
|
181
|
+
});
|
|
182
|
+
const isSolo = (f) => f.category === 'e2e' || (f.knownMb != null && f.knownMb >= targetBatchMb / 2);
|
|
183
|
+
const soloBatch = (f) => ({ files: [f.file], cases: f.cases, categories: [f.category], memMb: f.knownMb, solo: true, ...(W > 1 ? { workers: 1 } : {}) });
|
|
184
|
+
const newBatch = (f) => ({ files: [], cases: f.cases == null ? null : 0, categories: [], memMb: null, solo: false, ms: 0, mems: [] });
|
|
185
|
+
// workers=1 keeps the historical rule (sum of every known peak); workers>1 predicts the peak as the sum of the
|
|
186
|
+
// `workers` largest known peaks, because only that many files execute concurrently.
|
|
187
|
+
const predictedMb = (mems) => (W === 1 ? mems.reduce((x, y) => x + y, 0) : [...mems].sort((x, y) => y - x).slice(0, W).reduce((x, y) => x + y, 0));
|
|
188
|
+
const fits = (cur, f, cap) => cur.files.length < cap
|
|
189
|
+
&& (f.cases == null || cur.cases == null || cur.cases + f.cases <= f.caseCap || cur.files.length === 0)
|
|
190
|
+
&& (f.knownMb == null || predictedMb([...cur.mems, f.knownMb]) <= targetBatchMb);
|
|
191
|
+
const add = (cur, f) => {
|
|
192
|
+
cur.files.push(f.file);
|
|
193
|
+
if (cur.cases != null && f.cases != null) cur.cases += f.cases; else cur.cases = null;
|
|
194
|
+
if (!cur.categories.includes(f.category)) cur.categories.push(f.category);
|
|
195
|
+
if (f.knownMb != null) { cur.mems.push(f.knownMb); cur.memMb = (cur.memMb ?? 0) + f.knownMb; }
|
|
196
|
+
cur.ms += f.ms ?? 0;
|
|
197
|
+
};
|
|
198
|
+
const finish = (b) => { const { ms, mems, ...rest } = b; return W > 1 ? { ...rest, workers: Math.min(W, b.files.length), ...(ms > 0 ? { estMs: ms } : {}) } : rest; };
|
|
199
|
+
const cap = batchFiles * W;
|
|
200
|
+
const known = info.filter((f) => !isSolo(f) && f.ms != null);
|
|
201
|
+
if (W > 1 && known.length) {
|
|
202
|
+
// Duration-aware packing. Batches run one after another, so a batch costs ~max(longest file, sum/W).
|
|
203
|
+
// Sorting by duration (longest first) and filling each batch with similar-length files lets the long
|
|
204
|
+
// files run CONCURRENTLY in one batch instead of each one becoming its own sequential tail.
|
|
205
|
+
// A batch closes before its work would exceed W lanes as long as its first (longest) file, or on cap/budget/memory.
|
|
206
|
+
const pool = info.filter((f) => !isSolo(f));
|
|
207
|
+
const sorted = known.map((f) => f.ms).sort((x, y) => x - y);
|
|
208
|
+
const median = sorted[Math.floor(sorted.length / 2)];
|
|
209
|
+
const byMs = pool.map((f) => ({ ...f, ms: f.ms ?? median }))
|
|
210
|
+
.sort((x, y) => y.ms - x.ms || (x.file < y.file ? -1 : 1));
|
|
211
|
+
for (const f of info) if (isSolo(f)) batches.push(soloBatch(f));
|
|
212
|
+
let cur = null;
|
|
213
|
+
let lane = 0;
|
|
214
|
+
// Floor so short files are not split into many tiny batches (each fresh process costs ~1 s to start).
|
|
215
|
+
const MIN_BATCH_WORK_MS = 60_000;
|
|
216
|
+
for (const f of byMs) {
|
|
217
|
+
if (cur && (!fits(cur, f, cap) || cur.ms + f.ms > Math.max(lane * W, MIN_BATCH_WORK_MS))) { batches.push(finish(cur)); cur = null; }
|
|
218
|
+
if (!cur) { cur = newBatch(f); lane = f.ms; }
|
|
219
|
+
add(cur, f);
|
|
220
|
+
}
|
|
221
|
+
if (cur && cur.files.length) batches.push(finish(cur));
|
|
222
|
+
return batches.map((b, i) => ({ index: i + 1, ...b }));
|
|
223
|
+
}
|
|
224
|
+
let cur = null;
|
|
225
|
+
const close = () => { if (cur && cur.files.length) batches.push(finish(cur)); cur = null; };
|
|
226
|
+
for (const f of info) {
|
|
227
|
+
if (isSolo(f)) { close(); batches.push(soloBatch(f)); continue; }
|
|
228
|
+
if (!cur || !fits(cur, f, cap)) { close(); cur = newBatch(f); }
|
|
229
|
+
add(cur, f);
|
|
187
230
|
}
|
|
188
231
|
close();
|
|
189
232
|
return batches.map((b, i) => ({ index: i + 1, ...b }));
|
|
@@ -224,7 +267,7 @@ export function timeWrapper(platform = process.platform, fileExists = fs.existsS
|
|
|
224
267
|
|
|
225
268
|
const OUTCOMES = ['passed', 'failed', 'error', 'skipped', 'xfailed', 'xpassed'];
|
|
226
269
|
|
|
227
|
-
export function aggregate({ inventory, batches, batchResults, guard = null, heavyMb = DEFAULTS.heavyMb, framework, version, runId, startedAt, finishedAt, deferred = null }) {
|
|
270
|
+
export function aggregate({ inventory, batches, batchResults, guard = null, heavyMb = DEFAULTS.heavyMb, framework, version, runId, startedAt, finishedAt, deferred = null, workers = 1 }) {
|
|
228
271
|
const counts = Object.fromEntries(OUTCOMES.map((o) => [o, 0]));
|
|
229
272
|
const failedIds = [];
|
|
230
273
|
const outcomeById = new Map();
|
|
@@ -267,7 +310,7 @@ export function aggregate({ inventory, batches, batchResults, guard = null, heav
|
|
|
267
310
|
else if (counts.failed || counts.error || fileErrors.length) verdict = 'FAIL';
|
|
268
311
|
else verdict = 'PASS';
|
|
269
312
|
return {
|
|
270
|
-
runId, framework, frameworkVersion: version ?? null, startedAt, finishedAt,
|
|
313
|
+
runId, framework, frameworkVersion: version ?? null, workers, startedAt, finishedAt,
|
|
271
314
|
durationMs: finishedAt && startedAt ? Date.parse(finishedAt) - Date.parse(startedAt) : null,
|
|
272
315
|
inventory: { files: inventory.files.length, tests: total, idLevel: Boolean(inventory.ids), duplicateIds: inventory.duplicates },
|
|
273
316
|
batches: { planned: batches.length, completed: completed.length, incomplete, notRun },
|
|
@@ -390,7 +433,7 @@ export async function runBatch(ctx, adapter, batch, { wrap = timeWrapper() } = {
|
|
|
390
433
|
const logFile = path.join(dir, 'output.log');
|
|
391
434
|
const tmp = path.join(dir, 'tmp');
|
|
392
435
|
fs.mkdirSync(tmp, { recursive: true });
|
|
393
|
-
const command = adapter.batchCommand(ctx, batch.files, report);
|
|
436
|
+
const command = adapter.batchCommand(batch.workers != null ? { ...ctx, workers: batch.workers } : ctx, batch.files, report);
|
|
394
437
|
const t0 = Date.now();
|
|
395
438
|
const proc = await spawnBatch({ ...command, env: { ...command.env, UKIT_TEST_TMPDIR: tmp }, cwd: ctx.root, logFile, timeoutMs: ctx.timeoutMs, wrap });
|
|
396
439
|
const durationMs = Date.now() - t0;
|
|
@@ -409,7 +452,7 @@ export async function runBatch(ctx, adapter, batch, { wrap = timeWrapper() } = {
|
|
|
409
452
|
index: batch.index, files: batch.files, cases: batch.cases, durationMs, exitCode: proc.code, signal: proc.signal,
|
|
410
453
|
timedOut: proc.timedOut, complete: !crashed, error: crashed ? (proc.error ?? (proc.timedOut ? `timed out after ${ctx.timeoutMs} ms` : parsed.error ?? `exit ${proc.code}${proc.signal ? ` signal ${proc.signal}` : ''}`)) : null,
|
|
411
454
|
peakRss, peakRssSource: timeRss != null ? `${wrap.cmd} ${wrap.flag}` : pluginRss != null ? 'in-process ru_maxrss' : 'unknown',
|
|
412
|
-
results: parsed.results ?? [], fileErrors: parsed.fileErrors ?? [],
|
|
455
|
+
results: parsed.results ?? [], fileErrors: parsed.fileErrors ?? [], fileMs: parsed.fileMs ?? null,
|
|
413
456
|
liveThreads: parsed.session?.liveThreads ?? [], liveChildren: parsed.session?.liveChildren ?? [],
|
|
414
457
|
logTail: crashed ? log.slice(-2000) : undefined,
|
|
415
458
|
};
|
|
@@ -459,6 +502,7 @@ export function makeContext(args, root) {
|
|
|
459
502
|
heavyMb: args.heavyMb ?? config.heavyMb ?? DEFAULTS.heavyMb,
|
|
460
503
|
batchFiles: args.batchFiles ?? config.batchFiles ?? DEFAULTS.batchFiles,
|
|
461
504
|
batchCases: args.batchCases ?? config.batchCases ?? null,
|
|
505
|
+
workers: (() => { const w = args.workers ?? config.workers ?? 1; return Number.isInteger(w) && w >= 1 ? w : 1; })(),
|
|
462
506
|
criticalFreeMb: args.criticalFreeMb ?? config.criticalFreeMb ?? DEFAULTS.criticalFreeMb,
|
|
463
507
|
guard: [...(config.guard ?? []), ...args.guard],
|
|
464
508
|
};
|
|
@@ -468,9 +512,16 @@ export function readHistory(storage) {
|
|
|
468
512
|
try { const h = JSON.parse(fs.readFileSync(path.join(storage, 'history.json'), 'utf8')); return h && typeof h === 'object' ? h : { files: {} }; } catch { return { files: {} }; }
|
|
469
513
|
}
|
|
470
514
|
|
|
471
|
-
// Only single-file batches give per-file truth; multi-file peaks stay batch-level evidence.
|
|
515
|
+
// Only single-file batches give per-file memory truth; multi-file peaks stay batch-level evidence.
|
|
516
|
+
// Per-file durations come from the framework report of any completed batch (planning hint for balancing).
|
|
472
517
|
export function updateHistory(history, batchResults) {
|
|
473
518
|
const next = { files: { ...(history.files ?? {}) }, updatedAt: new Date().toISOString() };
|
|
519
|
+
for (const b of batchResults) {
|
|
520
|
+
if (!b.complete || !b.fileMs) continue;
|
|
521
|
+
for (const [file, ms] of Object.entries(b.fileMs)) {
|
|
522
|
+
if (b.files.includes(file) && Number.isFinite(ms)) next.files[file] = { ...(next.files[file] ?? {}), ms, at: next.updatedAt };
|
|
523
|
+
}
|
|
524
|
+
}
|
|
474
525
|
for (const b of batchResults) {
|
|
475
526
|
if (b.complete && b.files.length === 1 && b.peakRss != null) {
|
|
476
527
|
next.files[b.files[0]] = { isolatedPeakMb: toMb(b.peakRss), ms: b.durationMs, at: next.updatedAt };
|
|
@@ -496,7 +547,7 @@ function discoverAndPlan(ctx, adapter) {
|
|
|
496
547
|
if (!discovered.ok) return { error: discovered.error, version: discovered.version };
|
|
497
548
|
const inventory = buildInventory(discovered);
|
|
498
549
|
const history = readHistory(ctx.storage);
|
|
499
|
-
const batches = planBatches(inventory, { batchFiles: ctx.batchFiles, batchCases: ctx.batchCases, budgets: resolveBudgets(ctx.config), config: ctx.config, history });
|
|
550
|
+
const batches = planBatches(inventory, { batchFiles: ctx.batchFiles, batchCases: ctx.batchCases, budgets: resolveBudgets(ctx.config), config: ctx.config, history, workers: ctx.workers });
|
|
500
551
|
const check = verifyPlan(inventory, batches);
|
|
501
552
|
if (check.missing.length || check.duplicated.length || check.extra.length) return { error: `internal plan invariant broken: ${JSON.stringify(check)}`, version: discovered.version };
|
|
502
553
|
return { inventory, batches, version: discovered.version };
|
|
@@ -512,7 +563,7 @@ export async function runSuite(ctx, framework, deps = {}) {
|
|
|
512
563
|
return { runId: ctx.runId, framework, frameworkVersion: planned.version ?? null, verdict: 'INCOMPLETE', exitCode: EXIT.INCOMPLETE, error: planned.error };
|
|
513
564
|
}
|
|
514
565
|
const { inventory, batches } = planned;
|
|
515
|
-
fs.writeFileSync(path.join(ctx.runDir, 'manifest.json'), `${JSON.stringify({ framework, files: inventory.files, ids: inventory.ids, batches: batches.map((b) => ({ index: b.index, files: b.files, cases: b.cases })) }, null, 2)}\n`);
|
|
566
|
+
fs.writeFileSync(path.join(ctx.runDir, 'manifest.json'), `${JSON.stringify({ framework, workers: ctx.workers, files: inventory.files, ids: inventory.ids, batches: batches.map((b) => ({ index: b.index, files: b.files, cases: b.cases, ...(b.workers != null ? { workers: b.workers } : {}) })) }, null, 2)}\n`);
|
|
516
567
|
const guard = ctx.guard.length ? createGuard(ctx.root, ctx.guard) : null;
|
|
517
568
|
const batchResults = [];
|
|
518
569
|
let deferred = null;
|
|
@@ -523,7 +574,7 @@ export async function runSuite(ctx, framework, deps = {}) {
|
|
|
523
574
|
batchResults.push(result);
|
|
524
575
|
deps.onBatch?.(result, batches.length);
|
|
525
576
|
}
|
|
526
|
-
const summary = aggregate({ inventory, batches, batchResults, guard: guard ? guard.check() : null, heavyMb: ctx.heavyMb, framework, version: planned.version, runId: ctx.runId, startedAt, finishedAt: new Date().toISOString(), deferred });
|
|
577
|
+
const summary = aggregate({ inventory, batches, batchResults, guard: guard ? guard.check() : null, heavyMb: ctx.heavyMb, framework, version: planned.version, runId: ctx.runId, startedAt, finishedAt: new Date().toISOString(), deferred, workers: ctx.workers });
|
|
527
578
|
if (guard?.truncated) summary.warnings.push({ kind: 'guard-truncated', detail: `guard snapshot capped at ${DEFAULTS.guardMaxEntries} entries — narrow --guard paths` });
|
|
528
579
|
summary.batchDetail = batchResults.map((b) => ({ index: b.index, files: b.files.length, cases: b.cases, reported: b.results.length, durationMs: b.durationMs, msPerTest: b.msPerTest, peakMb: toMb(b.peakRss), peakSource: b.peakRssSource, complete: b.complete, error: b.error, silentFiles: b.silentFiles }));
|
|
529
580
|
fs.mkdirSync(ctx.storage, { recursive: true });
|
|
@@ -781,6 +832,7 @@ export function renderSummary(s) {
|
|
|
781
832
|
L.push(` inventory: ${s.inventory.files} files, ${s.inventory.tests ?? 'n/a (file-level)'} tests · reported ${s.reported}`);
|
|
782
833
|
L.push(` batches: ${s.batches.completed}/${s.batches.planned} complete${s.batches.incomplete.length ? ` · incomplete #${s.batches.incomplete.join(',#')}` : ''}${s.batches.notRun.length ? ` · not run #${s.batches.notRun.join(',#')}` : ''}`);
|
|
783
834
|
L.push(` passed ${c.passed} · failed ${c.failed} · error ${c.error} · skipped ${c.skipped} · xfailed ${c.xfailed} · xpassed ${c.xpassed}`);
|
|
835
|
+
L.push(` workers ${s.workers ?? 1}`);
|
|
784
836
|
L.push(` duration ${Math.round((s.durationMs ?? 0) / 1000)} s · max batch RSS ${s.maxBatchRssMb ?? 'unknown'} MB`);
|
|
785
837
|
for (const id of s.failedIds.slice(0, 50)) L.push(` FAILED ${id}`);
|
|
786
838
|
if (s.failedIds.length > 50) L.push(` … ${s.failedIds.length - 50} more failed ids in summary.json`);
|
|
@@ -53,6 +53,19 @@ async function coherentRoutingContext(root, sessionId) {
|
|
|
53
53
|
return state.routingContext || {};
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
// Git HEAD sha read straight from .git (no spawn). A commit moves HEAD, which stales prior
|
|
57
|
+
// verification verdicts, so re-verifying after a commit is progress, not a stalled retry.
|
|
58
|
+
async function gitHead(root) {
|
|
59
|
+
try {
|
|
60
|
+
const head = (await fs.readFile(path.join(root, '.git', 'HEAD'), 'utf8')).trim();
|
|
61
|
+
const m = /^ref:\s*(\S+)$/.exec(head);
|
|
62
|
+
if (!m) return head.slice(0, 40);
|
|
63
|
+
try { return (await fs.readFile(path.join(root, '.git', ...m[1].split('/')), 'utf8')).trim().slice(0, 40); } catch {}
|
|
64
|
+
const packed = await fs.readFile(path.join(root, '.git', 'packed-refs'), 'utf8');
|
|
65
|
+
return packed.split('\n').find((l) => l.endsWith(` ${m[1]}`))?.split(' ')[0] || '';
|
|
66
|
+
} catch { return ''; }
|
|
67
|
+
}
|
|
68
|
+
|
|
56
69
|
export async function progressFingerprint(root, runRoot = root, payload = {}) {
|
|
57
70
|
let cur = 'no-run';
|
|
58
71
|
try {
|
|
@@ -66,7 +79,7 @@ export async function progressFingerprint(root, runRoot = root, payload = {}) {
|
|
|
66
79
|
const led = await readJson(cache(root, path.join('exec-ledger', `${id || 'default'}.json`)), {});
|
|
67
80
|
const bank = (f) => Object.keys(led[f] && typeof led[f] === 'object' ? led[f] : {}).sort();
|
|
68
81
|
const rc = await coherentRoutingContext(root, payload.session_id);
|
|
69
|
-
return sha(JSON.stringify([cur, bank('bankedWrites'), bank('bankedVerifications'), rc.lastExplicitUserPromptText || '', rc.mutationOrder, rc.planOnly]));
|
|
82
|
+
return sha(JSON.stringify([cur, bank('bankedWrites'), bank('bankedVerifications'), rc.lastExplicitUserPromptText || '', rc.mutationOrder, rc.planOnly, await gitHead(root)]));
|
|
70
83
|
}
|
|
71
84
|
|
|
72
85
|
// Mode: router-stamped routingContext only.
|
|
@@ -142,8 +155,10 @@ export async function applyLoopBreak({ merged, projectRoot, runRoot, payload, se
|
|
|
142
155
|
});
|
|
143
156
|
if (!res?.limitReached) return merged;
|
|
144
157
|
const minutes = Math.max(0, Math.round((now - res.firstBlockedAt) / 60_000));
|
|
158
|
+
// attemptCount includes the current block, which is released rather than refused.
|
|
159
|
+
const refused = Math.max(1, res.attemptCount - 1);
|
|
145
160
|
const note = [
|
|
146
|
-
`[ukit-loop-breaker] BLOCKED/ESCALATED: ${merged.policyOwner} refused this stop ${
|
|
161
|
+
`[ukit-loop-breaker] BLOCKED/ESCALATED: ${merged.policyOwner} refused this stop ${refused} consecutive ${refused === 1 ? 'time' : 'times'} with no change in the work state (~${minutes} min, mode ${mode || 'UNKNOWN'}).`,
|
|
147
162
|
`Unresolved blocker: ${String(merged.reason || '').split('\n', 1)[0].slice(0, 200)}`,
|
|
148
163
|
'Stop released. This is NOT approval: completion evidence was not accepted by the blocking policy; this does not mean no verification ran; no safety/permission denial is lifted.',
|
|
149
164
|
'Report it verbatim; do not retry, wake up, or resume any handoff.',
|
|
@@ -105,12 +105,28 @@ function selfTree(rows, selfPid) {
|
|
|
105
105
|
return set;
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
// Agent host processes (Claude Code / codex / omp). A shell whose ancestor chain reaches a live
|
|
109
|
+
// host outside our own tree belongs to ANOTHER live session: never kill or report it.
|
|
110
|
+
const HOST_RE = /^(?:\S*\/)?(?:claude|codex|omp)(?:\s|$)|^(?:\S*\/)?node\s+(?:\S+\s+)*\S*\/(?:claude|codex|omp)(?:\.m?js)?(?:\s|$)/;
|
|
111
|
+
function ownedByOtherLiveHost(row, byPid, selfSet) {
|
|
112
|
+
for (let p = row.ppid, n = 0; p > 1 && n < 64; n += 1) {
|
|
113
|
+
if (selfSet.has(p)) return false;
|
|
114
|
+
const a = byPid.get(p);
|
|
115
|
+
if (!a) return false;
|
|
116
|
+
if (HOST_RE.test(a.command.trimStart())) return true;
|
|
117
|
+
p = a.ppid;
|
|
118
|
+
}
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
|
|
108
122
|
/** Pure classification of ps rows -> [{ kind, pid, ageMin, text, deterministic }]. */
|
|
109
123
|
export function classifyShells(rows, { staleMinutes, uid = null, selfPid = process.pid }) {
|
|
110
124
|
const selfSet = selfTree(rows, selfPid);
|
|
125
|
+
const byPid = new Map(rows.map((r) => [r.pid, r]));
|
|
111
126
|
const out = [];
|
|
112
127
|
for (const row of rows) {
|
|
113
128
|
if (excluded(row, selfSet, uid)) continue;
|
|
129
|
+
if (ownedByOtherLiveHost(row, byPid, selfSet)) continue; // another live session's shell: skip, never kill
|
|
114
130
|
const cmd = row.command;
|
|
115
131
|
const isShell = SHELL_C_RE.test(cmd) || cmd.includes(SNAPSHOT_MARKER);
|
|
116
132
|
const old = row.ageMin >= staleMinutes;
|
|
@@ -93,7 +93,7 @@ Chỉ active khi task đi qua `docs/AI_HANDOFF/` ("execute task TASK-xxx" hoặc
|
|
|
93
93
|
<!-- RULES: BUDGET-02 BUDGET-03 -->
|
|
94
94
|
- `docs/STATUS.md` for open-ended/continue; `docs/TASKS.md` only for queued-task prompts; `docs/WORKLOG.md` recent entries only. Verification: targeted first, widen on risk/shared scope, ask before broad runs.
|
|
95
95
|
<!-- RULE: TEST-01 -->
|
|
96
|
-
- **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never add parallel workers
|
|
96
|
+
- **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never launch a second copy or add your own parallel workers; in-batch workers come only from the runner's `workers` setting. Targeted 1-3 file runs use the bare runner directly.
|
|
97
97
|
- **Long commands run once:** start a full suite/release gate (>1 min) a single time; if it times out or goes to background, read its output — never launch a duplicate in parallel. Cheap deterministic gates first; trivial/simple tasks never need the full suite.
|
|
98
98
|
- **No hung shells:** a `[ukit-shell-watch] ACTION` line means kill the listed hung shells/stalled tasks and finish their work before the new prompt. Hookless engines (Codex): check `ps` for stale agent shells at the start of each prompt. Wait loops poll a pidfile / `kill -0 <pid>`, never a self-matching `pgrep -f`.
|
|
99
99
|
|
|
@@ -93,7 +93,7 @@ Chỉ active khi task đi qua `docs/AI_HANDOFF/` ("execute task TASK-xxx" hoặc
|
|
|
93
93
|
<!-- RULES: BUDGET-02 BUDGET-03 -->
|
|
94
94
|
- `docs/STATUS.md` for open-ended/continue; `docs/TASKS.md` only for queued-task prompts; `docs/WORKLOG.md` recent entries only. Verification: targeted first, widen on risk/shared scope, ask before broad runs.
|
|
95
95
|
<!-- RULE: TEST-01 -->
|
|
96
|
-
- **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never add parallel workers
|
|
96
|
+
- **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never launch a second copy or add your own parallel workers; in-batch workers come only from the runner's `workers` setting. Targeted 1-3 file runs use the bare runner directly.
|
|
97
97
|
- **Long commands run once:** start a full suite/release gate (>1 min) a single time; if it times out or goes to background, read its output — never launch a duplicate in parallel. Cheap deterministic gates first; trivial/simple tasks never need the full suite.
|
|
98
98
|
- **No hung shells:** a `[ukit-shell-watch] ACTION` line means kill the listed hung shells/stalled tasks and finish their work before the new prompt. Hookless engines (Codex): check `ps` for stale agent shells at the start of each prompt. Wait loops poll a pidfile / `kill -0 <pid>`, never a self-matching `pgrep -f`.
|
|
99
99
|
|
|
@@ -90,7 +90,7 @@ Chỉ active khi task đi qua `docs/AI_HANDOFF/` ("execute task TASK-xxx" hoặc
|
|
|
90
90
|
<!-- RULES: BUDGET-02 BUDGET-03 -->
|
|
91
91
|
- `docs/STATUS.md` for open-ended/continue; `docs/TASKS.md` only for queued-task prompts; `docs/WORKLOG.md` recent entries only. Verification: targeted first, widen on risk/shared scope, ask before broad runs.
|
|
92
92
|
<!-- RULE: TEST-01 -->
|
|
93
|
-
- **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never add parallel workers
|
|
93
|
+
- **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never launch a second copy or add your own parallel workers; in-batch workers come only from the runner's `workers` setting. Targeted 1-3 file runs use the bare runner directly.
|
|
94
94
|
- **Long commands run once:** start a full suite/release gate (>1 min) a single time; if it times out or goes to background, read its output — never launch a duplicate in parallel. Cheap deterministic gates first; trivial/simple tasks never need the full suite.
|
|
95
95
|
- **No hung shells:** a `[ukit-shell-watch] ACTION` line means kill the listed hung shells/stalled tasks and finish their work before the new prompt. Hookless engines (Codex): check `ps` for stale agent shells at the start of each prompt. Wait loops poll a pidfile / `kill -0 <pid>`, never a self-matching `pgrep -f`.
|
|
96
96
|
|