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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
|
import type { EngineInterface, On, PluginOptions, ResultOf } from 'claude-code'
import { lineOf, missingPathOf, noteCall, noteDone, noteFailure, prune, subjectOf, tallyOf } from './fleet/fleet'
import type { Host, OpenResult } from './host'
import { paint, tilesOf, type TouchKind } from './map/estate'
import { absOf, baseName, isUnder, join, norm, relTo } from './paths'
import { keysOfUnit, unitOfPath } from './reader/estate-model'
import { readOrNull } from './reader/fs'
import type { TestTotals } from './reader/modernized'
import { oneLineOf, readSnapshot, REVIEWS_FILE } from './reader/progress'
import type { ReviewVerdict } from './reader/progress'
import { nodeOfFile } from './reader/topology'
import { decide, ledgerJson, ledgerMarkdown, nextUnreviewed, queueOf, undecide, type DeckScope } from './review/deck'
import { mergeLedger, parseLedger } from './review/ledger'
import { signBrief } from './sign'
import {
newActivity,
newState,
PANE_ID,
PLUGIN_NAME,
RASTER_KEY,
SIGN_ID,
type FinishedCall,
type State,
} from './state'
import { readTestRun, TEST_COMMAND } from './tests-run'
import { deckView, signView } from './views/deck'
import { headerRowsOf, legendRowsOf, nextRowsOf, paneView, planOf, showBar, type Kit } from './views/pane'
import { plain } from './text'
import { xrayOf } from './xray/xray'
const REFRESH_DEBOUNCE_MS = 450
/** While a fleet of agents is writing, a read of everything on disk is due this often, not after every call. */
const REFRESH_BUSY_MS = 2500
const FRAME_MS = 140
const CLOCK_MS = 1000
const POLL_MS = 20_000
const WRITE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit'])
const QUIET_TOOLS = new Set(['Read', 'Glob', 'Grep', 'LS', 'WebFetch', 'WebSearch', 'TodoWrite', 'ToolSearch'])
const PARENT_TOOLS = new Set(['Agent', 'Task', 'Workflow'])
const STEP = /\/(?:[\w-]+:)?(modernize-[a-z-]+)\b[^\n]*/
const nowMs = (): number => Date.now()
/** A cell count as the engine reports it, made safe to do layout arithmetic on. */
const wholeOf = (value: unknown): number =>
typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0
/**
* Binds a Host from `$`. Declared in this file, each member spelled
* `$.noun.event(...)`, so the engine reads what the module calls off its source.
*/
function hostOf($: EngineInterface): Host {
return {
fs: {
read: path => $.fs.read(path),
write: (path, text) => $.fs.write(path, text),
list: path => $.fs.list(path),
exists: path => $.fs.exists(path),
stat: path => $.fs.stat(path),
},
now: () => $.clock.now(),
after: (ms, fn) => $.clock.after(ms, fn),
every: (ms, fn) => $.clock.every(ms, fn),
storeGet: key => $.store.get(key),
storeSet: (key, value) => $.store.set(key, value),
invalidate: () => $.ui.invalidate('ui.render'),
blit: args => $.ui.blit(args),
status: text => $.ui.status(text),
toast: (text, timeoutMs) => $.ui.toast(text, timeoutMs !== undefined ? { timeoutMs } : undefined),
log: text => $.ui.log(text),
openPane: pane => $.ui.open(pane) as Promise<OpenResult>,
closePane: pane => $.ui.close(pane),
registerCommand: spec => $.command.register(spec),
fillPrompt: input => $.prompt.fill(input),
submitPrompt: input => $.prompt.submit(input),
abortTurn: turnId => $.turn.abort({ turnId }),
}
}
/**
* `fs` with every relative path rooted at `cwd`: the artifacts live under the
* session's working directory, wherever the process itself happens to stand.
*/
function rootedAt(fs: Host['fs'], cwd: string): Host['fs'] {
return {
read: path => fs.read(absOf(cwd, path)),
write: (path, text) => fs.write(absOf(cwd, path), text),
list: path => fs.list(absOf(cwd, path)),
exists: path => fs.exists(absOf(cwd, path)),
stat: path => fs.stat(absOf(cwd, path)),
}
}
/**
* Registers the plugin's live hooks: the pane and its estate map, x-ray
* reads, the rule review deck, the fleet view and the sign-off dialog.
* `session.start` binds the engine; every hook after
* it works over that binding and one state object.
*
* @param on the engine's registrar
* @param raw the plugin's options as the settings hold them
*/
export function register(on: On, raw: PluginOptions) {
const state: State = newState(raw)
// ---------------------------------------------------------------- reading
async function refresh(host: Host): Promise<void> {
if (state.isRefreshing) {
state.isRefreshQueued = true
return
}
state.isRefreshing = true
try {
const snapshot = await readSnapshot(host.fs, state.cache, {
...((state.pickedSystem ?? state.options.system) !== '' && { system: state.pickedSystem ?? state.options.system }),
commandPrefix: state.options.commandPrefix,
legacyDir: state.options.legacyDir,
track: state.options.track,
writtenUnits: state.writtenUnits,
observed: state.observed,
nowMs: nowMs(),
})
// The pane opens by itself once there is modernization to show: the first artifact under analysis/,
// not only a legacy system that has not been touched.
const isFirstSight = snapshot !== null && snapshot.hasAnalysis && state.snapshot?.hasAnalysis !== true
state.snapshot = snapshot
state.readError = null
if (isFirstSight) {
maybeAutoOpen()
}
if (snapshot !== null) {
if (!state.deck.isOpen) {
state.deck.ledger = snapshot.reviews
}
// The pane says all of this already, and so does the bar that stands where it was while it is hidden. The
// pinned line is for a person who turned the pane off. A workspace that holds a legacy system and nothing
// yet under analysis/ has no modernization to report.
host.status(state.pane.isOpen || !snapshot.hasAnalysis || state.options.panel !== 'off' ? undefined : oneLineOf(snapshot))
}
if (state.estate !== null) {
state.estate = { ...state.estate, tiles: [] }
}
} catch (error) {
state.readError = error instanceof Error ? error.message : String(error)
} finally {
state.isRefreshing = false
host.invalidate()
if (state.isRefreshQueued) {
state.isRefreshQueued = false
scheduleRefresh(host)
}
}
}
function scheduleRefresh(host: Host): void {
// A read is already due, and it will see everything written so far. Pushing it out with every call would starve
// it for as long as agents keep writing, and the map would show nothing of a fan-out until it was over.
if (state.timers.has('refresh')) {
return
}
const isBusy = tallyOf(state.fleet, nowMs()).active >= 3
state.timers.set(
'refresh',
host.after(isBusy ? REFRESH_BUSY_MS : REFRESH_DEBOUNCE_MS, () => {
state.timers.delete('refresh')
void refresh(host)
}),
)
}
// ------------------------------------------------------------- animation
function frameOf(): { cells: string; isAnimating: boolean } | null {
const estate = state.estate
if (estate === null || state.snapshot === null) {
return null
}
const painted = paint(estate.tiles, estate.columns, estate.rows, state.touches, nowMs())
return { cells: painted.cells, isAnimating: painted.isAnimating }
}
function animate(host: Host): void {
if (state.timers.has('frames') || !state.pane.isOpen) {
return
}
state.timers.set(
'frames',
host.every(FRAME_MS, () => {
const estate = state.estate
const frame = frameOf()
if (estate === null || frame === null || !state.pane.isOpen) {
state.timers.get('frames')?.cancel()
state.timers.delete('frames')
return
}
void host
.blit({
requestId: PANE_ID,
key: RASTER_KEY,
cells: frame.cells,
columns: estate.columns,
rows: estate.rows,
})
.then(result => {
// Said once: a refused repaint means the map is stale, which is worth knowing.
if (result.deny !== undefined && !state.timers.has('blit-refused')) {
state.timers.set('blit-refused', host.after(60_000, () => state.timers.delete('blit-refused')))
host.log(`estate map: repaint refused (${result.deny})`)
}
})
.catch(() => undefined)
if (!frame.isAnimating) {
state.timers.get('frames')?.cancel()
state.timers.delete('frames')
}
}),
)
}
function touch(host: Host, nodeId: string, kind: TouchKind): void {
const held = state.touches.get(nodeId)
// A write outranks a read that is still fading.
if (held !== undefined && held.kind === 'write' && kind === 'read' && nowMs() - held.atMs < 1200) {
return
}
state.touches.set(nodeId, { atMs: nowMs(), kind })
animate(host)
}
/** The estate unit ids a tool call's paths and command text name, with how each was touched. */
function nodesTouched(tool: string, args: Readonly<Record<string, unknown>>): { id: string; kind: TouchKind }[] {
const snapshot = state.snapshot
const estate = snapshot?.estate
if (snapshot === null || estate === null || estate === undefined) {
return []
}
const legacyRoot = join(state.options.legacyDir, snapshot.system)
const modernRoot = join('modernized', snapshot.system)
const upliftRoot = join('modernized', `${snapshot.system}-uplifted`)
const out = new Map<string, TouchKind>()
const kind: TouchKind = WRITE_TOOLS.has(tool) ? 'write' : 'read'
const take = (path: string, how: TouchKind) => {
const rel = relTo(state.cwd, path)
if (rel === null) {
return
}
if (isUnder(rel, legacyRoot) && rel !== legacyRoot) {
const unit = unitOfPath(estate, snapshot.topology, rel.slice(legacyRoot.length + 1))
if (unit !== null) {
out.set(unit.id, how)
}
} else if (isUnder(rel, upliftRoot) && rel !== upliftRoot) {
// An uplift's working copy has the legacy tree's own layout, so the same path names the same unit.
const unit = unitOfPath(estate, snapshot.topology, rel.slice(upliftRoot.length + 1))
if (unit !== null) {
out.set(unit.id, how)
// An edit that keeps a file's size is invisible to the size comparison; a write seen here is not.
if (how === 'write') {
state.writtenUnits.add(unit.id)
}
}
} else if (isUnder(rel, modernRoot) && rel !== modernRoot) {
const dir = (rel.slice(modernRoot.length + 1).split('/')[0] ?? '').toLowerCase()
const unit = estate.units.find(candidate => keysOfUnit(candidate).some(key => key.toLowerCase() === dir))
if (unit !== undefined) {
out.set(unit.id, how === 'read' ? 'read' : 'write')
}
}
}
for (const key of ['file_path', 'path', 'notebook_path']) {
const value = args[key]
if (typeof value === 'string') {
take(value, kind)
}
}
const command = typeof args.command === 'string' ? args.command : ''
if (command !== '') {
const paths = command.match(/(?:\.{0,2}\/)?[\w.@~+-]+(?:\/[\w.@~+-]+)+/g) ?? []
const writes = /(?:>|\btee\b|\bsed\s+-i|\bmv\b|\bcp\b|\brm\b|\bpatch\b|\bgit\s+(?:apply|checkout|restore))/.test(command)
for (const path of paths.slice(0, 24)) {
const rel = relTo(state.cwd, path) ?? ''
take(path, writes && (isUnder(rel, modernRoot) || isUnder(rel, upliftRoot)) ? 'write' : 'read')
}
}
return [...out.entries()].map(([id, how]) => ({ id, kind: how }))
}
/** The module a shell command's text names by path, of those the pane knows: the longest path wins. */
function moduleOfCommand(command: string): string | null {
const snapshot = state.snapshot
if (snapshot === null) {
return null
}
const upliftRoot = join('modernized', `${snapshot.system}-uplifted`)
const candidates = [
...snapshot.modules.map(module => module.path),
...(snapshot.track === 'uplift'
? (snapshot.estate?.units ?? []).flatMap(unit => (unit.dir !== undefined && unit.dir !== '' ? [join(upliftRoot, unit.dir)] : []))
: []),
].sort((a, b) => b.length - a.length)
const escaped = (path: string) => path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
return (
candidates.find(path => new RegExp(`(?:^|[\\s'"=:@])(?:\\./)?${escaped(path)}(?=[\\s/'"]|$)`).test(command)) ?? null
)
}
// ------------------------------------------------------------------ deck
async function openDeck(host: Host, scope: DeckScope, filter: string): Promise<string> {
const snapshot = state.snapshot
if (snapshot === null || snapshot.rules === null) {
return 'No BUSINESS_RULES.md to review yet. Run the extract-rules command first.'
}
const queue = queueOf(snapshot.rules, scope, filter)
state.deck = {
isOpen: true,
scope,
filter,
queue,
ledger: snapshot.reviews,
edits: new Map(),
index: nextUnreviewed(queue, snapshot.reviews, 0),
source: null,
isSourceShown: false,
}
// The deck draws in the band above the prompt: nothing to open, only to draw.
host.invalidate()
return queue.length === 0
? 'Nothing to review under that scope.'
: `Reviewing ${queue.length} rule${queue.length === 1 ? '' : 's'}.`
}
async function saveLedger(host: Host): Promise<void> {
const system = state.snapshot?.system
if (system === undefined) {
return
}
// The review command writes this file too: what it added while the deck was open is kept, this session's decisions go on top.
const onDisk = parseLedger(await readOrNull(host.fs, join('analysis', system, REVIEWS_FILE)))
const merged = mergeLedger(onDisk, state.deck.edits)
state.deck.ledger = merged
await host.fs.write(join('analysis', system, REVIEWS_FILE), ledgerJson(system, merged))
await host.fs.write(join('analysis', system, 'RULE_REVIEWS.md'), ledgerMarkdown(system, merged))
scheduleRefresh(host)
}
async function loadSource(host: Host): Promise<void> {
const rule = state.deck.queue[state.deck.index]
const snapshot = state.snapshot
const citation = rule?.citations[0]
if (rule === undefined || snapshot === null || citation === undefined) {
return
}
const legacyRoot = join(state.options.legacyDir, snapshot.system)
const written = norm(citation.path)
// A citation comes from a file in the analysis tree: it names a file inside the code, never a way out of it.
if (written.startsWith('/') || /^[A-Za-z]:/.test(written) || written.split('/').includes('..')) {
return
}
const viaMap = snapshot.topology !== null ? nodeOfFile(snapshot.topology, written)?.file : undefined
const candidates = [
written,
join(legacyRoot, written),
...(viaMap !== undefined ? [join(legacyRoot, viaMap)] : []),
]
for (const path of candidates) {
const text = await readOrNull(host.fs, path)
if (text === null) {
continue
}
const lines = text.split('\n')
// From the cited line itself: in a short band every row of lead-in costs a row of the rule's own code.
const from = Math.max(1, citation.from)
const to = Math.min(lines.length, Math.max(citation.to + 2, from + 11), from + 39)
state.deck.source = {
ruleId: rule.id,
path,
startLine: from,
text: lines
.slice(from - 1, to)
.join('\n')
.replace(/[^\x09\x0a\x20-\x7e -]/g, ' ')
.slice(0, 9000),
}
return
}
state.deck.source = { ruleId: rule.id, path: written, startLine: citation.from, text: '(source file not found)' }
}
const deckActionsOf = (host: Host) => ({
decide: (verdict: ReviewVerdict) => {
const rule = state.deck.queue[state.deck.index]
if (rule === undefined) {
return
}
state.deck.ledger = decide(state.deck.ledger, rule, verdict, new Date(nowMs()).toISOString())
state.deck.edits.set(rule.id, state.deck.ledger[rule.id] ?? null)
state.deck.index = nextUnreviewed(state.deck.queue, state.deck.ledger, state.deck.index + 1)
state.deck.isSourceShown = false
void saveLedger(host).catch(() => undefined)
host.invalidate()
},
undo: () => {
const rule = state.deck.queue[state.deck.index]
if (rule !== undefined) {
state.deck.ledger = undecide(state.deck.ledger, rule.id)
state.deck.edits.set(rule.id, null)
void saveLedger(host).catch(() => undefined)
host.invalidate()
}
},
prev: () => {
const size = state.deck.queue.length
state.deck.index = size === 0 ? 0 : (state.deck.index - 1 + size) % size
state.deck.isSourceShown = false
host.invalidate()
},
next: () => {
const size = state.deck.queue.length
state.deck.index = size === 0 ? 0 : (state.deck.index + 1) % size
state.deck.isSourceShown = false
host.invalidate()
},
source: () => {
state.deck.isSourceShown = !state.deck.isSourceShown
if (state.deck.isSourceShown) {
void loadSource(host).then(() => host.invalidate())
}
host.invalidate()
},
close: () => {
state.deck.isOpen = false
host.invalidate()
},
})
// ------------------------------------------------------------------ sign
async function openSign(host: Host, name = ''): Promise<string> {
const snapshot = state.snapshot
if (snapshot === null || snapshot.brief === null) {
return 'There is no brief to sign yet. Run the brief command first.'
}
if (snapshot.brief.approval.isSigned) {
return `The brief is already signed${snapshot.brief.approval.by !== undefined ? ` by ${snapshot.brief.approval.by}` : ''}.`
}
if (state.activity.isWorking) {
return 'Wait for the running turn to finish before signing.'
}
state.sign = { isOpen: true, name: name !== '' ? name : state.sign.name, covers: 'phase-1', error: null }
await host.openPane({
id: SIGN_ID,
title: 'Sign the brief',
focus: true,
closeOnEscape: true,
holdToasts: true,
rows: 12,
})
host.invalidate()
return ''
}
const signActionsOf = (host: Host) => ({
name: (value: string) => {
state.sign.name = value
},
covers: (value: 'phase-1' | 'full') => {
state.sign.covers = value
host.invalidate()
},
cancel: () => {
state.sign.isOpen = false
void host.closePane({ id: SIGN_ID }).catch(() => undefined)
},
sign: () => {
void (async () => {
const system = state.snapshot?.system
const name = state.sign.name.trim()
if (system === undefined) {
return
}
if (name === '') {
state.sign.error = 'Type the approver\'s name first.'
host.invalidate()
return
}
if (state.activity.isWorking) {
state.sign.error = 'A turn is running; sign once it has finished.'
host.invalidate()
return
}
const path = join('analysis', system, 'MODERNIZATION_BRIEF.md')
const text = await readOrNull(host.fs, path)
const signed = text !== null ? signBrief(text, name, new Date(nowMs()).toISOString().slice(0, 10), state.sign.covers) : null
if (signed === null) {
state.sign.error = 'The brief has no approval block to sign.'
host.invalidate()
return
}
await host.fs.write(path, signed)
state.sign.isOpen = false
await host.closePane({ id: SIGN_ID }).catch(() => undefined)
host.log(`brief signed by ${name} (${state.sign.covers === 'full' ? 'full plan' : 'Phase 1 only'})`)
await refresh(host)
})()
},
})
// ------------------------------------------------------------------ pane
/**
* Opens the pane. Opened unasked on a terminal too narrow to dock a pane, the engine holds it undrawn: it is not open to
* the person, so the bar with the show button stays where it was, and pressing that button (the person asking) seats
* the pane at any width.
*/
async function openPane(host: Host): Promise<{ isPlaced: boolean; reason: string }> {
const result: OpenResult = await host.openPane({ id: PANE_ID, title: 'Modernization' })
const isPlaced = result === undefined || result.isPlaced !== false
state.pane.isOpen = isPlaced
state.pane.isWaiting = !isPlaced
state.pane.isClosedByPerson = false
void refresh(host)
return { isPlaced, reason: result !== undefined && result.reason !== undefined ? result.reason : '' }
}
const paneActionsOf = (host: Host) => ({
system: () => {
const systems = state.snapshot?.systems ?? []
const current = state.snapshot?.system
if (systems.length < 2 || current === undefined) {
return
}
// A different system is a different estate, a different brief and a different set of lit tiles.
state.pickedSystem = systems[(systems.indexOf(current) + 1) % systems.length] ?? current
state.touches.clear()
state.writtenUnits.clear()
state.estate = null
void refresh(host)
},
next: () => {
const next = state.snapshot?.next
if (next === null || next === undefined || next.isByHand) {
return
}
void host
.fillPrompt({ text: next.text })
.then(result => {
if (!result.isFilled) {
host.toast(`Next: ${next.text}`, 8000)
}
})
.catch(() => undefined)
},
review: () => {
void openDeck(host, 'flagged', '').catch(() => undefined)
},
sign: () => {
void openSign(host)
.then(message => {
if (message !== '') {
host.toast(message, 6000)
}
})
.catch(() => undefined)
},
close: () => {
state.pane.isOpen = false
state.pane.isWaiting = false
state.pane.isClosedByPerson = true
void host.closePane({ id: PANE_ID }).catch(() => undefined)
},
stop: () => {
const turnId = state.activity.turnId
if (turnId !== null) {
void host.abortTurn(turnId).catch(() => undefined)
}
},
})
/**
* Opens the pane by itself once there is something to show, the person has not closed it, and
* the layout docks panes (the fullscreen layout). What the layout is comes from whichever render
* last said: not every build draws every site, so each render hook reports what it saw.
*/
function maybeAutoOpen(viewport?: { columns?: number; isFullscreen?: boolean }): void {
state.viewport.columns = viewport?.columns ?? state.viewport.columns
state.viewport.isFullscreen = viewport?.isFullscreen ?? state.viewport.isFullscreen
const host = state.host
const shouldOpen =
host !== null &&
state.options.panel === 'auto' &&
!state.pane.isOpen &&
!state.pane.isWaiting &&
!state.pane.isClosedByPerson &&
!state.timers.has('auto-open') &&
state.snapshot !== null &&
state.snapshot.hasAnalysis &&
state.viewport.isFullscreen === true
if (shouldOpen && host !== null) {
// Opened from a timer: a render hook only draws.
state.timers.set(
'auto-open',
host.after(50, () => {
state.timers.delete('auto-open')
void openPane(host).catch(() => undefined)
}),
)
}
}
// ------------------------------------------------------------- lifecycle
on('session.start', async ($, e, next) => {
const bound = hostOf($)
const host: Host = { ...bound, fs: rootedAt(bound.fs, e.cwd) }
state.host = host
state.cwd = e.cwd
for (const timer of state.timers.values()) {
timer.cancel()
}
state.timers.clear()
await Promise.all([
host
.registerCommand({
name: 'modernize-panel',
description: 'Show or hide the modernization progress pane and estate map',
argumentHint: '[open|close|json]',
immediate: true,
})
.catch(() => undefined),
host
.registerCommand({
name: 'modernize-review-pane',
description: 'Review business rules one card at a time in the pane: confirm, wrong, or discuss',
argumentHint: '[flagged|p0|all] [filter]',
})
.catch(() => undefined),
host
.registerCommand({
name: 'modernize-sign',
description: 'Sign the modernization brief\'s approval block (a person\'s action)',
argumentHint: '[approver name, role]',
})
.catch(() => undefined),
])
await refresh(host)
state.timers.set(
'clock',
host.every(CLOCK_MS, () => {
if (state.pane.isOpen && (state.activity.isWorking || state.activity.running.size > 0)) {
host.invalidate()
}
}),
)
state.timers.set(
'poll',
host.every(POLL_MS, () => {
if (state.pane.isOpen && !state.activity.isWorking) {
scheduleRefresh(host)
}
}),
)
return next(e)
})
on('ui.render', { component: 'PromptHint' }, ($, e, next) => {
if (e.surface === 'terminal') {
maybeAutoOpen(e.viewport)
}
return next(e)
})
on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
const host = state.host
if (e.surface === 'terminal') {
// Not every build reports `isFullscreen`. The band's `maxRows` tells the same fact: under the
// fullscreen layout it is what the bottom slot has left; otherwise it is the terminal's height.
const rows = e.viewport?.rows
const inferred = rows !== undefined && e.props.maxRows > 0 ? e.props.maxRows < rows : undefined
maybeAutoOpen({
...(e.viewport?.columns !== undefined && { columns: e.viewport.columns }),
...((e.viewport?.isFullscreen ?? inferred) !== undefined && {
isFullscreen: e.viewport?.isFullscreen ?? inferred,
}),
})
}
// A survey holds the band first; the deck waits behind it.
if (host === null || e.props.hasSurvey || e.surface !== 'terminal') {
return next(e)
}
const table = $.ui.resolve(e)
// With no deck open, a hidden pane leaves one row and a button to bring it back: the pane is
// always one press away, on a terminal too narrow to open it unasked as well as on a wide one.
if (!state.deck.isOpen) {
const snapshot = state.snapshot
if (state.options.panel === 'off' || state.pane.isOpen || snapshot === null || !snapshot.hasAnalysis) {
return next(e)
}
return showBar(
{ Box: table.Box, Text: table.Text, Button: table.Button },
oneLineOf(snapshot),
e.props.bodyColumns,
() => {
void openPane(host)
.then(result => {
if (!result.isPlaced) {
host.toast(`The pane could not be shown: ${result.reason}`, 8000)
}
})
.catch(() => undefined)
},
)
}
return deckView(
{ Box: table.Box, Text: table.Text, Button: table.Button, Code: table.Code },
state.deck,
e.props.bodyColumns,
e.props.maxRows,
deckActionsOf(host),
)
})
on('ui.render', { component: 'Pane' }, async ($, e, next) => {
const host = state.host
if (host === null || (e.requestId !== PANE_ID && e.requestId !== SIGN_ID)) {
return next(e)
}
const table = $.ui.resolve(e)
const kit: Kit = {
Box: table.Box,
Text: table.Text,
Button: table.Button,
...('Raster' in table && { Raster: table.Raster }),
...('Code' in table && { Code: table.Code }),
...('Input' in table && { Input: table.Input }),
...('Select' in table && { Select: table.Select }),
}
const columns = Math.max(24, wholeOf(e.props.bodyColumns) - 1)
if (e.requestId === SIGN_ID) {
return signView(
kit,
state.sign,
state.snapshot?.system ?? '',
state.snapshot?.brief?.openQuestions ?? 0,
columns,
signActionsOf(host),
)
}
// A squeezed pane (a dialog or another panel has its rows) can report a body of no rows at all.
const rows = wholeOf(e.props.scroll.bodyRows)
state.pane.isOpen = true
state.pane.isWaiting = false
state.pane.bodyColumns = columns
state.pane.bodyRows = rows
state.pane.placement = e.props.placement
const snapshot = state.snapshot
const plan = planOf(rows, e.props.placement, {
phases: snapshot?.brief?.phases.length ?? 0,
modules: snapshot?.modules.length ?? 0,
attention:
(snapshot?.attention.length ?? 0) +
[...state.fleet.signatures.values()].filter(signature => signature.agents.size >= 3).length,
hasMap: snapshot !== null && snapshot.estate !== null && kit.Raster !== undefined,
headerRows: headerRowsOf(snapshot, columns),
nextRows: nextRowsOf(snapshot, state, columns),
legendRows: legendRowsOf(snapshot, columns),
})
let estate: { cells: string; columns: number; rows: number; tiles: State['estate'] extends infer T ? (T extends { tiles: infer U } ? U : never) : never } | null = null
// The plan sheds the map first when the body is too short; a Raster of no rows is refused.
if (snapshot !== null && snapshot.estate !== null && kit.Raster !== undefined && plan.estate >= 1 && columns >= 1) {
const mapRows = Math.min(256, plan.estate)
const held = state.estate
const tiles =
held !== null && held.columns === columns && held.rows === mapRows && held.tiles.length > 0
? held.tiles
: tilesOf(snapshot, columns, mapRows)
state.estate = { tiles, columns, rows: mapRows, isMounted: true }
const painted = paint(tiles, columns, mapRows, state.touches, nowMs())
estate = { cells: painted.cells, columns, rows: mapRows, tiles }
if (painted.isAnimating) {
animate(host)
}
} else {
// No map drawn: nothing for the frame timer to repaint.
state.estate = null
}
return paneView(
kit,
state,
{ columns, rows, placement: e.props.placement, nowMs: nowMs(), estate, plan },
paneActionsOf(host),
)
})
on('ui.close', async ($, e, next) => {
const result = await next(e)
if (result.deny !== undefined) {
return result
}
if (e.id === PANE_ID) {
state.pane.isOpen = false
state.pane.isWaiting = false
state.pane.isClosedByPerson = e.origin.kind === 'person' || state.pane.isClosedByPerson
if (state.estate !== null) {
state.estate.isMounted = false
}
} else if (e.id === SIGN_ID) {
state.sign.isOpen = false
}
return result
})
// -------------------------------------------------------------- commands
on('command.run', { command: 'modernize-panel' }, async ($, e, next) => {
const host = state.host
if (host === null) {
return next(e)
}
state.viewport.isFullscreen = e.presentation.isFullscreen
state.viewport.columns = e.presentation.columns
const arg = e.args.trim().toLowerCase()
if (arg === 'json') {
await refresh(host)
const snapshot = state.snapshot
return {
text:
snapshot === null
? 'no system under analysis/'
: `\`\`\`json\n${JSON.stringify(
{
system: snapshot.system,
stages: snapshot.stages.map(stage => ({ key: stage.key, done: stage.isDone, detail: stage.detail })),
brief: snapshot.brief && {
target: snapshot.brief.target,
approval: snapshot.brief.approval,
phases: snapshot.brief.phases.map(phase => ({
number: phase.number,
title: phase.title,
size: phase.size,
modules: phase.modules,
criteria: phase.criteria.length,
ticked: phase.criteria.filter(criterion => criterion.isTicked).length,
})),
},
modules: snapshot.modules.map(module => ({
dir: module.dir,
state: module.state,
tests: module.tests,
reviewDate: module.reviewDate,
})),
proof:
snapshot.verification === null
? null
: {
overall: snapshot.verification.overall,
modules: [...snapshot.proofs].map(([name, proof]) => ({ name, state: proof.state, verdict: proof.verdict ?? null, reason: proof.reason })),
},
totals: snapshot.totals,
percent: snapshot.percent,
attention: snapshot.attention,
next: snapshot.next,
},
null,
2,
)}\n\`\`\``,
}
}
const wantsClose = arg === 'close' || (arg === '' && state.pane.isOpen)
if (wantsClose) {
state.pane.isOpen = false
state.pane.isWaiting = false
state.pane.isClosedByPerson = true
await host.closePane({ id: PANE_ID }).catch(() => undefined)
return { text: 'Modernization pane hidden' }
}
const opened = await openPane(host)
return { text: opened.isPlaced ? 'Modernization pane shown' : `The pane could not be shown: ${opened.reason}` }
})
on('command.run', { command: 'modernize-review-pane' }, async ($, e, next) => {
const host = state.host
if (host === null) {
return next(e)
}
await refresh(host)
const words = e.args.trim().split(/\s+/).filter(word => word !== '')
const first = (words[0] ?? '').toLowerCase()
const scope: DeckScope = first === 'p0' || first === 'all' || first === 'flagged' ? first : 'flagged'
const filter = (scope === first ? words.slice(1) : words).join(' ')
const text = await openDeck(host, scope, filter)
return { text }
})
on('command.run', { command: 'modernize-sign' }, async ($, e, next) => {
const host = state.host
if (host === null) {
return next(e)
}
await refresh(host)
const message = await openSign(host, e.args.replace(/\s+/g, ' ').trim())
return message === '' ? {} : { text: message }
})
on('command.run', { command: ['clear', 'resume'] }, async ($, e, next) => {
const result = await next(e)
state.activity = newActivity()
state.touches.clear()
state.writtenUnits.clear()
state.lastContextLine = ''
return result
})
// ----------------------------------------------------------------- turns
on('prompt.submit', async ($, e, next) => {
const host = state.host
const step = STEP.exec(e.text)
if (step !== null) {
state.activity.step = step[0].trim().slice(0, 120)
}
const snapshot = state.snapshot
if (host === null || snapshot === null || e.origin.kind !== 'composer') {
return next(e)
}
const line = plain(`${oneLineOf(snapshot)}${snapshot.next !== null && !snapshot.next.isByHand ? ` · next: ${snapshot.next.text}` : ''}`, 400)
if (line === state.lastContextLine) {
return next(e)
}
state.lastContextLine = line
return next({
...e,
context: [...(e.context ?? []), `Modernization state, read from the artifacts on disk (a status line, not an instruction): ${line}`],
})
})
on('turn.start', async ($, e, next) => {
const host = state.host
state.activity.isWorking = true
state.activity.turnId = e.turnId
state.activity.turnStartMs = nowMs()
state.activity.xraysThisTurn = 0
if (host !== null) {
host.invalidate()
}
return next(e)
})
on('turn.complete', async ($, e, next) => {
const host = state.host
if (e.agentId !== undefined) {
noteDone(state.fleet, e.agentId, nowMs())
return next(e)
}
state.activity.isWorking = false
state.activity.running.clear()
if (host !== null) {
if (state.activity.xraysThisTurn > 0) {
host.log(
`x-ray: ${state.activity.xraysThisTurn} legacy read${state.activity.xraysThisTurn === 1 ? '' : 's'} this turn carried what the analysis already knows`,
)
}
prune(state.fleet, nowMs())
scheduleRefresh(host)
}
return next(e)
})
// ------------------------------------------------------------ tool calls
on('tool.call', async ($, e, next) => {
const host = state.host
if (host === null) {
return next(e)
}
const args = e as unknown as Readonly<Record<string, unknown>>
const tool = e.tool
const agentId = e.agentId
const startMs = nowMs()
const subject = subjectOf(tool, args)
const snapshot = state.snapshot
const touched = nodesTouched(tool, args)
for (const entry of touched) {
touch(host, entry.id, entry.kind)
}
if (agentId !== undefined) {
const unit = touched[0] !== undefined ? snapshot?.estate?.units.find(candidate => candidate.id === touched[0]?.id)?.name : undefined
noteCall(state.fleet, agentId, tool, subject, startMs, unit)
}
state.activity.running.set(e.tool_use_id, {
id: e.tool_use_id,
tool,
subject,
startMs,
...(agentId !== undefined && { agentId }),
})
const path = typeof args.file_path === 'string' ? args.file_path : typeof args.notebook_path === 'string' ? args.notebook_path : undefined
const rel = path !== undefined ? relTo(state.cwd, path) : null
let result: ResultOf['tool.call'] | undefined
let note: string | undefined
try {
result = await next(e)
if (result.deny !== undefined) {
return result
}
const extra: string[] = []
const isError = result.isError === true
const text = typeof result.text === 'string' ? result.text : ''
if (isError && agentId !== undefined) {
// What the call was aimed at is half of the cause: the path as the agent gave it, else the command's head.
const missing = missingPathOf(text)
const example = rel ?? (missing !== undefined ? (relTo(state.cwd, missing) ?? missing) : subject)
const signature = noteFailure(state.fleet, agentId, text, nowMs(), example)
if (signature !== null) {
const line = lineOf(signature)
host.toast(`Fleet: ${line}`, 9000)
host.log(`fleet: ${line}. One cause across agents usually belongs in the playbook, not in each agent.`)
}
}
if (tool === 'Read' && !isError && state.options.isXrayOn && snapshot !== null && rel !== null) {
const legacyRoot = join(state.options.legacyDir, snapshot.system)
if (isUnder(rel, legacyRoot) && rel !== legacyRoot) {
const xray = xrayOf(snapshot, {
fileRel: rel.slice(legacyRoot.length + 1),
...(typeof args.offset === 'number' && { offset: args.offset }),
...(typeof args.limit === 'number' && { limit: args.limit }),
})
if (xray !== null) {
extra.push(xray.text)
note = xray.summary.replace(/^x-ray [^:]+: /, 'x-ray ')
state.activity.xrays += 1
if (agentId === undefined) {
state.activity.xraysThisTurn += 1
}
}
}
}
// A citation in the analysis is relative to the legacy system's root, and an agent handed one
// often reads it from the workspace root. Say where the file is rather than let it search.
if (tool === 'Read' && isError && state.options.isXrayOn && snapshot !== null && rel !== null && /does not exist/i.test(text)) {
const legacyRoot = join(state.options.legacyDir, snapshot.system)
const candidate = join(legacyRoot, rel)
// Only a plain path is echoed back: the note is read by the model, and a name is text from the legacy tree.
if (plain(rel, 300) === rel && !isUnder(rel, state.options.legacyDir) && (await host.fs.exists(candidate))) {
extra.push(
`There is no ${rel} in the workspace, but ${candidate} exists. Paths cited under analysis/${snapshot.system}/ are relative to ${legacyRoot}/.`,
)
note = 'x-ray: the path exists under the legacy root'
}
}
if ((tool === 'Bash' || tool === 'PowerShell') && typeof args.command === 'string' && TEST_COMMAND.test(args.command)) {
const run = readTestRun(text)
if (run !== null) {
note = `${run.executed} executed${run.skipped > 0 ? `, ${run.skipped} skipped` : ''}${run.failed > 0 ? `, ${run.failed} failed` : ''}`
// A run in a module's own directory is its result even where its runner left no report file behind.
const home = moduleOfCommand(args.command)
if (home !== null && run.executed + run.skipped > 0) {
const seen: TestTotals = { tests: run.executed + run.skipped, failures: run.failed, errors: 0, skipped: run.skipped, reports: 1 }
state.observed.set(home, seen)
}
}
}
return extra.length > 0 ? { ...result, context: [...(result.context ?? []), ...extra] } : result
} finally {
const ms = nowMs() - startMs
state.activity.running.delete(e.tool_use_id)
if (agentId === undefined) {
const finished: FinishedCall = {
tool,
subject,
isOk: result !== undefined && result.deny === undefined && result.isError !== true,
ms,
...(note !== undefined && { note }),
}
state.activity.finished = [...state.activity.finished, finished].slice(-8)
}
if (!QUIET_TOOLS.has(tool) || tool === 'Read') {
const wrote = WRITE_TOOLS.has(tool) || tool === 'Bash' || tool === 'PowerShell' || PARENT_TOOLS.has(tool)
if (wrote) {
// A write may have changed the working copy: the next read lists it afresh.
for (const key of [...state.cache.keys()]) {
if (key.startsWith('changed:')) {
state.cache.delete(key)
}
}
scheduleRefresh(host)
} else if (state.pane.isOpen) {
host.invalidate()
}
}
}
})
}
export { PLUGIN_NAME }
|