-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoresearch.sh
More file actions
executable file
·726 lines (680 loc) · 42.4 KB
/
autoresearch.sh
File metadata and controls
executable file
·726 lines (680 loc) · 42.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
#!/usr/bin/env bash
set -euo pipefail
# Kapi durable-mode redesign scorer for pi-autoresearch.
# Emits METRIC lines consumed by run_experiment.
# This script intentionally runs the same public verification gate first so the
# score cannot diverge from human/project verification.
# Tracked maintainability metrics from the verification surface and
# scripts/code-quality-report.mjs:
# code_coverage_pct, max_cyclomatic_complexity, duplicated_code_pct,
# code_smells, coupling_max_imports, budget_warn_count,
# budget_pass_count, budget_not_configured_count.
branch_name="unknown"
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
branch_name="$(git branch --show-current 2>/dev/null || echo unknown)"
fi
if [[ ! "$branch_name" =~ ^autoresearch/ && ! "$branch_name" =~ ^(feat|fix|perf|refactor|test|docs|chore|build|ci)/autoresearch- ]]; then
echo "Refusing autoresearch benchmark on non-dedicated branch: $branch_name" >&2
echo "Create a dedicated autoresearch branch/worktree before launching the loop." >&2
exit 1
fi
verify_pass=0
if npm run verify --silent; then
verify_pass=1
fi
node - "$verify_pass" "$branch_name" <<'NODE'
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync, execSync } = require('node:child_process');
const verifyPass = Number(process.argv[2] ?? 0);
const branchName = String(process.argv[3] ?? 'unknown');
function read(file) {
try { return fs.readFileSync(file, 'utf8'); } catch { return ''; }
}
function walk(dir, files = []) {
if (!fs.existsSync(dir)) return files;
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === '.ilchul' || entry.name === '.kapi' || entry.name === 'references') continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walk(full, files);
else files.push(full);
}
return files;
}
const goal = read('GOAL.md');
const readme = read('README.md');
const sourceFiles = [...walk('src'), ...walk('test'), ...walk('skills'), ...walk('prompts'), ...walk('docs')]
.filter((file) => /\.(ts|js|md|json|mjs)$/.test(file));
const implementationFiles = sourceFiles.filter((file) => file.startsWith('src/') || file.startsWith('test/'));
const sourceImplementationFiles = sourceFiles.filter((file) => file.startsWith('src/'));
const contractSurfaceFiles = sourceFiles.filter((file) => file.startsWith('skills/') || file.startsWith('prompts/') || file.startsWith('docs/'));
const corpus = [goal, readme, ...sourceFiles.map(read)].join('\n');
const implementationCorpus = implementationFiles.map(read).join('\n');
const sourceCorpus = sourceImplementationFiles.map(read).join('\n');
const testCorpus = walk('test').filter((file) => /\.(ts|js)$/.test(file)).map(read).join('\n');
const contractSurfaceCorpus = [readme, ...contractSurfaceFiles.map(read)].join('\n');
const antiGamingCorpus = [read('package.json'), ...walk('scripts').map(read)].join('\n');
function countRegex(text, regex) {
return (text.match(regex) ?? []).length;
}
function hasAll(text, terms) {
return terms.every((term) => text.includes(term));
}
function points(condition, value) {
return condition ? value : 0;
}
const removedCommands = [
'/kapi-clarify',
'/kapi-plan',
'/kapi-execute',
'/kapi-review',
'/kapi-tdd',
'/kapi-ultrawork',
'/kapi-autopilot',
'/kapi-ralplan',
'/kapi-autoresearch-plan',
'/kapi-autoresearch-loop',
'/kapi-resume',
'/kapi-validate',
'/kapi-artifact',
'/kapi-evidence',
'/kapi-complete',
'/kapi-fail',
'/kapi-tmux',
'/kapi-worktree',
];
const requiredCommands = [
'/kapi-deep-interview',
'/kapi-ralph',
'/kapi-autoresearch',
'/kapi-integrate',
'/kapi-status',
'/kapi-clear',
];
const commandRegex = (command) => {
const escaped = command.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`${escaped}(?![-A-Za-z0-9_])`, 'g');
};
const countCommands = (commands, text) => commands.reduce((sum, command) => sum + countRegex(text, commandRegex(command)), 0);
const countRemovedCommands = (text) => countCommands(removedCommands, text);
const obsoleteCommandRefs = countRemovedCommands(`${sourceCorpus}\n${testCorpus}`);
const obsoleteContractRefs = countRemovedCommands(contractSurfaceCorpus);
const legacyFallbackRefs = countRegex(
implementationCorpus,
/(?:legacy|compat(?:ibility)?|removed|obsolete|shadow|hidden)\s+(?:alias|redirect|fallback|shim|path|command)|(?:alias|redirect|fallback|shim)\s+for\s+(?:legacy|compat(?:ibility)?|removed|obsolete)/gi,
);
const legacyStatusSubcommands = [
'read-artifact',
'write-artifact',
'record-evidence',
'worker-plan',
'dispatch-worker',
'refresh-worker',
];
const legacyCompatibilityRefs = countRegex(contractSurfaceCorpus, /Legacy compatibility|backward compatibility/gi);
const legacyStatusCommandRefs = legacyStatusSubcommands.reduce((sum, command) => sum + countRegex(`${sourceCorpus}\n${testCorpus}`, new RegExp(`(?<!tool-)${command.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`, 'g')), 0);
const legacySurfaceRefs = legacyFallbackRefs + legacyCompatibilityRefs + legacyStatusCommandRefs;
const antiGamingFlags =
countRegex(antiGamingCorpus, /assert\.ok\(true\)|METRIC\s+kapi_architecture_score=100|echo\s+["']?METRIC|exit 0\s*(?:#.*)?$|\|\|\s*true|--passWithNoTests|\.only\s*\(/gmi);
function baselineRef() {
try {
return execFileSync('git', ['merge-base', 'HEAD', 'dev'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || 'HEAD';
} catch {
return 'HEAD';
}
}
const baseline = baselineRef();
function readBaseline(file) {
try {
return execFileSync('git', ['show', `${baseline}:${file}`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
} catch {
return '';
}
}
function packageVerificationWeakeningFlags() {
const currentPackage = JSON.parse(read('package.json') || '{}');
const headPackage = JSON.parse(readBaseline('package.json') || '{}');
const protectedScripts = ['verify', 'test', 'check', 'quality', 'quality:budgets', 'quality:strict'];
return protectedScripts.filter((name) => {
const before = headPackage.scripts?.[name];
const after = currentPackage.scripts?.[name];
if (!before && !after) return false;
if (!after) return true;
if (before === after) return false;
return /\|\|\s*true|true\s*$|--passWithNoTests|--runInBand=false|echo\s+|exit\s+0/.test(after)
|| after.length < before.length * 0.7;
}).length;
}
function testWeakeningFlags() {
const currentTests = walk('test').filter((file) => /\.(ts|js)$/.test(file));
const deletedTestFiles = countRegex(execFileSync('git', ['diff', '--name-status', `${baseline}...HEAD`], { encoding: 'utf8' }), /^(D|R\d*)\s+test\//gm)
+ countRegex(execSync('git status --porcelain', { encoding: 'utf8' }), /^\s*(D|R)\s+test\//gm);
const currentSkipCount = currentTests.reduce((sum, file) => sum + countRegex(read(file), /\.(skip|only)\s*\(/g), 0);
const headSkipCount = currentTests.reduce((sum, file) => sum + countRegex(readBaseline(file), /\.(skip|only)\s*\(/g), 0);
const weakAssertionCount = currentTests.reduce((sum, file) => sum + countRegex(read(file), /assert\.(?:ok|strictEqual|deepStrictEqual)\s*\([^\n]*(?:true\s*\)|,\s*true\s*\)|,\s*[^,)]+\s*,\s*[^)]*TODO)/g), 0);
return deletedTestFiles + Math.max(0, currentSkipCount - headSkipCount) + weakAssertionCount;
}
function changedFilesSinceBaseline() {
const files = new Set();
try {
execFileSync('git', ['diff', '--name-only', `${baseline}...HEAD`], { encoding: 'utf8' })
.split('\n')
.filter(Boolean)
.forEach((file) => files.add(file));
} catch {}
try {
execSync('git status --porcelain', { encoding: 'utf8' })
.split('\n')
.map((line) => line.slice(3).trim())
.filter(Boolean)
.forEach((file) => files.add(file));
} catch {}
return [...files];
}
const changedFiles = changedFilesSinceBaseline();
const implementationChange = changedFiles.some((file) => /^(src|test)\//.test(file) || /^(index|eslint\.config|tsconfig|vite\.config)\.(ts|js|mjs|json)$/.test(file) || file === 'package.json' || file === 'package-lock.json');
const docsOnlyChange = changedFiles.length > 0 && !implementationChange ? 1 : 0;
const verificationWeakeningFlags = packageVerificationWeakeningFlags() + testWeakeningFlags();
const requiredModeRefs = requiredCommands.filter((command) => countRegex(sourceCorpus, commandRegex(command)) > 0).length;
const exactIdRegex = (id) => new RegExp(`["']${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`, 'g');
const actualDurableModeRefs = ['kapi-deep-interview', 'kapi-ralph', 'kapi-autoresearch', 'kapi-integrate'].filter((mode) => countRegex(sourceCorpus, exactIdRegex(mode)) > 0).length;
const safeAutoresearchBranch = /^autoresearch\//.test(branchName) || /^(feat|fix|perf|refactor|test|docs|chore|build|ci)\/autoresearch-/.test(branchName);
const unsafeBranch = safeAutoresearchBranch ? 0 : 1;
const sourceAndTests = `${sourceCorpus}\n${testCorpus}`;
const behaviorChecks = [
countRegex(testCorpus, /kapi-deep-interview/g) > 0,
countRegex(testCorpus, /kapi-ralph/g) > 0,
countRegex(testCorpus, /kapi-autoresearch(?!-)/g) > 0,
countRegex(testCorpus, /kapi-integrate/g) > 0,
countRegex(testCorpus, /pendingDecision|approve/g) > 0,
countRegex(testCorpus, /events\.jsonl|snapshot\.json|active inventory/g) > 0,
countRegex(testCorpus, /linkedInterview|linked workflow|linkedWorkflow/g) > 0,
countRegex(testCorpus, /\.ilchul\/workflows|001-/g) > 0,
countRegex(testCorpus, /\.ilchul\/worktrees|Commitizen/g) > 0,
countRegex(testCorpus, /merge-plan\.md|integration-report\.md|target branch.*dev|dev.*merge/g) > 0,
];
const behaviorPassed = behaviorChecks.filter(Boolean).length;
const behaviorScore = Math.round((behaviorPassed / behaviorChecks.length) * 40);
const inventoryChecks = [
requiredModeRefs === requiredCommands.length,
obsoleteCommandRefs === 0,
actualDurableModeRefs === 4,
hasAll(sourceCorpus, ['events.jsonl', 'snapshot.json']),
sourceCorpus.includes('active inventory') || sourceCorpus.includes('activeInventory'),
sourceCorpus.includes('pendingDecision'),
sourceCorpus.includes('code-simplifier'),
sourceCorpus.includes('.ilchul/worktrees'),
sourceCorpus.includes('Commitizen') || sourceCorpus.includes('Conventional Commit'),
sourceCorpus.includes('target branch is always `dev`') || sourceCorpus.includes('targetBranch') || sourceCorpus.includes('dev'),
];
const inventoryPassed = inventoryChecks.filter(Boolean).length;
const inventoryScore = Math.round((inventoryPassed / inventoryChecks.length) * 35);
const artifactChecks = [
hasAll(sourceAndTests, ['.ilchul/workflows', 'state.json', 'events.jsonl', 'snapshot.json']),
hasAll(sourceAndTests, ['contract.md', 'benchmark.sh', 'ledger.jsonl']),
hasAll(sourceAndTests, ['merge-plan.md', 'integration-report.md', 'conflict-matrix.md']),
sourceAndTests.includes('decision-report.md'),
sourceAndTests.includes('verify.md'),
];
const artifactPassed = artifactChecks.filter(Boolean).length;
const artifactScore = Math.round((artifactPassed / artifactChecks.length) * 15);
const sourceByFile = Object.fromEntries(sourceImplementationFiles.map((file) => [file, read(file)]));
const autoresearchCoreText = Object.entries(sourceByFile)
.filter(([file, text]) => /autoresearch/i.test(file) || /workflow-service|workflows|state-machine/.test(file) || /autoresearch/i.test(text))
.map(([, text]) => text)
.join('\n');
const autoresearchCompatibilityText = Object.entries(sourceByFile)
.filter(([file]) => /compat|migration|bridge/i.test(file))
.map(([, text]) => text)
.join('\n');
const legacyRootAutoresearchArtifacts = ['autoresearch.md', 'autoresearch.sh', 'autoresearch.checks.sh', 'autoresearch.jsonl', 'autoresearch.ideas.md', 'autoresearch.config.json'];
const kapiAutoresearchArtifacts = ['contract.md', 'benchmark.sh', 'checks.sh', 'ledger.jsonl', 'ideas.md'];
const expectedPiAutoresearchRoles = ['contract', 'benchmark', 'checks', 'ledger', 'ideas', 'keep', 'discard', 'crash', 'checks_failed', 'metric_parsing', 'resume_reconstruction'];
const workflowDefinitionsSource = read('src/domain/workflows.ts');
const quotedLiteralRegex = (literal) => new RegExp(`["']${literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`, 'g');
const quotedLiteralPresent = (text, literal) => quotedLiteralRegex(literal).test(text);
const bridgeNamedFiles = sourceImplementationFiles.filter((file) => /bridge/i.test(file) && !/-deps\.[tj]s$/.test(file));
const bridgeFilesWithExternalBoundary = bridgeNamedFiles.filter((file) => /compat|migration|root-level|project[ -]root|external|(?:^|[^a-z0-9-])pi-autoresearch(?:[^a-z0-9-]|$)/i.test(read(file)));
const bridgeTermMisuseCount = Math.max(0, bridgeNamedFiles.length - bridgeFilesWithExternalBoundary.length);
const rootAutoresearchDependencyCount = legacyRootAutoresearchArtifacts.reduce((sum, name) => sum + countRegex(autoresearchCoreText, quotedLiteralRegex(name)), 0);
const compatibilityIsolatedRootRefs = legacyRootAutoresearchArtifacts.reduce((sum, name) => sum + countRegex(autoresearchCompatibilityText, quotedLiteralRegex(name)), 0);
const durableAutoresearchArtifactRefs = kapiAutoresearchArtifacts.reduce((sum, name) => sum + countRegex(sourceCorpus, quotedLiteralRegex(name)), 0);
const durableWorkflowArtifactCoverage = kapiAutoresearchArtifacts.filter((name) => quotedLiteralPresent(workflowDefinitionsSource, name)).length;
const missingKapiAutoresearchArtifacts = kapiAutoresearchArtifacts.filter((name) => !quotedLiteralPresent(workflowDefinitionsSource, name));
const nonIsolatedRootAutoresearchRefs = Math.max(0, rootAutoresearchDependencyCount - compatibilityIsolatedRootRefs);
const autoresearchArtifactMismatchCount = missingKapiAutoresearchArtifacts.length + (nonIsolatedRootAutoresearchRefs > 0 ? 1 : 0);
const statusRoleCoverage = ['keep', 'discard', 'crash', 'checks_failed'].filter((role) => quotedLiteralPresent(sourceCorpus, role)).length;
const metricParsingRoleCovered = /parsedMetrics|parseMetric|METRIC\s+[^\n=]+=/i.test(sourceCorpus) ? 1 : 0;
const resumeReconstructionRoleCovered = /resume|reconstruct/i.test(sourceCorpus) && /ledger/i.test(sourceCorpus) ? 1 : 0;
const expectedRoleCoverage = durableWorkflowArtifactCoverage + statusRoleCoverage + metricParsingRoleCovered + resumeReconstructionRoleCovered;
const sourceOfTruthConflictCount = nonIsolatedRootAutoresearchRefs > 0 && durableAutoresearchArtifactRefs > 0 ? 1 : 0;
const semanticConsistencyChecks = [
bridgeTermMisuseCount === 0,
rootAutoresearchDependencyCount === compatibilityIsolatedRootRefs,
autoresearchArtifactMismatchCount === 0,
expectedRoleCoverage === expectedPiAutoresearchRoles.length,
sourceOfTruthConflictCount === 0,
];
const semanticConsistencyPassed = semanticConsistencyChecks.filter(Boolean).length;
const semanticConsistencyScore = Math.round((semanticConsistencyPassed / semanticConsistencyChecks.length) * 20);
const piAutoresearchReferenceChecks = [
durableWorkflowArtifactCoverage === kapiAutoresearchArtifacts.length,
statusRoleCoverage === 4,
quotedLiteralPresent(sourceCorpus, 'ledger.jsonl') && /append|jsonl|ledger/i.test(sourceCorpus),
quotedLiteralPresent(sourceCorpus, 'benchmark.sh') && quotedLiteralPresent(sourceCorpus, 'checks.sh'),
metricParsingRoleCovered === 1,
resumeReconstructionRoleCovered === 1,
];
const piAutoresearchReferencePassed = piAutoresearchReferenceChecks.filter(Boolean).length;
const piAutoresearchReferenceScore = Math.round((piAutoresearchReferencePassed / piAutoresearchReferenceChecks.length) * 20);
function runtimeAutoresearchProbe() {
const script = `
import { access, mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { FileWorkflowStore } from "./src/adapters/file-store.ts";
import { WorkflowService } from "./src/application/workflow-service.ts";
async function exists(file) {
try { await access(file); return true; } catch { return false; }
}
async function main() {
const workspace = await mkdtemp(path.join(os.tmpdir(), "kapi-runtime-autoresearch-"));
try {
const service = new WorkflowService(new FileWorkflowStore());
const result = await service.startWorkflow({ workspace, workflowId: "kapi-autoresearch", slug: "runtime-contract", task: "Optimize a metric" });
const names = new Set(result.state.artifacts.map((artifact) => artifact.name));
const requiredNames = ["state.json", "events.jsonl", "snapshot.json", "contract.md", "benchmark.sh", "checks.sh", "ledger.jsonl", "ideas.md"];
const metadataPass = requiredNames.every((name) => names.has(name)) && result.state.artifactRoot.includes(".ilchul/workflows/autoresearch/");
const filesPass = (await Promise.all(requiredNames.map((name) => exists(path.join(result.state.artifactRoot, name))))).every(Boolean);
console.log(JSON.stringify({ probeExecuted: 1, startPass: 1, contractPass: metadataPass && filesPass ? 1 : 0 }));
} catch (error) {
console.log(JSON.stringify({ probeExecuted: 1, startPass: 0, contractPass: 0, error: error instanceof Error ? error.message : String(error) }));
} finally {
await rm(workspace, { recursive: true, force: true });
}
}
main().catch((error) => {
console.log(JSON.stringify({ probeExecuted: 0, startPass: 0, contractPass: 0, error: error instanceof Error ? error.message : String(error) }));
});
`;
try {
return JSON.parse(execFileSync('npx', ['tsx', '-e', script], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());
} catch (error) {
return { probeExecuted: 0, startPass: 0, contractPass: 0 };
}
}
const autoresearchRuntimeProbe = runtimeAutoresearchProbe();
const runtimeAutoresearchProbeExecuted = Number(autoresearchRuntimeProbe.probeExecuted === 1);
const runtimeAutoresearchStartContractPass = Number(autoresearchRuntimeProbe.startPass === 1 && autoresearchRuntimeProbe.contractPass === 1);
const runtimeAutoresearchStartPass = Number(autoresearchRuntimeProbe.startPass === 1);
function runtimeModeProbe(workflowId) {
const script = `
import { access, mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { FileWorkflowStore } from "./src/adapters/file-store.ts";
import { WorkflowService } from "./src/application/workflow-service.ts";
async function exists(file) { try { await access(file); return true; } catch { return false; } }
async function parseJsonFile(file) { try { JSON.parse(await readFile(file, "utf8")); return true; } catch { return false; } }
async function parseJsonlFile(file) {
try {
const text = await readFile(file, "utf8");
const lines = text.split("\\n").filter(Boolean);
if (lines.length === 0) return false;
lines.forEach((line) => JSON.parse(line));
return true;
} catch { return false; }
}
async function main() {
const workspace = await mkdtemp(path.join(os.tmpdir(), "kapi-runtime-mode-"));
try {
const service = new WorkflowService(new FileWorkflowStore());
const result = await service.startWorkflow({ workspace, workflowId: ${JSON.stringify(workflowId)}, slug: "runtime-contract", task: "Probe runtime contract" });
const filesPass = (await Promise.all(result.state.artifacts.map((artifact) => exists(artifact.path)))).every(Boolean);
const rootPass = result.state.artifactRoot.includes(".ilchul/workflows/");
const eventsJsonlPass = await parseJsonlFile(path.join(result.state.artifactRoot, "events.jsonl"));
const snapshotJsonPass = await parseJsonFile(path.join(result.state.artifactRoot, "snapshot.json"));
const stateJsonPass = await parseJsonFile(path.join(result.state.artifactRoot, "state.json"));
console.log(JSON.stringify({ probeExecuted: 1, startPass: 1, contractPass: filesPass && rootPass ? 1 : 0, eventsJsonlPass: eventsJsonlPass ? 1 : 0, snapshotJsonPass: snapshotJsonPass ? 1 : 0, stateJsonPass: stateJsonPass ? 1 : 0 }));
} catch (error) {
console.log(JSON.stringify({ probeExecuted: 1, startPass: 0, contractPass: 0, eventsJsonlPass: 0, snapshotJsonPass: 0, stateJsonPass: 0, error: error instanceof Error ? error.message : String(error) }));
} finally {
await rm(workspace, { recursive: true, force: true });
}
}
main().catch((error) => console.log(JSON.stringify({ probeExecuted: 0, startPass: 0, contractPass: 0, eventsJsonlPass: 0, snapshotJsonPass: 0, stateJsonPass: 0, error: error instanceof Error ? error.message : String(error) })));
`;
try {
return JSON.parse(execFileSync('npx', ['tsx', '-e', script], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());
} catch {
return { probeExecuted: 0, startPass: 0, contractPass: 0, eventsJsonlPass: 0, snapshotJsonPass: 0, stateJsonPass: 0 };
}
}
const runtimeModeIds = ['kapi-deep-interview', 'kapi-ralph', 'kapi-integrate'];
const runtimeModeProbeResults = Object.fromEntries(runtimeModeIds.map((mode) => [mode, runtimeModeProbe(mode)]));
const runtimeDeepInterviewStartContractPass = Number(runtimeModeProbeResults['kapi-deep-interview'].startPass === 1 && runtimeModeProbeResults['kapi-deep-interview'].contractPass === 1);
const runtimeRalphStartContractPass = Number(runtimeModeProbeResults['kapi-ralph'].startPass === 1 && runtimeModeProbeResults['kapi-ralph'].contractPass === 1);
const runtimeIntegrateStartContractPass = Number(runtimeModeProbeResults['kapi-integrate'].startPass === 1 && runtimeModeProbeResults['kapi-integrate'].contractPass === 1);
const modeRuntimeProbeCoverage = runtimeDeepInterviewStartContractPass + runtimeRalphStartContractPass + runtimeAutoresearchStartContractPass + runtimeIntegrateStartContractPass;
const eventLogJsonlParsePass = Number(Object.values(runtimeModeProbeResults).every((result) => result.eventsJsonlPass === 1));
const snapshotJsonParsePass = Number(Object.values(runtimeModeProbeResults).every((result) => result.snapshotJsonPass === 1));
const stateJsonParsePass = Number(Object.values(runtimeModeProbeResults).every((result) => result.stateJsonPass === 1));
function commandSurfaceInventory() {
const workflowCommandNames = [...workflowDefinitionsSource.matchAll(/command:\s*["']\/(kapi-[^"']+)["']/g)].map((match) => match[1]);
const literalRegisteredNames = [...sourceCorpus.matchAll(/registerCommand\(["']([^"']+)["']/g)].map((match) => match[1]);
return [...new Set([...workflowCommandNames, ...literalRegisteredNames])];
}
const command_surface_probe_executed = 1;
const registeredHumanCommands = commandSurfaceInventory();
const allowedHumanCommands = ['kapi-deep-interview', 'kapi-ralph', 'kapi-autoresearch', 'kapi-integrate', 'kapi-status', 'kapi-clear'];
const extraHumanCommandCount = registeredHumanCommands.filter((command) => command.startsWith('kapi-') && !allowedHumanCommands.includes(command)).length;
const exactCommandSurfacePass = Number(extraHumanCommandCount === 0 && allowedHumanCommands.every((command) => registeredHumanCommands.includes(command)));
const modeSubcommandNames = ['status', 'resume', 'approve'];
const modeCommandHandlerText = read('src/presentation/commands.ts').match(/export function registerPrimaryWorkflowCommands[\s\S]*?export function registerSupportCommands/)?.[0] ?? '';
const missingModeSubcommandCount = ['kapi-deep-interview', 'kapi-ralph', 'kapi-autoresearch', 'kapi-integrate'].reduce((sum, mode) => sum + modeSubcommandNames.filter((subcommand) => !new RegExp(`\\b${subcommand}\\b`).test(modeCommandHandlerText)).length, 0);
const modeSubcommandBehaviorPass = Number(missingModeSubcommandCount === 0);
const docsChecks = [
hasAll(goal, ['references/oh-my-codex', 'references/ouroboros']) && /(?:^|[^a-z0-9-])pi-autoresearch(?:[^a-z0-9-]|$)/i.test(goal),
hasAll(goal, ['No Legacy Shadow Architecture', 'ordinary Pi']),
hasAll(readme + goal, requiredCommands),
obsoleteContractRefs === 0,
hasAll(goal, ['Code coverage', 'Cyclomatic complexity', 'Duplicated code', 'Code smells', 'Dependency and coupling']),
];
const docsPassed = docsChecks.filter(Boolean).length;
const docsScore = Math.round((docsPassed / docsChecks.length) * 10);
// Test-conversion score tracks whether the test suite has been honestly moved
// from the removed workflow surface to the durable-mode contract. It is a
// negative debt metric: -100 means essentially unconverted, 0 means these
// stale-test indicators are gone. This is diagnostic only and does not replace
// the primary architecture score or the npm verify hard gate.
const testConversionChecks = [
!/\/kapi-(?:tdd|review|execute|plan|ralplan|ultrawork|autopilot|autoresearch-(?:plan|loop))\b/.test(testCorpus),
!/strict TDD|failing-test-first|TDD RED|RED\/GREEN|tdd_without_/i.test(testCorpus),
!/progress\.json/.test(testCorpus),
!/workflowArtifactSegment\("kapi-ralph"\),\s*"(?:plan|execute)"/.test(testCorpus),
!/Kapi (?:plan|execute|review|ultrawork):active/.test(testCorpus),
!/read-artifact context\.md kapi-ralph|artifactName:\s*"plan\.md"|artifact\.name === "context\.md"/.test(testCorpus),
!/approved \/kapi-ralph handoff|approved unstarted ralplan|ralplan state|startAutoresearchLoopFromPlan/i.test(testCorpus),
/IMPLEMENTATION_PLAN\.md/.test(testCorpus) && /verify\.md/.test(testCorpus),
/kapi-deep-interview/.test(testCorpus) && /kapi-ralph/.test(testCorpus) && /kapi-autoresearch/.test(testCorpus) && /kapi-integrate/.test(testCorpus),
/events\.jsonl/.test(testCorpus) && /snapshot\.json/.test(testCorpus),
];
const testConversionPassed = testConversionChecks.filter(Boolean).length;
const testConversionScore = -100 + Math.round((testConversionPassed / testConversionChecks.length) * 100);
const staleTestConversionFlags = testConversionChecks.length - testConversionPassed;
let antiGamingPenalty = 0;
if (antiGamingFlags > 0) antiGamingPenalty += 100;
if (verificationWeakeningFlags > 0) antiGamingPenalty += 100;
if (docsOnlyChange > 0) antiGamingPenalty += 100;
if (legacyFallbackRefs > 0) antiGamingPenalty += 100;
if (obsoleteCommandRefs > 0) antiGamingPenalty += 100;
if (unsafeBranch > 0) antiGamingPenalty += 100;
if (verifyPass !== 1) antiGamingPenalty += 100;
let qualityMetrics = {};
try {
const qualityReport = JSON.parse(execFileSync('node', ['scripts/code-quality-report.mjs', '--json', '--budgets'], { encoding: 'utf8' }));
qualityMetrics = qualityReport.metrics ?? {};
} catch {
qualityMetrics = {};
}
const baseArchitectureScore = behaviorScore + inventoryScore + artifactScore + docsScore;
const qualityHeadroomBonus =
Math.max(0, 5 - (qualityMetrics.code_smells ?? 5)) +
Math.max(0, 10 - (qualityMetrics.coupling_max_imports ?? 10)) +
Math.max(0, Math.round((5 - (qualityMetrics.duplicated_code_pct ?? 5)) * 10)) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 180, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 170, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 160, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 158, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 157, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 155, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 149, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 148, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 147, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 145, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 144, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 142, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 140, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 139, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 138, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 135, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 133, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 129, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 128, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 127, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 126, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 125, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 124, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 123, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 122, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 121, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 120, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 119, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 118, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 117, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 116, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 115, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 114, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 113, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 112, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 111, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 110, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 109, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 108, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 107, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 106, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 105, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 104, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 103, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 102, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 101, 1) +
points((qualityMetrics.module_dependency_edges ?? Infinity) <= 100, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 50, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 47, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 46, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 45, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 44, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 43, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 42, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 41, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 40, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 39, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 38, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 37, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 36, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 35, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 34, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 33, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 32, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 31, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 30, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 29, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 28, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 27, 1) +
points((qualityMetrics.facade_dependency_files ?? Infinity) <= 26, 1);
const maintainabilityBonus =
points((qualityMetrics.budget_warn_count ?? 1) === 0, 2) +
points((qualityMetrics.budget_pass_count ?? 0) >= 4, 4) +
points((qualityMetrics.budget_pass_count ?? 0) >= 6, 2) +
points((qualityMetrics.max_cyclomatic_complexity ?? Infinity) <= 3, 3) +
points((qualityMetrics.duplicated_code_pct ?? Infinity) <= 5, 3) +
points((qualityMetrics.code_smells ?? Infinity) <= 5, 3) +
points((qualityMetrics.coupling_max_imports ?? Infinity) <= 10, 3) +
qualityHeadroomBonus;
const legacyRemovalScore = legacySurfaceRefs === 0 ? 10 : 0;
let score = baseArchitectureScore + maintainabilityBonus + legacyRemovalScore - antiGamingPenalty;
score = Math.max(0, score);
const runtimeBlockerChecks = [
runtimeAutoresearchStartContractPass === 1,
modeRuntimeProbeCoverage === 4,
eventLogJsonlParsePass === 1,
snapshotJsonParsePass === 1,
exactCommandSurfacePass === 1,
modeSubcommandBehaviorPass === 1,
];
const semanticBlockerChecks = [
semanticConsistencyPassed === semanticConsistencyChecks.length,
piAutoresearchReferencePassed === piAutoresearchReferenceChecks.length,
autoresearchArtifactMismatchCount === 0,
sourceOfTruthConflictCount === 0,
nonIsolatedRootAutoresearchRefs === 0,
];
const runtimeBlockerCount = runtimeBlockerChecks.filter((passed) => !passed).length;
const semanticBlockerCount = semanticBlockerChecks.filter((passed) => !passed).length;
const shipBlockerCount = runtimeBlockerCount + semanticBlockerCount;
const readinessChecks = [...runtimeBlockerChecks, ...semanticBlockerChecks, verifyPass === 1, antiGamingPenalty === 0];
const kapiReadinessScore = Math.round((readinessChecks.filter(Boolean).length / readinessChecks.length) * 100);
const metrics = {
kapi_architecture_score: score,
kapi_readiness_score: kapiReadinessScore,
ship_blocker_count: shipBlockerCount,
runtime_blocker_count: runtimeBlockerCount,
semantic_blocker_count: semanticBlockerCount,
base_architecture_score: baseArchitectureScore,
maintainability_bonus: maintainabilityBonus,
quality_headroom_bonus: qualityHeadroomBonus,
legacy_removal_score: legacyRemovalScore,
behavior_score: behaviorScore,
inventory_score: inventoryScore,
artifact_score: artifactScore,
docs_score: docsScore,
semantic_consistency_score: semanticConsistencyScore,
pi_autoresearch_reference_score: piAutoresearchReferenceScore,
runtime_autoresearch_probe_executed: runtimeAutoresearchProbeExecuted,
runtime_autoresearch_start_pass: runtimeAutoresearchStartPass,
runtime_autoresearch_start_contract_pass: runtimeAutoresearchStartContractPass,
runtime_deep_interview_start_contract_pass: runtimeDeepInterviewStartContractPass,
runtime_ralph_start_contract_pass: runtimeRalphStartContractPass,
runtime_integrate_start_contract_pass: runtimeIntegrateStartContractPass,
mode_runtime_probe_coverage: modeRuntimeProbeCoverage,
event_log_jsonl_parse_pass: eventLogJsonlParsePass,
snapshot_json_parse_pass: snapshotJsonParsePass,
state_json_parse_pass: stateJsonParsePass,
command_surface_probe_executed,
exact_command_surface_pass: exactCommandSurfacePass,
extra_human_command_count: extraHumanCommandCount,
missing_mode_subcommand_count: missingModeSubcommandCount,
mode_subcommand_behavior_pass: modeSubcommandBehaviorPass,
anti_gaming_penalty: antiGamingPenalty,
verify_pass: verifyPass,
module_dependency_edges: qualityMetrics.module_dependency_edges ?? 0,
facade_dependency_files: qualityMetrics.facade_dependency_files ?? 0,
verification_weakening_flags: verificationWeakeningFlags,
obsolete_command_refs: obsoleteCommandRefs,
obsolete_contract_refs: obsoleteContractRefs,
legacy_fallback_refs: legacyFallbackRefs,
legacy_surface_refs: legacySurfaceRefs,
legacy_status_command_refs: legacyStatusCommandRefs,
legacy_compatibility_refs: legacyCompatibilityRefs,
required_mode_refs: requiredModeRefs,
actual_durable_mode_refs: actualDurableModeRefs,
unsafe_branch: unsafeBranch,
docs_only_change: docsOnlyChange,
changed_file_count: changedFiles.length,
behavior_passed: behaviorPassed,
behavior_total: behaviorChecks.length,
inventory_passed: inventoryPassed,
inventory_total: inventoryChecks.length,
artifact_passed: artifactPassed,
artifact_total: artifactChecks.length,
docs_passed: docsPassed,
docs_total: docsChecks.length,
semantic_consistency_passed: semanticConsistencyPassed,
semantic_consistency_total: semanticConsistencyChecks.length,
pi_autoresearch_reference_passed: piAutoresearchReferencePassed,
pi_autoresearch_reference_total: piAutoresearchReferenceChecks.length,
bridge_term_misuse_count: bridgeTermMisuseCount,
root_autoresearch_dependency_count: rootAutoresearchDependencyCount,
compatibility_isolated_root_refs: compatibilityIsolatedRootRefs,
autoresearch_artifact_mismatch_count: autoresearchArtifactMismatchCount,
source_of_truth_conflict_count: sourceOfTruthConflictCount,
durable_autoresearch_artifact_refs: durableAutoresearchArtifactRefs,
durable_workflow_artifact_coverage: durableWorkflowArtifactCoverage,
durable_workflow_artifact_total: kapiAutoresearchArtifacts.length,
non_isolated_root_autoresearch_refs: nonIsolatedRootAutoresearchRefs,
expected_pi_autoresearch_role_coverage: expectedRoleCoverage,
expected_pi_autoresearch_role_total: expectedPiAutoresearchRoles.length,
pi_autoresearch_metric_parsing_role: metricParsingRoleCovered,
pi_autoresearch_resume_reconstruction_role: resumeReconstructionRoleCovered,
test_conversion_score: testConversionScore,
stale_test_conversion_flags: staleTestConversionFlags,
test_conversion_passed: testConversionPassed,
test_conversion_total: testConversionChecks.length,
state_model_refs: countRegex(corpus, /command\/event\/snapshot|events\.jsonl|snapshot\.json|active inventory/gi),
worktree_boundary_refs: countRegex(corpus, /~\/\.kapi\/worktrees|Kapi-created worktree|Commitizen|<type>\/<mode>-<goal-slug>/gi),
anti_gaming_flags: antiGamingFlags,
};
for (const [name, value] of Object.entries(metrics)) {
console.log(`METRIC ${name}=${value}`);
}
NODE
# Propagate verification and anti-gaming failures after emitting metrics so checks still fail.
if [[ "$verify_pass" != "1" ]]; then
exit 1
fi
if grep -Eq 'assert\.ok\(true\)|METRIC\s+kapi_architecture_score=100|echo\s+.*METRIC|exit 0\s*(#.*)?$|\|\|\s*true|--passWithNoTests' package.json scripts/* 2>/dev/null; then
echo "Refusing autoresearch benchmark because anti-gaming patterns were detected." >&2
exit 1
fi
if node <<'NODE'
const fs = require('node:fs');
const { execFileSync, execSync } = require('node:child_process');
function read(file) { try { return fs.readFileSync(file, 'utf8'); } catch { return ''; } }
function baselineRef() { try { return execFileSync('git', ['merge-base', 'HEAD', 'dev'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || 'HEAD'; } catch { return 'HEAD'; } }
const baseline = baselineRef();
function head(file) { try { return execFileSync('git', ['show', `${baseline}:${file}`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); } catch { return ''; } }
function directMetricHardcode(file) {
return read(file).split('\n').some((line) => {
if (/antiGaming|grep -Eq|METRIC\\s|countRegex/.test(line)) return false;
return /METRIC\s+kapi_architecture_score\s*=\s*(?:100|[0-9]+)/.test(line) || /echo\s+.*METRIC/.test(line);
});
}
const current = JSON.parse(read('package.json') || '{}');
const before = JSON.parse(head('package.json') || '{}');
const protectedScripts = ['verify', 'test', 'check', 'quality', 'quality:budgets', 'quality:strict'];
for (const name of protectedScripts) {
const oldScript = before.scripts?.[name];
const newScript = current.scripts?.[name];
if (!oldScript && !newScript) continue;
if (!newScript || (/\|\|\s*true|true\s*$|--passWithNoTests|--runInBand=false|echo\s+|exit\s+0/.test(newScript)) || (oldScript !== newScript && newScript.length < oldScript.length * 0.7)) process.exit(1);
}
if (directMetricHardcode('autoresearch.sh') || directMetricHardcode('autoresearch.checks.sh')) process.exit(1);
const status = execSync('git status --porcelain', { encoding: 'utf8' });
const diffStatus = execFileSync('git', ['diff', '--name-status', `${baseline}...HEAD`], { encoding: 'utf8' });
if (/^\s*(D|R)\s+test\//m.test(status) || /^(D|R\d*)\s+test\//m.test(diffStatus)) process.exit(1);
const testFiles = execFileSync('find', ['test', '-type', 'f', '(', '-name', '*.ts', '-o', '-name', '*.js', ')'], { encoding: 'utf8' }).trim().split('\n').filter(Boolean);
const currentSkipCount = testFiles.reduce((sum, file) => sum + ((read(file).match(/\.(skip|only)\s*\(/g) || []).length), 0);
const headSkipCount = testFiles.reduce((sum, file) => sum + ((head(file).match(/\.(skip|only)\s*\(/g) || []).length), 0);
const weakAssertionCount = testFiles.reduce((sum, file) => sum + ((read(file).match(/assert\.(?:ok|strictEqual|deepStrictEqual)\s*\([^\n]*(?:true\s*\)|,\s*true\s*\)|,\s*[^,)]+\s*,\s*[^)]*TODO)/g) || []).length), 0);
if (currentSkipCount > headSkipCount || weakAssertionCount > 0) process.exit(1);
NODE
then
:
else
echo "Refusing autoresearch benchmark because verification weakening was detected." >&2
exit 1
fi
if node <<'NODE'
const fs = require('node:fs');
const path = require('node:path');
const obsoleteCommands = ['/kapi-clarify','/kapi-plan','/kapi-execute','/kapi-review','/kapi-tdd','/kapi-ultrawork','/kapi-autopilot','/kapi-ralplan','/kapi-autoresearch-plan','/kapi-autoresearch-loop','/kapi-resume','/kapi-validate','/kapi-artifact','/kapi-evidence','/kapi-complete','/kapi-fail','/kapi-tmux'];
function walk(dir, files = []) { if (!fs.existsSync(dir)) return files; for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { if (entry.name === '.ilchul' || entry.name === '.kapi') continue; const full = path.join(dir, entry.name); if (entry.isDirectory()) walk(full, files); else files.push(full); } return files; }
const text = [...walk('src'), ...walk('test')].filter((file) => /\.(ts|js|json|md)$/.test(file)).map((file) => fs.readFileSync(file, 'utf8')).join('\n');
process.exit(obsoleteCommands.some((command) => text.includes(command)) ? 1 : 0);
NODE
then
:
else
echo "Refusing autoresearch benchmark because obsolete Kapi commands remain in source/tests." >&2
exit 1
fi
if grep -REiq '(legacy|compat(ibility)?|removed|obsolete|shadow|hidden)[[:space:]]+(alias|redirect|fallback|shim|path|command)|(alias|redirect|fallback|shim)[[:space:]]+for[[:space:]]+(legacy|compat(ibility)?|removed|obsolete)' src 2>/dev/null; then
echo "Refusing autoresearch benchmark because legacy/fallback command behavior was detected." >&2
exit 1
fi
baseline="$(git merge-base HEAD dev 2>/dev/null || echo HEAD)"
changed_files="$({ git diff --name-only "$baseline...HEAD" 2>/dev/null; git status --porcelain | awk '{print substr($0,4)}'; } | sort -u)"
if [[ -n "$changed_files" ]] && ! grep -Eq '^(src|test)/|^(index|eslint\.config|tsconfig|vite\.config)\.(ts|js|mjs|json)$|^package(-lock)?\.json$' <<<"$changed_files"; then
echo "Refusing docs-only autoresearch change; implementation or test changes are required for keep-worthy score movement." >&2
exit 1
fi