-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlearn-loop.ts
More file actions
2862 lines (2597 loc) · 115 KB
/
Copy pathlearn-loop.ts
File metadata and controls
2862 lines (2597 loc) · 115 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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {ModApi} from '@commandcode/harness';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import {spawnSync} from 'node:child_process';
// ── Learn Loop — the learning slot of the truth pipeline ────────────────────
//
// learn-loop distills project workflow patterns from raw episodes
// (project-scoped <project>/.agents/learning/). It records everything,
// distills later, and manages the candidate → shadow → active artifact
// lifecycle.
//
// It sits BESIDE memory-bank, which owns durable project facts in
// .agents/memory/ with a write-bar. The split:
// memory-bank = memory (gated verified facts: what the project IS)
// learn-loop = learning (ungated raw feed: how the work goes — issues,
// corrections, workflows — distilled into patterns)
//
// They share no state, no commands, and no store. Both may recall
// contextually — memory-bank injects [memory] leads, learn-loop injects
// pattern leads — and both stay quiet and capped.
//
// Harness-neutral twin: the templates kit's learning-loop.md protocol owns
// this lifecycle (record → distill → shadow → promote → merge/decay) for any
// harness. The `.agents/learning/` store layout is shared with the protocol —
// if this mod's layout changes, update the protocol's "drift boundary" note.
// ── Types ────────────────────────────────────────────────────────────────────
interface Episode {
task_signature: string;
files: string[];
tools: string[];
verify: string[];
outcome: string;
user_corrections: string[];
subagents: string[];
skill_used: string | null;
model: string;
confidence: number;
ts: string;
distilled?: boolean;
}
interface Artifact {
kind: 'skill' | 'taste' | 'warning' | 'guard';
status: 'candidate' | 'shadow' | 'active' | 'archived' | 'rejected';
path: string;
scope: 'user' | 'project' | 'global';
tags: string[];
description: string;
confidence: number;
shadow_runs: number;
green: number;
red: number;
rejections: number;
episodes: number[];
created: string;
last_verified: string;
last_used: string;
pinned: boolean;
version?: number;
use_count: number;
installed_at?: string;
rejection_reason?: string;
}
interface IndexData {
artifacts: Record<string, Artifact>;
episode_count: number;
last_curator_run: string;
digests: DigestEntry[];
}
interface DigestEntry {
date: string;
summary: string;
}
interface EpisodeInFlight {
task_signature: string;
files: Set<string>;
tools: Set<string>;
verify: Set<string>;
user_corrections: string[];
subagents: Set<string>;
skill_used: string | null;
failures: number;
model: string;
draftCreated: boolean;
distilled: boolean;
}
interface EpisodeLine {
line: number;
id: number;
data: Record<string, unknown>;
}
// ── Paths ────────────────────────────────────────────────────────────────────
// Project-scoped, shared .agents convention: <project>/.agents/learning/
// Reassigned at factory start from cmd.cwd (module scope has no cmd).
let LEARNING_DIR = path.join(os.homedir(), '.commandcode', 'learning');
let EPISODES_PATH = path.join(LEARNING_DIR, 'episodes.jsonl');
let INDEX_PATH = path.join(LEARNING_DIR, 'index.json');
let CANDIDATES_DIR = path.join(LEARNING_DIR, 'candidates');
let ACTIVE_DIR = path.join(LEARNING_DIR, 'active');
let GRAVEYARD_DIR = path.join(LEARNING_DIR, 'graveyard');
// Real skill output: Command Code auto-loads .agents/skills/. Promotion
// installs the SKILL.md here so it becomes a live, loadable skill.
let SKILLS_OUTPUT_DIR = path.join(os.homedir(), '.agents', 'skills');
// Autonomous-action receipts: one JSONL line per autonomous move.
let AUTONOMY_PATH = path.join(LEARNING_DIR, 'autonomy.jsonl');
// Persistent merge-pair dismissals: agent judgment "these are different jobs".
let MERGE_DISMISSALS_FILE = path.join(LEARNING_DIR, 'merge-dismissals.json');
// ── Cross-process file lock ──────────────────────────────────────────────
// Parallel Command Code sessions run in separate processes but share this
// project's store files. Read-modify-write sequences (loadIndex→saveIndex,
// episode appends, skill-dir moves) must not interleave. The lock is a
// mutually-exclusive mkdir with an atomic rename — no dependency, works
// across processes, and the metadata file records who holds it.
//
// Reentrant per process: nested acquire() calls from the same process share
// one lock handle (a depth counter), so saveIndex inside a locked region
// doesn't self-deadlock. Cross-process waiters retry for up to ~10s, then
// steal a lock whose holder is gone (stale) — the mutex never hard-blocks.
const LOCK_KEYS = new Map<string, {depth: number}>();
const LOCK_WAIT_MS = 10000;
const LOCK_RETRY_MS = 40;
function lockTarget(key: string): string {
return path.join(LEARNING_DIR, '.locks', `${slugifyLock(key)}.lock`);
}
function slugifyLock(key: string): string {
return key.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 40);
}
function lockHolder(lockDir: string): string {
try {
return fs.readFileSync(path.join(lockDir, 'owner.json'), 'utf-8').trim();
} catch {
return '?';
}
}
function acquireLock(key: string): (() => void) | null {
const existing = LOCK_KEYS.get(key);
if (existing) {
existing.depth += 1;
return () => {
existing.depth -= 1;
if (existing.depth <= 0) LOCK_KEYS.delete(key);
};
}
const target = lockTarget(key);
try { ensureDir(path.dirname(target)); } catch { /* best-effort */ }
const started = Date.now();
const tmp = target + '.tmp-' + process.pid;
while (true) {
try {
fs.mkdirSync(tmp, {recursive: false});
try {
fs.renameSync(tmp, target);
} catch {
// Another process won the race or holds the lock.
fs.rmSync(tmp, {recursive: true, force: true});
if (Date.now() - started > LOCK_WAIT_MS) {
// Stale-steal: holder pid no longer alive.
const holder = lockHolder(target);
if (/^\d+$/.test(holder) && !isProcessAlive(Number(holder))) {
fs.rmSync(target, {recursive: true, force: true});
continue;
}
return null;
}
sleepMs(LOCK_RETRY_MS);
continue;
}
} catch {
if (Date.now() - started > LOCK_WAIT_MS) return null;
sleepMs(LOCK_RETRY_MS);
continue;
}
try {
fs.writeFileSync(path.join(target, 'owner.json'),
JSON.stringify({pid: process.pid, ts: new Date().toISOString()}));
} catch { /* lock is held even without metadata */ }
const handle = {depth: 1};
LOCK_KEYS.set(key, handle);
return () => {
handle.depth -= 1;
if (handle.depth > 0) return;
LOCK_KEYS.delete(key);
try { fs.rmSync(target, {recursive: true, force: true}); } catch { /* stale later */ }
};
}
}
function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return (e as NodeJS.ErrnoException).code === 'EPERM';
}
}
function sleepMs(ms: number): void {
const until = Date.now() + ms;
// Busy-wait is fine here: contention is rare, and SyncFS calls must not
// yield to timers (node timers don't fire during tight sync loops).
while (Date.now() < until) { /* spin */ }
}
function withLock<T>(key: string, fn: () => T): T | null {
const release = acquireLock(key);
if (!release) return null;
try {
return fn();
} finally {
release();
}
}
function writeReceipt(entry: Record<string, unknown>): void {
try {
ensureDir(LEARNING_DIR);
fs.appendFileSync(AUTONOMY_PATH, JSON.stringify({ts: new Date().toISOString(), ...entry}) + '\n');
} catch { /* receipts are best-effort */ }
}
const STOPWORDS = new Set([
'the', 'and', 'for', 'that', 'this', 'with', 'from', 'have', 'are',
'was', 'not', 'but', 'you', 'all', 'can', 'had', 'her', 'was', 'one',
'our', 'out', 'has', 'been', 'when', 'your', 'how', 'will', 'each',
'about', 'which', 'their', 'said', 'would', 'make', 'like', 'just',
'into', 'them', 'than', 'then', 'its', 'over', 'also', 'after',
'what', 'only', 'other', 'more', 'some', 'could', 'these', 'very',
]);
// ── Helpers ──────────────────────────────────────────────────────────────────
function ensureDir(dir: string): void {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, {recursive: true});
}
function loadIndex(): IndexData {
try {
if (fs.existsSync(INDEX_PATH)) {
const parsed = JSON.parse(fs.readFileSync(INDEX_PATH, 'utf-8'));
return {
artifacts: parsed.artifacts && typeof parsed.artifacts === 'object' ? parsed.artifacts : {},
episode_count: typeof parsed.episode_count === 'number' ? parsed.episode_count : 0,
last_curator_run: typeof parsed.last_curator_run === 'string' ? parsed.last_curator_run : '',
digests: Array.isArray(parsed.digests) ? parsed.digests : [],
};
}
} catch { /* corrupted, start fresh */ }
return {artifacts: {}, episode_count: 0, last_curator_run: '', digests: []};
}
function saveIndex(idx: IndexData): void {
ensureDir(LEARNING_DIR);
const tmp = INDEX_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(idx, null, 2));
fs.renameSync(tmp, INDEX_PATH);
}
function appendEpisode(ep: Episode): void {
// Locked: two parallel sessions flushing at once would interleave the
// append and the index count bump, dropping episodes or corrupting the
// file. Best-effort under contention (skip rather than corrupt).
withLock('episodes', () => {
ensureDir(LEARNING_DIR);
fs.appendFileSync(EPISODES_PATH, JSON.stringify(ep) + '\n');
const idx = loadIndex();
idx.episode_count += 1;
saveIndex(idx);
});
}
function readEpisodeLines(): EpisodeLine[] {
try {
if (!fs.existsSync(EPISODES_PATH)) return [];
const lines = fs.readFileSync(EPISODES_PATH, 'utf-8').split('\n');
const out: EpisodeLine[] = [];
for (let i = 0; i < lines.length; i++) {
const text = lines[i];
if (!text.trim()) continue;
try {
out.push({line: i + 1, id: i + 1, data: JSON.parse(text)});
} catch { /* skip corrupt line */ }
}
return out;
} catch { return []; }
}
function isTombstone(data: Record<string, unknown>): boolean {
return data._tombstone === true;
}
function replaceEpisodeLine(line: number, data: Record<string, unknown>): void {
withLock('episodes', () => {
try {
if (!fs.existsSync(EPISODES_PATH)) return;
const raw = fs.readFileSync(EPISODES_PATH, 'utf-8').split('\n');
if (line < 1 || line > raw.length) return;
raw[line - 1] = JSON.stringify(data);
const tmp = EPISODES_PATH + '.tmp';
fs.writeFileSync(tmp, raw.join('\n'));
fs.renameSync(tmp, EPISODES_PATH);
} catch { /* ok */ }
});
}
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 60);
}
function extractKeywords(text: string): string[] {
const words = text.toLowerCase().split(/[\s\-_.,;:!?()[\]{}"'`~@#$%^&*+=<>/\\|]+/);
return words
.filter(w => w.length > 2 && !STOPWORDS.has(w))
.slice(0, 20);
}
function extractTaskSignature(userText: string, cwd: string): string {
const shortCwd = path.basename(cwd);
const verbs = [
'fix', 'debug', 'build', 'add', 'create', 'implement', 'refactor',
'migrate', 'deploy', 'test', 'update', 'remove', 'configure', 'setup',
'write', 'generate', 'analyze', 'optimize', 'review', 'document',
];
const lower = userText.toLowerCase();
const verb = verbs.find(v => lower.startsWith(v)) || 'task';
const clean = userText
.replace(/^(can you |please |help me |i need (to |you to )?)/i, '')
.replace(/[^a-z0-9\s-]/gi, '')
.replace(/\s+/g, '-')
.toLowerCase()
.slice(0, 80);
return `${shortCwd}:${verb}:${clean}`;
}
function extractFilePath(input: unknown): string | null {
if (typeof input === 'object' && input !== null && 'file_path' in input) {
return String((input as Record<string, unknown>).file_path);
}
return null;
}
function extractCmd(input: unknown): string {
if (typeof input !== 'object' || input === null) return '';
const rec = input as Record<string, unknown>;
let cmd = '';
if (typeof rec.command === 'string') cmd = rec.command;
if (Array.isArray(rec.args)) {
cmd = cmd + ' ' + (rec.args as unknown[]).map(String).join(' ');
}
return cmd.trim();
}
function scoreMatch(queryKeys: string[], keys: string[]): number {
let overlap = 0;
for (const qk of queryKeys) {
if (keys.includes(qk)) overlap++;
else {
for (const k of keys) {
if (k.includes(qk) || qk.includes(k)) { overlap += 0.5; break; }
}
}
}
return queryKeys.length > 0 ? overlap / queryKeys.length : 0;
}
// Tool results are content blocks, not strings — normalize for regex checks.
function contentText(result: unknown): string {
if (typeof result === 'string') return result;
if (Array.isArray(result)) {
return result
.map(block => {
if (typeof block === 'object' && block !== null &&
(block as Record<string, unknown>).type === 'text') {
return String((block as Record<string, unknown>).text ?? '');
}
return '';
})
.join('\n');
}
if (result && typeof result === 'object') {
const rec = result as Record<string, unknown>;
return [rec.stdout, rec.stderr]
.filter((v): v is string => typeof v === 'string')
.join('\n');
}
return '';
}
function resolveArtifactFile(art: Artifact): string | null {
try {
const base = path.join(LEARNING_DIR, art.path);
if (!fs.existsSync(base)) return null;
const st = fs.statSync(base);
if (st.isFile()) return base;
if (st.isDirectory()) {
const files = fs.readdirSync(base).filter(f => f.endsWith('.md') || f.endsWith('.ts'));
if (files.length > 0) return path.join(base, files[0]);
}
} catch { /* ok */ }
return null;
}
// ── Real skill file helpers ─────────────────────────────────────────────────
// Promotion of kind=skill artifacts installs a live SKILL.md under
// .agents/skills/ (auto-loaded by Command Code). Taste/warning/guard stay
// internal to the learning store — they are patterns, not skills.
function skillFileFor(id: string): string {
return path.join(SKILLS_OUTPUT_DIR, id, 'SKILL.md');
}
// Ownership marker: learn-loop only manages skill dirs it installed itself.
// User-installed skills are never touched.
const MANAGED_MARKER = '.managed.json';
function markerFileFor(id: string): string {
return path.join(SKILLS_OUTPUT_DIR, id, MANAGED_MARKER);
}
function isManagedSkillDir(id: string): boolean {
const markerPath = markerFileFor(id);
if (!fs.existsSync(markerPath)) return false;
try {
const marker = JSON.parse(fs.readFileSync(markerPath, 'utf-8'));
return marker && marker.owner === 'learn-loop';
} catch {
return false;
}
}
// Returns null if the skill dir is absent or managed by learn-loop.
// Returns an error string if a foreign (user-installed) skill dir exists.
function foreignSkillConflict(id: string): string | null {
const dir = path.join(SKILLS_OUTPUT_DIR, id);
if (!fs.existsSync(dir)) return null;
if (isManagedSkillDir(id)) return null;
return `foreign skill "${id}" at .agents/skills/${id}/ is not managed by learn-loop — rename it or pick a different artifact name`;
}
function installSkillFile(id: string, content: string): string | null {
try {
const conflict = foreignSkillConflict(id);
if (conflict) return conflict;
const target = skillFileFor(id);
ensureDir(path.dirname(target));
fs.writeFileSync(target, content);
fs.writeFileSync(markerFileFor(id), JSON.stringify({
owner: 'learn-loop', artifactId: id, installedAt: new Date().toISOString(),
}));
return null;
} catch (e) {
return e instanceof Error ? e.message : String(e);
}
}
// Remove the installed skill dir only if it carries the learn-loop marker.
function removeSkillFile(id: string): string | null {
try {
const dir = path.join(SKILLS_OUTPUT_DIR, id);
if (!fs.existsSync(dir)) return null;
if (!isManagedSkillDir(id)) {
return `refusing to remove foreign skill "${id}" — not managed by learn-loop`;
}
fs.rmSync(dir, {recursive: true, force: true});
return null;
} catch (e) {
return e instanceof Error ? e.message : String(e);
}
}
// Sync an artifact's full directory (main file + references/) into the live
// .agents/skills/ location. Returns an error string or null on success.
function syncInstalledSkill(art: Artifact): string | null {
const id = art.path.split('/').pop() || 'skill';
try {
const conflict = foreignSkillConflict(id);
if (conflict) return conflict;
const srcDir = path.join(LEARNING_DIR, art.path);
if (!fs.existsSync(srcDir)) return `artifact dir missing for "${id}"`;
const targetDir = path.join(SKILLS_OUTPUT_DIR, id);
if (!fs.existsSync(targetDir)) ensureDir(targetDir);
// Find the main artifact file (skill.md), build SKILL.md from it.
const mainFile = resolveArtifactFile(art);
if (!mainFile) return `cannot find main artifact file for "${id}"`;
const body = skillBodyOnly(fs.readFileSync(mainFile, 'utf-8'));
fs.writeFileSync(skillFileFor(id), buildSkillContent(art, body));
// Copy supporting files/dirs (references, scripts, templates, examples).
if (fs.statSync(srcDir).isDirectory()) {
// Prune stale files in the target that no longer exist in the source.
if (fs.statSync(targetDir).isDirectory()) {
const kept = new Set<string>();
for (const entry of fs.readdirSync(srcDir)) {
if (path.basename(entry) === path.basename(mainFile)) continue;
kept.add(entry);
}
for (const entry of fs.readdirSync(targetDir)) {
if (entry === 'SKILL.md' || entry === MANAGED_MARKER) continue;
if (!kept.has(entry)) {
fs.rmSync(path.join(targetDir, entry), {recursive: true, force: true});
}
}
}
for (const entry of fs.readdirSync(srcDir)) {
if (path.basename(entry) === path.basename(mainFile)) continue;
const from = path.join(srcDir, entry);
const to = path.join(targetDir, entry);
if (fs.statSync(from).isDirectory()) {
fs.cpSync(from, to, {recursive: true});
} else {
fs.copyFileSync(from, to);
}
}
}
// Write/refresh the ownership marker so the install is learn-loop-managed.
fs.writeFileSync(markerFileFor(id), JSON.stringify({
owner: 'learn-loop', artifactId: id, installedAt: new Date().toISOString(),
}));
return null;
} catch (e) {
return e instanceof Error ? e.message : String(e);
}
}
// Build a spec-compliant SKILL.md body from artifact metadata.
// Standard frontmatter: name, description, version, metadata.tags.
function buildSkillContent(art: Artifact, body: string): string {
const name = art.path.split('/').pop() || 'skill';
const description = (art.description || `${name} — learned project skill`).slice(0, 60);
const version = typeof art.version === 'number' && art.version > 0
? `1.${art.version}.0` : '1.0.0';
const lines = ['---', `name: ${name}`, `description: ${description}`, `version: ${version}`];
if (art.tags.length > 0) {
lines.push('metadata:', ' tags:', ...art.tags.map(t => ` - ${t}`));
}
lines.push('---', '', body);
return lines.join('\n');
}
// Strip a SKILL.md frontmatter block, returning the body.
function skillBodyOnly(content: string): string {
if (content.startsWith('---')) {
const end = content.indexOf('\n---', 3);
if (end > 0) return content.slice(end + 4).trimStart();
}
return content.trim();
}
function moveDir(src: string, dest: string): void {
if (!fs.existsSync(src)) return;
ensureDir(path.dirname(dest));
if (fs.existsSync(dest)) fs.rmSync(dest, {recursive: true, force: true});
try {
fs.renameSync(src, dest);
} catch {
// Cross-device fallback
fs.cpSync(src, dest, {recursive: true});
fs.rmSync(src, {recursive: true, force: true});
}
}
// ── Mod ──────────────────────────────────────────────────────────────────────
export default function (cmd: ModApi): void {
// ── Resolve store paths against THIS project ─────────────────────────────
LEARNING_DIR = path.join(cmd.cwd, '.agents', 'learning');
EPISODES_PATH = path.join(LEARNING_DIR, 'episodes.jsonl');
INDEX_PATH = path.join(LEARNING_DIR, 'index.json');
CANDIDATES_DIR = path.join(LEARNING_DIR, 'candidates');
ACTIVE_DIR = path.join(LEARNING_DIR, 'active');
GRAVEYARD_DIR = path.join(LEARNING_DIR, 'graveyard');
SKILLS_OUTPUT_DIR = path.join(cmd.cwd, '.agents', 'skills');
AUTONOMY_PATH = path.join(LEARNING_DIR, 'autonomy.jsonl');
MERGE_DISMISSALS_FILE = path.join(LEARNING_DIR, 'merge-dismissals.json');
// ── Flags ───────────────────────────────────────────────────────────────
// addFlag supports only 'boolean' | 'string' — numbers arrive as strings
// when set via --mod-option, so parse them in numFlag().
cmd.addFlag('ll-recall-threshold', {type: 'string', default: '0.3',
description: 'Minimum match score to inject recall context'});
cmd.addFlag('ll-max-recall-items', {type: 'string', default: '6',
description: 'Max items in the recall block'});
cmd.addFlag('ll-decay-days', {type: 'string', default: '90',
description: 'Days since last use before an active artifact is archived'});
cmd.addFlag('ll-auto-distill', {type: 'boolean', default: true,
description: 'Automatically run a distillation turn after signal-rich sessions'});
cmd.addFlag('ll-auto-promote', {type: 'boolean', default: true,
description: 'Automatically promote shadows with verified green evidence on self-repair verdicts'});
cmd.addFlag('ll-max-distills', {type: 'string', default: '1',
description: 'Max autonomous distillation turns per session'});
cmd.addFlag('ll-distill-min-tools', {type: 'string', default: '8',
description: 'Min tool iterations for a verify-driven distillation trigger'});
cmd.addFlag('ll-min-shadow-runs', {type: 'string', default: '2',
description: 'Min shadow runs (green>=red, no rejections) before auto-promotion'});
cmd.addFlag('ll-candidate-ttl-days', {type: 'string', default: '30',
description: 'Days before an untouched candidate is pruned to the graveyard'});
cmd.addFlag('ll-write-approval', {type: 'boolean', default: false,
description: 'Require human approval before learning_manage write actions land (Hermes write_approval parity). Review with /learn pending, /learn approve, /learn reject'});
cmd.addFlag('ll-auto-merge', {type: 'boolean', default: true,
description: 'Propose overlapping learned skills for agent-judged merge review at stop time'});
cmd.addFlag('ll-merge-threshold', {type: 'string', default: '0.6',
description: 'Minimum mechanical similarity (0-1) for a pair to be proposed. The pre-filter only — the agent reads both skills and makes the final merge call'});
cmd.addFlag('ll-auto-delete-days', {type: 'string', default: '180',
description: 'Days an archived artifact lingers before actual deletion'});
cmd.addFlag('ll-merge-proposals', {type: 'string', default: '2',
description: 'Max merge pairs proposed per review (keeps the review prompt small)'});
cmd.addFlag('ll-merge-dismiss-ttl-days', {type: 'string', default: '30',
description: 'Days a dismissed merge pair stays dismissed before it can be re-proposed'});
cmd.addFlag('ll-max-skill-lines', {type: 'string', default: '300',
description: 'Refuse a merge if the resulting skill body exceeds this many lines'});
cmd.addFlag('ll-usage-receipts', {type: 'boolean', default: false,
description: 'Write a receipt line for every learned-skill usage signal'});
function numFlag(name: string, fallback: number, min: number = 0): number {
const v = cmd.getFlag(name);
const n = typeof v === 'number' ? v : parseFloat(String(v));
if (!Number.isFinite(n) || n < min) return fallback;
return n;
}
function boolFlag(name: string, fallback: boolean): boolean {
const v = cmd.getFlag(name);
if (typeof v === 'boolean') return v;
const s = String(v).toLowerCase();
if (s === 'true' || s === '1' || s === 'yes' || s === 'on') return true;
if (s === 'false' || s === '0' || s === 'no' || s === 'off') return false;
return fallback;
}
// ── In-session state (closure-scoped, flushed on onRunEnd) ──────────────
let episode: EpisodeInFlight | null = null;
let toolIterations = 0;
let modelName: string = '';
let sessionStart: string = '';
let distillsThisRun = 0;
const recalledThisRun = new Set<string>();
const activeSkillsUsedThisRun = new Set<string>();
// Merge-review bookkeeping: pairs already reviewed this run (so the stop
// hook doesn't re-propose a pair the agent already judged), and persistent
// dismissals ("different jobs, don't merge").
const mergeReviewedThisRun = new Set<string>();
let mergeDismissals: Record<string, number> = {};
try {
if (fs.existsSync(MERGE_DISMISSALS_FILE)) {
mergeDismissals = JSON.parse(fs.readFileSync(MERGE_DISMISSALS_FILE, 'utf-8'));
}
} catch { mergeDismissals = {}; }
function resetEpisode(): void {
episode = null;
toolIterations = 0;
sessionStart = new Date().toISOString();
recalledThisRun.clear();
activeSkillsUsedThisRun.clear();
}
function ensureEpisode(userText?: string): EpisodeInFlight {
if (!episode) {
const sig = userText
? extractTaskSignature(userText, cmd.cwd)
: `${path.basename(cmd.cwd)}:session`;
episode = {
task_signature: sig,
files: new Set(),
tools: new Set(),
verify: new Set(),
user_corrections: [],
subagents: new Set(),
skill_used: null,
failures: 0,
model: modelName || 'unknown',
draftCreated: false,
distilled: false,
};
}
return episode;
}
function flushEpisode(outcome: string): Episode | null {
if (!episode) return null;
// Skip duplicate: same signature + outcome as the very last episode line
const lines = readEpisodeLines();
const last = lines[lines.length - 1];
if (last && !isTombstone(last.data)) {
const sig = typeof last.data.task_signature === 'string' ? last.data.task_signature : '';
if (sig === episode.task_signature && String(last.data.outcome) === outcome) {
return null;
}
}
const ep: Episode = {
task_signature: episode.task_signature,
files: Array.from(episode.files).slice(0, 30),
tools: Array.from(episode.tools),
verify: Array.from(episode.verify),
outcome,
user_corrections: episode.user_corrections.slice(-10),
subagents: Array.from(episode.subagents),
skill_used: episode.skill_used,
model: episode.model,
confidence: 0.0,
ts: sessionStart,
distilled: episode.distilled,
};
appendEpisode(ep);
return ep;
}
// ── Recall: search artifacts, inject via transformContext ───────────────
function buildRecallBlock(userText: string): string | null {
const queryKeys = extractKeywords(userText);
if (queryKeys.length < 2) return null;
const threshold = numFlag('ll-recall-threshold', 0.3);
const maxItems = Math.round(numFlag('ll-max-recall-items', 6));
const index = loadIndex();
const matches: {score: number; kind: string; label: string; detail: string}[] = [];
for (const [id, art] of Object.entries(index.artifacts)) {
if (art.status !== 'active' && art.status !== 'shadow') continue;
const artKeys = extractKeywords((art.description || '') + ' ' + (art.tags || []).join(' '));
const score = scoreMatch(queryKeys, artKeys);
if (score < threshold) continue;
const badge = art.status === 'shadow' ? '[shadow]' : '';
const green = art.green > 0 ? ` · ${art.green} green` : '';
const red = art.red > 0 ? ` · ${art.red} red` : '';
const kindLabel = art.kind === 'warning' ? '⚠ Warning' :
art.kind === 'taste' ? '🎯 Taste' :
art.kind === 'guard' ? '🛡 Guard' : '📋 Skill';
matches.push({
score, kind: art.kind, label: id,
detail: `${kindLabel} ${badge}: ${(art.description || '').slice(0, 120)}${green}${red}`,
});
recalledThisRun.add(id);
}
matches.sort((a, b) => b.score - a.score);
const top = matches.slice(0, maxItems);
if (top.length === 0) return null;
const lines = ['\n[learned-patterns] Prior workflow patterns (leads — verify before acting):'];
for (const m of top) {
lines.push(`- ${m.detail}`);
}
return lines.join('\n');
}
// ── Hooks: transformContext (recall injection) ──────────────────────────
cmd.hooks({
transformContext: ({messages}) => {
let lastUser = '';
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m && typeof m === 'object' && (m as Record<string, unknown>).role === 'user') {
const content = (m as Record<string, unknown>).content;
if (typeof content === 'string') { lastUser = content; break; }
if (Array.isArray(content)) {
const textParts = content
.filter((p: unknown) => typeof p === 'object' && p !== null &&
(p as Record<string, unknown>).type === 'text')
.map((p: unknown) => String((p as Record<string, unknown>).text || ''));
lastUser = textParts.join(' ');
if (lastUser) break;
}
}
}
if (!lastUser || lastUser.length < 5) return messages;
if (!episode) {
ensureEpisode(lastUser);
}
const block = buildRecallBlock(lastUser);
if (!block) return messages;
// Surface the most recent automatic-loop run, if any, as a one-line
// note in the recall block. This is the Hermes-style "session-boot
// reads the skills registry" pattern, applied to the script's
// output: the next turn's context window sees "[learn-loop] N
// candidates proposed, M graduated, K rejected — see autonomy.jsonl"
// so the agent knows the loop ran and what it produced.
let loopNote = '';
if (lastLoopRun) {
if (lastLoopRun.ok) {
loopNote = `\n[learn-loop] observed=${lastLoopRun.observed}, proposed=${lastLoopRun.proposed}, graduated=${lastLoopRun.graduated}, rejected=${lastLoopRun.rejected} (ran ${lastLoopRun.ranAt})`;
} else {
loopNote = `\n[learn-loop] error: ${lastLoopRun.error || 'unknown'} (ran ${lastLoopRun.ranAt})`;
}
}
// Array content blocks — the harness's wire projection assumes
// message.content is always an array; string content crashes it.
const recallMsg = {role: 'user', content: [{type: 'text', text: block + loopNote}]};
// Insert directly before the final user message (cache-optimal tail
// position): only the last array entry falls outside the cached
// prefix, instead of the last two from a length-2 splice.
const insertIdx = Math.max(0, messages.length - 1);
const result = [...messages];
result.splice(insertIdx, 0, recallMsg as never);
return result;
},
});
// ── Hooks: transformInput (detect user corrections) ─────────────────────
cmd.hooks({
transformInput: ({text}) => {
const lower = text.toLowerCase();
// Usage signal 3: explicit skill references in user text.
// The harness emits skill_loaded for inferred activations, but an
// explicit slash reference can be missed when an inferred expansion
// already matched, so count it directly. Handles /name and the
// namespaced /skill:name (or /skill name) forms.
const found = new Set<string>();
for (const m of text.matchAll(/(?:^|\s)\/([a-z0-9][a-z0-9-]{0,62})\b/g)) {
found.add(m[1]);
}
const nsMatch = text.match(/(?:^|\s)\/skill\s*[::]\s*([a-z0-9][a-z0-9-]{0,62})\b/i);
if (nsMatch) { found.delete('skill'); found.add(nsMatch[1]); }
for (const name of found) recordSkillUse(name, 'slash-reference');
const correctionSignals = [
/no[,.\s]+\w+ly\s+/i, /don'?t\s+\w+/i, /never\s+\w+/i,
/instead[,.\s]+/i, /prefer\s+/i, /always\s+\w+/i,
/wrong[,.\s]+/i, /incorrect/i, /shouldn'?t/i,
/do it (differently|like this)/i, /not like that/i,
/that'?s not (what|how|right)/i,
];
const isCorrection = correctionSignals.some(r => r.test(lower));
if (isCorrection && episode) {
const clean = text.slice(0, 200).replace(/\n/g, ' ');
episode.user_corrections.push(clean);
// 3+ corrections on the same pattern → auto-draft a candidate.
// Correction signal is real evidence: draft straight to shadow.
if (episode.user_corrections.length >= 3 && !episode.draftCreated) {
episode.draftCreated = true;
const sig = slugify(episode.task_signature.split(':').slice(1).join('-'));
const joined = episode.user_corrections.map(c => `- ${c}`).join('\n');
// Kind heuristic: corrections about build/test/tool/workflow → skill;
// style/approach language → taste (the old behavior).
const styleWords = /\b(prefer|always|never|instead|shouldn'?t|like this|that way|this way)\b/i;
const workflowWords = /\b(test|build|command|tool|script|run|compile|deploy|setup|config|steps?)\b/i;
const kind: Artifact['kind'] =
workflowWords.test(joined) && !styleWords.test(joined) ? 'skill' : 'taste';
const candidateId = `${kind}-${sig}`;
// Locked: candidate dir write + index insert is read-modify-write.
withLock('index', () => {
const idx = loadIndex();
if (!idx.artifacts[candidateId]) {
const content = kind === 'skill'
? `# ${sig || 'Learned workflow'} (auto-drafted)\n\n## When to use\n${episode?.user_corrections[episode?.user_corrections.length - 1]?.slice(0, 200) ?? ''}\n\n## Steps\n${joined}\n`
: '# Taste rule (auto-drafted)\n\n' + joined + '\n';
const art: Artifact = {
kind,
status: 'shadow',
path: `candidates/${candidateId}`,
scope: 'user',
tags: extractKeywords(episode.task_signature),
description: `User correction pattern: ${episode.user_corrections[episode.user_corrections.length - 1].slice(0, 80)}`,
confidence: 0.1,
shadow_runs: 1,
green: 1,
red: 0,
rejections: 0,
episodes: [],
created: new Date().toISOString(),
last_verified: '',
last_used: '',
pinned: false,
};
ensureDir(path.join(CANDIDATES_DIR, candidateId));
fs.writeFileSync(path.join(CANDIDATES_DIR, candidateId, kind === 'skill' ? 'skill.md' : 'taste.md'), content);
idx.artifacts[candidateId] = art;
saveIndex(idx);
cmd.ui.setStatus(buildStatus());
writeReceipt({
action: 'seed',
id: candidateId,
kind,
reason: '3+ user corrections in session',
evidence: {corrections: episode.user_corrections.length},
});
}
});
cmd.ui.notify(
`I've noticed you correct this pattern often. Drafting a ${kind} ` +
`candidate (shadowed): ${candidateId}.`,
);
}
}
return {action: 'continue'};
},
});
// ── Observer: event recording ───────────────────────────────────────────
// tool_queued carries the ORIGINAL input; tool_completed does not carry input.
cmd.on('tool_queued', event => {
if (event.type !== 'tool_queued') return;
const ep = ensureEpisode();
const name = typeof event.toolName === 'string' ? event.toolName : '';
ep.tools.add(name);
toolIterations++;
const input = (event as Record<string, unknown>).input;
const fp = extractFilePath(input);
if (fp) ep.files.add(fp);
// Detect verification commands from the queued input. Explicit runner
// names only — avoid \btest\b matching "latest" or prose.
const cmdText = extractCmd(input);
if (/\b(npm|pnpm|yarn|bun|npx|cargo|make|dotnet|go)\b[^\n]*\b(test|check|typecheck|lint)\b/i.test(cmdText) ||
/\b(pytest|vitest|jest|mocha|ava|playwright|cypress|tsc|eslint)\b/.test(cmdText)) {
ep.verify.add(cmdText.slice(0, 120));
}
});
cmd.on('tool_errored', event => {
if (event.type !== 'tool_errored') return;
const ep = ensureEpisode();
ep.failures++;
const name = typeof event.toolName === 'string' ? event.toolName : '';
ep.tools.add(name);
toolIterations++;
});
cmd.on('subagent_start', event => {
if (event.type !== 'subagent_start') return;
const ep = ensureEpisode();
ep.subagents.add(String((event as Record<string, unknown>).subagentType || 'unknown'));
});
cmd.on('subagent_stop', event => {
if (event.type !== 'subagent_stop') return;
const ep = ensureEpisode();
ep.subagents.add(String((event as Record<string, unknown>).subagentType || 'unknown'));
});
cmd.on('subagent_progress', event => {
if (event.type !== 'subagent_progress') return;
const ep = ensureEpisode();
const name = String((event as Record<string, unknown>).toolName || '');
ep.tools.add(`agent:${name}`);
});
cmd.on('skill_loaded', event => {
if (event.type !== 'skill_loaded') return;
const name = String((event as Record<string, unknown>).name || '');
const ep = ensureEpisode();
ep.skill_used = name;
recordSkillUse(name, 'skill_loaded');
});
// ── Usage tracking: multiple signals feed last_used/use_count ─────────────
// skill_loaded (harness event, fires on inferred/expansion activation),
// activate_skill tool calls (the model explicitly activating a skill), and
// explicit /skill-name references in user text. A skill only decays if
// NONE of these signals fired within the decay window.
function recordSkillUse(name: string, source: string): void {
if (!name || !isManagedSkillDir(name)) return;
withLock('index', () => {
const idx = loadIndex();
const art = idx.artifacts[name];
if (art && art.kind === 'skill' && art.status === 'active') {
art.last_used = new Date().toISOString();
art.use_count = (art.use_count ?? 0) + 1;
activeSkillsUsedThisRun.add(name);
saveIndex(idx);
if (boolFlag('ll-usage-receipts', false)) {
writeReceipt({action: 'skill-use', id: name, source});
}
}
});
}