@evomap/evolver-cli 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/antiGeneBenchmark.d.ts +9 -0
- package/dist/antiGeneBenchmark.js +173 -0
- package/dist/antiGeneRollout.d.ts +14 -0
- package/dist/antiGeneRollout.js +276 -0
- package/dist/atp.d.ts +122 -0
- package/dist/atp.js +413 -0
- package/dist/atpAutoDeliver.d.ts +53 -0
- package/dist/atpAutoDeliver.js +197 -0
- package/dist/atpAutobuyPrompt.d.ts +48 -0
- package/dist/atpAutobuyPrompt.js +109 -0
- package/dist/autoDistillAntiGene.d.ts +63 -0
- package/dist/autoDistillAntiGene.js +396 -0
- package/dist/autoDistillLlm.d.ts +94 -0
- package/dist/autoDistillLlm.js +510 -0
- package/dist/autoDistillTranscript.d.ts +87 -0
- package/dist/autoDistillTranscript.js +364 -0
- package/dist/autoRecall.d.ts +25 -0
- package/dist/autoRecall.js +80 -0
- package/dist/autoexec.d.ts +237 -0
- package/dist/autoexec.js +1041 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +7 -0
- package/dist/cliContracts.d.ts +72 -0
- package/dist/cliContracts.js +815 -0
- package/dist/commands.d.ts +9 -0
- package/dist/commands.js +10 -0
- package/dist/cursorRewrite.d.ts +42 -0
- package/dist/cursorRewrite.js +65 -0
- package/dist/cycleConsumer.d.ts +42 -0
- package/dist/cycleConsumer.js +519 -0
- package/dist/daemonLoop.d.ts +33 -0
- package/dist/daemonLoop.js +72 -0
- package/dist/dispatch.d.ts +10 -0
- package/dist/dispatch.js +75 -0
- package/dist/distillObserver.d.ts +33 -0
- package/dist/distillObserver.js +146 -0
- package/dist/distillPrimitives.d.ts +48 -0
- package/dist/distillPrimitives.js +142 -0
- package/dist/doctor.d.ts +54 -0
- package/dist/doctor.js +931 -0
- package/dist/geneValue.d.ts +37 -0
- package/dist/geneValue.js +97 -0
- package/dist/index.d.ts +193 -0
- package/dist/index.js +1135 -0
- package/dist/lifecycle.d.ts +75 -0
- package/dist/lifecycle.js +859 -0
- package/dist/login.d.ts +10 -0
- package/dist/login.js +38 -0
- package/dist/migrate/divergenceAudit.d.ts +29 -0
- package/dist/migrate/divergenceAudit.js +37 -0
- package/dist/migrate/fieldMap.d.ts +18 -0
- package/dist/migrate/fieldMap.js +68 -0
- package/dist/migrate/v1Import.d.ts +16 -0
- package/dist/migrate/v1Import.js +118 -0
- package/dist/phub.d.ts +18 -0
- package/dist/phub.js +284 -0
- package/dist/recall.d.ts +26 -0
- package/dist/recall.js +162 -0
- package/dist/recipe.d.ts +61 -0
- package/dist/recipe.js +564 -0
- package/dist/reflectionObserver.d.ts +8 -0
- package/dist/reflectionObserver.js +6 -0
- package/dist/reuse.d.ts +48 -0
- package/dist/reuse.js +300 -0
- package/dist/reuseReport.d.ts +20 -0
- package/dist/reuseReport.js +255 -0
- package/dist/reviewFilter.d.ts +4 -0
- package/dist/reviewFilter.js +6 -0
- package/dist/runtimeSessionSource.d.ts +9 -0
- package/dist/runtimeSessionSource.js +29 -0
- package/dist/setupHooks.d.ts +2 -0
- package/dist/setupHooks.js +410 -0
- package/dist/skill2gep.d.ts +144 -0
- package/dist/skill2gep.js +321 -0
- package/dist/skillDistill.d.ts +75 -0
- package/dist/skillDistill.js +342 -0
- package/dist/solo/breaker.d.ts +14 -0
- package/dist/solo/breaker.js +21 -0
- package/dist/solo/gitGuard.d.ts +17 -0
- package/dist/solo/gitGuard.js +62 -0
- package/dist/solo/mode.d.ts +12 -0
- package/dist/solo/mode.js +55 -0
- package/dist/thesis.d.ts +43 -0
- package/dist/thesis.js +179 -0
- package/dist/trajectoryExport.d.ts +1 -0
- package/dist/trajectoryExport.js +895 -0
- package/dist/valueDigest.d.ts +33 -0
- package/dist/valueDigest.js +94 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +14 -0
- package/package.json +38 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export type AutobuyPromptState = 'env_set' | 'non_tty' | 'ack_present' | 'eligible';
|
|
2
|
+
export interface AutobuyPromptResult {
|
|
3
|
+
prompted: boolean;
|
|
4
|
+
decision: 'yes' | 'no' | 'later' | null;
|
|
5
|
+
reason: string;
|
|
6
|
+
}
|
|
7
|
+
interface TtyLike {
|
|
8
|
+
isTTY?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface AutobuyPromptReaderOptions {
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
}
|
|
13
|
+
type AskFn = (question: string, io: {
|
|
14
|
+
input: NodeJS.ReadableStream;
|
|
15
|
+
output: NodeJS.WritableStream;
|
|
16
|
+
}, options?: AutobuyPromptReaderOptions) => Promise<string>;
|
|
17
|
+
export interface AutobuyPromptOptions {
|
|
18
|
+
input?: (NodeJS.ReadableStream & TtyLike);
|
|
19
|
+
output?: NodeJS.WritableStream;
|
|
20
|
+
env?: NodeJS.ProcessEnv;
|
|
21
|
+
ask?: AskFn;
|
|
22
|
+
promptTimeoutMs?: number;
|
|
23
|
+
consentPath?: string;
|
|
24
|
+
now?: () => Date;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Decide whether the prompt is eligible. Precedence (env_set > non_tty > ack_present > eligible) is read straight
|
|
28
|
+
* off getAtpConsent's `source` so it stays bug-for-bug aligned with the runtime gate: a set env => source 'env'
|
|
29
|
+
* regardless of any ack file, and an ack file (env unset) => source 'ack'. We classify env BEFORE TTY so a daemon
|
|
30
|
+
* with the env already set reports 'env_set' (the actionable truth) rather than the generic 'non_tty'.
|
|
31
|
+
*/
|
|
32
|
+
export declare function classifyAutobuyPrompt(env: NodeJS.ProcessEnv, stdin: TtyLike | undefined, ackPath?: string): AutobuyPromptState;
|
|
33
|
+
/**
|
|
34
|
+
* Default reader: a single readline question, settled exactly once. The 'close' handler covers EOF/Ctrl-D, and the
|
|
35
|
+
* bounded timer covers open pseudo-TTYs where no operator ever types. Both fall through to '' -> the caller's safe
|
|
36
|
+
* 'later' branch (no ack written, env untouched).
|
|
37
|
+
*/
|
|
38
|
+
export declare function defaultAsk(question: string, io: {
|
|
39
|
+
input: NodeJS.ReadableStream;
|
|
40
|
+
output: NodeJS.WritableStream;
|
|
41
|
+
}, options?: AutobuyPromptReaderOptions): Promise<string>;
|
|
42
|
+
/**
|
|
43
|
+
* Run the first-run auto-buyer prompt at most once per `evolver autoexec` invocation, BEFORE the resident loop
|
|
44
|
+
* starts. A no-op (no I/O, no file) on every non-eligible branch. Callers should wrap in try/catch so a prompt
|
|
45
|
+
* failure can never block the run — see runAutoExec.
|
|
46
|
+
*/
|
|
47
|
+
export declare function runAutobuyPrompt(opts?: AutobuyPromptOptions): Promise<AutobuyPromptResult>;
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// First-run prompt that introduces the ATP auto-buyer to INTERACTIVE users (PORT v1 #10).
|
|
2
|
+
//
|
|
3
|
+
// v2 already owns the consent substrate (atp.ts: getAtpConsent/setAtpConsent/atpConsentPath, the same
|
|
4
|
+
// `atp-autobuy-ack.json` ack file). What it lacked is the onboarding seam: a one-shot prompt that surfaces the
|
|
5
|
+
// opt-in instead of expecting every operator to discover `evolver atp enable`. This module is that seam — it does
|
|
6
|
+
// NOT introduce a new ack format or a second source of truth; it writes through setAtpConsent so the prompt's
|
|
7
|
+
// decision and the `evolver atp` command land in the exact same file with the exact same precedence.
|
|
8
|
+
//
|
|
9
|
+
// Fires only when ALL hold (mirrors v1, but classified through getAtpConsent's source so the precedence can't
|
|
10
|
+
// drift from the gate):
|
|
11
|
+
// - EVOLVER_ATP_AUTOBUY is unset (a set env always wins → nothing to ask)
|
|
12
|
+
// - stdin is a TTY (skipped under systemd / Docker / CI — exactly where a blocking question would wedge a daemon)
|
|
13
|
+
// - no ack file yet (the operator has not already decided)
|
|
14
|
+
//
|
|
15
|
+
// Outcomes:
|
|
16
|
+
// - y / yes -> ack enabled=true, EVOLVER_ATP_AUTOBUY flipped to 'on' for this process (opt in now)
|
|
17
|
+
// - n / no -> ack enabled=false, never prompted again
|
|
18
|
+
// - anything -> no file written, prompted again next run ("later")
|
|
19
|
+
import { createInterface } from 'node:readline';
|
|
20
|
+
import { atpConsentPath, getAtpConsent, setAtpConsent } from './atp.js';
|
|
21
|
+
const DEFAULT_AUTOBUY_PROMPT_TIMEOUT_MS = 10_000;
|
|
22
|
+
/**
|
|
23
|
+
* Decide whether the prompt is eligible. Precedence (env_set > non_tty > ack_present > eligible) is read straight
|
|
24
|
+
* off getAtpConsent's `source` so it stays bug-for-bug aligned with the runtime gate: a set env => source 'env'
|
|
25
|
+
* regardless of any ack file, and an ack file (env unset) => source 'ack'. We classify env BEFORE TTY so a daemon
|
|
26
|
+
* with the env already set reports 'env_set' (the actionable truth) rather than the generic 'non_tty'.
|
|
27
|
+
*/
|
|
28
|
+
export function classifyAutobuyPrompt(env, stdin, ackPath = atpConsentPath(env)) {
|
|
29
|
+
const consent = getAtpConsent(env, ackPath);
|
|
30
|
+
if (consent.source === 'env')
|
|
31
|
+
return 'env_set';
|
|
32
|
+
if (!stdin || !stdin.isTTY)
|
|
33
|
+
return 'non_tty';
|
|
34
|
+
if (consent.source === 'ack')
|
|
35
|
+
return 'ack_present';
|
|
36
|
+
return 'eligible';
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Default reader: a single readline question, settled exactly once. The 'close' handler covers EOF/Ctrl-D, and the
|
|
40
|
+
* bounded timer covers open pseudo-TTYs where no operator ever types. Both fall through to '' -> the caller's safe
|
|
41
|
+
* 'later' branch (no ack written, env untouched).
|
|
42
|
+
*/
|
|
43
|
+
export function defaultAsk(question, io, options = {}) {
|
|
44
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs !== undefined && options.timeoutMs >= 0
|
|
45
|
+
? options.timeoutMs
|
|
46
|
+
: DEFAULT_AUTOBUY_PROMPT_TIMEOUT_MS;
|
|
47
|
+
return new Promise((resolve) => {
|
|
48
|
+
const rl = createInterface({ input: io.input, output: io.output });
|
|
49
|
+
let settled = false;
|
|
50
|
+
const timer = setTimeout(() => settle(''), timeoutMs);
|
|
51
|
+
function settle(answer) {
|
|
52
|
+
if (settled)
|
|
53
|
+
return;
|
|
54
|
+
settled = true;
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
rl.close();
|
|
57
|
+
resolve((answer || '').trim().toLowerCase());
|
|
58
|
+
}
|
|
59
|
+
rl.on('close', () => settle('')); // EOF / Ctrl-D: settle as '' (later) and never leak the interface
|
|
60
|
+
rl.question(question, (answer) => settle(answer));
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Run the first-run auto-buyer prompt at most once per `evolver autoexec` invocation, BEFORE the resident loop
|
|
65
|
+
* starts. A no-op (no I/O, no file) on every non-eligible branch. Callers should wrap in try/catch so a prompt
|
|
66
|
+
* failure can never block the run — see runAutoExec.
|
|
67
|
+
*/
|
|
68
|
+
export async function runAutobuyPrompt(opts = {}) {
|
|
69
|
+
const input = opts.input ?? process.stdin;
|
|
70
|
+
const output = opts.output ?? process.stdout;
|
|
71
|
+
const env = opts.env ?? process.env;
|
|
72
|
+
const ask = opts.ask ?? defaultAsk;
|
|
73
|
+
const ackPath = opts.consentPath ?? atpConsentPath(env);
|
|
74
|
+
const state = classifyAutobuyPrompt(env, input, ackPath);
|
|
75
|
+
if (state !== 'eligible')
|
|
76
|
+
return { prompted: false, decision: null, reason: state };
|
|
77
|
+
try {
|
|
78
|
+
output.write('\n');
|
|
79
|
+
output.write('[ATP-AutoBuyer] During autonomous execution your evolver can place small ATP\n');
|
|
80
|
+
output.write('orders to fill a capability gap, instead of solving it from scratch (default OFF).\n');
|
|
81
|
+
output.write(' - manual `evolver buy` is unaffected — this is only the autonomous spend path.\n');
|
|
82
|
+
output.write(' - change anytime: `evolver atp enable|disable|status`\n');
|
|
83
|
+
output.write(' - or set EVOLVER_ATP_AUTOBUY=on|off to override the ack file at runtime.\n');
|
|
84
|
+
output.write('\n');
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return { prompted: false, decision: null, reason: 'io_error' };
|
|
88
|
+
}
|
|
89
|
+
let answer;
|
|
90
|
+
try {
|
|
91
|
+
answer = await ask('Enable autoBuyer for this session? [y/n/later] ', { input, output }, {
|
|
92
|
+
timeoutMs: opts.promptTimeoutMs ?? DEFAULT_AUTOBUY_PROMPT_TIMEOUT_MS,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return { prompted: true, decision: null, reason: 'ask_error' };
|
|
97
|
+
}
|
|
98
|
+
const now = opts.now ?? (() => new Date());
|
|
99
|
+
if (answer === 'y' || answer === 'yes') {
|
|
100
|
+
setAtpConsent(true, ackPath, now);
|
|
101
|
+
env['EVOLVER_ATP_AUTOBUY'] = 'on';
|
|
102
|
+
return { prompted: true, decision: 'yes', reason: 'user_accepted' };
|
|
103
|
+
}
|
|
104
|
+
if (answer === 'n' || answer === 'no') {
|
|
105
|
+
setAtpConsent(false, ackPath, now);
|
|
106
|
+
return { prompted: true, decision: 'no', reason: 'user_declined' };
|
|
107
|
+
}
|
|
108
|
+
return { prompted: true, decision: 'later', reason: 'user_postponed' };
|
|
109
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { assetstore, events } from '@evomap/evolver-core';
|
|
2
|
+
import { type LlmDistillRunner } from './autoDistillLlm.js';
|
|
3
|
+
export type AutoDistillAntiGeneMode = 'off' | 'shadow' | 'enforce';
|
|
4
|
+
interface AntiGeneCandidate {
|
|
5
|
+
id?: string;
|
|
6
|
+
summary: string;
|
|
7
|
+
trigger: string[];
|
|
8
|
+
avoid: string[];
|
|
9
|
+
rationale?: string;
|
|
10
|
+
severity?: 'low' | 'medium' | 'high';
|
|
11
|
+
evidence_capsules?: string[];
|
|
12
|
+
source_clusters?: string[];
|
|
13
|
+
}
|
|
14
|
+
interface AntiGeneAsset extends assetstore.AssetRecord {
|
|
15
|
+
type: 'AntiGene';
|
|
16
|
+
schema_version: string;
|
|
17
|
+
id: string;
|
|
18
|
+
summary: string;
|
|
19
|
+
trigger: string[];
|
|
20
|
+
avoid: string[];
|
|
21
|
+
source_clusters: string[];
|
|
22
|
+
evidence_capsules: string[];
|
|
23
|
+
failure_count: number;
|
|
24
|
+
asset_id: string;
|
|
25
|
+
rationale?: string;
|
|
26
|
+
severity?: 'low' | 'medium' | 'high';
|
|
27
|
+
}
|
|
28
|
+
export type AutoDistillAntiGeneResult = {
|
|
29
|
+
ok: true;
|
|
30
|
+
mode: 'enforce';
|
|
31
|
+
antiGene: AntiGeneAsset;
|
|
32
|
+
dataHash: string;
|
|
33
|
+
stored: boolean;
|
|
34
|
+
} | {
|
|
35
|
+
ok: false;
|
|
36
|
+
mode: AutoDistillAntiGeneMode;
|
|
37
|
+
reason: string;
|
|
38
|
+
dataHash?: string;
|
|
39
|
+
candidate?: AntiGeneCandidate;
|
|
40
|
+
};
|
|
41
|
+
export interface AutoDistillAntiGeneOptions {
|
|
42
|
+
mode?: AutoDistillAntiGeneMode;
|
|
43
|
+
env?: NodeJS.ProcessEnv;
|
|
44
|
+
store: assetstore.AssetStoreProvider;
|
|
45
|
+
review?: assetstore.ReviewLedger;
|
|
46
|
+
ingestor?: events.Ingestor;
|
|
47
|
+
statePath?: string;
|
|
48
|
+
cwd?: string;
|
|
49
|
+
now?: () => number;
|
|
50
|
+
runner?: LlmDistillRunner;
|
|
51
|
+
minFailures?: number;
|
|
52
|
+
triggerOverlapMin?: number;
|
|
53
|
+
maxClusters?: number;
|
|
54
|
+
}
|
|
55
|
+
export interface AutoDistillAntiGeneWiring {
|
|
56
|
+
enabled: boolean;
|
|
57
|
+
mode: AutoDistillAntiGeneMode;
|
|
58
|
+
reason?: 'off';
|
|
59
|
+
tick: () => Promise<AutoDistillAntiGeneResult>;
|
|
60
|
+
}
|
|
61
|
+
export declare function autoDistillAntiGene(options: AutoDistillAntiGeneOptions): Promise<AutoDistillAntiGeneResult>;
|
|
62
|
+
export declare function resolveAutoDistillAntiGene(env: NodeJS.ProcessEnv, opts: Omit<AutoDistillAntiGeneOptions, 'env' | 'mode'>): AutoDistillAntiGeneWiring;
|
|
63
|
+
export {};
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// Anti-gene LLM distillation (#326 slice 2): learn guardrails from repeated failures without adding executable
|
|
2
|
+
// strategies to the Gene pool. The output is a local AntiGene asset, quarantined by default, and never selected by
|
|
3
|
+
// the Gene candidate/fallback pool. Approved, signal-matched AntiGenes are surfaced only as advisory warnings.
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { algo, assetstore, events, hub, wire } from '@evomap/evolver-core';
|
|
7
|
+
import { p3Decide, resolveDistillRunner, } from './autoDistillLlm.js';
|
|
8
|
+
const DEFAULT_TIMEOUT_MS = 180_000;
|
|
9
|
+
const DEFAULT_COOLDOWN_MS = 1_800_000;
|
|
10
|
+
const DEFAULT_MAX_ATTEMPTS = 3;
|
|
11
|
+
const DEFAULT_HASH_CAP = 64;
|
|
12
|
+
const DEFAULT_MAX_CLUSTERS = 8;
|
|
13
|
+
const DEFAULT_SEVERITY = 'medium';
|
|
14
|
+
const ALL_CAPSULES_LIMIT = Number.MAX_SAFE_INTEGER;
|
|
15
|
+
function autoDistillAntiGeneStatePath(home = events.evomapHome()) {
|
|
16
|
+
return join(home, 'evolution', 'auto-distill-anti-gene-state.json');
|
|
17
|
+
}
|
|
18
|
+
function envInt(env, name, fallback) {
|
|
19
|
+
const n = Number.parseInt(String(env[name] ?? ''), 10);
|
|
20
|
+
return Number.isFinite(n) && n > 0 ? n : fallback;
|
|
21
|
+
}
|
|
22
|
+
function envFloat(env, name, fallback) {
|
|
23
|
+
const n = Number.parseFloat(String(env[name] ?? ''));
|
|
24
|
+
return Number.isFinite(n) && n > 0 && n <= 1 ? n : fallback;
|
|
25
|
+
}
|
|
26
|
+
function resolveMode(env, explicit) {
|
|
27
|
+
const raw = String(explicit ?? env['EVOLVER_AUTO_DISTILL_ANTI_GENE'] ?? 'off').trim().toLowerCase();
|
|
28
|
+
return raw === 'shadow' || raw === 'enforce' ? raw : 'off';
|
|
29
|
+
}
|
|
30
|
+
function readState(path) {
|
|
31
|
+
if (!existsSync(path))
|
|
32
|
+
return { version: 1, by_hash: {} };
|
|
33
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
34
|
+
return { version: 1, by_hash: parsed.by_hash && typeof parsed.by_hash === 'object' ? parsed.by_hash : {} };
|
|
35
|
+
}
|
|
36
|
+
function writeState(path, state) {
|
|
37
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
38
|
+
const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
39
|
+
writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`);
|
|
40
|
+
renameSync(tmp, path);
|
|
41
|
+
}
|
|
42
|
+
function hasSkipState(record) {
|
|
43
|
+
return Boolean(record?.enforced_at || record?.shadowed_at || (record?.failed_attempts ?? 0) > 0);
|
|
44
|
+
}
|
|
45
|
+
function capByHash(byHash, cap, preserveKey) {
|
|
46
|
+
const keys = Object.keys(byHash);
|
|
47
|
+
if (keys.length <= cap)
|
|
48
|
+
return byHash;
|
|
49
|
+
const age = (key) => {
|
|
50
|
+
const rec = byHash[key] ?? {};
|
|
51
|
+
return Math.max(Date.parse(rec.shadowed_at ?? '') || 0, Date.parse(rec.enforced_at ?? '') || 0, Date.parse(rec.last_attempt_at ?? '') || 0);
|
|
52
|
+
};
|
|
53
|
+
const evictable = keys
|
|
54
|
+
.filter((key) => key !== preserveKey && !hasSkipState(byHash[key]))
|
|
55
|
+
.sort((a, b) => age(a) - age(b));
|
|
56
|
+
const terminalEvictable = keys
|
|
57
|
+
.filter((key) => key !== preserveKey && hasSkipState(byHash[key]))
|
|
58
|
+
.sort((a, b) => age(a) - age(b));
|
|
59
|
+
for (const key of [...evictable, ...terminalEvictable]) {
|
|
60
|
+
if (Object.keys(byHash).length <= cap)
|
|
61
|
+
break;
|
|
62
|
+
delete byHash[key];
|
|
63
|
+
}
|
|
64
|
+
return byHash;
|
|
65
|
+
}
|
|
66
|
+
function patchState(path, dataHash, patch, cap) {
|
|
67
|
+
try {
|
|
68
|
+
const state = readState(path);
|
|
69
|
+
const cur = state.by_hash[dataHash] ?? { shadowed_at: null, enforced_at: null, enforced_gene_id: null, failed_attempts: 0, last_attempt_at: null };
|
|
70
|
+
const next = { ...cur, ...patch };
|
|
71
|
+
if (patch.failed_attempts_inc)
|
|
72
|
+
next.failed_attempts = (cur.failed_attempts ?? 0) + 1;
|
|
73
|
+
delete next.failed_attempts_inc;
|
|
74
|
+
state.by_hash[dataHash] = next;
|
|
75
|
+
state.by_hash = capByHash(state.by_hash, cap, dataHash);
|
|
76
|
+
writeState(path, state);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function isRecord(value) {
|
|
84
|
+
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
|
85
|
+
}
|
|
86
|
+
function findJsonObjects(text) {
|
|
87
|
+
const s = String(text ?? '');
|
|
88
|
+
const out = [];
|
|
89
|
+
let start = s.indexOf('{');
|
|
90
|
+
while (start >= 0) {
|
|
91
|
+
let depth = 0;
|
|
92
|
+
let inString = false;
|
|
93
|
+
let escaped = false;
|
|
94
|
+
let advanced = -1;
|
|
95
|
+
for (let i = start; i < s.length; i += 1) {
|
|
96
|
+
const ch = s[i];
|
|
97
|
+
if (inString) {
|
|
98
|
+
if (escaped) {
|
|
99
|
+
escaped = false;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (ch === '\\') {
|
|
103
|
+
escaped = true;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (ch === '"')
|
|
107
|
+
inString = false;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (ch === '"') {
|
|
111
|
+
inString = true;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (ch === '{')
|
|
115
|
+
depth += 1;
|
|
116
|
+
if (ch === '}') {
|
|
117
|
+
depth -= 1;
|
|
118
|
+
if (depth === 0) {
|
|
119
|
+
try {
|
|
120
|
+
out.push(JSON.parse(s.slice(start, i + 1)));
|
|
121
|
+
advanced = i + 1;
|
|
122
|
+
}
|
|
123
|
+
catch { /* keep scanning from the next opening brace */ }
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
start = s.indexOf('{', advanced >= 0 ? advanced : start + 1);
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
function pickAntiGeneObject(text) {
|
|
133
|
+
const objects = findJsonObjects(text);
|
|
134
|
+
const antiGene = objects.find((object) => isRecord(object) && object['type'] === 'AntiGene');
|
|
135
|
+
if (antiGene)
|
|
136
|
+
return antiGene;
|
|
137
|
+
const decline = objects.find((object) => isRecord(object) && object['type'] === 'none');
|
|
138
|
+
if (decline)
|
|
139
|
+
return decline;
|
|
140
|
+
return objects[0] ?? null;
|
|
141
|
+
}
|
|
142
|
+
function isAntiGeneOrDecline(value) {
|
|
143
|
+
return isRecord(value) && (value['type'] === 'AntiGene' || value['type'] === 'none');
|
|
144
|
+
}
|
|
145
|
+
function parseAntiGeneOutput(stdout) {
|
|
146
|
+
const text = String(stdout ?? '');
|
|
147
|
+
const lines = text.split('\n').map((line) => line.trim()).filter(Boolean);
|
|
148
|
+
const last = lines.at(-1);
|
|
149
|
+
if (!last)
|
|
150
|
+
return null;
|
|
151
|
+
try {
|
|
152
|
+
const parsed = JSON.parse(last);
|
|
153
|
+
if (isRecord(parsed) && 'is_error' in parsed) {
|
|
154
|
+
if (parsed['is_error'])
|
|
155
|
+
return null;
|
|
156
|
+
const result = parsed['result'];
|
|
157
|
+
if (typeof result === 'string')
|
|
158
|
+
return pickAntiGeneObject(result);
|
|
159
|
+
return isAntiGeneOrDecline(result) ? result : pickAntiGeneObject(text) ?? result;
|
|
160
|
+
}
|
|
161
|
+
return isAntiGeneOrDecline(parsed) ? parsed : pickAntiGeneObject(text) ?? parsed;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return pickAntiGeneObject(text);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function strings(value) {
|
|
168
|
+
if (!Array.isArray(value))
|
|
169
|
+
return [];
|
|
170
|
+
return [...new Set(value.map(String).map((item) => item.trim()).filter(Boolean))];
|
|
171
|
+
}
|
|
172
|
+
function asSeverity(value) {
|
|
173
|
+
return value === 'low' || value === 'medium' || value === 'high' ? value : undefined;
|
|
174
|
+
}
|
|
175
|
+
function asAntiGeneCandidate(value) {
|
|
176
|
+
if (!isRecord(value))
|
|
177
|
+
return null;
|
|
178
|
+
if (typeof value['type'] === 'string' && value['type'] !== 'AntiGene')
|
|
179
|
+
return null;
|
|
180
|
+
const summary = typeof value['summary'] === 'string' ? value['summary'].trim() : '';
|
|
181
|
+
const trigger = strings(value['trigger']);
|
|
182
|
+
const avoid = strings(value['avoid']);
|
|
183
|
+
if (!summary || trigger.length === 0 || avoid.length === 0)
|
|
184
|
+
return null;
|
|
185
|
+
return {
|
|
186
|
+
...(typeof value['id'] === 'string' && value['id'].trim() ? { id: value['id'].trim() } : {}),
|
|
187
|
+
summary,
|
|
188
|
+
trigger,
|
|
189
|
+
avoid,
|
|
190
|
+
...(typeof value['rationale'] === 'string' && value['rationale'].trim() ? { rationale: value['rationale'].trim() } : {}),
|
|
191
|
+
...(asSeverity(value['severity']) ? { severity: asSeverity(value['severity']) } : {}),
|
|
192
|
+
...(strings(value['evidence_capsules']).length > 0 ? { evidence_capsules: strings(value['evidence_capsules']) } : {}),
|
|
193
|
+
...(strings(value['source_clusters']).length > 0 ? { source_clusters: strings(value['source_clusters']) } : {}),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function slug(value) {
|
|
197
|
+
const out = value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);
|
|
198
|
+
return out || 'recurring-failure-guardrail';
|
|
199
|
+
}
|
|
200
|
+
function buildAntiGenePrompt(input) {
|
|
201
|
+
const clusters = hub.redactDeep(input.failureClusters.map((cluster) => ({
|
|
202
|
+
clusterId: cluster.clusterId,
|
|
203
|
+
trigger: cluster.trigger,
|
|
204
|
+
sharedTrigger: cluster.sharedTrigger,
|
|
205
|
+
capsuleIds: cluster.capsuleIds,
|
|
206
|
+
genes: cluster.genes,
|
|
207
|
+
failures: cluster.failureCapsules.map((capsule) => ({
|
|
208
|
+
capsuleId: capsule.capsuleId,
|
|
209
|
+
trigger: capsule.trigger,
|
|
210
|
+
gene: capsule.gene,
|
|
211
|
+
summary: capsule.summary,
|
|
212
|
+
outcome: capsule.outcome,
|
|
213
|
+
proofOfWork: capsule.proofOfWork,
|
|
214
|
+
})),
|
|
215
|
+
})));
|
|
216
|
+
return [
|
|
217
|
+
'You are synthesizing one EvoMap AntiGene from recurring failed Capsules.',
|
|
218
|
+
'An AntiGene is a guardrail: it says what to avoid or check before repeating a known failure pattern.',
|
|
219
|
+
'Return only JSON. Do not use markdown. Do not include commentary.',
|
|
220
|
+
'',
|
|
221
|
+
'Rules:',
|
|
222
|
+
'- Produce a single AntiGene object.',
|
|
223
|
+
'- Do not include executable strategy steps. The asset must never be used as a Gene strategy.',
|
|
224
|
+
'- Trigger tokens must be generic failure signals, not one-off file names or secrets.',
|
|
225
|
+
'- Avoid entries must be concrete guardrails phrased as things NOT to do, or pre-flight checks to prevent recurrence.',
|
|
226
|
+
'- If the clusters do not show a reusable repeated failure pattern, return exactly {"type":"none"}.',
|
|
227
|
+
'',
|
|
228
|
+
'Required JSON shape:',
|
|
229
|
+
'{"type":"AntiGene","id":"anti_gene_<descriptive-kebab-name>","summary":"...","trigger":["signal"],"avoid":["guardrail"],"rationale":"...","severity":"low|medium|high","source_clusters":["anti_cluster_..."],"evidence_capsules":["sha256:..."]}',
|
|
230
|
+
'',
|
|
231
|
+
`DATA_HASH: ${input.dataHash}`,
|
|
232
|
+
`FAILED_CAPSULE_COUNT: ${input.failedCapsuleCount}`,
|
|
233
|
+
'FAILURE_CLUSTERS:',
|
|
234
|
+
JSON.stringify(clusters, null, 2),
|
|
235
|
+
].join('\n');
|
|
236
|
+
}
|
|
237
|
+
function toAntiGeneAsset(candidate, input) {
|
|
238
|
+
const sourceClusters = candidate.source_clusters?.length
|
|
239
|
+
? candidate.source_clusters
|
|
240
|
+
: input.failureClusters.map((cluster) => cluster.clusterId);
|
|
241
|
+
const evidenceCapsules = candidate.evidence_capsules?.length
|
|
242
|
+
? candidate.evidence_capsules
|
|
243
|
+
: [...new Set(input.failureClusters.flatMap((cluster) => cluster.capsuleIds))].sort();
|
|
244
|
+
const failureCount = input.failureClusters.reduce((sum, cluster) => sum + cluster.capsuleIds.length, 0);
|
|
245
|
+
const record = {
|
|
246
|
+
type: 'AntiGene',
|
|
247
|
+
schema_version: wire.SCHEMA_VERSION,
|
|
248
|
+
id: candidate.id && candidate.id.startsWith('anti_gene_') ? candidate.id : `anti_gene_${slug(candidate.id ?? candidate.summary)}`,
|
|
249
|
+
summary: candidate.summary,
|
|
250
|
+
trigger: [...new Set(candidate.trigger)].sort(),
|
|
251
|
+
avoid: [...new Set(candidate.avoid)],
|
|
252
|
+
source_clusters: [...new Set(sourceClusters)].sort(),
|
|
253
|
+
evidence_capsules: [...new Set(evidenceCapsules)].sort(),
|
|
254
|
+
failure_count: failureCount,
|
|
255
|
+
...(candidate.rationale ? { rationale: candidate.rationale } : {}),
|
|
256
|
+
severity: candidate.severity ?? DEFAULT_SEVERITY,
|
|
257
|
+
};
|
|
258
|
+
const assetId = wire.computeAssetId({ ...record, asset_id: '' });
|
|
259
|
+
if (!assetId)
|
|
260
|
+
throw new Error('AntiGene asset_id compute failed');
|
|
261
|
+
return { ...record, asset_id: assetId };
|
|
262
|
+
}
|
|
263
|
+
async function emitDistilledEventIfAbsent(ingestor, antiGene, dataHash, clusterCount) {
|
|
264
|
+
if (!ingestor)
|
|
265
|
+
return;
|
|
266
|
+
const exists = ingestor.readAll().some((event) => {
|
|
267
|
+
const payload = event.payload;
|
|
268
|
+
return event.type === 'anti_gene.distilled' && payload?.['assetId'] === antiGene.asset_id && payload?.['source'] === 'auto-distill-anti-gene';
|
|
269
|
+
});
|
|
270
|
+
if (exists)
|
|
271
|
+
return;
|
|
272
|
+
await ingestor.ingest({
|
|
273
|
+
type: 'anti_gene.distilled',
|
|
274
|
+
payload: {
|
|
275
|
+
antiGeneId: antiGene.id,
|
|
276
|
+
assetId: antiGene.asset_id,
|
|
277
|
+
source: 'auto-distill-anti-gene',
|
|
278
|
+
dataHash,
|
|
279
|
+
clusterCount,
|
|
280
|
+
failureCount: antiGene.failure_count,
|
|
281
|
+
},
|
|
282
|
+
human: { title: `anti-gene distilled ${antiGene.id}`.slice(0, 80), severity: 'info' },
|
|
283
|
+
actor: { kind: 'machine', id: 'auto-distill-anti-gene' },
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
async function emitShadowObservationIfAbsent(ingestor, dataHash, observation) {
|
|
287
|
+
if (!ingestor)
|
|
288
|
+
return;
|
|
289
|
+
const exists = ingestor.readAll().some((event) => {
|
|
290
|
+
const payload = event.payload;
|
|
291
|
+
return event.type === 'anti_gene.distill_shadowed' && payload?.['dataHash'] === dataHash && payload?.['source'] === 'auto-distill-anti-gene';
|
|
292
|
+
});
|
|
293
|
+
if (exists)
|
|
294
|
+
return;
|
|
295
|
+
const payload = observation.status === 'candidate'
|
|
296
|
+
? {
|
|
297
|
+
dataHash,
|
|
298
|
+
source: 'auto-distill-anti-gene',
|
|
299
|
+
status: 'candidate',
|
|
300
|
+
summary: observation.candidate.summary,
|
|
301
|
+
trigger: observation.candidate.trigger,
|
|
302
|
+
avoid: observation.candidate.avoid,
|
|
303
|
+
}
|
|
304
|
+
: { dataHash, source: 'auto-distill-anti-gene', status: 'declined' };
|
|
305
|
+
const title = observation.status === 'candidate'
|
|
306
|
+
? `shadow anti-gene candidate ${slug(observation.candidate.summary)}`
|
|
307
|
+
: 'shadow anti-gene declined';
|
|
308
|
+
await ingestor.ingest({
|
|
309
|
+
type: 'anti_gene.distill_shadowed',
|
|
310
|
+
payload,
|
|
311
|
+
human: { title: title.slice(0, 80), severity: 'info' },
|
|
312
|
+
actor: { kind: 'machine', id: 'auto-distill-anti-gene' },
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
export async function autoDistillAntiGene(options) {
|
|
316
|
+
const env = options.env ?? process.env;
|
|
317
|
+
const mode = resolveMode(env, options.mode);
|
|
318
|
+
if (mode === 'off')
|
|
319
|
+
return { ok: false, mode, reason: 'disabled' };
|
|
320
|
+
const capsules = await options.store.list('Capsule', ALL_CAPSULES_LIMIT);
|
|
321
|
+
const input = algo.collectAntiDistillInput(capsules, {
|
|
322
|
+
minFailures: options.minFailures ?? envInt(env, 'EVOLVER_AUTO_DISTILL_ANTI_GENE_MIN_FAILURES', algo.ANTI_DISTILL_MIN_FAILURES),
|
|
323
|
+
triggerOverlapMin: options.triggerOverlapMin ?? envFloat(env, 'EVOLVER_AUTO_DISTILL_ANTI_GENE_TRIGGER_OVERLAP_MIN', algo.ANTI_DISTILL_TRIGGER_OVERLAP_MIN),
|
|
324
|
+
maxClusters: options.maxClusters ?? envInt(env, 'EVOLVER_AUTO_DISTILL_ANTI_GENE_MAX_CLUSTERS', DEFAULT_MAX_CLUSTERS),
|
|
325
|
+
});
|
|
326
|
+
if (input.failureClusters.length === 0)
|
|
327
|
+
return { ok: false, mode, reason: 'insufficient_data', dataHash: input.dataHash };
|
|
328
|
+
const now = options.now?.() ?? Date.now();
|
|
329
|
+
const statePath = options.statePath ?? autoDistillAntiGeneStatePath();
|
|
330
|
+
let state;
|
|
331
|
+
try {
|
|
332
|
+
state = readState(statePath);
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
return { ok: false, mode, reason: 'state_read_failed', dataHash: input.dataHash };
|
|
336
|
+
}
|
|
337
|
+
const cooldownMs = envInt(env, 'EVOLVER_AUTO_DISTILL_ANTI_GENE_COOLDOWN_MS', DEFAULT_COOLDOWN_MS);
|
|
338
|
+
const maxAttempts = envInt(env, 'EVOLVER_AUTO_DISTILL_ANTI_GENE_MAX_ATTEMPTS', DEFAULT_MAX_ATTEMPTS);
|
|
339
|
+
const decision = p3Decide(mode, state.by_hash[input.dataHash], now, { cooldownMs, maxAttempts });
|
|
340
|
+
if (decision !== 'spawn')
|
|
341
|
+
return { ok: false, mode, reason: decision, dataHash: input.dataHash };
|
|
342
|
+
const hashCap = envInt(env, 'EVOLVER_AUTO_DISTILL_ANTI_GENE_HASH_CAP', DEFAULT_HASH_CAP);
|
|
343
|
+
if (!patchState(statePath, input.dataHash, { last_attempt_at: new Date(now).toISOString() }, hashCap)) {
|
|
344
|
+
return { ok: false, mode, reason: 'state_write_failed', dataHash: input.dataHash };
|
|
345
|
+
}
|
|
346
|
+
const prompt = buildAntiGenePrompt(input);
|
|
347
|
+
if (hub.detectEnvValueLeaks(prompt, env).length > 0) {
|
|
348
|
+
return { ok: false, mode, reason: 'prompt_env_leak_blocked', dataHash: input.dataHash };
|
|
349
|
+
}
|
|
350
|
+
const runner = options.runner ?? resolveDistillRunner(env);
|
|
351
|
+
const timeoutMs = envInt(env, 'EVOLVE_DISTILL_TIMEOUT_MS', DEFAULT_TIMEOUT_MS);
|
|
352
|
+
const llm = await runner(prompt, { cwd: options.cwd ?? process.cwd(), timeoutMs, env });
|
|
353
|
+
if (llm.exitCode !== 0) {
|
|
354
|
+
return { ok: false, mode, reason: llm.exitCode === null ? 'llm_spawn_error' : 'llm_nonzero_exit', dataHash: input.dataHash };
|
|
355
|
+
}
|
|
356
|
+
const parsed = parseAntiGeneOutput(llm.stdout);
|
|
357
|
+
if (parsed && isRecord(parsed) && parsed['type'] === 'none') {
|
|
358
|
+
if (mode === 'shadow') {
|
|
359
|
+
await emitShadowObservationIfAbsent(options.ingestor, input.dataHash, { status: 'declined' });
|
|
360
|
+
if (!patchState(statePath, input.dataHash, { shadowed_at: new Date(now).toISOString() }, hashCap)) {
|
|
361
|
+
return { ok: false, mode, reason: 'state_write_failed_after_shadow', dataHash: input.dataHash };
|
|
362
|
+
}
|
|
363
|
+
return { ok: false, mode, reason: 'shadow_logged', dataHash: input.dataHash };
|
|
364
|
+
}
|
|
365
|
+
if (!patchState(statePath, input.dataHash, { enforced_at: new Date(now).toISOString() }, hashCap)) {
|
|
366
|
+
return { ok: false, mode, reason: 'state_write_failed_after_decline', dataHash: input.dataHash };
|
|
367
|
+
}
|
|
368
|
+
return { ok: false, mode, reason: 'no_reusable_failure_pattern', dataHash: input.dataHash };
|
|
369
|
+
}
|
|
370
|
+
const candidate = asAntiGeneCandidate(parsed);
|
|
371
|
+
if (!candidate) {
|
|
372
|
+
patchState(statePath, input.dataHash, { failed_attempts_inc: true }, hashCap);
|
|
373
|
+
return { ok: false, mode, reason: 'no_anti_gene_in_response', dataHash: input.dataHash };
|
|
374
|
+
}
|
|
375
|
+
if (mode === 'shadow') {
|
|
376
|
+
await emitShadowObservationIfAbsent(options.ingestor, input.dataHash, { status: 'candidate', candidate });
|
|
377
|
+
if (!patchState(statePath, input.dataHash, { shadowed_at: new Date(now).toISOString() }, hashCap)) {
|
|
378
|
+
return { ok: false, mode, reason: 'state_write_failed_after_shadow', dataHash: input.dataHash, candidate };
|
|
379
|
+
}
|
|
380
|
+
return { ok: false, mode, reason: 'shadow_logged', dataHash: input.dataHash, candidate };
|
|
381
|
+
}
|
|
382
|
+
const antiGene = toAntiGeneAsset(candidate, input);
|
|
383
|
+
await emitDistilledEventIfAbsent(options.ingestor, antiGene, input.dataHash, input.failureClusters.length);
|
|
384
|
+
options.review?.quarantineIfAbsent(antiGene.asset_id, 'anti-gene LLM-distilled - review before use');
|
|
385
|
+
const put = await options.store.put(antiGene);
|
|
386
|
+
const stateWritten = patchState(statePath, input.dataHash, { enforced_at: new Date(now).toISOString(), enforced_gene_id: antiGene.id }, hashCap);
|
|
387
|
+
if (!stateWritten)
|
|
388
|
+
return { ok: false, mode, reason: 'state_write_failed_after_store', dataHash: input.dataHash };
|
|
389
|
+
return { ok: true, mode, antiGene, dataHash: input.dataHash, stored: put.stored };
|
|
390
|
+
}
|
|
391
|
+
export function resolveAutoDistillAntiGene(env, opts) {
|
|
392
|
+
const mode = resolveMode(env);
|
|
393
|
+
if (mode === 'off')
|
|
394
|
+
return { enabled: false, mode, reason: 'off', tick: async () => ({ ok: false, mode, reason: 'disabled' }) };
|
|
395
|
+
return { enabled: true, mode, tick: () => autoDistillAntiGene({ ...opts, env, mode }) };
|
|
396
|
+
}
|